title: Drupal File Uploads

text:
# Question
Title: Drupal File Uploads
I am implementing a custom form with file uploads and having trouble getting the form to post the files.

Here is my form code for the input:

```
for ($x = 1; $x <= $photo_count; $x++) {
    $form['photo_'.$x] = array(
      '#type' => 'file',
      '#name' => 'files[' . implode('_', $form['photo_'.$x]['#parents']) . ']',
      '#title' => t('Choose a file'),
      '#title_display' => 'invisible',
      '#theme_wrappers' => array(),
    );
  }

```

$photo\_count is a variable set in the config settings for this module, so they can change the amount of photos a person can upload whenever.

In my validate:

```
foreach ($form_state['values'] as $key => $value) {
    if (preg_match('/photo_/', $key)) {
      $file_key = file_save_upload($key, array(
        'file_validate_is_image' => array(), // Validates file is really an image.
        'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
      ));
      // If the file passed validation:
      if ($file_key) {
        // Move the file, into the Drupal file system
        if ($file_key = file_move($file_key, 'public://temp_uploads')) {
         // Save the file for use in the submit handler.
         $form_state['values'][$file_key] = $file_key;
        } else {
         form_set_error($file_key, t('Failed to write the uploaded file the site\'s file folder.'));
        }
      }
    }
  }

```

Except when I dump $form\_state on the validate/submit steps, it's always empty, and file\_save\_upload returns NULL.

I looked at a few examples on how to do this, and I think I have everything I need, but something is wrong. The form ENCTYPE is set to multipart, too. My form is multistep, implemented with CTools Wizard if that matters.

Edit:

If I dump $\_POST and $form\_state, there are no values for files. However, if I dump $\_FILES, the files I chose are in the array and I can operate on them. Why are they not making their way into the POST or $form\_state in Drupal?

# Answer
I could not find a way to capture uploads into the Drupal Form API without looking at `$_FILES` and taking them that way. I still do not see files in `$form_state` values.
> 1 votes

---
Tags: 7, forms, chaos-tool-suite, files
---


title: Decode entities in node titles

text:
# Question
Title: Decode entities in node titles
I have a few node titles that are being saved with & and displaying that way too.

Is there any way to not encode them while being saved? I tried:

```
$node = node_load(727);
$node->title = html_entity_decode($node->title);
node_save($node);

```

I dump out the node and the title is corrected, but is not saved that way. Should I only try to correct the display using the same function?

# Answer
> 1 votes
Filter input, escape output. You can't be sure that everything in your database is safe.

---
Tags: 7, security
---


# Question
Title: How to display $date in node.tpl.php using a preprocess function in template.php
I want to check if the node is not a static page, and display `$date` in "node.tpl.php" within this `<div>`:

```
<div id="postDateArea"></div>

```

I currently have this in my node.tpl.php file:

```
<div id="postDateArea"><?php print $date; ?></div>

```

I currently have this in my template.php file:

```
function thebridge_preprocess_node(&$vars) {
  if($vars['type'] != 'static_page') {
  }
}

```

# Answer
> 3 votes
```
function thebridge_preprocess_node(&$vars) {
  if($vars['type'] != 'static_page') {
    $vars['date'] = date('Y-m-d');
  }
}

```

You might want to change the parameters of date(). More information in the Drupal documentation.

# Answer
> 3 votes
You can use the format\_date function:

```
function thebridge_preprocess_node(&$vars) {
  $vars['date'] = format_date($vars['node']->created);
}

```

There are more parameters to `format_date`, most important the 'custom' format which allows for a custom PHP `date()` format.

```
function thebridge_preprocess_node(&$vars) {
  $vars['date'] = format_date($vars['node']->created, 'custom', 'F j');
}

```

---
Tags: 7, theming
---


title: Collapsible fieldset misbehaviour

text:
# Question
Title: Collapsible fieldset misbehaviour
For weeks now I have been using collapsible fieldsets to display a particular node type field without problems. Sometime during the last week it inexplicably stopped working. Collapsible fieldsets still work correctly for core stuff (e.g. module listing) and the legend element appears as it used to, only the fieldset is collapsed (as it should be) and can't be expanded (the legend isn't clickable). Inspecting the HTML I can see that the value that should be in the fieldset is indeed there. What's extra curious is that in the Views GUI the fieldsets work correctly but not on the frontend of the same view.

Edit: I have been using collapsible fieldsets successfully outside of views on manually created content. This is the first time I try to use them in a view and it was how I discovered they'd ceased to function, both on the view I'm working on and the PHP code I've written myself. As per Laxman13's post, collapse.js is not being loaded on my own pages for some reason.

# Answer
> 3 votes
This sounds like the necessary JS file is not being loaded. Check Firebug or Developer Tools, etc to see if collapse.js is being added to the `<head>` of the page. The file can be found at YOUR\_DRUPAL\_ROOT/misc/collapse.js

---
Tags: views, 6
---


# Question
Title: How to share Drupal code across multisites that are each in subdirectories?
I have two websites on my own server (I have full control of the Apache config, etc.)

I want to install Drupal 'into' each of them, in a subdirectory of the site root.

I'd like to share a Drupal codebase between the two.

And, I'd like to have the URLs appear without the subdirectory.

My problem is I can't figure out how to do all at once.

I can get to this easily,

```
/src/www
  /website1
    /drupal1
       ...
       sites/website1.com/themes/website1.com
       ...
    /other_stuff_1a
    /other_stuff_1b
  /website2
    /drupal2
       ...
       sites/website2.com/themes/website2.com
       ...
    /other_stuff_2a
    /other_stuff_2b

```

But I'm not sure how to share the Drupal7 code in this case. Do I have to use symlinks or something?

I'd appreciate any help or ideas.

Frank

# Answer
> 1 votes
Drupal come with already a multi site feature, you ca read more about it here.

After, if for some reasons you don't want install Drupal with multi-site and keep the both separate in your server, you can still use Git or SVN and co.

The idea is simple, you've the same codebase for development and multiple `clone` or `checkout` in your server. For example, in your case it will be `drupal1` and `drupal2`.

---
Tags: installation, multi-sites
---


title: How to implement a taxonomy view?

text:
# Question
Title: How to implement a taxonomy view?
I would like to show a list of taxonomy terms and include:

* number of nodes that are linked to this term
* datestamp of latest node with author and title that is linked to this term

Can this be done in a view, or do I need a custom query? From a performance standpoint, wouldn't it be better to save that info in taxonomy fields?

# Answer
Try to create a **View** using grouping.

Set **Format** to ***Table***
Go to **Settings** \> ***Grouping field*** = "***Tags***" (your taxonomy term field)

Field "Tag" should have this setting:

* Exclude from display \[X\]

There are some modules I didn't try that could help you with adding summary field to your Views:
> 1 votes

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


title: Show Media Preview Image on Views

text:
# Question
Title: Show Media Preview Image on Views
I want to show the Preview Image from Media Youtube videos in Views. But I can't figure out how to display them in views. Is it supported? How?

# Answer
Figured it out: visit **admin/config/media/file-types** and pick the file type you want to edit (Youtube media are Videos). Pick one of the file displays (Small, Big, Original) and enable the Youtube Preview Image display. Finally, pick an image style in the dropdown menu.

Then, visit the Manage Display tab. If you previously chose the Small file display, for example, edit the Display to make sure the File will be shown.
> 4 votes

---
Tags: 7, views, media
---


# Question
Title: Is there a way to print out a list of all possible template files for a page?
Including template files used for views, rows, blocks, etc. on that page?

# Answer
> 3 votes
I suggest review Theme Developer module http://drupal.org/project/devel\_themer, it will help to find possible templates that can help to modify (theming) specific parts of your site.

in this resource http://drupal.org/node/209561 you will find how to use the module.

---
Tags: 6, theming
---


# Question
Title: Why doesn't print module_invoke('user', 'block', 'view', 0); use template files?
If I invoke the user login block using module\_invoke it doesn't use block-user-0.tpl.php. If I drop the block in the right sidebar and print $right it does use block-user-0.tpl.php.

Also, why will it only print the block once so that printing $right and module\_invoke only results in one login form?

# Answer
> 1 votes
The code `module_invoke('user', 'block', 'view', 0)` eventually calls `user_block('view', 0)`. The user\_block function returns an array in this case; that's just how hook\_block works. The documentation for hook\_block says:

> If $op is 'view': return an array which must define a 'subject' element (the localized block title) and a 'content' element (the block body) defining the block indexed by $delta. If the "content" element is empty, no block will be displayed even if "subject" is present.

If you want to know how to render this block, check this comment on the theme\_block documentation page.

# Answer
> 0 votes
1st:

Call

```
 print drupal_get_form('user_login_block');

```

2nd:

Drupal marks each printed element with

```
$elements['#printed'] = TRUE;

```

so any content cannot be rendered twice. You can modify this value if you need to render twice any element.

---
Tags: 6, blocks
---


# Question
Title: Where are the "Publishing options" for a node stored in the database?
I need to order a column in a custom module by whether the node is published or not. Can't figure out where this is being stored in the database.

# Answer
> 4 votes
It's the status field in the node table (in Drupal 7).

---
Tags: database, users
---


# Question
Title: Issue with drupal_add_css, can do it by nid but not by alias
I am using the drupal\_add\_css function in my template.php file (Drupal 6) and this code works:

```
if (arg(0)=="node"&&arg(1)=="74" ) {
drupal_add_css(drupal_get_path('theme', 'mythemename') . '/css/slider.css', 'theme');
  }

```

However if I use this code, it does not work.

```
if (arg(0)=="web-portfolio") {
drupal_add_css(drupal_get_path('theme', 'mythemename') . '/css/slider.css', 'theme');
  }

```

I am wondering what I am doing wrong. (note "mythemename" is used in place of my actual theme name here and the actual aliased path is example.com/web-portfolio

# Answer
if http://example.com/web-portfolio is the path alias for http://example.com/node/74, when you call `arg(0)` and Drupal is visualizing http://example.com/web-portfolio, the function doesn't return "web-portfolio" as you would think, but "node" because `$_GET['q']`, the variable used by `arg()`, is changed using the following code:

```
  // Drupal 6.
  // This code is part of drupal_init_path().
  if (!empty($_GET['q'])) {
    $_GET['q'] = drupal_get_normal_path(trim($_GET['q'], '/'));
  }
  else {
    $_GET['q'] = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
  }

```

```
  // Drupal 7.
  // This is the code of drupal_path_initialize().
  if (!empty($_GET['q'])) {
    $_GET['q'] = drupal_get_normal_path($_GET['q']);
  }
  else {
    $_GET['q'] = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
  }

```

The only way to get the path alias is to call drupal\_get\_path\_alias() as `drupal_get_path_alias($_GET['q'])` (Drupal 6), or `drupal_get_path_alias()` (Drupal 7).

If you are going to use `$_SERVER['REQUEST_URI']`, remember that the string contained in `$_SERVER['REQUEST_URI']` can vary from "/web-portfolio" to "/?q=web-portfolio" (when the clean URLs are not enabled), or from "/dr61/web-portfolio" to "/dr61/?web-portfolio" (when Drupal is installed in the "dr61" directory of the web root directory). It could also change basing on which server is used to run Drupal (e.g. IIS versus Apache).
> 1 votes

# Answer
arg() doesn't work with path as far as I know. I'm sure there are better aproaches to doing this, but I found a bit of a hack.

```
if(strstr($_SERVER['REQUEST_URI'], "web-portfolio")) {
  drupal_add_css(drupal_get_path('theme', 'mythemename') . '/css/slider.css', 'theme');
}

```

I wouldn't use this however its not really the Drupal way. You are adding CSS for a slider, I guess that slide is made with views. You could just make your drupal\_add\_css call from the views template. That way you'll have it even if you change the path.
> 1 votes

# Answer
Normally, I get the path this way

```
$path = drupal_get_path_alias(request_uri());

```

I use request\_uri because it is best to program to the interface and not the specific implementation. drupal\_get\_path\_alias also gets called to handle cases where a page has multiple aliases, but global redirect isn't enabled.

You can then use `$path` for your test if you still want to do conditional includes.

Personally, I add all CSS and JS to all pages via the theme info file, or w/o a conditional in a `hook_init` if from a module.
> 0 votes

---
Tags: theming
---


# Question
Title: Embed a single webforms different fields in to two different pages - Drupal 6
In Drupal 6 , I have a webform which asks for basic info like the Name and email. Then on the basis of if the user is a special user (asked with option button) will choose to ask more questions if they are one else will not ask anything else.

I have created 2 webforms to do that. Is there a way to do that with only 1 webform? More so is it possible to embed the remaining fields in to a different page.

Thanks.

# Answer
Have not received an answer So based on my research I believe the Webform paging can solve this problem since it can display the webform in two parts.
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: Slideshow Question - Slider for images uploaded to a node
I am building a review web page. I want to be able to upload 3-5 pictures for the product to be reviewed and have those images displayed as a slideshow within the product node. Pictures are uploaded and stored as a CCK field.

I have been able to get the Views Nivo Slider to get to work for my homepage slider, but I'm not sure it if is possible to use it to build a slideshow for fields within the same node.

Is there a way to use Views Nivo Slider to showcase the uploaded images for the product node? If not, can you recommend another slideshow module?

# Answer
While I haven't specifically used Views Nivo Slider, I have used Views Slideshow to display uploaded CCK images in a view. The trick here is to use Arguments (or Contextual Filters, depending on which Views UI you're using) from the current nid, with a view that is set to display image fields.
> 1 votes

---
Tags: entities, media, files, javascript
---


# Question
Title: What is the difference between template_preprocess_search_result() and template_preprocess_search_results()?
I am seeing 2 functions like `template_preprocess_search_result()` and `template_preprocess_search_results()` in Drupal 7. I just got confused on which function I should use when modifying my search results.

Can anyone tell me what the basic difference between these 2 functions is?

# Answer
`template_preprocess_search_result` is to process variables for `search-result.tpl.php` which will render output for each of the search result independently.

`template_preprocess_search_results` is to process variables for `search-results.tpl.php` which will render output after each of the search result is already rendered through `search-result.tpl.php`

For example, if there are 4 search results. for each of the results `search-result.tpl.php` will be used. and at the end `search-results.tpl.php` will be used. Ending up using `search-result.tpl.php` for 4 times for each of the results and `search-results.tpl.php` only once at the end.

Hope that is clear.
> 10 votes

# Answer
It depends what you want to change.

The one could be used for changing the markup for the actual result, for example headline + trimmed description, while the other is for all the results for example list, table or divs.

So you might need to use one or both, or maybe just use template files.
> 2 votes

---
Tags: 7, search, theming
---


# Question
Title: How can I use Entity API to integrate my entities with views?
I've set my entity up with a custom controller but I want views integration. I tried to follow the entity\_test.module example, but it's for one bundle. I want to create 4 bundles for my entity. When I check views it does not appear in the list.

Here is my code:

```
function module_entity_info() {
  $return['module_content'] = array(
    'label' => t('Module Content'),
    'module' => 'module',
    'entity class' => 'ModuleContentClass',
    'controller class' => 'EntityAPIController',
    'views controller class' => 'EntityDefaultViewsController',
    'base table' => 'module_content',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'cid',
      'bundle' => 'type',
    ),
    // Make use of the class' label() and uri() implementation by default
    'label callback' => 'entity_class_label',
    'uri callback' => 'entity_class_uri',
    'static cache' => TRUE,
    'bundles' => array(),
    'bundle keys' => array(
      'bundle' => 'type',
    ),
    'view modes' => array(
      'full' => array(
        'label' => t('Full content'),
        'custom settings' => FALSE,
      ),
      'teaser' => array(
        'label' => t('Teaser'),
        'custom settings' => FALSE,
      ),
    ),
    'module_property' => array(
      'label' => t('Property'),

      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
    'module_agent' => array(
      'label' => t('Agent'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
    'module_open_house' => array(
      'label' => t('Open House'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
    'module_office' => array(
      'label' => t('Office'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
  );

  return $return;
}

function module_entity_info_alter(&$entity_info) {
  foreach (module_content_get_types() as $type => $info) {
    $entity_info['module_content']['bundles'][$type] = array(
      'label' => $info->label,
    );
  }
}

function module_content_get_types($type = NULL) {
  $types = entity_load_multiple_by_name('module_content', isset($type) ? array($type) : FALSE);
  return isset($type) ? reset($types) : $types;
}

```

I think something is wrong with either `module_content_get_types()` or `module_entity_info_alter` because when I try to use dpm statements in those functions nothing is output. Please advise on any changes that should be made to improve my entity definition. If you need to see additional code I can provide that as well.

# Answer
You dont create views integration for bundles but for entities. The reason is that each bundle by definition stores it's core data the same way.

Think of node types = bundles. When you create a view you select to use nodes (Content) not if you want to use articles, pages, blog posts etc.
> 3 votes

---
Tags: 7, views, entities
---


# Question
Title: how to set an absolute position to a view (or div class)?
I have 2 views that displays ads on both sidebars of the page. on top of one of them, is another view that displays articles. the view that displays articles can be a height of anywhere between 20px, and 200px, depending on how many articles there are at the time. I need the ads underneath it to be aligned with the ads on the other sidebar. If I use something like margin-top, it will only work if there are the same amount of articles throughout the life of the site. I was hoping to do something like anchor the view to the bottom, or to set a specific position to put the view.

# Answer
> 1 votes
If you have the div's parent element set to position: relative, you can then set the ad div to be position: relative and give it and offset from the bottom. eg. bottom: 20px; You will need to be careful that your article list div doesn't expand over the space where your ads are as they will overlap. Post a link if you need more help. Hope this helps.

---
Tags: views, navigation, theming
---


# Question
Title: How do I implement the autocomplete functionality in Webforms?
I have a drop down box with college names that has 9000 options to choose from. I am unable to use the drop-down field in Webforms.

Is there a way to use an autocomplete in a text field for Drupal 6?

# Answer
> 2 votes
> Autocomplete is implemented in Drupal through AJAX. When users type into a textbox, code on the client page dynamically loads new data from the server (a Drupal website) and uses this data to update the user display (provide a drop-down list of matching options, which the user can select from).

Available autocomplete functions (D6):

* user\_autocomplete() - Use this function to load matching user names.
* taxonomy\_autocomplete() - Use this function to load matching taxonomy terms.

If you want to have your own autocomplete function it is also possible. Please see a full article on this subject on drupal.org "Textfield that uses autocomplete" to see how to build a custom autocomplete function.

---
Tags: javascript, webforms, ajax
---


# Question
Title: Calendar popup field get a default value. How to avoid this?
I have all necessary module to add "Calendar popup" fields to my nodes.

When creating a new node this field is populated with the current date. Since this field is not mandatory I need it empty by default.

I can´t figure out how to accomplish this. Please help.

I upload a capture

# Answer
> 2 votes
Edit the date field in your Content Type. There should be a `MORE SETTINGS AND VALUES` accordion that drops down to reveal more options including `DEFAULT VALUES`. Set the default value to *No Default Value*. You probably have it set to *Now*.

---
Tags: 7, datetime
---


# Question
Title: Custom user registration email - Drupal 6
I want to add image icons for Facebook, Twitter etc with associated links and Join Us hyperlink like Join Us to the user registration email.

Can anyone give me idea?

# Answer
you can create and send system html emails using mimemail module and a wysiwyg editor http://drupal.org/project/mimemail (or even http://drupal.org/project/htmlmail )
> 1 votes

# Answer
You can control the content of registration emails through the Drupal admin interface...
D6: http://example.dev/admin/user/settings
D7: http://example.dev/admin/config/people/accounts

There are a number of different templates for various emails sent out to users. By default, these emails are in plain text. You'll need a module (like HTML Mail) to enable sending HTML emails. Then, you should be able to edit any of the built-in user email templates to include images and links.
> 1 votes

---
Tags: media, users, navigation, emails
---


# Question
Title: Best approach to create a troubleshouting section?
I am looking to create some kind of troubleshooting section on a website. Sort of like the Windows help with some sections, questions and answers.

I was thinking of doing this with a regular Book, and write a small form module which allows me to track the page with a "Was this information helpful or not?" question.

But are there possible alternatives, either existing modules or an approach which works best?

# Answer
> 1 votes
If you go down the book route then you can always use the flag module for the "Was this information helpful".

There is also the FAQ module which doesn't quite fit your use case but might be worth checking out just in case.

---
Tags: 7, forms, nodes
---


# Question
Title: How to load a user field in template_preprocess_comment()
I added a country field to users and want to show it below the username on comments (in the Bartik theme). How can I load that field into the `bartik_preprocess_comment()` function?

# Answer
Drupal already loads the user object. You can see the user object on that function:

```
function bartik_preprocess_comment($variables) {
  $user = $variables['user'];
  // Full load user
  $user = user_load($user->uid);
  // Now access your field
  $country = field_get_items('user', $user, 'field_country');
  if ($country) {
    $variables['author_country'] = $country[0]['safe_value'];
  }
  else {
    $variables['author_country'] = '';
  }
  // On your comment.tpl.php using $author_country
}

```
> 5 votes

# Answer
template\_preprocess\_comment(), the preprocess function that is called before `MODULE_preprocess_HOOK()` and `THEME_preprocess_HOOK()`, uses `$variables['user']`, but from the code it is using, I take that variable contains the user object for the user who is viewing the comment; differently the CSS class it is adding would not be "comment-by-viewer" (`$comment->uid` is the user ID for the author of the comment).

```
if ($comment->uid === $variables['user']->uid) {
  $variables['classes_array'][] = 'comment-by-viewer';
}

```

If you want to load any field associated with the user who created the comment, you can use `$comment->uid`, and pass it to `user_load()`. In fact, `template_preprocess_comment()` contains the following code, which means that `$comment->uid` is the user ID of the user who created the comment; once compared with `$variables['node']->uid`, the code is able to say that the comment was created by the node author.

```
if ($comment->uid == $variables['node']->uid) {
  $variables['classes_array'][] = 'comment-by-node-author';
}

```
> 3 votes

---
Tags: 7, theming
---


# Question
Title: Using a select form field for the field that selects the groups where a node is posted
The form for creating a node for the content type that has been set as content type for the Organic Groups module has checkboxes for choosing the groups where a node is posted; I want to use a select form field instead of the checkboxes.

How should I alter the form field?

I have tried some patches from drupal.org, but they do not works correctly.

I have used the following code.

```
/**
 * Helper function; Make the groups audience accept only a single group.
 */
function og_single_group_form_alter(&$form, $form_state, $form_id) {
  if (module_exists('og_access')) {
    $path = drupal_get_path('module', 'og_single_group');
    drupal_add_js($path . '/og_single_group_hideoption.js');
  }

  if (!empty($form['og_nodeapi']['visible']['og_groups']) && ($form['og_nodeapi']['visible']['og_groups']['#type'] != 'value')) {
    $options = array();
    $options = array(t('Personal blog')) + $form['og_nodeapi']['visible']['og_groups']['#options'];
    $form['og_nodeapi']['visible']['og_groups']['#type'] = 'select';
    $form['og_nodeapi']['visible']['og_groups']['#multiple'] = FALSE;
    $form['og_nodeapi']['visible']['og_groups']['#options'] = $options;
    // Add own submit handler so we can cast the groups back to an array.
    $form['#submit'][] = 'og_single_group_submit';
  }
}

 /**
  * Submit handler; Since we permit only a single group per content, we need to
  * case to groups into an array
  */
function og_single_group_submit($form, &$form_state) {
   if (!empty($form_state['values']['og_groups']) && !is_array($form_state['values']['og_groups'])) {
     $form_state['values']['og_groups'] = drupal_map_assoc((array)$form_state['values']['og_groups']);
   }
  else if (empty($form_state['values']['og_groups'])) {
    $form_state['values']['og_groups'] = array();
  }
}

```

The code causes the following error:

> Warning: array\_filter() \[function.array-filter\]: The first argument should be an array in /var/www/mysite/sites/all/modules/contrib/og/og.module on line 1303.

# Answer
I am replying basing on what you wrote in the comment to your question.

Organic Groups shows checkboxes or a select field basing on the number of groups that are listed in the "Audience" form field. If the number of groups is less than 20, the module will use checkboxes; otherwise, it will use a select box.

There is no way to change which form field is used, except using a module that alters the form fields added by Organic Groups. The following code, contained in og.module, is the code that adds the audience form field to the node edit form.

```
// show multi-select. if less than 20 choices, use checkboxes.
$type = $cnt >= 20 || $is_optgroup ? 'select' : 'checkboxes';
$max_groups = variable_get('og_max_groups_'.$node->type,'');
$description_max_groups = ($max_groups && !user_access('administer nodes')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
$form['og_nodeapi']['visible']['og_groups'] = array(
  '#type' => $type,
  '#title' => t('Audience'),
  '#attributes' => array('class' => 'og-audience'),
  '#options' => $type == 'checkboxes' ? array_map('filter_xss', $options) : $options,
  '#required' => $required,
  '#description' =>  format_plural(count($options), 'Show this post in this group.', 'Show this post in these groups.') . $description_max_groups,
  '#default_value' => $groups ? $groups : array(),
  '#required' => $required,
  '#multiple' => TRUE);

```

It is enough to have a module that executes the following line, and the form field will always use a select box to show the list of groups to which associate a post.

```
$form['og_nodeapi']['visible']['og_groups']['#type'] = 'select';

```

The code needs to be executed inside the implementation of `hook_form_alter()`, or `hook_form_FORM_ID_alter()`.
> 2 votes

# Answer
Inside the Spaces module there is the Spaces OG module. This removes the "audience" field, and makes it appear where you can only post to a single group.
> 0 votes

---
Tags: organic-groups, nodes
---


# Question
Title: Specifying CCK Field for Filter Processing
In Drupal 6, I have a custom filter, and I would like it to process a field other than the body field, depending on the content type. Is it possible to have it process other fields?

For example, for a page I'd like `hook_filter()` to be passed the body field as `$text`, but for a custom content type, I'd like it to be passed a different field. Is this possible?

# Answer
> 1 votes
It is not possible.
An implementation of `hook_filter()` is invoked not only for nodes, but also for comments, CCK fields, etc. When it is invoked, the hook doesn't know in which case it is being called, and it only gets the content of the text that needs to be filtered; it cannot understand from that if the text is the body of a node, or it is the content of a comment, nor does it get a reference to the object containing the text that needs to be altered.

The function that calls the implementations of `hook_filter()` is check\_markup(), which is then called by other functions, such as:

As you can see, the input filters are called by `user_comment()` for rendering the signature of the user, and another module could use the input filters for rendering text for which an administrator user decides which input format users can use.

---
Tags: hooks, input-formats
---


# Question
Title: How can I find out what's denying permission to access a path?
user/uid/edit is giving permission denied where uid = the current user's uid. The permissions all look correct. Is there any way to find out what exactly is denying the permission?

# Answer
> 0 votes
Users should always be able to edit their own profile. The access callback used for "user/%user\_category/edit" is user\_edit\_access(), which contains the following code:

```
return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;

```

When the currently logged-in user tries to edit his/her account, the function returns `TRUE`, which means s/he has access to the edit form.

There could be a third-party module that altesr the access callback for that menu item, and which is using code that doesn't allow the currently logged-in user to edit his/her own account, or that doesn't consider such a case.

---
Tags: 6, users
---


title: Term name of current node in title

text:
# Question
Title: Term name of current node in title
I'm trying to echo out the current term name that my node is inside of into my function, but it only keeps echoing out 1 and not the name. This is what I have.

```
function bartik_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);

    if (drupal_is_front_page()) {
      $variables['head_title'] = implode(' - ', $variables['head_title_array']);
    }
    elseif (node_is_page()) {
      $terms_name = print $term_name->name;
      $variables['head_title'] = implode(' - '.$terms_name.' - ', $variables['head_title_array']);
    }
  }
}

```

can anyone help?

# Answer
> 3 votes
Your code is using the following line:

```
$terms_name = print $term_name->name;

```

You are assigning to `$terms_name` the value returned by `print $term_name->name`, which is 1.
If you try executing `$var = print "ciao";`, you will notice that the value assigned to `$var` is 1.

The other issue with that code is that `$term_name` is not a variable defined from the code you showed; executing that code, you get an "access to a not defined variable" error.

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


# Question
Title: How do I set my custom module to use a template for a specific page?
I have created a custom module that adds some form elements to nodes of specific content types. Another part of this module requires a specific formatting output of data that is a little more complex than using `$form['']`.

How can I tell my module that for a specific function, it should load a certain template file?

# Answer
> 1 votes
Template files are associated with theme functions. To use a template, the theme function that is declared in hook\_theme() must report that it is using a template file, and this is done adding the "template" property.
For example, the following definition used from the Node module says to Drupal that for the "node" theme function, it needs to use the "node.tpl.php" template file; every times a module calls `theme('node', …)`, Drupal will know to use that template.

```
function node_theme() {
  return array(
    'node' => array(
      'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
      'template' => 'node',
    ),
    // …
  );
}

```

For a page that is visible on http://example.com/parcels, Drupal checks for a template file named "page-parcels.tpl.php" exists, and use it in that case. The template files are looked in the directory of the currently set theme, though; this mean that the template is not found if it is in the directory of a module.

---
Tags: theming, 6
---


# Question
Title: Unable to get CKEditor to work using Drupal 7
I've installed the Wysiwyg module for Drupal 7, as well as the latest CKEditor, configured the settings, and yet it refuses to appear! I've gotten other editors to work but they're not as good.

I'm the only one using the site so I don't have to configure permissions right?

I would have thought this would be one of the simpler things to do in Drupal!

Any help greatly appreciated.

# Answer
I thought the directions were quite confusing, so I agree that this should be easier. The problem is that you need two downloads, and one of them is a wrapper for the other.

Here's what I did that works on Drupal 7.7 and 7.8:

1. Download CKEditor 3.6.1 from http://ckeditor.com/download
2. Download CKEditor 7.x-1.3 from http://drupal.org/project/ckeditor
3. Unpack CKEditor 7.x-1.3. This will create a folder called CKEditor
4. Unpack CKEditor 3.6.1. This will create a folder called CKEditor2
5. Move the contents of the CKEditor2 folder into the CKEditor subfolder of the CKEditor that was created in step 3. This subfolder should have a file called COPY\_HERE.txt in it (Yes, I know this is confusing)
6. Delete the CKEditor2 folder
7. Upload the contents of the CKEditor folder to your /sites/all/libraries folder. If you've done this correctly, the Libraries folder will have ckeditor-rtl.css, ckeditor.api.php, ckeditor.config.js, a number of other individual files, AND a CKEditor folder that contains a number of files (one of which should be the all-important ckeditor.js)

Hope this helps. I wish it were simpler. (TinyMCE is easier to install.)
> 2 votes

# Answer
Here are the steps that worked for me on Drupal 7.7

1. Instal the WYSIWYG module and enable
2. Download the latest CKEditor and unzip it in sites/all/libraries
3. Go to configuration =\> wysiwyg and choose the editor for the input format (use it on the full HTML or PHP)
4. Now you can edit and there you can choose under buttons and plugins what buttons appear
5. When you create a content type don't forget to set the correct text format

btw a while back I had a problem where the WYSIWYG used the background from my site. I had to change the CSS settings, below buttons and plugins, and set it to use editor default.
> 3 votes

---
Tags: wysiwyg
---


# Question
Title: Drupal version control - professional development
I have been assigned to develop a site in Drupal. I will be working on it alone. Is there a need for version control? An if yes which is optimal for drupal? How should I set the development process? (ex:make a testing site locally, then get it live). Thank you in advance.

# Answer
> 3 votes
If you've got a complex setup, you may want to look into the Aegir project, which is a Drupal-based tool for managing Drupal site installations.

If your needs aren't big enough to require Aegir, a lot of the tasks which it does can also be automated using Drush, which is a command-line tool for managing a Drupal site.

Even if you feel Aegir is overkill, you should definitely use Drush - it will make your life a *lot* easier when it comes to deployment between your development and live versions and management thereafter.

As for version control: If you're writing any of your own code, then yes, you should be using version control. If you're simply using Drupal plus third-party modules, then you probably don't need it, since you're not in charge of the code anyway. But you might find it useful nonetheless, because there's always a chance you might find yourself needing to tweak a third party module (or even the core) to get things to work the way you need to, and at that point you will need version control, and it will help if you already have it set up.

You can't very easily do version control on your site content, because it's all in the Drupal database. You can do a certain amount by moving your site structure from database to code using the Features module, at which point it becomes possible to version control it in the same way as other code, but your actual content remains in the database.

To do version control on content, the main option you have is the Diff module, which allows the database to store multiple versions of page content, which can then be administered.

Hope that helps.

# Answer
> 3 votes
Version control is always required. The best i would say is GIT. There are multiple ways of deployment e.g. DOG(Drupal On Git) and a few others.

You can use gitflow also for deployment.

Make use of makefiles and installation profiles if you want your instance to be redistributable.

Make use of features to maintain db changes that you make on your local in sync with the staging or testing server.

Read about the above stuffs mentioned. Comment if you need any more info.

Hope this helps.

# Answer
> 2 votes
I developed a few Drupal 6 and Drupal 7 sites and in my opinion the first thing you should provide to your site is a robust way to backup and restore it quickly in case of issues (especially after the site has gone live!).

To accomplish these tasks there are a couple of modules:

Backup and Migrate and Backup and Migrate Files (still in dev but functional).

Another interesting feature is the content revisions which will give you the opportunity to roll back to a previous version of a node. It is available every time you create/edit a node.

Working locally have some advantages like speed for example but I work both locally and remotely (hosted somewhere in the wild!) and trust me, it is going to happen all the time that you will need to upgrade a module or make some live changes on a prod site so my choice is again for a smooth and fast backup and restore (database and files/dirs structure) process.

good luck and happy drupaling! :)

# Answer
> 1 votes
My feeling is that version control is ALWAYS needed. Even if you are working alone, and don't have to coordinate with others, the knowledge that your files are safe, and any changed can quickly and easily be rolled back, is invaluable.

So just for your own peace of mind, use VC. I use SubVersion, which has very nice integration with Windows, NetBeans (my preferred IDE) and almost everything else. There are even do-everything-for-you installers for many platforms.

To deploy, I commit from my development machine, check out to a test server, then check out the tested site to production.

---
Tags: version-control
---


# Question
Title: Overiding homepage template problem. "page__front.tpl.php" won't be loaded
I am trying to overriding the homepage by creating a template file named "page\__front.tpl.php"; I placed it under the theme folder where page.tpl.php lives.

After refreshing the site, the homepage still loads "page.tpl.php" instead of "page\__front.tpl.php."
The cache and the theme registry are cleared.

# Answer
> 1 votes
The template filename should be "page--front.tpl.php"; you should use hyphens, not underscores.

---
Tags: 7, theming
---


# Question
Title: What function should I use to truncate a string?
What function should I use to truncate a string in Drupal 5?

# Answer
truncate\_utf8() is present in all Drupal versions; just check that the parameters are the same.
> 3 votes

---
Tags: 5
---


title: Form #redirect not working?

text:
# Question
Title: Form #redirect not working?
I'm trying to make the user creation form redirect back to the home page when you submit it. I'm using Content Profiles so it is two forms sharing a submit button. Even if I set #redirect = '/' on both forms the form always redirects back to itself. It works and everything, but won't redirect how I want.

Any ideas?

Code:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
      switch ($form_id) {
        case 'user_register':
        $form['#redirect'] = '/';
        break;
        case 'coordinator_node_form':
        $form['#redirect'] = '/';
    }
}

```

# Answer
There are two facts to keep in consideration about `$form['#redirect']`:

* `$form_state['#redirect']`, set in a form submission handler, takes the precedence over `$form['#redirect']`.
* `$form['#redirect']` and `$form_state['#redirect']` are ignored for forms where "#action" has been set by a module. That is what happen with the user login form.
* `$form['#redirect']` and `$form_state['#redirect']` are ignored when `$_REQUEST['destination']` is set; its value is instead used.

If you want to redirect a form, and be sure it gets redirected to the path you set, you should implement `hook_form_alter()` to add a form submission handler that alters `$form_state['#redirect']`. The module implementing that hook should be executed after other modules that alter `$form_state['#redirect']` for that module.
This doesn't have any effect, though, in the last two cases I listed before.
> 7 votes

# Answer
Ok after much digging I found the answer here: http://drupal.org/node/934664

Apparently destination overwrites #redirect so I just unset destination and it works.
> 4 votes

---
Tags: 6, forms, users
---


title: Can't get hook_menu to work

text:
# Question
Title: Can't get hook_menu to work
Can't seem to get hook\_menu to work at all. I'm using the following code:

```
function mymodule_menu(){
  $items = array();

  $items['node/%node/mymodule-product'] = array(
    'title' => 'Edit Product',
    'page callback' => 'mymodule_product_redirect',
    'page arguments' => array(1),
    'access callback' => 'edit any commerce product entity',
    'weight' => 6,
    'type' => MENU_LOCAL_TASK,
  );
  dsm('check');
  return $items;
}

```

`dsm()` from the devel module is outputting fine when I clear the site cache, so the hook is firing, however for whatever reason the link is refusing to display on the node tabs.

Visiting any of the node tabs already displaying, outputs the following errors:

```
Notice: Undefined index: access in _menu_translate() (line 778 of includes/menu.inc).
Notice: Undefined index: access in menu_local_tasks() (line 1892 of includes/menu.inc).

```

And manually going to a page that would be defined in hook\_menu outputs a load more errors in the same vein:

```
Notice: Undefined index: access in _menu_translate() (line 778 of includes/menu.inc).
Notice: Undefined index: access in menu_get_item() (line 464 of includes/menu.inc).
Notice: Undefined index: access in menu_execute_active_handler() (line 499 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_local_tasks() (line 1845 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).

```

While these are all only PHP Notices, I assume they still may be relevant.

Thanks!

# Answer
> 5 votes
'access callback' needs to be a function name. The function should return TRUE or FALSE;

From the API:

> "**access callback**": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user\_access() unless a value is inherited from the parent menu item; only MENU\_DEFAULT\_LOCAL\_TASK items can inherit access callbacks. To use the user\_access() default callback, you must specify the permission to check as 'access arguments' (see below).
>
> "**access arguments**": An array of arguments to pass to the access callback function, with path component substitution as described above. If the access callback is inherited (see above), the access arguments will be inherited with it, unless overridden in the child menu item.

This means you could ommit 'access callback' and use 'access arguments' instead:

```
// This will be true for users with the access content permission
'access arguments' = array('access content');

```

---
Tags: 7, routes, hooks
---


# Question
Title: How to disable adsense for this error page
I want to disable adsense ads for this url: http://www.indiacustomercare.com/node/167/submission/274

which is accessible only to the admin.

How can I do it for my D6 site?

# Answer
> 2 votes
use the Adsense module, you can specify pages where to display it or not to display it using :

Show AdSense on specific pages:

* Show on every page except the listed pages.
* Show on only the listed pages.
* Show if the following PHP code returns TRUE (PHP-mode, experts only).

---
Tags: 6
---


# Question
Title: How can I override JavaScript settings used by a contributed module?
I am using the Fivestar module for rating purpose in my project.
In that module there is a function called `fivestar_add_js()`, which is used to add the necessary terms to Javascript. The function is given below:

```
function fivestar_add_js() {
  static $js_added = FALSE;

  // Add necessary javascript only once per page.
  if (!$js_added) {
    $settings = array(
      'titleUser' => t('Your rating') .': ',
      'titleAverage' => t('Average') .': ',
      'feedbackSavingVote' => t('Saving your vote...'),
      'feedbackVoteSaved' => t('Your vote has been saved.'),
      'feedbackDeletingVote' => t('Deleting your vote...'),
      'feedbackVoteDeleted' => t('Your vote has been deleted.'),
    );

    drupal_add_js(drupal_get_path('module', 'fivestar') .'/js/fivestar.js');
    drupal_add_js(array('fivestar' => $settings), 'setting');
    $js_added = TRUE;
  }
}

```

In that function I need to replace the word from vote to rating.
How can I do this?

# Answer
Ok, the title is a little misleading here. You actually want to override a JavaScript *setting*, not a *file*. The difference is that settings are inline on a page.

The strings are processed through t() so there are "proper" ways to do replacement.

Putting this in your "settings.php" file should work.

```
$conf["locale_custom_strings_en"] = array(
  "Saving your vote..." => "Saving your rating...",
  "Your vote has been saved." => "Your rating has been saved.",
  "Deleting your vote..." => "Deleting rating vote...",
  "Your vote has been deleted." => "Your rating has been deleted.",
);

```

In Drupal 7, I think you need to change the first line to

```
$conf["locale_custom_strings_en"][""] = array(

```

I believe you can also use String Overrides to accomplish the same thing, but I don't have direct experience with this module.
> 2 votes

# Answer
As those strings are passed to `t()` the faster way to rewrite those strings is to overwrite then in the settings.php file, using something similar to the following code (write only the code for the Drupal version you are using):

```
// Drupal 6.
$conf['locale_custom_strings_en'] = array(
  'Saving your vote' => 'Saving your rating',
  'Your vote has been saved' => 'Your rating has been saved',
  'Deleting your vote...' => 'Deleting your rating...',
  'Your vote has been deleted.' => 'Your rating has been deleted.'
);

// Drupal 7.
$conf['locale_custom_strings_en'][''] = array(
  'Saving your vote' => 'Saving your rating',
  'Your vote has been saved' => 'Your rating has been saved',
  'Deleting your vote...' => 'Deleting your rating...',
  'Your vote has been deleted.' => 'Your rating has been deleted.'
);

```
> 2 votes

---
Tags: javascript
---


# Question
Title: Control content access whilst creating content
Is there a way to control access during the content creation process?

With the Content Access module I can setup access controls for individual nodes of the same type, but only after I have created that content.

Could this process be integrated into the content creation process for the sake of intuitiveness.

# Answer
**Workbench, Workbench Access** and **Workbench Moderation** modules could help you with access control and content management.

**Workbench** improves content management for Drupal 7. It has more then 1200 reported installs.

Workbench allows to :

* simplify the user interface for content creators and editors limiting training and support time.
* control who has access to edit any content based on an organization's structure not the website structure
* customize editorial workflow that integrates with the access control feature described above or works independently on its own

**Workbench Access** Workbench Access provides hierarchical permissions across "Sections" of your website. You can use menus, taxonomy or create your own hierarchical structure for controlling access to the content.

**Workbench Moderation** provides editorial workflow. It is a flexible system. It provides default workflow states like Drafts, Needs Review, and Published. You can also change these states to suit your needs.
> 2 votes

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


# Question
Title: Why isn't my new module listed in the list of modules?
I am trying to build a new module, but, it is not listed in the list of modules.

This is the content of the add\_new\_chapter.info file:

```
;$Id$

name = Chapters field
description = Will create a field that will refrence a node of type chapter type
package = Online School Development
core = 7.x
files[] = add_new_chapter.module

```

I placed the add\_new\_chapter.info file in the directory "add\_new\_chapter" at drupalroot/sites/all/modules/add\_new\_chapter.

what I expect is to see a new category ("Online School Development") in the page listing the modules but it doesn't get listed.

I tried to clear the Drupal cache, but the module didn't get listed too.

# Answer
> 1 votes
The first things I would check:

1. Permissions settings of the files (chmod - chown)
2. Remove a module to see if it has any effect

# Answer
> -1 votes
Yes, install the Devel module and set it to rebuild the theme registry on every page load.

Do **not** forget to turn this off on your production site. It will increase page load times for your users. Use it just for development.

---
Tags: 7
---


# Question
Title: How to add custom field to the user profile according to its role in Drupal 7?
i need to add some custom fields to the user. These fields are not the same for every user, but they vary according to their roles. How can i do that?

I saw that you can add some custom fields in the configuration menu but those cannot be differentiated according to the role.

# Answer
> 2 votes
**User role field** module allows you to specify role-specific fields. When creating a new field, you specify what roles this field is enabled for.

Fields are only visible and editable if a user has a specific role.

This role does not determine access controls for visible fields. You could use the **Field Permissions** module for setting access controls.

More then 120 sites currently use this module.

---
Tags: 7, users
---


title: How to disable status messages?

text:
# Question
Title: How to disable status messages?
I am creating/updating terms and nodes dynamically using code. It shows a lot of status message as usual. But I need to hide those message only for this task. That means if any user creates/updates terms or nodes it will show the status message.

How can I do that? Please note that the task will run by cron, so a lot of status massage will be stacked for display. Obviously nobody wants to be the poor person to see the huge list of status messages.

# Answer
take a look to Disable Messages module http://drupal.org/project/disable\_messages I think that could be useful for your needs.

> Features
>
> ```
> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.
>
> ```
> 4 votes

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


# Question
Title: Modifying a module's function from another module
A particular module has a theme function (`theme_nice_menus_build()`) that I'd like to give a slightly different output; I'd rather not modify the .module file to be able to continue updating the module when new versions are available.

Is it possible to modify that function from another custom module or from template.php?

# Answer
All theme functions can be overwritten in template.php by replacing theme with phptemplate. so your function in template.php should be like

```
phptemplate_nice_menu_build

```
> 1 votes

---
Tags: theming
---


# Question
Title: How can I control the order of Drupal.behaviors?
I want the JavaScript code from module X to run only after the one from module Y has run. Whats the best way to do this?

# Answer
The JavaScript code used by Drupal 7 is the following:

```
Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.attach)) {
      this.attach(context, settings);
    }
  });
};

```

Drupal 6 uses similar code:

```
Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
    jQuery.each(Drupal.behaviors, function() {
      this(context);
    });
  }
};

```

If JavaScript would guarantee that object/array properties are always traversed in the same order they are added, then the values would be passed from `jQuery.each()` to the function used as its second parameter in the same order they are inserted in the array passed as first parameter.
This would mean that the first behavior inserted in `Drupal.behaviors`is executed first.
In this case, to allow the behaviors defined by your module to be executed first you could use a lighter weight for it. If you want they are executed before the other ones, the module weight should be set to -50; other values can work too. If you are using Drupal 7, drupal\_add\_js() allows to associate a weight to the JavaScript code; JavaScript code with a lighter weight appears first in the HTML output. This is not possible with Drupal 6, thought.

JavaScript doesn't guarantee that properties are traversed in the same order they are added. This means that different JavaScript implementations would present the same properties using a different order; it also means that the same order could change in different versions of the same browser.
> 5 votes

# Answer
Use the Behavior Weights module.
(Please give it some testing before you use it on a production site)

The module allows to attach weights to behaviors, and then it hijacks/replaces `drupal.attachBehaviors` with a custom implementation, that does respect the weights.

---

Why not module weight instead, as suggested in the other answer?

* module weight is quite a heavy tool. It applies to all hook implementations (php) and behaviors (js) of the module, while we are only interested in one single behavior.
* the order of properties in a js object is not guaranteed by the spec (although it is implemented as-you-would-expect in almost all browsers).

See
Is the order of fields in a javascript object predicatble when looping through them? and
Elements order - for (… in …) loop in javascript.
> 5 votes

# Answer
For Drupal 6 -

A simple solution, if this does not need to be portable is to put the JS you want to run last in to the theme template.php file. Theme drupal\_add\_js calls are always called after modules.

If it does need to be portable the "cleanest" solution in drupal 6 is to add a new module that has different weight than your module with the php. You could even have the two modules in the same folder, make the first module dependent on the first, and adjust the weights in the install/update hooks. None of which is necessary, just makes installation easier.
> 0 votes

---
Tags: javascript
---


# Question
Title: How do I access the "#default_value" property from $form_state['values']
I am trying to get the "#default\_value" property of a form element that is embedded in a fieldset.

The problem is that in my code I know the element name only, but I do not know the element fieldset in which it resides. Is there a mechanism to fetch that out without having to search up and down the `$form` array to find in which fieldset my element resides, and then getting it using `$form['someFieldset']['myElement']['#default_value']`?

# Answer
The array indexes contained in `$form_state` are reported in Form generation.

The default values are only present in the `$form` array, which is passed as argument to the form validation handlers, the form submission handlers, and any implementation of hook\_form\_alter() (including `hook_form_FORM_ID_alter()`).

The only way to access the default value for a form field is to know the array structure of `$form`. If the code is using a form created from a module you are writing, that is not difficult; if the code is using a form created by a module you didn't write, you need to check the structure of the form array created by that module.
> 1 votes

---
Tags: 7, forms
---


title: Using "IN" with db_query()

text:
# Question
Title: Using "IN" with db_query()
First off, let me say that I've tried the Drupal 6 answer shown in Using IN clause in db\_query and it doesn't work.

I have a query that previously only needed to include items from a single taxonomy id:

```
$images = db_query("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid = %d AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, 134, $displays_count);

```

The requirement has changed and we now need to pull images from multiple taxonomy ids. Based on the linked post above, I tried this:

```
$tax_ids = array(134, 139);
$placeholders = db_placeholders($tax_ids);
$images = db_query("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid IN ($placeholders) AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, $tax_ids, $displays_count);

```

I just get a blank screen there. When I turn on Devel and display the query log, what it shows as running is:

```
SELECT n.nid, n.title, f.filepath, cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = 1)
WHERE n.type = 'imagevault' AND tn.tid IN (1,5) AND n.status = 1
ORDER BY n.created DESC LIMIT 0

```

I have no idea where the 1,5 is coming from in the rendered query. What do I need to do to make this work? Does it only work for nid when selecting directly from a node? If so, how can I use an array in the query? Do I skip the placeholder for that param and just put it directly in the WHERE clause?

### Updated info

So it appears that completely aside from the strange case of 134, 139 being translated to 1,5, I also have another issue. Although the variable $displays\_count is set further up the page to 5, it's still translating in the query to 0. (I've echoed the value out right before the query, and it's still 5 there, so I don't know what's happening or why changing the tn.tid placeholder would have any effect on the limit placeholder.)

```
$tax_ids = array(134, 139);
$params = $user->uid;
$params[] = $tax_ids;
$params[] = $displays_count;

$images = db_query(db_rewrite_sql("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid IN (" . db_placeholders($tax_ids) .") AND n.status = 1
ORDER BY n.created DESC LIMIT %d"), $params);

```

# Answer
> 0 votes
For now, since we only have two options, I've decided to just go with an OR clause, instead of trying to deal with the IN.

```
$images = db_query("SELECT n.nid, n.title, f.filepath, cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND (tn.tid = %d OR tn.tid = %d) AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, 134, 139, $displays_count);

```

# Answer
> 4 votes
The last three arguments you are passing to `db_query()` are wrong; you should merge them in an array, and pass that instead of them.

block\_list() contains the following code:

```
$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (" . db_placeholders($rids) . ") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));

```

Similarly, blogapi\_mt\_validate\_terms() contains the following code:

```
  $term_list = array_unique($node->taxonomy);
  $params = $term_list;
  $params[] = $node->type;
  $result = db_query(db_rewrite_sql("SELECT t.tid, t.vid FROM {term_data} t INNER JOIN {vocabulary_node_types} n ON t.vid = n.vid WHERE t.tid IN (" . db_placeholders($term_list) . ") AND n.type = '%s'", 't', 'tid'), $params);

```

In your specific case, your code should be similar to the following one:

```
$tax_ids = array(134, 139);
$placeholders = db_placeholders($tax_ids);
$args = array_merge(array($user->uid), $tax_ids, array($displays_count));

/**
 * Alternatively the previous three lines could be replaced by the following ones:
 * $args = array(134, 139);
 * $placeholders = db_placeholders($args);
 * array_unshift($args, $user->uid);
 * $args[] = $displays_count;
 */

$images = db_query("SELECT n.nid, n.title, f.filepath,
  cti.field_iv_source_name_value AS source, bf.nid AS flagged
  FROM node n
  JOIN content_type_imagevault cti ON n.nid = cti.nid
  JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
  JOIN files f ON cfaf.field_att_file_fid = f.fid
  JOIN term_node tn ON tn.nid = n.nid
  LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
  WHERE n.type = 'imagevault' AND tn.tid IN ($placeholders) AND n.status = 1
  ORDER BY n.created DESC LIMIT %d", $args);

```

---
Tags: 6, database
---


# Question
Title: How to limit what is available for a role in Administration menu ?
I am using Drupal 7 and installed the Administration menu. It works fine and I am really happy with it but after creating a new role, and also creating a new user for that role, he seems to have the entire menu available even though permissions are restricted.

To clarify, I removed permissions to flush cache and administer blocks. When he clicks those links, it says access denied but he can still click the links. How do I keep those links he cannot click from appearing in the menu at all?

# Answer
Check if this user role is marked as the "Administrator Role" on User Settings.

There is also an option to rebuild the menu tree on Admin Menu settings...
> 1 votes

---
Tags: 7, users, forms
---


# Question
Title: What module might make all my links redirect the current window with target="_blank"?
I'm at a loss. None of my own JS is doing it. When I set a link to target="\_blank" it opens a new window to that location, but also redirects the original window. Does anyone have a clue what module may be involved?

# Answer
I had the same problem before and it was because of Google analytics module. This link may help you http://drupal.org/node/1091932
> 3 votes

---
Tags: 6
---


title: Botched my site upgrade

text:
# Question
Title: Botched my site upgrade
I tried following the directions drupal provides for upgrading a site, but something went wrong. Now I can't log into the admin page (and the site is in maintenance mode). I'm getting the following errors:

```
Notice: Undefined index: bluemarine in drupal_theme_initialize() (line 100 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _drupal_theme_initialize() (line 145 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_load_registry() (line 283 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Undefined index: bluemarine in theme_get_setting() (line 1166 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Undefined index: bluemarine in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Warning: array_keys() [function.array-keys]: The first argument should be an array in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).

```

And then a second error:

```
Warning: Cannot modify header information - headers already sent by (output started at /home1/osuskite/public_html/includes/common.inc:2567) in drupal_send_headers() (line 1018 of /home1/osuskite/public_html/includes/bootstrap.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'osuskite_drupal.cache_token' doesn't exist: DELETE FROM {cache_token} WHERE (expire <> :db_condition_placeholder_0) AND (expire < :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => 0 [:db_condition_placeholder_1] => 1316109148 ) in cache_clear_all() (line 169 of /home1/osuskite/public_html/includes/cache.inc).
Notice: Undefined index: bluemarine in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Warning: array_keys() [function.array-keys]: The first argument should be an array in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).

```

From what I could surmise, there error is being caused by Acquia Marina. I have downloaded the latest version and put it into the themes directory, but the error didn't change.

Any help would be appreciated. Googling this issue only pointed me to hundreds of other sites with the error instead of a solution.

EDIT: Truncating the SQL caches did nothing.

# Answer
> 2 votes
Switch to a stock D7 theme - clearing the cache is not enough if there's a bug in your theme as the buggy code is still going to reload.

* Either use drush (highly recommended) to change your default theme to another, or...
* Use the techniques mentioned here (should apply to D7): http://drupal.org/node/200774 or...
* Rollback to your D6 code/database, disable the borked theme, and then retry the upgrade.

---
Tags: 7, upgrading
---


title: Services Browser in Services 3

text:
# Question
Title: Services Browser in Services 3
I just switch from drupal 6 services 2 to drupal 7 services 3. I'm having little trouble figuring out how to configure services, I'm used to being able to test different services using the services browser, but it seems like there is no services browser in services 3, does anyone have a good method for do these test?

# Answer
See http://drupal.org/node/790416. There is a Firefox addon called Poster which you can use or there is one for Chrome called REST Console.
> 2 votes

# Answer
Theres also Fetcher, on the app store if you are on a Mac
> 0 votes

---
Tags: 7, services
---


# Question
Title: {Date_Repeat} Every day of the week doesn't work
This question is in regards with Date module (date\_repeat)

I am setting the frequency date to "every" "weeks" until a certain time with the following advanced setting:

Day of the week: Every Saturday

but the result doesn't respect my advanced setting and it will repeat the date every "seven days" regardless the length of the month

How do I fix this?

* I am using Node Repeat for this purpose.

# Answer
Is there any chance that in your time zone there's a Daylight Saving Time change on Saturday, November 6 ? Like for exemple in Los Angeles.
Because this would explain the shift of one hour you get after the 5th of November (remember, remember :) ).

> **Inspiration**: OMG Ponies!!! (Aka Humanity: Epic Fail), Jon Skeet - Stack Overflow Dev Days London 2009, video and transcript.
> 0 votes

---
Tags: datetime
---


# Question
Title: .js extension for javascript file is missing
I am using below code in my custom module "my\_module".

```
    function my_module_theme(){
        return array(
                'my_module_javascript'=>array('arguments'=>array(),),
        );
 }

 function my_module_init(){
        theme('my_module_javascript');
 }

 function theme_my_module_javascript(){
        drupal_add_js(drupal_get_path('module','my_module').'/my_module.js');
 }

```

After I enable the module page source is showing the javascript file without .js extension. like src="modulepath/my\_module?lrmjns" Am I doing anything wrong? why is it skipping .js?

# Answer
> 2 votes
What version you are using? And are you sure the my\_module.js is exist?

I think the best way is using `hook_library` to add js and css for your module:

```
function my_module_library() {
  $libraries['my-module'] = array(
    'title' => 'My custom module library',
    'version' => '1.0',
    'js' => array(
      drupal_get_path('module', 'my_module') . '/my_module.js' => array(),
    ),
  );
  return $libraries;
}

function my_module_init() {
  drupal_add_library('my_module', 'my-module');
}

```

---
Tags: 7, javascript
---


# Question
Title: Submit of custom node with imagefield ends without warning after imagefield save
I have a custom Drupal node type with a bunch of text fields, a taxonomy-dropdown and an imagefield. Only the title is mandatory, all other fields are optional. I have added no custom code that should interfere with the form being processed.

When I submit the filled-out form to add a node of this type, the form reloads without adding the node and without displaying any kind of error message. When I leave the title blank, the expected error is displayed.

**EDIT/UPDATE**

I have started reconstructing the content type and found out that the imagefield seems to be the culprit. The node will save flawlessly if the the type does not have an imagefield.

The minute I add the imagefield, saving fails. The image will even be uploaded, thumbnails will be displayed, but then the form will reappear with no further message.

# Answer
The issue had something to do with duplicate translations for button labels that basically lead to only the file field being submitted when saving the node, see: http://drupal.org/node/684426 A simple update of the localization files solves the problem and makes you hate Drupal just a teensy bit.
> 1 votes

---
Tags: nodes, entities, 6, media
---


# Question
Title: What's the best way to add an entity (of a specific type) selector to a form?
I can achieve what I want by using the `EntityFieldQuery` and transforming it to be the right format for a radio options array. Is there a better way?

# Answer
> 0 votes
If you're operating on an entity, you can just use an Entityreference field which will do it for you.

If not, then yes, write it yourself and use `EntityFieldQuery`. Just watch out, `entityCondition('bundle')` is broken for comments and taxonomy terms, and entity access is non-existent (so it will show all users instead of the non-blocked ones, etc). Entityreference implements workarounds for this (until it gets fixed in core), so you can take a look and borrow that code if needed.

---
Tags: 7, forms, entities
---


title: How to import a view in .install file?

text:
# Question
Title: How to import a view in .install file?
I have an exported view code.How can I import it in .install file?

# Answer
You don't. You implement `hook_views_default_views()` in yourmodule.views\_default.inc and place the export there.

See Using default views in your module for a detailed guide.
> 4 votes

---
Tags: 7, views, nodes, importing-exporting
---


# Question
Title: How to disable edit links/tasks for mobile theme?
I have a separate sub domain and theme for a mobile version of my site. I would like to disable the edit links/tabs for nodes if viewed from that subdomain/theme, but still allow users from editing in the main theme.

Any help or tips will be appreciated.

# Answer
Items should be disabled, if they are usually enabled, but not useful in that particular circumstance. For example, a submit button could be disabled when the form does not validate. Having an item that is permanently disabled raises the question why the item is displayed at all.

If you want to hide the items, you can do this using CSS if there is an appropriate CSS selector. Have a look at the HTML to figure that out.

For Drupal 4.7.x, 5.x and 6.x, you can also remove the links as described on the drupal.org page *Remove unwanted tabs from pages*.

Note that both methods only remove the link from the page. They do not prevent users from actually editing the page (e.g. by entering the URL manually).
> 0 votes

---
Tags: theming
---


# Question
Title: Problems getting Default Content module to work with Features
I'm trying to export some Default Content when creating a drupal 7 distribution. Noticed that Phase II is using Default Content module to set default content for OpenPublic. I can't find any documentation on how to get the module to work.

How do you get the Default Content Module to work?

# Answer
> 2 votes
Figured this out.

After you enable the Default Content Module, there will be a new setting for each Node by where you can select Revision information, URL path settings, Comment settings, etc.

This new setting is Machine Name. You make a machine name for the node of the default content.

Then when you make a new feature (I guess it is best practice to have all of the default content nodes in one feature so when you deactivate the feature all of the default content will turn off and the features will still work) there will be a new component "Content Item".

This will have all of the machine names that you made while creating/editing nodes.

Hopefully someone will find this useful so they don't bang their heads against the wall like I did.

---
Tags: 7, features
---


title: Wysiwyg Comments is not turning off

text:
# Question
Title: Wysiwyg Comments is not turning off
I'm new at Drupal and I am having trouble with comments in some content types. I create a new content type and check that it'll hava comments, but I don't want the Wysiwyg editor, so I disable it, but it's still there, how can I disable it for a content type speciffic? NOTE: I Turn off the Wysiwyg comments in this content Type.

# Answer
For Drupal 6, I normally add the following to a custom module:

```
function mymodule_form_alter (&$form, &$form_state, $form_id)
{
  if ($form['#id'] == 'comment-form') {
    $form['comment_filter']['format'] = array(); // nuke wysiwyg from comments
  }
}

```

To be honest, I can't recall why I am using `$form['#id']` instead of `$form_id` for the conditional.
> 2 votes

---
Tags: nodes, comments
---


# Question
Title: Set the inital number of empty values for a cck multi-value field
I have CCK fields that can hold multiple values, I would like some of them to default to showing say 5 values initially.

I'm not looking for any validation that all 5 values are used however.

Thanks!

# Answer
> 1 votes
Unfortunately there is no way to do this without altering the module code of CCK.

There have been a few patches created that will allow you to set the number of fields initially shown *and* let you choose how many more to add when click the "Add another" button. However, this feature is not available in the core of Drupal 7 which may be a problem if you choose to upgrade.

Patch created for CCK 2: http://drupal.org/node/530828#comment-3397196

Patch created for CCK 3: http://drupal.org/node/841914#comment-3209072

---
Tags: 6, entities
---


# Question
Title: What is the most drupally way to add a slide show (as a block? So I can reuse it in multiple places)
I'm very new to Drupal 7, and just getting started.

I'm looking to add this slide show on my site: http://jquery.malsup.com/cycle/int2.html

The "Manual and Auto Advance (hover to pause, click to advance)" one.

What is the best way to do this? My understanding is that Drupal 7 already supports a lot of core jquery stuff. So, in which drupal file would I add the code

```
$('#id_name').cycle({
    fx:     'fade',
    speed:   300,
    timeout: 3000,
    next:   '#s3',
    pause:   1
});

```

If this plugin is not already supported, then in which drupal file would I add the jquery cycle declaration, and where would I install those files?

More importantly, I am asking these operating under the assumption that I should make this a block, so that I could conceivably show this slideshow in multiple places on my site. Is that a good strategy, or is there something better?

# Answer
> 1 votes
If the content you want to use is already in nodes then you could use Views and Views Slideshow (which uses the cylce plugin you linked to).

With views you can create a block which can be re-used wherever you want in the site.

Learning how to use Views is one of the best things a new user to Drupal can do, it'll provides a lot of nice tools in a point and click interface.

# Answer
> 0 votes
Creating a content type to hold your slideshow elements is exactly what I do - title, text, link, image, basically whatever elements you need and then use Views with a Views Slideshow display type.

---
Tags: javascript
---


# Question
Title: Is it possible/ feasible to convert ordinary nodes to Ubercart nodes?
I have a site that imports content from several XML and CSV feeds, which creates nodes for each item (the items are products, but the site does not directly sell each product).

I'm just wondering if it's i) possible and ii) feasible to convert these nodes to be usable with Ubercart? Although the site doesn't directly sell the products (each product links to the supplier's site), there are features in Ubercart that are attractive to use - in particular, an Ubercart theme that I would like to use on the site.

# Answer
> 1 votes
I'm not sure how the ubercart theme you're interested in works, but you can declare any content type as an ubercart 'product' type. This would eliminate the need to convert exsiting/imported nodes, but I'm not sure if the theme you're looking at is only set up for the default Product type that ubercart creates for itself.

---
Tags: 6, nodes, ubercart
---


# Question
Title: Does Organic Groups Views allows post to group relationships?
Does anyone know how to create relationships between Post entity and Group entity. I have a view that lists group posts and I want to add group title on the same row. This issue (http://drupal.org/node/1006860) says it is possible, but it is probably not. But strange, since it is views integration basics.

# Answer
> 2 votes
it's possible, see the screenshot: (open image in new window to see full size) . Add the 2 relationships as "required" to only show nodes belonging to groups. The naming conventions of the group objects is very confusing to me, it helped me to look at the "og" and "og\_membership" tables in the DB and then check the SQL that views builds for you.

---
Tags: 7, views, organic-groups, entities
---


# Question
Title: how to create a view that shows blogs count for a user?
I want to create a view that list out the following fields

1. User name
2. User email
3. Discussion count
4. Blog count

I created the view and add the User: Name and User: Email in the fields but it shows me the duplicate users and Also I have no idea about how to add the discussion count and blog count to the view.

I have created the view of node type. Any help?

# Answer
> 1 votes
I'm going to take a stab at answering this. Create a view where:

Under Fields you select the User name, email and User:Uid. Then add a custom field. Under the custom field write a query in Value:

```
<?php $result = db_result(db_query("SELECT COUNT(nid) FROM node where uid='%s' and type='blog'",$data->users_uid));
echo $result;
?>

```

This query find the number of posts written by each user.

Under filters choose Node:type = 'content type used to store profiles' (as you want to count the number of blogs of every user who has a profile).

---
Tags: views, 6
---


# Question
Title: Show node if exists, else show node creation form
I would like to setup an environment where each of my users will be creating a node every day. I know all of my users won't be able to log in every day and they will want to check what they added on past days. I figured the best way to accomplish adding past days & displaying created content would be checking the url and returning either the node (if they have created one) or the node/add form if they have not.

For example, user 1234 navigates to: url = example.com/user/1234/2011/09/10

If they have a node created with a date field set to this day it would show the node. If not, it returns the node/add form with a hidden field set to the date in the url (easy, I can take care of that).

My first thought was panels/page manager, but I don't see a way to check if a node is created based on a date structure, if it can be accomplished I am all ears. If you think another solution is better... I am all ears!

EDIT: It has been brought to my attention that my original question overlooked a node type. I might have more than one, and I could see this being useful for other people so lets say for arguments sake that the url looks like this:

example.com/user/1234/\[node-type\]/2011/09/10

# Answer
> 2 votes
I ended up getting this to work with views, date and some custom code. Basically I created a page view that with a conditional filter for a post date in YYYYMMDD format (a default argument provided by date), if one didn't exist I added some code in the "No Results" field that would load the node creation form with basically:

```
$form = node_add(arg(0));
print drupal_render($form);

```

So a url of `/story/20110915` would show the story from that date if it existed, otherwise it would show the node/add form for the story content type.

In the final product I actually had the view load an .inc file from my custom module in the "No Results" field (also much faster than editing the view every time while developing). But I think this gets the basic point across.

Sorry @ram4nd if I made it seem like I didn't want to write code, I just was looking for the best approach. So far this seems like it is pretty solid.

---
Tags: 7, nodes, datetime
---


title: How to create dynamic link in views?

text:
# Question
Title: How to create dynamic link in views?
I have created a page in Views, and the path is node/%/images. Now I want to put a dynamic link in the header. I want to link to http://www.example.com/node/add/album/\[nid\], where "\[nid\]" is the node ID of the node being viewed. How can I do this?

---

How do I add HTML tags to it? I want to make it as a image button.

# Answer
`arg(1)` would be your friend here. In your view header definition (PHP format) put something like:

```
print l(t('Add album'), 'node/add/album/' . arg(1));

```
> 4 votes

# Answer
Then you can do it like this

```
print "<a href='node/add/album" . arg(1) . "'>Add album</a>";

```
> 1 votes

---
Tags: views, routes
---


# Question
Title: Drupal: on node save, redirect user to homepage?
How can I redirect the user to the home page (or another drupal page) on node save instead of them seeing the saved content?

# Answer
The Rules module will help you.

If you found a problem with using this module and you want to know how to do this technically, just tell me and I will explain in detail.
> 4 votes

# Answer
Have a look to the code reported in this comment, which is for Drupal 6; similar code can be used for Drupal 7, but it needs to be adjusted to it (e.g. `hook_nodeapi()` is not used with Drupal 7).

```
function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;
  switch ($op) {
    case 'insert':
      if ($node->type == 'h_energy_feedback' && $user->uid == 0) {
        drupal_set_message(t('Your feedback has been saved. Thanks for taking the time!'));
        drupal_goto();
      } else {
        drupal_set_message(t('The feedback was saved.'));
        drupal_goto('forms/henergy-feedback');
      }
      break;
  }
}

```
> -1 votes

---
Tags: nodes, redirection
---


# Question
Title: How can I save multiple images to one image field programtically?
I have an image field that I am trying to save multiple images to. There is one field but when I set up the array, only the first image fid is saved.

```
$i = 0;
foreach ($photos as $photo) {
// make sure we actually retrived this particular image
if ($photo['Success'] == TRUE) {
    // setup the filename and filepath, then write the file to disk
    $filename = "{$id}-{$number}.jpg";
    $filepath = "public://drealty_img/{$filename}";

    // Create image object
    $file = file_save_data($photo['Data'], $filepath, FILE_EXISTS_REPLACE);

    // add this image to the content entity
    $content->images = array(
        'und' => array(
            $i => array(
                'fid' => $file->fid,
            ),
        ),
    );
} // endif $photo['Sucess']
$i++;
} // endfor $photos

```

Am I saving the image field incorrectly? Or is there something that needs to be set up to allow for multiple images to be saved?

# Answer
> 1 votes
I changed the following code:

```
 $content->images = array(
        'und' => array(
            $i => array(
                'fid' => $file->fid,
            ),
        ),
    );

```

to

```
$content->images['und'][$i] = array(
  'fid' => $file->fid,
);

```

And it worked

---
Tags: 7, media
---


# Question
Title: how to add one form element into another form?
I have a webform. And I want to add some fields of user registration form to the webform because I also want to add the facility of registration on webform submission. So I want to add those fields of user registration form which are required to the webform.

Any help?

# Answer
> 1 votes
Probably you should do it programatically.

Use hook\_form\_alter to modify form A, load data of form B by drupal\_retrieve\_form inside this function and get fields from form B data which you want to add them to form A

---
Tags: 6, forms, users
---


title: How to list all the form IDs

text:
# Question
Title: How to list all the form IDs
I have installed CAPTCHA module. In CAPTCHA module I need to give the machine name of a form of another module called Printer, e-mail and PDF versions. How do I find the machine\_name of this from.

If I could list all the machine names somewhere, I will probably figure out the machine name of that form.

# Answer
> 7 votes
It sounds like that just means the form ID. As far as finding the form ID from the interface (which i assume is what you're trying to accomplish), what you can do if you have something like Firefox with Firebug is inspect the form whose ID you're trying to get (or view the source code of the page if not). In the div element that wraps that form you will find an `id` like `form-id-of-the-form`. That will likely be the ID of the form Captcha is looking for or it may be that with underscores `form_id_of_the_form`.

Alternatively, you can make a custom module to get the form ID rather quickly. Just make a small module with this code in it:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message('The form ID is ' . $form_id);
}

```

...and navigate to the page with the form in question.

# Answer
> 8 votes
Creating a registry of all form IDs on a site is, in general, impossible because you can create dynamic form IDs by using `hook_forms`. If you want to add an identical button to, say, every image in a gallery you might actually want to do that.

```
function example_forms($form_id, $args) {
  $forms = array();
  if (!empty($args) && is_object($args[0]) && isset($args[0]->nid) && $form_id == 'example_myform_' . $args[0]->nid) {
    $forms[$form_id]['callback'] = 'example_myform';
  }
  return $forms;
}

```

now you can call `drupal_get_form('example_myform_' . $node->nid, $node)` without a problem for any node and have as many form IDs as nodes. I find this easier than putting the gallery inside a form (say, it's generated by Views...) and generating a different-named button with a button-level `#submit` handler.

Anyways, I am sure there are other problems making it necessary to have an arbitrary number of form IDs.

---
Tags: captcha
---


# Question
Title: How to move the form label into the input field on all node edit forms
I have been able to customize it in the search form using template file. I am not able to figure out how to do this in the node creation/edit forms. eg: http://drupal.org search box at the left top.

# Answer
I overrode the form in the template.php

```
$form['title']['#attributes'] = array(
  'onblur' => "if (this.value == '') {this.value = '".$form['title']['#value']."';} this.style.color = '#333333';",
  'onfocus' => "if (this.value == '".$form['title']['#value']."') {this.value = '';} this.style.color = '#333333';"
);

```
> 1 votes

---
Tags: nodes, theming
---


# Question
Title: How to check if a database query has results?
How do I check if the following code has results?

I tried the *empty* function but it always returns *FALSE*

```

$query = db_select('my_table', 't');
$query->condition('code', 10)
      ->fields('t', array('cid'));
$result = $query->execute();

```

# Answer
If I'm correct the result of the execute() call should be a DatabaseStatementInterface which has a rowCount function.
> 14 votes

# Answer
If you print `var_dump($result);` you will see that `$result` contains the query and other variables so it's never empty.
You can put `$result` in a `foreach` loop to see the results.

```
foreach ($result as $record) {
  var_dump($record);
}

```

Inside the `foreach` loop, you can print the results with this code.

```
foreach ($result as $record) {
  print $record->nid;
  print $record->title;
}

```

If there is only one record as result use `mysql_fetch_array()` to handle the record.
> 1 votes

# Answer
Try this

```
while($record = $result->fetchAssoc()) {
print_r($record);
}

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: Using Acquia for a production site and running Wordpress concurrently
I've been building a website for my library in Drupal 6 using the Acquia Installer package on my local machine, a Win7 PC. I'm also going to need to run 2-3 Wordpress blogs alongside Drupal on the same machine, both on my local machine and when everything is migrated to our Server 2008/IIS 7 machine.

Do I need to ditch Acquia Installer now while still developing in order to run WP alongside Drupal? I've thought about installing WAMP alongside Acquia just to run WP on my local machine. But that seems like it would kill my local machine, running two separate installs of Apache, MYSQL, PHP, etc. And Acquia + WAMP probably isn't the smartest way to set up an efficient production environment on my server.

# Answer
> 2 votes
Acquia Installer is just an \*AMP package. It installs standard versions of Apache, MySQL, and PHP, so you can configure Apache for multiple vhosts just as you would on any other machine.

Here's a guide to setting up vhosts on drupal.org http://drupal.org/node/111238

If you are deploying to IIS, I'd suggest at least testing your site locally before you push to live. These links may be of help:

http://learn.iis.net/page.aspx/505/install-drupal-on-iis/ http://www.microsoft.com/web/downloads/platform.aspx

The second is a Microsoft IIS installer with native Drupal support. MS are supporting Drupal as part of their Windows 8 push, so there are more resources around for IIS as a platform than previously.

# Answer
> -2 votes
Thats what I would recommend, actually ditching the Aquila installer and using WAMP locally for both Drupal and Wordpress on different Apache vhosts. Then in production host it on a traditional LAMP server.

The other alternative would be to make your Drupal 7 install a "multisite" with different URLs and settings in /sites//modules etc. and host all the Blogs and the Drupal sites on Drupal, its MORE than capable and the blog modules are all in core default install so you already have everything :)

---
Tags: 6
---


title: Mass update of taxonomy term references

text:
# Question
Title: Mass update of taxonomy term references
I need to update the taxonomy field on nodes with the term from a new vocabulary. I could accomplish this easily in Drupal 6, and haven't been able to find a method in Drupal 7. I am looking for a UI based solution like VBO.

# Answer
There is no native support for this in VBO, due to the way that Taxonomy has now been moved into the fields API. There is an outstanding task that is being worked on to bring Taxonomy actions back into VBO.

In the meantime, you can try this patch against VBO 7.x-3.0-beta2, kindly posted by erik2e.
> 3 votes

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