title: No error messages from validate?

text:
# Question
Title: No error messages from validate?
I'm creating a simple contact form and it works flawlessly, besides the validation.

When I try to exercise the validate function, no error messages are shown. The text in the correspondent field turns red, so that works, but where is the messages?

If I fill in the form correctly and the mail gets sent, messages are shown just like they should.

Here's my code:

```
function mymodule_buysell_contact_form($form, &$form_state) {
    // The form

    $form['contact'] = array(

        '#title' => t('Skicka ett meddelande till säljaren'),

        '#type' => 'fieldset'

    );
    $form['contact']['message'] = array(

        '#type' => 'textarea',

        '#title' => t('Meddelande:'),

        '#cols' => 35,

        '#rows' => 6,

        '#resizable' => FALSE

    );
    $form['contact']['name'] = array(

        '#type' => 'textfield',

        '#title' => t('Ditt Namn:'),

        '#size' => 35,

        '#maxlength' => 30

    );
    $form['contact']['compname'] = array(

        '#type' => 'textfield',

        '#title' => t('Företag:'),

        '#size' => 35,

        '#maxlength' => 30

    );
    $form['contact']['phone'] = array(

        '#type' => 'textfield',

        '#title' => t('Telefon:'),

        '#size' => 35,

        '#maxlength' => 30

    );
    $form['contact']['cellphone'] = array(

        '#type' => 'textfield',

        '#title' => t('Mobiltelefon:'),

        '#size' => 35,

        '#maxlength' => 30

    );

    $form['contact']['mail'] = array(

        '#type' => 'textfield',

        '#title' => t('Din E-mail:'),

        '#size' => 35,

        '#maxlength' => 30

    );

    $form['contact']['captcha'] = array (
        '#type' => 'captcha',
        '#captcha_type' => 'image_captcha/Image',
    );

    $form['contact']['submit'] = array(

        '#type' => 'submit',

        '#value' => t('Skicka')

    );

    return $form;
    }

    function mymodule_buysell_contact_form_validate($form, &$form_state) {
    // Validate message

    $valid_message = $form_state['values']['message'];

        if (empty($valid_message)) {

        form_set_error('message', 'Du har inte skrivit något meddelande');

        }
    // Validate if a name is submitted

    $valid_name = $form_state['values']['name'];

        if (empty($valid_name)) {

        form_set_error('name', 'Du har inte fyllt i ett namn');

        }

    // Validate if a company name is submitted

    $valid_compname = $form_state['values']['compname'];

        if (empty($valid_compname)) {

        form_set_error('compname', 'Du har inte fyllt i ditt företagsnamn');

        }
    // Validate phone by look for numbers

    $valid_phone = $form_state['values']['phone'];

        if (!is_numeric($valid_phone)) {

        form_set_error('phone', 'Ditt nummer verkar inte vara korrekt ifyllt (endast siffror)');

        }
    // Validate cellphone by look for numbers

    $valid_cellphone = $form_state['values']['cellphone'];

        if (!is_numeric($valid_cellphone)) {

        form_set_error('cellphone', 'Ditt mobilnummer verkar inte vara korrekt ifyllt (endast siffror)');

        }

    // Validate the mail, using Drupals own function

    $valid_email = $form_state['values']['mail'];

        if (!valid_email_address($valid_email)) {

        form_set_error('mail', 'Din Epost verkar inte vara korrekt ifylld');

        }
}

```

# Answer
> 1 votes
For fieldsets I think you have to include the parent as well.

Try changing

form\_set\_error('**phone**', 'Ditt nummer v.... to

form\_set\_error('**contact\]\[phone**', 'Ditt nummer v....

You can read more here: http://drupal.org/node/678816

---
Tags: forms
---


# Question
Title: how to Views call images of each node? I saw that is not in SQL of the view
I have a View that shows the first image of each node (so, a common View). I saw the SQL of this view, and I saw that the image is not called inside this SQL, so, what's the way that Views call images of each node?

# Answer
> 0 votes
Views for Drupal 7 uses entity\_load() to display Field API fields (to load the entity for each row and get the field data). It is not pulled through SQL, which is why you don't see it (the field table gets added only once you filter by a field, etc).

This is because Field API expects to receive a full entity when rendering a field. Views tried to simulate an entity (before alpha1 was released), but that failed miserably (broken formatters, translation fallback...). Hence the current approach.

# Answer
> 0 votes
It sounds like your view is configured to show nodes instead of fields.

When a view is showing nodes (either as teaser or full), the view only uses SQL to get which nodes to show. Then it calls `node_load()` and `node_view()` before outputting. `node_view()` will output a node just like you were looking at it regularly and this is where the image is being pulled in, not in views itself (hence why there is no SQL to get the image).

When a view is showing fields, it grabs all the fields data using SQL instead of `node_load()` and displays that data using it's own templates instead of `node_view()`.

Let me know if I can clarify further.

# Answer
> 0 votes
I just tested for Drupal 7 and it actually happens even if you use mode "Fields".
As I can see from source of Views 3.0-rc1, Views uses special function field\_view\_field() for displaying field and don't need to join on any tables. It allows to use cached data for fields, as I think.
If you turn on filter or sorting by image field, then JOIN will appears.

---
Tags: views, media, database
---


title: Problems with theming a grid

text:
# Question
Title: Problems with theming a grid
I am having problems trying to control the layout and fields together in a grid style of a view.
On the internet I saw several tutorials about how to theme views, and they suggest using functions in template.php, or using view template files. I cannot find a tutorial that helps me.

Specifically, when I use a template file, I cannot control the disposition of fields (controlling the disposition of each field; controlling the fields altogether; adding conditionals; adding classes; trying to use "views-view--," "views-view-field--," "views-view-fields--," or "views-view-grid--"), and when I use a function in template.php, I cannot get the variables/values of fields.

I must say that I know how to include a custom design using the Views module interface, to control the design per fields (or controling all fields of each item, if I include the design and fields in the last field). But I want to do this using some external way to custom display in a **centralized way** (also to not allow to change the design from the web interface, and to have the control in a files, not in the database).

When I say **a centralized way**, I mean, using a file or files to control the disposition of each field, control fields together, add conditionals, add classes, add functions, (such as a theme in Drupal).

I am using Drupal 6 and Views 2.

# Answer
> 2 votes
in views-view-grid--viewname.tpl.php, with `print_r($variables)`, you will find the whole values in the 'view' array (is a very huge output, so I recomend only pull 1 item in this test).

here you will discover that '`result`' carry the `stdClass Object` with the fields of views (not it all, seems that the images are not there), to print this you can use:

```
print_r($variables['view']->result);

```

with the id of the values, you can use these values for example, show a node title:

```
echo $variables['view']->result[$i]->node_title;

```

or you can use the id of the node to get, for example, images from nodes (seems that the images are not in `result`).

```
$nIdItem = $variables['view']->result[$i]->nid;
$node = node_load($nIdItem);
echo "<img src='/".$node->field_image[0]['filepath']."'>";

```

so with this way is possible to control each field, set of fields, and/or add conditions, functions.

I do not know the performance or security implications of using this way, this may be a new question.

---
Tags: views, theming
---


# Question
Title: How to programmatically set node field values.
I have a content type. I have firstname, lastname and email address fields. I need the default value for each field to be the firstname, lastname and email address of the user profile. Also, I need to prevent the user from modifying these values. The user should be able to see the values by default, but the user shouldn't be able to edit them.

# Answer
This code works for me:

```
function test_form_alter(&$form, &$form_state, $form_id){
global $user;
    if($form_id == 'story_node_form' ){
    if ($user->uid) {
profile_load_profile($user);
        $form['field_first_name'] = array(
            '#type' => 'textfield',
            '#title' => 'First name',
           '#default_value' => $user->profile_first_name,
            '#disabled'=> 'TRUE'
        );
        $form['#submit'][] = 'test_field_first_name_submit';
    }
     }
}

```
> 0 votes

# Answer
You can create a custom module and add use hook\_form\_alter to change the default\_value of your field and change them to `#disabled => true`. Here is an example. Don't forget to chage modulename to the name of your module and form-id to the id of your form :-).

```
function modulename_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form['#id'] == 'form-id') {
        $form['field_name'] = array(
            '#disabled' => TRUE,
            '#default_value' => $user->name
        );
    }
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Why are IDs showing in URLs when clean URLs are enabled?
I've enabled clean URLs on my site, and currently, URLs are of the form:

> /node/123

How can I force them to to use human-readable URLs? Something like:

> /node/title-of-node

# Answer
> 10 votes
The Clean URLs setting turns your URLs from `index.php?q=node/123` to `/node/123`.

The path module that comes with core Drupal enables the `URL path settings` tab on node add/edit forms. Here you can specify **any** URL alias that will load the node instead of `/node/123`. These aliases must be entered manually for each node.

The Pathauto module allows you to automatically generate URL aliases. By enabling pathauto and not doing any further configuration your URLs will turn into `/content/title-of-node`. You can change how the URL is generated in the pathauto settings (so it can be `/node/title-of-node` for example).

# Answer
> 1 votes
Adding to what reported by rocketeerbkw, I will suggest you to check also the Sub-path URL Aliases module (Drupal 6) or the Sub-pathauto (Sub-path URL Aliases) module (Drupal 7). The Pathauto module creates the aliases for URLs like example.com/node/1, or example-com/user/1; it doesn't create a path alias for example.com/node/1/edit, for example, and the purpose of those modules is to allow using the path alias also for example.com/node/1/edit, which would become example.com/node\_alias\_1/edit, where node\_alias\_1 is the alias for node/1.

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
>
> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.

# Answer
> 0 votes
If path module is enabled, you can change URLs in admin/config/search/path.
Or you can change the URL alias directly when adding new content in URL path settings field.

---
Tags: path-aliases
---


# Question
Title: How can I place a  new  textfield in the tab vocabularies in a content type?
I want to place a new text field in the "Vocabularies" field set of a node; the text field is not tag.

I am using the Vertical Tabs module, and my fields in the content type are in group.

The following is the structure of my content type:

* Title
* Vocabularies (taxonomy) -\> Here I want to place a field too.
* fieldset1 (Fields: field1, field2, and field3)
* fieldset2 (Fields: field4, field5)

# Answer
The fieldset for the vocabularies used by a node are added from taxonomy\_form\_alter(), using the following code (the relevant part is the one between "// 3" and "// 4"):

```
// 1
if (!isset($node->taxonomy)) {
  $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
}
else {
  // After a preview or form reload, the terms must be converted to objects.
  reset($node->taxonomy);
  if (!is_object(current($node->taxonomy))) {
    $node->taxonomy = taxonomy_preview_terms($node);
  }
  $terms = $node->taxonomy;
}

$c = db_query(db_rewrite_sql("SELECT v.* FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $node->type);

while ($vocabulary = db_fetch_object($c)) {
  if ($vocabulary->tags) {
    if (isset($form_state['node_preview'])) {
      // Typed string can be changed by the user before preview,
      // so we just insert the tags directly as provided in the form.
      $typed_string = $node->taxonomy['tags'][$vocabulary->vid];
    }
    else {
      $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
    }
// 2
    if ($vocabulary->help) {
      $help = filter_xss_admin($vocabulary->help);
    }
    else {
      $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
    }
    $form['taxonomy']['tags'][$vocabulary->vid] = array(
      '#type' => 'textfield',
      '#title' => $vocabulary->name,
      '#description' => $help,
      '#required' => $vocabulary->required,
      '#default_value' => $typed_string,
      '#autocomplete_path' => 'taxonomy/autocomplete/' . $vocabulary->vid,
      '#weight' => $vocabulary->weight,
      '#maxlength' => 1024,
    );
  }
  else {
    // Extract terms belonging to the vocabulary in question.
    $default_terms = array();
    foreach ($terms as $term) {
      // Free tagging has no default terms and also no vid after preview.
      if (isset($term->vid) && $term->vid == $vocabulary->vid) {
        $default_terms[$term->tid] = $term;
      }
    }

// 3
    $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), filter_xss_admin($vocabulary->help));
    $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
    $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
  }
}
if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
  if (count($form['taxonomy']) > 1) {
    // Add fieldset only if form has more than 1 element.
    $form['taxonomy'] += array(
      '#type' => 'fieldset',
      '#title' => t('Vocabularies'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
  }
  $form['taxonomy']['#weight'] = -3;
  $form['taxonomy']['#tree'] = TRUE;
// 4
}

```

The fieldset, which is then changed by the Vertical Tabs module in a tab, is added only when there are more than one vocabulary associated with the content type of the node being created.

To add a new field in that fieldset, you should implement `hook_form_alter()` in a module, and add code similar to the following one:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && && $form['type']['#value'] . '_node_form' == $form_id) {
    if (isset($form['taxonomy']['#type']) && $form['taxonomy']['#type'] == 'fieldset') {
      // Add your field.
      $form['taxonomy']['mymodule_field] = array(
        // …
      );
    }
  }
}

```

The module you write should be executed after the Taxonomy module, or the module will not find the fieldset added by the Taxonomy module. The module is executed after the Taxonomy module if it has a name such as TaxonomyAddendum, or if the weight of the module is higher than the weight of the Taxonomy module (10 should be enough).

As for altering the existing fields for the taxonomy terms, you should look at the code between the comments "// 1" and "// 2"; as form is build using the vocabulary ID, as in `$form['taxonomy'][$vocabulary->vid]`, you need to know it to get all the form fields used for the taxonomy terms. If you want to change the form field for a vocabulary for which you know the ID, then the code is simpler, as you don't need to get all the vocabularies that are associated to the node being edited; that is also true if you want to alter the form field for a vocabulary you know by name. You can use the following code to get a vocabulary object knowing the vocabulary name.

```
$result = db_fetch_object(db_query(db_rewrite_sql("SELECT v.vid, v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' AND v.name = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $type, $vocabulary_name));

```

`$type` is the content type that, in your case, is `$form['#node']->type`; `$vocabulary_name` is the name of the vocabulary.

If you know the vocabulary ID, then you can simply use taxonomy\_vocabulary\_load() to get the vocabulary object, which you could need to populate the taxonomy term form field.
> 0 votes

---
Tags: taxonomy-terms, forms
---


# Question
Title: How can I fix a call to undefined function libraries_load() in GeShi Filter?
I just installed GeSHi Filter and had to install the Libraries API for it. When I try to go to configuration settings I get this error:

```
Fatal error: Call to undefined function libraries_load() in /home/username/public_html/drupal/sites/all/modules/geshifilter/geshifilter.module on line 23

```

For the moment, I uninstalled all the above modules and its back to normal. Does anyone have any idea on how to fix it?

# Answer
> 5 votes
It appears you tried to use the recommended branch of Libraries API (marked green): 7.x-1.0. Generally, this is a good thing to do, but it can cause problems when modules have dependencies that are still in development.

In this case, Libraries API 7.x-1.0 doesn't the define the `libraries_load()` function that GeSHi Filter needs. You need to use the latest 7.x-2.x development snapshot.

# Answer
> 2 votes
As reported in the project page, you should use the development snapshot 7.x-2.x-dev of the Libraries API module for the branch 7.x-1 of the GeSHi Filter module.

> The 7.x branch requires the Libraries API (2.x-dev). A drush make file is also included that will download both the libraries API and the geshi dependency.

---
Tags: 7
---


title: Adjusting Ubercart package weight

text:
# Question
Title: Adjusting Ubercart package weight
I've got an e-shop for which I'm getting pretty accurate shipping rates from Australia Post eDRC (uc\_auspost\_2).

The problem is that sometimes I get overcharged because of the weight of the packaging material, envelope and a bunch of business cards I chuck into each package. On the other hand, I want to avoid overcharging customers by raising product weights.

Is it possible to automatically add say 200 grams to the weight of each package before requesting shipping rates? There is the *Shipping rate markup* configuration, but that only adjusts the rate *after* it has been received for a particular package weight.

# Answer
> 1 votes
There doesn't seem to be an "elegant" way to do this. All that Ubercart provides for shipping modules is a hook to register callback functions. The hard work of dividing products into individual packages is left on the modules. Which kind of makes sense, but also makes the system absolutely "unhookable".

Thus, to add an initial weight to each package, you would have to hack every shipping quote module and initialize each new package's weight before the individual products' weights are added up.

This is what I ended up doing with my UC Auspost module:

```
--- uc_auspost.module.orig      2011-08-15 08:59:46.000000000 +1000
+++ uc_auspost.module   2011-08-15 09:04:04.000000000 +1000
@@ -562,6 +562,7 @@ function _uc_auspost_package_products($p
           $addresses[++$last_key] = $address;
           $key = $last_key;
           $packages[$key][0] = new stdClass();
+          $packages[$key][0]->weight = 200;
         }
       }
       $packages[$key][0]->weight += $product->weight * $product->qty * uc_weight_conversion($product->weight_units, 'g');

```

---
Tags: 6, ubercart
---


title: The best way to deal with relations

text:
# Question
Title: The best way to deal with relations
I am trying to learn views/panels and therefore am working on cinema listings: there are 2 cities, each has 2 cinemas, each cinema has 2 show halls and there is a list of 10 movies, that are shown in some of these halls during the period of 5 days.

The question is - what would be the easiest way to enter and display such listings - should I use panels pages, panel nodes and is it possible to create such things using node references and relations?

please correct me if I'm wrong - i'm a newbie here:

I was thinking to create 10 nodes for each movie, where there is description of the movie, picture, etc, but then I am lost - shoud I create a node for each cinema and so on, or is it better to use taxonomy terms and to add these to each movie: city, cinema, hall and show time - I'm lost here... :(

the result that i want to achieve is that I'm clicking on a movie and I'm getting description and all it's showtimes. And if I'm clicking on particular cinema - I'm getting a timetable with movie names and times.

# Answer
> 1 votes
You need to get the data structure right, then everything will fall in place using Views.

Apart from city, cinema and movie content types, I'd suggest creating a session content type, too, which would link a movie with cinema, adding the time and hall number information. To maintain relationships between individual chunks of data, you want to use the CCK's node reference module (it is part of D7).

Roughly, you'd go with content types like so:

```
city (name)
cinema (name, city_ref, hall_count)
movie (name, description, picture, rating)
session (movie_ref, cinema_ref, hall_number, date_time)

```

It always depends on your requirements, but in this particular case I'd recommend using a separate content type for cinemas instead of taxonomy. Each cinema's node would serve information about the cinema, number of halls, and it would also reference the city it's located in and would be referenced by the screening nodes.

On the other hand if you have no other information about a city other than it's name, it should be safe to set it up as taxonomy.

To make it all work together, i.e. display listing pages, or allow users to search for movies and session times, you'll have to pick up the Views module.

Implementation of a "movie description and all it's showtimes" page would be the movie node page with a view attached (via Views Attach for D6 or EVA for D7) that would list show times for the movie passed as node ID from URL.

For the "cinema timetable with movie names and times", you'd do the same thing, but since you're displaying information about multiple movies, you would also use Views relationship (session -\> movie\_ref) to fetch in the movie nodes to be able to use their names as a views field.

---
Tags: taxonomy-terms, nodes
---


# Question
Title: How do I implement hook_page_alter() in a module?
I'm trying to add a piece on content to the `$page['content']` variable, but it's just not working and the examples are not helping me. My code is the following:

```
function my_modulename_page_alter(&$page) {
    $page['content'] = $extracontent . $page['content'];
}

```

`dpm()` doesn't allow me to see the available variables. What am I doing wrong?

# Answer
Try using hook\_page\_build(&$page). hook\_page\_alter(&$page), which is called directly after it, is meant for themers to use after all the modules are finished with their business.

I just implemented function `MODULE_page_alter(&$page)`, and it worked in the module as expected.
Did you clear the cache so the module is registered?
> 5 votes

# Answer
`$page['content']` is not a string, but an array that contains many indexes. As reported in hook\_page\_alter(), the 'content' element contains the main content of the current page, and its structure will vary depending on what module is responsible for building the page.

When the page is build from the Node and Blog modules, `$page['content']` contains:

* `$page['content']['system_main']['nodes'][$nid]['body']`: the node body
* `$page['content']['system_main']['nodes'][$nid]['links']`: the array of links attached to the node
* `$page['content']['system_main']['nodes'][$nid]['#node']`: the node object
* `$page['content']['system_main']['pager']`: the pager for the results.
> 3 votes

# Answer
For me, it's accessed at `$page['content']['system_main']['nodes'][$nid][<fieldname>]`. I've been wondering if it can also be accessed with hook\_node\_view\_alter().

As for `dpm()`, it does 2 weird things for me:
> 0 votes

---
Tags: 7
---


# Question
Title: What is the best slideshow to CCK image field?
I would like to know your suggestions about the best slideshow module to images uploaded from CCK image field. When I mean best, I want to say **quality/quantity of features supported** according your experience, but if you know another criteria (like support), please feel free to give your suggestion according your criteria.

# Answer
Well, there is of course this page in the drupal docs: http://drupal.org/node/418616

Unless you have a very specific use case which can be accommodated by a specialized module you really should go with the views slideshow module (http://drupal.org/project/views\_slideshow). Very well maintained, fairly well documented (but a lot of tutorials flying around) and a lot of modules integrating with it. With this module you can do almost everything slideshow-wise but it might be a bit complicated (but again: lots of tutorials available).

You can of course check out some of the other modules if they offer something more matching to your specific needs.
> 1 votes

---
Tags: entities, media
---


title: Undefined property in a Views PHP field

text:
# Question
Title: Undefined property in a Views PHP field
I need to have a field with user's picture URL. I'm trying to build it with a Views PHP field.

The field's value is defined

```
$account = user_load($row->uid);
$uri = $account->picture->uri;
$url = image_style_url('avatar', $uri);
return $url;

```

It returns value I expect, but returns also a warning

> Notice: Trying to get property of non-object in \__lambda\_func() (line 2 of /home/testwww/web/informator/sites/all/modules/views\_php/plugins/views/views\_php\_handler\_field.inc (131): runtime-created function).

Do you have any idea on how to solve the issue or what exactly is the cause?

From what I've found out:

* it seems that the notice concerns `uri` attribute of `$account->picture.`.
* The result of `print_r($account->picture)` is

```
        stdClass Object
        (
            [fid] => 168
            [uid] => 58
            [filename] => picture-58-1310836862.jpg
            [uri] => public://portrait/picture-58-1310836862.jpg
            [filemime] => image/jpeg
            [filesize] => 49505
            [status] => 1
            [timestamp] => 1310836862
            [rdf_mapping] => Array
                (
                )
        )

```

# Answer
> 4 votes
Users who have not uploaded a picture (also the anonymous user) will not have any object set for `$account->picture`. You just need to check that there is an object available:

```
$uri = isset($account->picture->uri) ? $account->picture->uri : NULL;

```

`image_style_url()` will return a bogus URI when passed NULL. You'll want to handle this somehow.

Note:
The user picture is already available as a field, you don't need PHP to get it.

In views 3, you must first add the "Content: Author" relationship before the User fields (including one for the user picture) will show up.

---
Tags: 7, views
---


# Question
Title: Problem with integer field format in Drupal 7
I just created an integer field for one of my content types. I'm using it to display a value for a year. However, when it is displayed, it is putting in a space between the 1000s column and the 100s column; so, for example, "1991" is displayed as "1 991".

I'm guessing this is something to do with the formatting of the field. Can anyone tell me how I can correct this or change the formatting?

# Answer
Go to the "Manage display" tab and edit "Thousand marker".
> 5 votes

---
Tags: entities
---


title: Most popular tags in a list as a block

text:
# Question
Title: Most popular tags in a list as a block
The Tagadelic module works very well out of the box; it is the only plug-and-play feature for a tag cloud available for Drupal 7.

I do not need to use the "cloud" format. I need the tags to be shown as list, from the most popular to the least popular, rendered using the same font, style, and size.

How can Tagadelic be modified to achieve this? I guess it should require more than a CSS fix.
Is there any better option than Tagadelic?

# Answer
You can do this with views:

* create a view of terms
* add a required relationship to "content using tags"
* set use aggregation: yes
* add the "term name" field a second time, set one of the to "aggregation type: count"
* add "term name" as a sort criteria, set "aggregation type: count"

A sample view is at http://drupalbin.com/19467
> 14 votes

# Answer
Tagadelic actually does what you want, but then uses CSS to modify the list into a cloud.

All you need, is to override the CSS in your theme:

```
.wrapper.tagadelic {
  display: block;
  text-align : left;
  margin-right: 0;
}

.tagadelic.level1,
.tagadelic.level2,
.tagadelic.level3,
.tagadelic.level4,
.tagadelic.level5,
.tagadelic.level6,
.tagadelic.level7,
.tagadelic.level8,
.tagadelic.level9,
.tagadelic.level10 {
  font-size : 1em;
}

```
> 2 votes

# Answer
See the cctags module as an alternative.

> flexible configuration and advanced features for theming clouds. (individual files of templates for tags, the names of the dictionary, pages clouds)
> 1 votes

---
Tags: 7, taxonomy-terms
---


title: Removing the Text Format selection

text:
# Question
Title: Removing the Text Format selection
Every textarea gives you an option to use either Filtered, Full, or Plain Text. Is there a way to remove or hide it so the layout becomes more streamlined? I'm using CKEditor if it means anything.

# Answer
You can change who has permission to use which input format under Settings (Site Configuration) -\> Input formats for Drupal 6 or Configuration -\> Text formats for Drupal 7.

If you uncheck all the other options (I'm assuming the one with the editor is set as default) then the option won't appear for those users who only have the default checked.

That's at least one way.
> 5 votes

# Answer
You can also use CSS to hide the select box.
> 2 votes

---
Tags: wysiwyg
---


# Question
Title: How do I display the raw value of a CCK field securely?
I have a CCK field that I can print out by doing:

```
print $node->field_cck[0]['value'];

```

Are there any security concerns with doing this?

# Answer
Yes! Lots of security concerns. You'll want to use `check_plain()`, `check_markup()` or one of the other functions to output that securely.

Check out Writing Secure Code for more information.
> 4 votes

---
Tags: 6, theming, entities
---


# Question
Title: Textfield default value to user email NOT WEBFORM
I am using the Drupal 6 Form API to build a custom form. I am not using the Webform module or CCK. How do I assign the user's email as a default value for a form element?

I know about `#default_value =>` but I do not know what to assign to this.

# Answer
> 2 votes
In your form function, you can add `global $user;` at the top. Then in your #default\_value you can use `$user->mail`.

---
Tags: forms
---


# Question
Title: path_set_alias() generates the wrong alias, and creates a 301 redirect to the desired alias's path
I'm creating a webform when organic groups are created and I'm trying to set an alias for it with `hook_nodeapi()`. It successfully creates the alias when the insert operation for the group is called after the webform has been created and associated to the group, but if you edit and update the group it does not update the alias with the code I have written. and a SQL error is displayed.

Here is the code that is called by `hook_nodeapi()` on insert and update operations:

```
// Webform
$nid = $node->field_webform_id[0]['value'];
$webform = db_fetch_object(db_query("SELECT count(src) as total FROM {url_alias} WHERE src = 'node/%d'", $nid));
if ($webform->total > 0) {
  db_query("DELETE FROM {url_alias} WHERE src LIKE 'node/%d'", $nid);
}
path_set_alias('node/'.$nid, 'local/'.$state.'/'.$county.'/submit-tip');

```

I'm getting the webform node ID from a CCK field on the group, checking if there are aliases set already for that node, and deleting them from the url\_alias table. Then I'm using path\_set\_alias to recreate an alias (in this case it is the same as before).

The error message displayed when updating a group:

> user warning: Duplicate entry 'local/pa/adams/submit-tip-' for key 'source\_language' query: INSERT INTO path\_redirect (source, redirect, query, fragment, language, type, last\_used) VALUES ('local/pa/adams/submit-tip', 'node/209', '', '', '', 301, 1311098626) in /var/aegir/platforms/crimewatchpa-dev-v2011-07-12-15-42/includes/common.inc on line 3538.

Instead of creating local/pa/adams/submit-tip as an alias to node/209, it creates an alias submit-tip-0 (submit-tip already exists on another node). A 301 redirect is also created with the path: local/pa/adams/submit-tip to node/209.

# Answer
> 0 votes
The trick was to set `$node->pathauto_perform_alias = FALSE;` before calling node\_save. Then my manual aliasing was allowed to take effect.

I still haven't figured out how to prevent the 301 redirect. It only produces a warning now, and the alias stays the way I want.

---
Tags: 6, path-aliases
---


title: How do I import blogs?

text:
# Question
Title: How do I import blogs?
How can I import blogs that were created in a Drupal 6 site to a Drupal 7 site? I'm not looking to upgrade the Drupal 6 site because the Drupal 7 site is a complete redesign of the old one and I wanted a clean start. I would like to not have to manually copy all of the blogs to the new site.

# Answer
> 1 votes
You should use the excellent Migrate module for this. Another quick way to do this, is using the Feeds module, which lets you import data using RSS and a variety of other formats.

---
Tags: 7, nodes
---


title: How theming off-line page?

text:
# Question
Title: How theming off-line page?
I read API and put files theme folder.

`maintenance-page.tpl.php` works well,

but `maintenance-page--offline.tpl.php` don't work.

How theming off-line page ?

# Answer
> 1 votes
Are you sure that your database server was offline when you tested ? The API description says

> "maintenance-page--offline.tpl.php" can be used when the database is offline to hide errors and completely replace the content.

---
Tags: 7, theming, maintenance-mode
---


title: Impossible to add new content

text:
# Question
Title: Impossible to add new content
I migrated my web to webhosting. There is a problem when I want to add new content, it's not able to add new content with images or files. Do you know where to look to solve it? Does it relate to access rights to directories where Drupal stores those files or is it something else?

When I want to upload an image, it writes:

* Warning: move\_uploaded\_file() \[function.move-uploaded-file\]: Unable to access public://image.jpg in file\_save\_upload() (line 1528 of /web/www/x.y.com/includes/file.inc).
* File upload error. Could not move uploaded file.

thank you

# Answer
review permissions in the /sites/all/files directory. you can **test** inside **files** directory, changing permissions to test the correct permissions. for example you, for test, can change to 755 in recursive mode: `chmod 755 files/ -R`. also review the owner of directory. According my experience, the owner can be a cause.

(According I remember, permission 777 number is the most higher number, but not is recommended).
> 1 votes

# Answer
Please define "it's not able to add new content with images or files" ? was the content save failed or only the image failed to attach ? I suggest you check Drupal status report.
> -1 votes

---
Tags: 7, files, media
---


title: Background Image not shown

text:
# Question
Title: Background Image not shown
I use the Bluemaster theme for my site. Since I installed this theme, it worked well, but a few days ago the background image was not shown.

I think this is because there are a large photo in background.
How do I fix this problem?

# Answer
> 2 votes
Your css is the problem. There is no images/bg.gif. There is an image/bg.png file.

Change

```
body {
    background: url("images/bg.gif") repeat scroll 0 0 transparent;
    color: #666666;
    font-family: Tahoma;
    font-size: 12px;
    padding: 0;
    text-align: center;
}

```

to:

```
body {
    background: url("images/bg.png") repeat scroll 0 0 transparent;
    color: #666666;
    font-family: Tahoma;
    font-size: 12px;
    padding: 0;
    text-align: center;
}

```

---
Tags: 6, media, theming
---


# Question
Title: How do I add custom order fields for users to fill out at checkout
Drupal 7 - Commerce

I have 2 fields related to the order. one is radio button where user selects Pickup, Delivery. the other one I won't mention as it might confuse some people. I want the user to select which one they want at checkout. How do I do this?

I've added the fields the order. admin/commerce/config/order/fields. They don't show up on the checkout, but they do show up when the admin tries to edit the order.

I tried setting the fields as required, but the order gets created with these fields blank (this is a bug).

There are no options to add these fields on Checkout Settings admin/commerce/config/checkout.

I am not looking to add fields inside Billing Information nor Shipping Information.

# Answer
> 20 votes
I was able to solve this problem using Commerce Field Group. What you do is:

* create the fields you want.
* create the field group.
* put the new fields inside the field group.

Then

* goto the Checkout Settings (admin/commerce/config/checkout) and add the group inside `Review`

---
Tags: commerce
---


# Question
Title: Where is the logic located which determines the tpl file for the front page?
We are using Drupal 6. When accessing `http://www.mysite.com/`, the tpl file which is displayed is named `page-front_page.tpl.php`. I cannot figure out where the logic is which decides that `page-front_page.tpl.php` will be used for the front page.

I created a second file, named `page-front.tpl.php`, and this will display instead of `page-front_page.tpl.php`, seemingly bypassing `page-front_page.tpl.php`.

Does anybody know how `page-front_page.tpl.php` is defined as a front page? Or is there some sort of automatic URL parsing happening here?

**Edit 1.0:** Please read my comments to answers below for more information.

# Answer
> 3 votes
please review in /includes/theme.inc near to the line `if (drupal_is_front_page()) {`...

```
if (drupal_is_front_page()) {
    $suggestions[] = 'custom-page-front-name-here';
  }

```

I changed the `$suggestions[]` value, and I saw that .tpl.php name to the front page can be customized.

According the comment of nmc,

> this file/code should not be modified as it is part of Drupal core

. this is only to locate where can be stablished the value.

# Answer
> 2 votes
If the URL for the page that you set as front page is example.com/front\_page, then one of the suggestions used by Drupal is "page-front\_page"; this causes Drupal to look for "page-front\_page.tpl.php."

The code that selects that suggestion is in template\_preprocess\_page():

```
  // Build a list of suggested template files in order of specificity. One
  // suggestion is made for every element of the current path, though
  // numeric elements are not carried to subsequent suggestions. For example,
  // http://www.example.com/node/1/edit would result in the following
  // suggestions:
  //
  // page-node-edit.tpl.php
  // page-node-1.tpl.php
  // page-node.tpl.php
  // page.tpl.php
  $i = 0;
  $suggestion = 'page';
  $suggestions = array();
  while ($arg = arg($i++)) {
    $arg = str_replace(array("/", "\\", "\0"), '', $arg);
    $suggestions[] = $suggestion . '-' . $arg;
    if (!is_numeric($arg)) {
      $suggestion .= '-' . $arg;
    }
  }
  if (drupal_is_front_page()) {
    $suggestions[] = 'page-front';
  }

```

For example.com/front\_page, `arg(0)` returns "front\_page" and the suggestion will be "page-front\_page."

That suggestion comes before "page-front"; that means that in the case there is a file named "page-front\_page.tpl.php" it will be used instead of "page-front.tpl.php."

---
Tags: theming
---


title: drupal_add_js and inline code

text:
# Question
Title: drupal_add_js and inline code
I am trying to use inline javascript, added with `hook_alpha_preprocess_page`, to add support to IE.

```
drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            $("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                width: 420,
                columns: 3
            });
        }
  });', 'inline');

```

While this loads on the page, nothing is happening. Is this because my selector starts with $? What should I change it to for this to work?

# Answer
yes it has something to do with your selector starting with $. Your code in your question may have worked in Drupal 6. jQuery has changed in Drupal 7

Try wrapping your function like this:

```
(function ($) {

 // in this function, you can use the $ which refers to the jQuery object

}(jQuery));

```

For more information checkout

http://drupal.org/update/modules/6/7#javascript\_compatibility
> 2 votes

# Answer
First of all you need to replace $ with jQuery and secondly you also need to put the width and coulmn properties inside double quotes. i.e,

```
drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            jQuery("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                "width": "420",
                "columns": "3"
            });
        }
  });', 'inline');

```
> 4 votes

---
Tags: 7, theming, javascript
---


# Question
Title: Validation when having 2 webform in same page?
On Drupal 6, I have 2 different webforms which I have available as 'blocks'. Then I create a 'page panel' and added the 2 blocks. Everything works just fine but I have 2 problems.

1. One comes when sending any of the forms and the validation shows up. Both 'name' inputs are red marked.
2. When the form is correctly sent I'm redirected to the succes page but when I hit the 'back' button it takes me to the webform node instead of the 'page panel'.

# Answer
> 0 votes
1. Try changing the field name of one of the 'name' fields to that they are unique across both forms.
2. You'll need to copy the webform-submissions.tpl.php from the Webform module into your theme, and update the link at the bottom.

---
Tags: blocks, panels, webforms
---


# Question
Title: Add textfield as option for checkbox 'other' entry
I am creating a form using the Drupal 6 Form API and I have a set of checkboxes. One of the options is "Other."

Is there a way to have one of these options be a fillable field? How would I define that in the options array.

Thinking something like:

```
[] Option A
[] Option B
[] Other ___________

```

Any ideas?

# Answer
> 3 votes
The easiest way is to add the Select or Other module.

It lets you define these using the Form API, CCK, Webform and some others.

# Answer
> 0 votes
There is a neat CCK field here: CCK Select Other

I just installed it and it seems to be working fine, but don\`t take my word for it as I see it is still dev. version.

---
Tags: forms
---


title: Drush: Update core from stable to dev

text:
# Question
Title: Drush: Update core from stable to dev
I would like to upgrade from drupal core 7.7 to 7.x-dev, is this possible using Drush?

UPDATE:

Ok, looks like either I needed Drush 4.5, or the process of updating Drush from 4.4 corrected something with the installation, as `drush up drupal-7.x` worked, and I'm noticing that `drush up` now shows all installed modules everytime.

# Answer
> 3 votes
Yes it is. Navigate to your Drupal directory and run the following command:

```
drush pm-update drupal-7.x

```

Note you can use the same tactic to update any module to a development version from a stable version, as well as update a development version to a newer, stable version.

---
Tags: 7, drush, updating
---


# Question
Title: Updating to Drupal 7.x-dev until next stable release
I am currently using Drupal core 7.7 and Commerce 7.x-1.0-rc3 which requires changes that are only currently present in Drupal core 7.x-dev.

If I upgrade to 7.x-dev now in order to get the updates that the latest Commerce version needs, am I committing my project to following dev branch, and is there a danger of not being able to come back to stable cleanly, when the next stable release comes about?

It's not a live site, so temporary instability a dev branch may introduce is not necessarily an issue if I'll end up back on stable soon.

EDIT: Additionally, instruction for how to upgrade core from stable to dev using Drush would be super: Drush: Update core from stable to dev :)

# Answer
> 1 votes
No you are not: the Drupal core development workflow makes minor versions just tags of the main 7.x development branch. Periodically, the branch maintainer decides enough things have been committed to the branch to make a release worthwhile, and a new minor version release is packaged.

So let's say you download a snapshot of 7.x-dev dated 2011-08-15. At the end of the month, Drupal 7.8 is released. Drupal 7.8 would contain all of the changes you had received in the 2011-08-15 snapshot, and anything else committed between that point and the end of the month. It's essentially the same as if you downloaded a new development snapshot on 2011-08-30.

So, if you need to use the dev branch, feel free to do so with relative impunity.

---
Tags: 7, updating
---


# Question
Title: How to put a node in a menu using an URL parameter?
While creating a new node, I'd like to pass a parameter in the URL: `node/add/page?plid=123` in order to put the newly created node in this menu item as its child.

I tried to `hook_form_alter()` the node form but I couldn't populate the menu part, also I'd like to hide this part to the end user as they shouldn't alter it.

Should this be done in a `hook_node_insert()` with something like this answer: How to enable menu link when creating a new node ?

# Answer
`hook_node_insert()` is probably the place to do this. You'll want to call `menu_link_save()` to create the menu item, using the `$_GET` superglobal to retrieve the *plid* parameter.

```
function mymodule_node_insert($node) {
  $item = array(
    'link_path' => 'node/' . $node->nid,
    'link_title' => $node->title,
    'plid' => $_GET['plid'],
  );
  if (!menu_link_save($item)) {
    // It has not been possible to save the menu item.
    // Handle this failure case.
  }
}

```
> 1 votes

---
Tags: 7, routes, nodes
---


# Question
Title: What are the interfaces implemented in the object passed to hook_query_alter()?
Looking at the documentation for hook\_query\_alter(), I see that the parameter is reported to implement QueryAlterableInterface; looking at the code of \_node\_query\_node\_access\_alter(), called by an implementation of `hook_query_TAG_alter()`, I notice that it is using methods not defined in the `QueryAlterableInterface` interface, such as `$query->getTables()`.

If I implement `hook_query_alter()`, or `hook_query_TAG_alter()`, what methods should I use, and which methods can I effectively use?

# Answer
> 2 votes
In core, the `QueryAlterableInterface` interface is extended by the `SelectQueryInterface` interface, which is where you'll find `SelectQueryInterface::getTables()`.

`SelectQuery` and `SelectQueryExtender`, in turn, implement `SelectQueryInterface` and, by extension, `QueryAlterableInterface`.

---
Tags: hooks, database
---


# Question
Title: How do I keep <span thmr="foo"> tags from displaying?
I have a field in a view that shows some HTML tags that, no matter what I do, keep showing up:

What's adding them? How do I get rid of them?

# Answer
> 3 votes
You have the Theme Developer module installed, which adds `<span thmr="foo">` tags to everything.

> Firebug for Drupal themeing. See the screenshot and screencast. Note that this module injects markers into the DOM to do its magic. This may cause some themes to behave erratically and less capable browsers may make it worse (especially IE). Enable it when needed, and disable it afterwards.

The module uses a bit of brute forcing when it comes to adding those tags, and this can cause problems with complex themes that don't go out of their way to support it.

Disable it and they'll go away. You should only have that module enabled during development/debugging, anyway.

---
Tags: theming
---


# Question
Title: Setting View Filter Operator to "Greater Than Or Equal To"?
I have a view for which I've set different exposed filters and users can search for objects of different criteria. However, I want some fields to be searched by "Less than/Greater than or equal to" what the user types. I don't have those options in the operator field. Some people seem to have them however.

# Answer
> 0 votes
The operators you get in a Views exposed form depends on the type of data that is stored. If you store a text string you can't use GT or LT, instead you can use starts with or ends with.

Most likely your problem is that you are storing numbers as text in the database instead of storing them as numbers.

---
Tags: views
---


# Question
Title: Adding assets (css/js) for a custom module block (and withstanding a cache enabled install)
I've created my own block which calls a `hook_theme` implementation which then prepares some data and then renders `myblock.tpl.php`

All of the above is working fine but my module does have some required assets, specifically some css & js files, currently I was `doing drupal_add_css/js` in my `hook_block($delta = 'view')` but I've discovered that both the hook\_block and hook\_theme do not get called when the **Admin \> Config \> Performance - Enable Block Cache** has been turned on.

Obviously when I clear the cache the first load of a page (with my block included) loads all assets properly, but anon-users etc do not see any of my assets.

How should I be including these assets in a way that would withstand caching and only add assets on a page which includes my block?

Thanks!

# Answer
> 1 votes
Modules can report how Drupal should cache the output of a module, through the use of a set of constants.

The constants should be used as in the following example of hook\_block():

```
function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Mymodule block #1 shows ...'),
      'weight' => 0,
      'status' => 1,
      'region' => 'left',
    );
    // BLOCK_CACHE_PER_ROLE will be assumed for block 0.

    $blocks[1] = array(
      'info' => t('Mymodule block #2 describes ...'),
      'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE,
    );

    return $blocks;
  }
  // …
}

```

The constants that can be used are:

* BLOCK\_NO\_CACHE: The block should not be cached.
* BLOCK\_CACHE\_GLOBAL: The block is the same for every user, in every page it is shown.
* BLOCK\_CACHE\_PER\_ROLE: The block could change basing on the roles the user who is watching the page has.
* BLOCK\_CACHE\_PER\_USER: The block could change basing on the user who is watching the page.
* BLOCK\_CACHE\_PER\_PAGE: The block could change basing on the page being viewed.

You could use some of the constants together; for example, if the block changes basing on the page, and the user who is watching the page, you can use `BLOCK_CACHE_PER_PAGE|BLOCK_CACHE_PER_USER`.

In Drupal 7, those constants have been renamed, and a new constant is added; this is the list of the constants used in Drupal 7:

* DRUPAL\_NO\_CACHE
* DRUPAL\_CACHE\_GLOBAL
* DRUPAL\_CACHE\_PER\_ROLE
* DRUPAL\_CACHE\_PER\_USER
* DRUPAL\_CACHE\_PER\_PAGE
* DRUPAL\_CACHE\_CUSTOM

The last constant is used to report to Drupal 7 that the module uses its own cache. For Drupal it has the same effect of using `DRUPAL_NO_CACHE`.

---
Tags: 6, blocks, javascript, theming
---


# Question
Title: drupal_add_js does not add javascript on after_build
I'm using the following line to add JavaScript code to my module form:

```
$form['#after_build'][] = 'myModule_after_build'

```

In `myModule_after_build()`, I add the Javascript code with calling `drupal_add_js('myJavascript','inline')`.

Unfortunately, it seems that the JavaScript code is added only during the first page call. I would like to pass some arguments to JavaScript, and manipulate the content of the JavaScript, according to the options in the form.

Is there any configuration that I can set to add 'myJavascript' with different arguments to every button click?

# Answer
> 1 votes
`#after_build` is called every time the form it built. I've used this myself many times to add JS to forms. Most likely you have a flaw in the script or after build function itself, or you are using cached data when creating the script to display.

If you posted your code, we could provide a better answer.

---
Tags: 7, forms, javascript
---


# Question
Title: EVA + Corresponding Node References + Views + Sort by Order of Appearance on Page Node
Thanks in advance for any help or suggestions with this problem. I will try to be as clear as possible. Basically, what I want to do is customize my Page node "County" to show a table of "Organization" nodes (along with their contact information) referenced in the county node.

So what I have done is to use the EVA + Corresponding Node References modules to create a table view on my county page. The problem is that I cannot figure out how to configure Views so it will list the organizations in the same order that I referenced them in the county node -- See screenshot http://www.diigo.com/item/image/16wo5/0jmw. As you can see from my screenshot I have ordered them first "Org 3" and then "Org 1", but in the views table they are ordered first "Org 1" and then "Org 3".

From reading other posts I suspect that I need to add a relationship in my view but I feel like I have tried almost everything and I still can't get it to sort correctly. Here's a screenshot of my Views admin page -- http://www.diigo.com/item/image/16wo5/x7hr

Thanks again for any help.

-Scott

# Answer
> 1 votes
Ok, I think I figured this out after some ideas I got while researching kalabro's answer. Basically I needed a better understanding of the logic of how EVA works with node references and related objects in views. So here's what I did --

First I changed the contextual filter in my view to "Content: Nid" with a default value of "Content ID from URL". Next I added a relationship to the field "Related Org" (which is the node reference field in my County content type) and did not check "require this relationship. Then I filtered my results to only include County content types and added the "Related Org" relationship to the title and body of my included fields -- except for the first title field (the related county itself) which I used to group the related organization by. Finally, I removed all sort criteria from the table settings and from the sort section.

Here's a screen shot of my views set-up: http://www.diigo.com/item/image/16wo5/7chr

Here's a screen shot of my county view: http://www.diigo.com/item/image/16wo5/r1dx

After thinking about this problem some more I'm not sure that I actually needed to create the corresponding node reference in order to accomplish this. I haven't tested it yet. Also, there may still be some tweaks to this set-up that don't show up because of my limited testing. Still, I feel like I'm on the right path now with a better understanding of how EVA, node references, contexts and relationships work together in views. And I am definitely left with a greater appreciation of the power of Drupal 7.

If anyone wants more details about my set-up please let me know.

Thanks to kalabro for helping me to get started thinking in a different direction.

-Scott

# Answer
> 0 votes
You shouldn't use 2 references at the same time. If you prefer your «Related Org» field, you don't need EVA at all. Just customize display settings for your «Related Org» field.

Help link: http://drupaleasy.com/blogs/ryanprice/2009/08/theming-nodereference-or-reusing-complex-data-drupal

---
Tags: nodes, entities, views
---


title: Secondary Menu Tab (local task)

text:
# Question
Title: Secondary Menu Tab (local task)
I was wondering if there is any good documentation out there on building second level tabs using the menu system. Here is some of the menu code in my module:

```
  $items['admin/settings/cvminterviews'] = array(
    'title' => 'Interview Scheduler',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'cvminterviews_overview_page',
    'access arguments' => array('administer cvminterviews'),
  );

  $items['admin/settings/cvminterviews/overview'] = array(
    'title' => 'Overview',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'cvminterviews_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );

  $items['admin/settings/cvminterviews/interviewers'] = array(
    'title' => 'Interviewers',
    'description' => 'Interviewers',
    'file' => 'cvminterviews_admin_interviewers.inc.php',
    'page callback' => 'cvminterviews_interviewers_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

  $items['admin/settings/cvminterviews/interviewers/import'] = array(
    'title' => 'Import Interviewers',
    'description' => 'Import Interviewers',
    'file' => 'cvminterviews_admin_interviewers_import.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_interviewers_import_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

```

I would like to have

> admin/settings/cvminterviews/interviewers/import

Be a secondary tab to:

> admin/settings/cvminterviews/interviewers

but the above code doesn't seem to do anything with it. Any thoughts?

# Answer
I needed to add the following to my code:

```
  $items['admin/settings/cvminterviews/interviewers/interviewers'] = array(
    'title' => 'Interviewers',
    'description' => 'Interviewers',
    'file' => 'cvminterviews_admin_interviewers.inc.php',
    'page callback' => 'cvminterviews_interviewers_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

```

The important part is to make this the exact same callbacks as the `'admin/settings/cvminterviews/interviewers'` menu item, but with one more level, and assign the `MENU_DEFAULT_LOCAL_TASK` type.
> 0 votes

---
Tags: 6, routes
---


# Question
Title: How to change the machine name of the content type in Drupal 7
I found an annoying typo in the machine name of one of the content types, and I'd like to fix it. The only way I know is to delete the content type, and create a fresh one, but there is a plenty of fields in that content type that I don't want to recreate.

Is there a better way?

# Answer
Go to structure, click content types, click edit next to the content type you want to edit. Click edit next to the machine name and change it to the name you want.

>

>

If you merely want to change the administrative name, then change that instead.
> 16 votes

# Answer
If the name is unique (it probably is if it contains a typo), change all occurrences of the name in the database (including table names) and clear the cache.

In D6 the table `node_type` contains content type machine name definitions. Those names are also used in tables with the prefix `content_type_`. If the content types aren't used anywhere else, changing the entry and the table name should do it. It's possible that those names have changed in D7.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Creating a node programmatically for a user who doesn't have the permission to create nodes of that content type
Let's say user X does not have the permission to create nodes of the content type Y, but the user does something which triggers an action, and this action is supposed to create a node of type Y. Will this be possible?

I want to do this because I don't want the user to manually create content as he could mess things up; I'd rather have this automatically done, hence the user not having permissions to create this type of node.

I'm using Drupal 6.

# Answer
If the code calls node\_save() passing to the function a node object that is associated to user Y (i.e., the value of `node->uid` is the user ID of user Y), the function will save the node without checking if a node of that content type can be created from the user. It is the code that calls `node_save()` that eventually checks if the user has the permission of creating that content type, or it's the code that shows the link to the form for creating a node of a content type that makes the link visible only to users who has the permission to create nodes of that content type.

`node_save()` allows you to save a node that is associated to a user who don't have the permission to create a node of the content type Y; the problem is eventually when the user X doesn't have the permission to update nodes of the content type Y, which would not allow the user to update the node that has been created for him.
> 1 votes

# Answer
IF you're looking for a module, I know rules in D7 can absolutely do this. I believe rules in D6 can do this as well.
> 0 votes

---
Tags: nodes, users
---


title: Views dynamic date

text:
# Question
Title: Views dynamic date
I am trying to setup a view which will return a single nodes data. The idea is only one story type will be created per day.

My view is filtering on "node type: story" and "node:published". As an argument, I have "node:created date". I set it to "provide default argument" and then selected "current date".

Then idea is for the story node for today to be the sole result of the view. And at the stroke of midnight, the view should provide the next day's node or be empty if no such node has been created.

My probel is the view show the current dates node but at midnight, and beyond, I keep getting the same node rather than the next one.

please assist if you are able and I thank you in advance.

# Answer
> 1 votes
This sounds like a views caching problem. If this is the most recent version of views, click the "Advanced Arrow" then under other click "caching" and select "time based". Set the desired amount (not sure why 1 day isn't there, but as long as you do it at the right time, "6 hours" should be fine for both.

If that doesn't work, you can look into disabling caching completely under the views settings tab (serious performance hit), or writing something custom in cron to clear the views cache.

---
Tags: views, datetime
---


# Question
Title: Hierarchical select as radio buttons and checkboxes
I have a need to display a hierarchical select of a vocabulary as a series of radio buttons representing the top-level terms. When the user selects one of the radio buttons, the child taxonomy terms should be displayed below as checkboxes.

Do I need to build a custom AHAH form, or can I look at form altering the default hierarchical select widget?

# Answer
> 1 votes
For drupal 6 you may want to check out the module https://drupal.org/project/conditional\_fields which basically lets you control which form elements depend on other form elements. It also has a handy GUI for doing this.

FYI drupal 7 has completely changed the game here and has implemented 'states api' - here is an example of what can easily be achieved - http://api.drupal.org/api/examples/form\_example--form\_example\_states.inc/function/form\_example\_states\_form/7

# Answer
> 0 votes
I managed to do something like that using Taxonomy Super Select (TSS) for Drupal 6. Here is a quote about it (from the module's project page):

> ... seamlessly overrides the select box generated by the taxonomy module and renders the terms based on if you are allowing multiple selections or not.
>
> **Features**:
>
> * Multiple selection vocabularies show as checkboxes.
> * Single selection terms display as radio buttons.
> * Parent terms display as nested fieldsets
> * Option to display parented terms as form items
> * Ability to control which content types TSS will apply to
> * Works with all hierarchy configurations
> * Free tagging vocabularies are now supported.

---
Tags: 6, taxonomy-terms, forms
---


# Question
Title: CCK field. how to use dynamic names to call CCK fields? (like: $node->$cckname)
I have several cck image fields. Each field has a consecutive name, for example:

**field\_photos\_1**, **field\_photos\_2**, **field\_photos\_3**, **field\_photos\_4** ... until 20

So my question is: How to call the image fields in a loop?

for example (pseudocode:)

```
for($i = 0; $i >= 20; $i++){
$cckname = 'field_photos_'.$i; //$cckname is changing the image field name, then...
echo "<img src='/".$node->$cckname[0]['filepath']."'";
}

```

The question in a general way could be: how to use dynamic names to call fields?

# Answer
> 1 votes
You can't access an array directly from a variable variable class property.

You have two options:

```
for($i = 0; $i >= 20; $i++){
  $cckname = 'field_photos_' . $i;
  $cckfield = $node->$cckname;
  echo "<img src='/" . $cckfield[0]['filepath'] . "'";
}

```

Or typecast the node object as an array:

```
for($i = 0; $i >= 20; $i++){
  $cckname = 'field_photos_' . $i;
  $node_array = (array) $node;
  echo "<img src='/" . $node_array[$cckname][0]['filepath'] . "'";
}

```

# Answer
> 2 votes
You use curly braces `{}` to delimit the variable inside your reference, as

```
for($i = 0; $i >= 20; $i++) {
  $cckname = 'field_photos_' . $i; //$cckname is changing the image field name, then...
  echo "<img src='/" . $node->{$cckname}[0]['filepath'] . "'";
}

```

This syntax is used in many places in Drupal core, see for example hook\_field\_prepare\_translation.

---
Tags: entities
---


# Question
Title: Contextual information on custom Access Denied page
I'm trying to implement my own access denied page, and I'd like to get some information about the context of the access being denied... for example, if the user is on a specific node type page, I'd like to still display a short snippet of that node before the access denied message, so the user knows he's at least in the right part of my site.

However, I can't use `menu_get_object()`, as `arg(0)` simply returns 'access denied' in my page callback. Is there any way of passing in the path information for an access denied page? See my code below:

```
<?php
/**
 * Implements hook_menu().
 */
function custom_menu() {
  $items['access-denied'] = array(
    'title' => 'Access Denied',
    'page callback' => 'custom_access_denied',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}
?>

```

And in my page callback:

```
<?php
/**
 * Access Denied page.
 */
function fn_custom_access_denied() {
  global $user;
  $html = '';

  // Display access denied message and login form for anonymous users.
  if (!$user->uid) {
    $html .= '<p>' . t('The content you are trying to access is protected. Please log in or create an account to view the page.') . '</p>';
    $html .= drupal_render(drupal_get_form('user_login'));
    drupal_set_title('Login Required');
  }

  // Display access denied message for logged-in users.
  if ($user->uid) {
    $html .= '<p>' . t('The content you are trying to access is protected.') . '</p>';
    drupal_set_title('Private Content');
  }

  return $html;
}
?>

```

# Answer
Supposing that the site is using clean URLs, I would rather use the following code:

```
function fn_custom_access_denied() {
  $path = drupal_get_normal_path(trim($_SERVER['REQUEST_URI'], '/'));

  if (($node = menu_get_object('node', 1, $path)) && ($node->type == 'event')) {
    drupal_set_message(t("%event is a private event.", array('%event' => $node->title));
  }

  return "";
}

```
> 2 votes

# Answer
I eventually found that I could get at the original query string by accessing the $\_SERVER\['REQUEST\_URI'\] global, but I wish I could get the information in a more drupal-y way...

Here's how I did it in the page callback:

```
<?php
$arguments = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
// If the content is node content, display contextual information.
if (is_numeric($arguments[1]) && $node = node_load($arguments[1])) {
  if ($node->type == 'event') {
    $html .= '<div class="messages warning">' . t("<strong>!event</strong> is a Private Event.", array('!event' => $node->title)) . '</div>';
  }
}
?>

```
> 1 votes

---
Tags: hooks, users
---


# Question
Title: How do I handle a dynamic domain i.e. www.(dynamic|.*).(com|org|ca|etc ...)
So here is the deal, I recently started working on a site, actually three sites that have been split into three drupal installations. These sites have the same function but different appearance. So my thought was to merge them with different themes. Now I have a new issue, two of the three sites are going to allow for others to use their own urls. So www.hiya.com would point to my www.example.com.

Each of these new domains is in our db with what theme it is supposed to be. My first impulse is to look up the site, and change theme in `hook_theme()`. There are some logic differences but worst case scenario I would just use a session variable to deal with those

I am new to drupal and wanted some thoughts, opinions, criticisms, wild accusations, etc...

# Answer
> 1 votes
I've seen this done three different ways. Here they are, from basic to advanced:

1. Use Drupal's built-in multisite support by setting up different sites in the sites/ folder. This is sort of the "standard" way, and you'll end up needing things like the Features module.
2. Use Domain Access and all of its modules. This allows you to do all kinds of sharing between multiple sites, and you can generally accomplish a lot with very little coding. Ken Rickard, the owner of that project, will bend over backwards to help you, and you can typically ping him in IRC #drupal-contribute.
3. A custom module that intercepts the request early in the process (hook\_boot, hook\_init, and other places in D7) can often give you a chance to initialize the theme layer (and sometimes other subsystems) in a request-specific way. This is how we do our mobile version of our site (in D6), which uses the same nodes and stuff, but has much different template logic.

# Answer
> 0 votes
The Domain Access suite of modules is designed to address these kinds of design challenges.

---
Tags: uri
---


# Question
Title: Display twitter tweets for own account in drupal 6
Suppose My twitter account is drupaltest so I want to display all the mentions of #drupaltest or @drupaltest on the Drupal 6 website. Looking at the twitter module http://drupal.org/project/twitter but that one is a little confusing. So let me know whats the best way to post tweets for your accounts on the Drupal 6 website? I am not looking for any reverse functionality of posting on twitter through my website, just want to display those tweets.

Thanks.

# Answer
> 1 votes
The easiest way is definitely to install the Twitter module that you have already discovered. I used to do this on my website as a way of pulling in tweets to my blog. You will only need the read-only configuration for the module, and you may find it easiest to use the Views integration.

If you'd rather code your own, the QueryPath module allows you to write jQuery-like requests directly against Twitter's API, but you'll have to write your own module. (You can start with the sample modules that come with QueryPath).

# Answer
> 1 votes
I'm not familiar with the Twitter module, but I know Twitter has a profile widget at http://twitter.com/about/resources/widgets/widget\_profile which will generate javascript you can use to insert a twitter block on your site.

---
Tags: 7, social-network
---


# Question
Title: Why wouldn't hook_form_submit be called?
```
function mymodule_reviewer_node_form($node, &$form_state) {
global $school;
if ($school) {
    $form['field_reviewer_school']['#value'] = array(array('nid' => $school));
    $form['field_reviewer_school']['#access'] = FALSE;
}
  return $form;
}

function mymodule_reviewer_node_form_submit($node, &$form_state) {
}

```

The form gets submitted successfully, but form\_submit never gets called. What might cause this?

# Answer
> 1 votes
The form should be:

```
   function  mymod_reviewer_node_form($form_state) {
     $form = array();

     // Build the form...

     return $form;
   }

```

The submit handler should be:

```
   function mymod_reviewer_node_form_submit($form, &$form_state) {
     // Do something with $form_state['values'] or whatever
   }

```

And make sure that whatever is rendering the form passes through `drupal_get_form()`.

Finally, one tricky bit: Make sure you are not accidentally overriding a hook. `mymod_form()`, for example, implements `hook_form()`, which is probably not what you really intend to do.

I find that nine times out of ten, if the submit handler is not being called, it's because I named the function incorrectly.

---
Tags: 6, forms
---


# Question
Title: How to create a confirmation page linking to the content just created by a user
I would like to create a page that that user sees once it has submitted a new piece of content. That page will provide a link to the page that the user has just created, allowing them to share that link through various social networks.

What is the best way to implement something like this? I am not using a webform. The user is allowed to submit an unlimited number of content.

Thanks, Lauren

# Answer
> 1 votes
use Rules module http://drupal.org/project/rules, you can build a new rule to redirect (to a new page) the user when create, for example, a node. see examples to Drupal 6 http://drupal.org/node/298483 or Drupal 7 http://drupal.org/node/878712

specifically, I suggest that you review events like 'After saving new content' or/and 'After updating existing content' , then you can launch task (or add conditions to the task and lauch the task) according your needs. Seems that 'Page redirect' Action can be useful.

---
Tags: nodes
---


# Question
Title: Detecting if site is inside iframe - loading custom CSS
I would like to add an extra stylesheet for my site if it's being embedded inside an iframe on another site.

I found a JS method to try detecting an iframe embed over here: https://stackoverflow.com/questions/326069

Basically, you can run a script like:

`if (top === self) { not in a frame } else { in a frame }`

But I was wondering if it's possible to have that code add a stylesheet to the page in Drupal. Or maybe if there were some way to do it in Drupal, in hook\_init() or something, that would be even better...

A final method I could think about is using the JS above to maybe add a URL parameter like `?embed=TRUE` so I can detect that and add a stylesheet... but that would require a refresh inside the iframe :-/

# Answer
You could...

* munge the `window.location` object to add the additional param, but that will force the page to reload. From there you can access the param in Drupal and write server-side code to do a `drupal_add_css()`.
* Use jQuery (which comes with Drupal) to add the CSS directly.
* Use jQuery to add a link to the remote stylesheet.

Example of the third method:

```
if (top !== self) {
  var cssURL = 'http://example.com/my/stylesheet.css';
  $('head').append('<link rel="stylesheet" href="' + cssURL + '"/>');
}

```

I would think that as long as you can predict the stylesheet name, the last option is going to be the most elegant.

Note that you would want to add the JavaScript to the document with `drupal_add_js()` in Drupal.
> 1 votes

---
Tags: theming
---


# Question
Title: Custom Views filter for multi-level taxonomy
I'm struggling to set up two kinds of views for displaying multi-level taxonomy. One would list terms that are final nodes, and the other would list nodes that have children. Somehow, I can't.

I stated that what I really need is a filter criterion "Content: Has taxonomy terms (with depth=1) which have children". Does anyone know of a module/add-in that would add such a filter criterion, or perhaps knows how to define a native Views equiv (I'm still too fresh to say if that is possible).

Thanks Artur

# Answer
> 3 votes
in Relationships you add:
Taxonomy: Parent item

then in Filters add:
Taxonomy: Term ID, set Relationship to the above Parent, and the Operator: Is empty(NULL)

This way you only get the top level terms, because they don't have parents. Or you set it to Not empty(NOT NULL) to get the child terms.

I hope this method helps you in some way.

---
Tags: 7, taxonomy-terms, views
---


# Question
Title: How do I add a My Account Item to a New Menu?
Hi I need to add a My Account link to a new menu. I know about me aliases module and others, but I would like to do it using my own code. Any ideas ?

**Update:** I am using Drupal 6. Is it possible to use the My Account provided by the user module in a differente menu than Navigation ?

# Answer
> 0 votes
You can move the "My account" item from the navigation menu. Visit /admin/build/menu-customize/navigation, and click the edit link for "my account".

# Answer
> 1 votes
```
/**
* Implementation of hook_menu().
*/
function mymenu_menu() {
$items['user/%user_uid_only_optional'] = array(
'title' => 'My account',
'title callback' => 'user_page_title',
'title arguments' => array(1),
'page callback' => 'user_view_page',
'page arguments' => array(1),
'access callback' => 'user_view_access',
'access arguments' => array(1),
'menu_name' => 'your-menu',
);
return $items;
}

```

# Answer
> 0 votes
Assuming you know the name of the menu you want to modify, you can do this programmatically.

The best function to start with is `menu_link_save()`. The entire API is explained here:

http://api.drupal.org/api/drupal/includes--menu.inc/group/menu/7

(change the 7 to 6 if you want the D6 version)

You should be able to create a link to the user's page by simply sending the user to `/user`.

---
Tags: 7, routes
---


# Question
Title: Why Isn't #value valid for 'textfield' form types in Drupal 7?
I can set `#default_value` but there is no `#value` for text fields?

http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html/7#textfield

Is there a work around?

# Answer
> 4 votes
Form API is an abstraction over regular HTML form elements, so there are cases where attributes don't match up exactly.

In the context of Form API, `#value` is for values you don't want the user changing, and doesn't make sense with respect to text `<input>` controls.

Instead, you want to use `#default_value`, which is for values you *do* want the user to change. That is:

```
$form['mytextfield'] = array(
   'type' => 'textfield',
   '#default_value' => 'Foo',
);

```

is the same as:

```
<input type="text" value="Foo" />

```

If you want to mimic the behavior of Form API's `#value` (i.e. provide a default value and prevent the user from changing it), use the `#disabled` property:

```
$form['mytextfield'] = array(
   'type' => 'textfield',
   '#default_value' => 'Foo',
   '#disabled' => TRUE,
);

```

For more information about the internals, check out `form_builder()`, which constructs the render array for the form and `_form_builder_handle_input_element()`, which replaces `#value` with the value of `#default_value` prior to rendering.

---
Tags: 7, forms
---


# Question
Title: How do I add a template suggestion for a node based on the current view?
I have a view that lists a bunch of nodes of a certain content type. I want to style this list of nodes in a way that I can't do easily with the standard node.tpl.php that they're being rendered with. I'm trying to override my themename\_preprocess\_node function to add a template suggestion depending on what view the nodes were called from. I tried this:

```
<?php
  function themename_preprocess_node(&$variables)
  {
    // Add theming based on view name. If the view is named
    // 'featurefront' one of the template suggestions will be
    // 'node-view--featurefront.tpl.php'.
    if (isset($variables['view']))
    {
       $variables['theme_hook_suggestions'][] = 'node_view__'.
            str_replace('_', '--', $variables['view']->name);
    }
  }
?>

```

but it doesn't work because $variables\['view'\] isn't ever set anywhere. Basically my question comes down to this:

What variable can theme\_preprocess\_node use that will tell it the name of the current view or whether it was called from a view at all?

# Answer
You can leverage the `views_get_current_view()` function to get the current view being rendered. I haven't tested the code below, but it should get you close to what you are trying to do. Note that it could have unintended consequences if nodes are being rendered somewhere else on the page.

```
function themename_preprocess_node(&$variables)  {
  if (($view = views_get_current_view()) && 'featurefront' == $view->name) {
    $variables['theme_hook_suggestions'][] = 'node_view__' . $view->name;
  }
}

```

Views doesn't set template variables for nodes, which is why the technique above has to be leveraged.
> 2 votes

---
Tags: views, nodes, theming
---


title: Nodehierarchy and access control...

text:
# Question
Title: Nodehierarchy and access control...
This webcast has a walkthru of NH; it includes the NH.Access module. I assume that he is using 6.x, as a lot of stuff is still very much beta'ish in 7.x, including NH.

I'm wondering if there is a module that gives me the ability to assing a permission to a node and its children.

My current setup is replacing a "Per-node" permission system, so the current Node Access grant is acceptable. I would like to progress into a "Per-Hierarchy" permission, so that a user can create children and maintain them without my intervention.

I just want to be sure I'm not missing a "related module" that's functional.

# Answer
> 2 votes
You might consider the Workbench Access module: It is a hierarchy based approach to grants; it might be a much better match for your use case, and it can use a number of different hierarchy management tools, such as the Menu system, Taxonomy, etc.

---
Tags: 7, users, nodes
---


title: How do I manually slide a carousel?

text:
# Question
Title: How do I manually slide a carousel?
I am using jCarousel as below:

```
jcarousel_add('#jcarousel',
  array('vertical' => false, 'scroll' => 3, 'horizontalDirection' => $direction, 'initCallback' => 'slCarousel_initCallback')
);

```

How can I manually slide the carousel?

When I run `jQuery("#jcarousel").jcarousel().next();`, in Firebug I get the following:

```
>>> jQuery("#jcarousel").jcarousel().next();
[]

```

I have tried this as well in the Firebug console:

```
var carousel = jQuery("#jcarousel").data('jcarousel');
//alert (carousel);
carousel.next();

```

I got the following:

```
>>> var carousel = jQuery("#jcarousel").data('jcarousel'); carousel.next()
TypeError: carousel is undefined

```

# Answer
> 2 votes
I fixed it by creating a global variable, and then assigning the value of the carousel to it.

```
var global_jc="";
function slCarousel_initCallback(carousel) {
  global_jc=carousel;
  // ...
}

```

Wherever I want to use `next()`, I use the following code:

```
global_jc.next();

```

# Answer
> 1 votes
According to jCarousel Docs you need to use

```
var carousel = jQuery("#jcarousel").data('jcarousel');

```

You can then use controls (as demonstrated at this example)

```
carousel.next()

```

---
Tags: javascript
---


# Question
Title: Problem with calling drupal_get_form from an AJAX callback
So, I have a paged, AJAX-enabled list view of entities. As a part of the entity build process for rendering, an AJAX comment form is built, rendered and attached to it.

Now, when I move to the second page in the view (retrieved via AJAX), the comment form shows up but the AJAX property is not attached to it anymore. I used Drupal 7's #ajax on the submit button. Also, the form action is now set to views/ajax when I want it to be the same as the original page. Any way to get around these two issues?

# Answer
Ensure that `Drupal.attachBehaviors()` is called from your AJAX callback. See Drupal 7 JavaScript API for more details.
> 2 votes

---
Tags: ajax
---


title: How do I change certain page titles?

text:
# Question
Title: How do I change certain page titles?
How do I change certain page titles in Drupal, most notably the *create new account*, *log in*, and *request new password* tab headings?

# Answer
> 2 votes
If you want to change the strings used in Drupal, you can use string overrides: Add code similar to the following one, at the bottom of the settings.php file used by your Drupal site.

```
$conf['locale_custom_strings_en'] = array(
  'forum'      => 'Discussion board',
  '@count min' => '@count minutes',
);

```

The description given for strings overrides in the settings.php file is the following:

> String overrides:
>
> To override specific strings on your site with or without enabling locale module, add an entry to this list. This functionality allows you to change a small number of your site's default English language interface strings.

# Answer
> 3 votes
you can `create a module`. inside the module you can use the function form\_alter to modify the form, and specifically use the function `drupal_set_title()` to add the title, for example:

create a module with the name "change\_title". add a form\_alter function (note that the name of the module is added to the \_form\_alter name function)

```
function change_title_form_alter(&$form, &$form_state, $form_id) {

 //dsm($form_id) this function is to know the $form_id

   if ($form_id == 'content_type_node_form') {
       drupal_set_title('this is my new title');
   }

}

```

note: about how to get the $form\_id value, you can use Devel module to use the function dsm($form\_id), then the return of this function will show you the $form\_id value.

# Answer
> 2 votes
The String Overrides module will do this.

From the project page:

> Provides a quick and easy way to replace any text on the site.

It also has versions for both D6 and D7.

---
Tags: 6
---


# Question
Title: Get this jQuery Youtube Playlist working?
Drupal 7. I'm trying to get this to work - seems simple enough. I added the .js file through my theme's .info file, and it's picking that up. I selected "Full HTML" as the format for my block, and pasted the code in (both the js and the ul). Just doesn't work.

http://www.geckonewmedia.com/blog/2009/8/14/jquery-youtube-playlist-plugin---youtubeplaylist

Any ideas? I suspect the js needs to be loaded somewhere else, that maybe it's being stripped out from the block code?

---

Per SoftArtisans (thanks) this is now what I have in the Body of my custom block (set to full HTML):

```
    <script type="text/ecmascript">

(function ($) {
  $("ul.aintv").ytplaylist({addThumbs:true, autoPlay: false, holderId: 'ytvideo'});
}(jQuery));

</script>

<div class="yt_holder">

<div id="ytvideo"></div>

  <ul class="aintv">
    <li><a href="http://www.youtube.com/watch?v=QBBWKvY-VDc">Video 1</a></li>
    <li><a href="http://www.youtube.com/watch?v=ZXMQqLnRhRI">Video 2</a></li>
    <li><a href="http://www.youtube.com/watch?v=Wvo-g_JvURI">Video 3</a></li>
  </ul>

</div>

```

It's still not working. I verified the other .js file is being picked up in the source.

# Answer
Remove your JS path from the .info file and try something like this (replace /path/to/yourscript.js with the path to your script):

```
jQuery.noConflict();

jQuery(document).ready(function($){
   $.getScript('/path/to/yourscript.js', function() {
        $("ul.demo1").ytplaylist();
   });
});

```

This dynamically loads your JS when the DOM is fully loaded and it makes sure that `$` can be used without conflicting with other libraries.
> 1 votes

# Answer
In Drupal, you can't just call jQuery quite like that. The reason is mostly because there my be other JavaScript libraries in use so jQuery is not aliased as `$()` in Drupal. For more details on that you can view the Drupal Docs about JavaScript compatibility, or the specific issue in the queue.

The solution is to wrap your jQuery code as described in the Drupal docs page linked to above. In your case it would look something like this...

```
(function ($) {
  $("ul.demo1").ytplaylist();
})(jQuery);

```
> 5 votes

# Answer
jquery.youtubeplaylist.js uses directly `$` instead of jQuery. Contrary to what is said above, you have to modify that plugin and replace all `$` by `jQuery`.
> 1 votes

# Answer
It seems like you are trying to make a Drupal Module when there is already something that does this out there. Check out http://drupal.org/project/mediafront which is a video/img/music skin that works with the Media Module, Media:YouTube & Media:Vimeo Modules for url pasting (which you are looking for).

Bonus is there is a video http://www.mediafront.org/dallas-drupal-days-2011-presenting-media where the person who made the module is presenting. He demos pasting in urls at 44 minutes.

This module is written in jQuery (like the one you are trying to use) and is set up for Drupal so you don't have to figure out the configurations and is so amazing your mind will be blown.
> 0 votes

---
Tags: 7, javascript, files
---


title: Views exposed taxonomy hierarchy

text:
# Question
Title: Views exposed taxonomy hierarchy
I have a taxonomy with 4 categories; each category has child-categories beneath them.

This taxomony term is exposed in a view filter, but I get a combination of the parent and child categories in the resulting dropdown list options. What I actually want is just the parent-categories listed and not the child-categories.

Can anyone help?

# Answer
Never mind!

I just discovered the "limit list to selected items" check box which solved my problem. It does mean I have to manually select the taxonomy terms I want visible. So, it's not a fully automated solution but it will do for now.
> 2 votes

---
Tags: taxonomy-terms, views
---


# Question
Title: Which modules should I use to create a community based site?
I am a grey-haired professional programmer, quiet conversant in PHP, MySql, HTL, CSS which means I can tweak things or code plugins if need be, but I’d like something off the shelf as far as possible.

I am trying to create a social site for ex-pats to help them adjust to their new country. Preparing to get there, legal/visa issues, employment opportunities, accommodation, shopping, plus social stuff.

The demographic is mainly girls in their 20s, so a social angle is important. Integration of FaceBook, Flikr & the like might be nice. What I am thinking of is

* main content provided by me and a few moderators
* a Wiki to which everyone can contribute
* forums for discussions
* small ads/freebie
* user registration (which may limit access to certain parts of the site)
* groups of friends, with shared .. stuff (photos, discussion rooms, etc)
* per user blog
* per user photo album
* mailing lists

As I said, I was originally set on Drupal, which also has some pre-configured distros, but I didn’t find one yet that really matches my needs.

Do you have any suggestions?

# Answer
> 3 votes
If you mostly want to configure, a distribution is probably your best bet. Looking at your requirements, I'd say take a look at Drupal Commons. It will get you most of the features you need, and you can turn on/off features as needed. The rest of your feature set can be added with specific modules.

# Answer
> 1 votes
this book is about how to build a comunity with Drupal 6

http://book.drupalfun.com/

I guess that will give interesting suggestions about steps, modules, integrations, configurations and some "best practices". (review the 'Table of contents' to see list of modules and other topics).

# Answer
> 1 votes
We use Commons for many of the features you've described. And yes, features can be turned off, although Commons does have some core module dependencies (as most distributions do).

The only requirements I see in your list that would require additional work are the per-user photo album (you can do this with views) and mailing lists (there are a number of good mailing list integration modules that provide integration for the biggest mailing list apps, including PhPList, MailChimp and ConstantContact).

---
Tags: 7, theming
---


# Question
Title: How do I execute my custom submission handler before any other submission handler?
I want to execute my custom submission handler for a button before any other submission handler associated with that button. How could I do this?

# Answer
> 2 votes
You should add it at the first position in handlers array.

```
$form['actions']['submit']['#submit'] = array_merge( array('your_form_submit'), $form['actions']['submit']['#submit']);

```

# Answer
> 2 votes
array\_unshift() the name of the function onto the "#submit" array of the button.

---
Tags: forms
---


title: Where do I add a jQuery UI in Drupal 7?

text:
# Question
Title: Where do I add a jQuery UI in Drupal 7?
I have a view where I want to use the jQuery UI slider. For the moment, I've just put the following in my template.php:

```
drupal_add_library('system', 'ui.slider');

```

This doesn't feel right.

Is there a better place to put something like that, or at least do a check so it only get loaded when it is needed?

# Answer
> 1 votes
Ok, you can use preprocess functions for views.

1. Drupal 6 - Add Javascript to a View
2. Programmatically set a css class of a view
3. Using views preprocesses to add css and js to a view

---
Tags: views, theming, javascript
---


# Question
Title: Share a value between two different hooks
I have 2 hook functions in my module: `hook_views_pre_render()` and `hook_form_alter()`; in `hook_views_pre_render()`, I retrieve some data about what nodes that are available that I need in `hook_form_alter()`.

I'm looking for a way to pass the data from `hook_views_pre_render()` to `hook_form_alter()`. It seems simple, but I can't get it to work. Does anyone any idea?

What works for the moment is to add `global $aVariable` to both the hook functions, but I believe there should be a better way.

# Answer
you can use `variable_set($name, $value)` and `variable_get($name, $default = NULL)`
> 3 votes

# Answer
In Drupal 7, drupal\_static() could be used too, if the stored value doesn't need to be persistent between different pages.

`drupal_static()` is normally called as `drupal_static(__FUNCTION__, $default_value)`, but if you use the name of the function, you can access the same value accessed from the function that calls `drupal_static()`.

Using `variable_set()` and `variable_get()` the value is persistent between different pages, and it is not automatically removed. If the first hook execute code similar to the following one, then the second module would get an older value.

```
if ($condition) {
  variable_set($variable_name, $value);
}

```

Rather than using such code, the first hook should execute code similar to the following one.

```
if ($condition) {
  variable_set($variable_name, $value);
}
else {
  variable_del($variable_name);
}

```

Whatever method you choose, be sure the hook reading the value is effectively running after the hook setting that value.
> 8 votes

# Answer
If you need to pass information that is only available in `hook_views_pre_render` to `hook_form_alter` a global variable might be your best option; preferably named to make it's restricted role clear, e.g., `_mymodule_available_nodes`.

The best approach would be to add your data to any objects the two calls have in common. In this case unfortunately there there appear to be none in common, so this won't work.

You might be able to use session data, but that would be overkill for this application, and doesn't seem to offer clear benefits over a global.

I don't recommend using variable\_set/variable\_get. `variable_set` clears the variable cache on every call, plus all variable values are fetched on every page request. This is not a good match for data that is constantly changing, and of potentially large size.
> 0 votes

---
Tags: hooks
---


title: Block Naming Issue

text:
# Question
Title: Block Naming Issue
I used Theme Developer module to find the candidate name for a block that I'm using and it gives me this candidate name: block\__menu\_block\__1 But it doesn't take action when I name as block--menu-block-1.tpl.php . I've tried several other variations to no avail, and I have cleared my cache. What would I name this block?

# Answer
Checkout the template suggestions: http://drupal.org/node/1089656

It should be: block--menu-block--1.tpl.php
> 5 votes

# Answer
When translating from a suggestion to a template filename, Drupal replaces every underscore with an hyphen; in this case, "block\__menu\_block\__1" becomes "block--menu-block-−1.tpl.php" (there is a hyphen more than you used).

The code that converts underscores in hyphens is in drupal\_find\_theme\_templates().

```
if (!isset($info['base hook']) && !empty($pattern)) {
  // Transform _ in pattern to - to match file naming scheme
  // for the purposes of searching.
  $pattern = strtr($pattern, '_', '-');
  // …
}

```
> 2 votes

---
Tags: 7, theming, blocks
---