# Question
Title: How to display exposed sort in views using one drop-down widget?
By default Views 3.0 module for Drupal 7 uses two drop-downs to display exposed sort. First drop-down to select field name, and other one - to select sort direction.

How do i can exposed sort in one drop-down?

# Answer
You need to create small module with following hooks:

```
/**
 * Implements hook_form_alter().
 *
 * Alter exposed filter form in views
 */
function MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['sort_by'])) {
    // Combine sort drop-downs into one.
    $form['sorting'] = array(
      '#type' => 'select',
      '#id'   => 'sort',
      '#title' => $form['sort_by']['#title'],
    );
    foreach ($form['sort_by']['#options'] as $sort_by_key => $sort_by_title) {
      foreach ($form['sort_order']['#options'] as $sort_order_key => $sort_order_title) {
        $form['sorting']['#options'][$sort_by_key . '|' . $sort_order_key] = $sort_by_title . ' ' . $sort_order_title;
      }
    }

    // Get default value for combined sort.
    $sort_by_keys = array_keys($form['sort_by']['#options']);
    $form['sorting']['#default_value'] = $sort_by_keys[0] . '|' . $form['sort_order']['#default_value'];
  }

  // Explode combined sort field into two values that are appropriate for views.
  if (isset($form_state['input']['sorting'])) {
    $sorting = explode('|', $form_state['input']['sorting']);
    $form_state['input']['sort_by'] = $sorting[0];
    $form_state['input']['sort_order'] = $sorting[1];
  }
}

/**
 * Default preprocess function for all filter forms.
 */
function MODULE_preprocess_views_exposed_form(&$vars) {
  $form = &$vars['form'];

  // Render new created sort field.
  if (isset($form['sorting'])) {
    $form['sorting']['#printed'] = FALSE;
    $vars['sorting'] = drupal_render($form['sorting']);

    // Need to rebuild the submit button.
    $form['submit']['#printed'] = FALSE;
    $vars['button'] = drupal_render_children($form);
  }
}

```

Then you need copy "views/theme/views-exposed-form.tpl.php" file into your theme folder and replace **$sort\_by** and **$sort\_order** widgets with new **$sorting**

Find:

```
<?php if (!empty($sort_by)): ?>
  <div class="views-exposed-widget views-widget-sort-by">
    <?php print $sort_by; ?>
  </div>
  <div class="views-exposed-widget views-widget-sort-order">
    <?php print $sort_order; ?>
  </div>
<?php endif; ?>

```

Replace with:

```
<?php if (!empty($sorting)): ?>
  <div class="views-exposed-widget views-widget-sort-by">
    <?php print $sorting; ?>
  </div>
<?php endif; ?>

```
> 9 votes

# Answer
You can use Better exposed filters module for that purpose. It has such option to combine sort field and directions in one select list.
> 13 votes

---
Tags: 7, theming, views
---


title: How to improve CDN on a drupal site?

text:
# Question
Title: How to improve CDN on a drupal site?
I'm checking a drupal site with YSlow and I get a "Grade E on Use a Content Delivery Network (CDN)" with this message:

> "There are 43 static components that are not on CDN."

Just wondering if the cdn will help to improve this situation.

# Answer
> 3 votes
It will only help if your files are actually on a CDN...if they are, then install that module, set it up, and you should see some performance benefits.

If not, then installing it will have zero effect, except to add a very slight extra overhead to your page build (when the module is included/hooks are run/etc).

# Answer
> 1 votes
If you can afford a CDN account/space (most of which as far as I know are paid services to be useful enough for a live site) and your site has adequate static content that will be used the module should help, just like @Clive says the files need to be physically present in your CDN to make the difference, else it will be just serving as a dead load whose hooks will be listened to on all page requests and events without any use. You could make the final call keeping in mind that what YSlow offers is only suggestions on improving performance and if your site has adequate hits to use a CDN that aids response.

# Answer
> 1 votes
It's pretty simple. First install the CDN module on your drupal site. Then make use of Cloudflare which is free of cost. It has CDN feature which distributes your content around the world so it’s closer to your visitors (speeding up your site).

---
Tags: cdn
---


title: Change a comment's body programatically

text:
# Question
Title: Change a comment's body programatically
I am building a small custom module that will change the value of a comment's body when the comment in posted. So far I have:

```
function comment_loader_comment_insert($comment) {
}

```

So pretty much nothing, just that I want to use hook\_comment\_insert to change after the comment has been posted.

So what do I need to affect the comment body?

\[I am a student who is just learning php and drupal, so clarity is appreciated\]

**edit:**

code so far:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function comment_loader_form_comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['#validate'][] = 'comment_loader_comment_form_validate';
}

/**
 * Implements hook_form_validate().
 */
function comment_loader_comment_form_validate($form, &$form_state) {
  $new_body = 'some text';
  $form_state['values']['comment_body']['#object']->comment_body['und'[0]['value'] = $new_body;
}

```

Still doesn't have any affect. I am no working in a development environment so I don't know if there are errors.

# Answer
> 1 votes
`hook_comment_insert()` is fired after the comment body has already been saved to the database, so it's probably not the hook you're looking for.

Instead you could hook up your own validation function to the comment form and alter the body there. That way you're not having to make any extra db calls.

In it's simplest terms you would implement `hook_form_FORM_ID_alter()` and add the validation function like so:

```
function MYMODULE_form_comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['#validate'][] = 'MYMODULE_comment_form_validate';
}

function MYMODULE_comment_form_validate($form, &$form_state) {
  $current_body = $form_state['values']['comment_body'][LANGUAGE_NONE][0]['value'];

  $new_body = $current_body . ' some extra text';

  $form_state['values']['comment_body'][LANGUAGE_NONE][0]['value'] = $new_body;
}

```

---
Tags: comments, forms
---


# Question
Title: hook node access drupal 7, not working when the node is updated
I have created a module using the following code.

```
<?php
global $user;

if (in_array('contributor', array_values($user->roles))) {
    function publishEntities_node_access($node, $op, $account) {
        if (in_array('article', node_permissions_get_configured_types())) {
            if($node->status==0) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
            }
            elseif($node->status==1) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
            }
        }

        if (in_array('events', node_permissions_get_configured_types())) {
            if($node->status==0) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_ALLOW;
                    }
                }
            }
            elseif($node->status==1) {
                if ($op == 'update') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
                if ($op == 'delete') {
                    if ($account->uid == $node->uid) {
                        return NODE_ACCESS_DENY;
                    }
                }
            }
        }
    }
}

```

The module does not work after the node is being updated.

Can anybody help me to make this module work as expected?

# Answer
> 1 votes
I cant seem anything that stands out as a problem other than maybe moving:

```
if (in_array('contributor', array_values($user->roles))) {

```

Into the hook\_node\_access and change $user for $account.

However when troubleshooting problems like this I would firstly ensure you do not have any other access control modules enabled, they can often override each other depending on the modules weight in the system table.

Turn off all modules but core and try isolate parts of your code to get it working bit by bit. For example start off initially with:

```
function publish_entities_node_access($node, $op, $account) {

        if ($op == 'view') {
            if ($account->uid == $node->uid) {
                  return NODE_ACCESS_ALLOW;
            }
            else {
                  return NODE_ACCESS_DENY;
            }
        }
 }

```

This code should work and easy to test, if you are not the author of the node then you will not be able to view it. You can then start adding on your additional if statements above until you run into a problem.

You can also install the devel module to nicely output the array's to ensure the values you are using conditionally in your code are available.

---
Tags: nodes, users
---


title: Core search, use wildcards by default

text:
# Question
Title: Core search, use wildcards by default
I've been trying to Google my way out of this one but I can't seem to find a solid solution for using wildcards by default for the core search module. Only things I can find are patches which aren't really looking like totally stable. And I want my customer's multi-lingual production site to be as stable as possible.

So, the current situation is as follows:

1. When I search for `foo` I will get only `foo` as result.
2. When I search for `foo*` I will be getting `foo` **and** `foobar` as result.

What I want is:

When I search for `foo` I will get `foo` **and** `foobar`, regardless of language.

Is there any way to elegantly solve this. I'm prepared to solve this with a custom module for example.

# Answer
I've always used the Porter Stemmer module to handle that, it works a treat.

> This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.
>
> The process of stemming reduces each word in the search index to its basic root or stem (e.g. 'blogging' to 'blog') so that variations on a word ('blogs', 'blogger', 'blogging', 'blog') are considered equivalent when searching. This generally results in more relevant search results.
> 1 votes

---
Tags: 7, search
---


# Question
Title: D7 jquery dropdown menu categorized/ordered by content type and taxonomy
In D7 I want to create a jquery dropdown menu categorized/ordered by content type (first level) and (if content type has taxnonomy tags) taxonomy via views.

What is the best approach? thnx!

# Answer
> 1 votes
I now use custom menu items and the modules 'Taxonomy Menu' together with 'Nice Menu' and some custom jquery javascript.

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


# Question
Title: Preprocess title field in all contexts (sitewide)
If you put a backslash in a title of a node I need to rewrite that title and remove the backslash wrapping the text after in tags. I'm currently doing this using multiple preprocess functions. It seems that I have to create a new preprocess function for every context that a title might appear in:

```
function project_preprocess_page(&vars){/*rewrite*/}
function project_preprocess_node(&vars){/*rewrite*/}
function project_preprocess_node(&vars){/*rewrite*/}
function project_preprocess_panels_pane(&$vars){/*rewrite*/}

```

This is working but it's frustrating (and probably inefficient) as there are so many different contexts where titles are displayed.

It seems like there should be a function where I can just override this once and not worry about it anymore. Can anyone suggest a solution?

Thanks

# Answer
I'm sure hook\_node\_view can do it for you, but you might need to call drupal\_set\_title on some situations.
> 1 votes

---
Tags: entities, theming
---


# Question
Title: Strategy for organizing category pages with Views and Panels
I have created a vocabulary and using a 2 level tree for organizing content into categories. Each category and sub-category will have it's own page, where a view block will list the teasers from the content types linked to the filtered term(s).

Now I can go and create a View block for each category, but that just doesn't seem to be proper. I'm new to Views and I have been reading a lot but I'm still not at ease with best practices on using Views.

Should I create just one single View and make a Display for each category or there's a better way to do this?

I'll be using Panels to lay out the category pages. Do I have to create 1 page for each category/subcategory and add the corresponding view to it? Is there's a better Panel's usage strategy, that permits to skip the use of multiple page panels ?

I'm using D7, Views 3.3, Panels 3.2

# Answer
> 3 votes
I don't know if you figured this out already, but I'll give a quick answer.

The magic you need: arguments / contextual filters. You want to have just one Views block that takes term IDs as arguments (in a contextual filter), so it will filter on the term present in the url. Instead of a regular views block, you can also use a Views content pane (for tighter integration with Panels).

As for Panels: you need one panel page to override the taxonomy system path. When you enable Page manager (part of CTools) some page override templates are provided, just activate the taxonomy one.

Add a variant (you can optionally add a selection rule if you want this override to only work on terms of one vocabulary) and add your Views block. Since this is a taxonomy system path, term IDs are already available as arguments for the view block (Panels is also excelent for manipulating which arguments the page will provide).

Page manager, Panels and Views are complex so it's a good idea to understand how it works. I recommend checking out NodeOne's Learn Page manager screencasts (especially Views content panes), and maybe also parts of the Views series (especially contextual filters).

---
Tags: views, panels
---


# Question
Title: Separate permissions for administering user configuration and administering users
In Drupal 7 there is one permission for administering users, "Administer users".

This covers both the main user management page at 'admin/people/permissions', and the configuration of settings/fields for the user entity at 'admin/config/people/accounts' and 'admin/config/people/accounts/fields'.

A very common requirement for a site that's being released to a client is that they can administer the users (fair enough right?), so they need the "Administer users" permissions.

However, granting that permission also gives them access to edit the user entity settings/fields, which is very undesirable (no client should be able to change the underlying structure of the user once it's been set up, for obvious reasons).

This must be something a lot of people have to deal with...what methods/modules/custom code do people use to get around this limitation in the user module?

# Answer
> 11 votes
One method is to create a new permission

```
function MYMODULE_permission() {
  return array(
    'administer user configuration' => array(
      'title' => t('Administer User Configuration')
    )
  );
}

```

and then re-assign the pages under 'admin/config/people' to that permission:

```
function MYMODULE_menu_alter(&$items) {
  foreach ($items as $path => &$item) {
    if (strpos($path, 'admin/config/people') === 0) {
      $item['access callback'] = 'user_access';
      $item['access arguments'] = array('administer user configuration');
    }
  }
}

```

Then the user role in question can have the 'Administer users' permission, but not have access to the admin/people/config pages.

This feels messy at best though.

# Answer
> 1 votes
I do this by altering the access arguments of a menu item.

```

function MODULENAME_menu_alter(&$items) {
    // Accounts filter
    $items['admin/config/people/accounts/fields']['access arguments'] = array('custom user permission');
    $items['admin/config/people/accounts/display']['access arguments'] = array('custom user permission');

}

/**
 * Implements hook_permission().
 */
function MODULENAME_permission() {
   return array(
    'custom user permission' => array(
      'title' => t('Custom user account permission'),
      'description' => t('Customized users permission @see MODULENAME.module'),
    ),
  );
}

```

---
Tags: 7, users
---


title: How can i write url specific CSS

text:
# Question
Title: How can i write url specific CSS
How can i write css for content of the dynamic url page like 'http://mysitename/user/23/prayerrequests'. Here 23, assume user id. I want to effect conent div css of this dynamic url's.

# Answer
you can use the following, it implements `drupal_add_css()`.

```
if($_GET['q']=="user/23/prayerrequests") {
  drupal_add_css(path_to_theme() . '/custom_stylesheet.css', 'theme', 'all');
}

```

**Edit 1:**
If you want this to be able to do it for all users, you could use me aliases module. It enables you to use `me` in place of `%uid`.
So, the code would become

```
// "me" from the code is automatically replaced by uid of current logged in user.
if($_GET['q']=="user/me/prayerrequests") {
  drupal_add_css(path_to_theme() . '/custom_stylesheet.css', 'theme', 'all');
}

```

**Edit 2:** You can use the variable `global $user` in the above code. You'll not need to install me aliases module.

```
//replace THEME with your theme name
function THEME_preprocess_page(&$variables) {
  global $user;
  if($user->uid == 0) {
    return;
  }
  elseif ($_GET['q']=="user/".$user->uid."/prayerrequests") {
    drupal_add_css(path_to_theme() . '/custom_stylesheet.css', 'theme', 'all');
}

```

Don't forget to clear the caches.
> 5 votes

# Answer
If you want to load a different stylesheet for every user, then this would work:

```
function MYTHEME_preprocess_page($variables) {
  if (arg(0) == 'user' && is_int(arg(1)) && (empty(arg(2)) || arg(2) == 'view') {
    drupal_add_css(path_to_theme() . '/user-' . arg(1) . '.css';
  }
}

```

However, if what you're looking for is a dynamic stylesheet, I'd recommend against that — but it can be achieved with Less or Sassy.
> 1 votes

# Answer
If your not looking to write your own module, you can also look into something like Themekey:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.
> 1 votes

---
Tags: theming, uri
---


# Question
Title: How to add more Display Suite template suggestions
If you have Display Suite installed, then on the "Manage Display" tab of any content type you will see template suggestions:

> Possible template suggestions are:
>
> * ds-1col--node.tpl.php
> * ds-1col--node-page.tpl.php
> * ds-1col--node-page-search-result.tpl.php

None of these suit what I'm wanting to achieve, as I wanted a template to apply to all "search-result" view modes for **any** content type. So my template suggestion would be:

> ds-1col--search-result.tpl.php

But it seems it's not by default accepted. **Which hook can I use to add this template suggestion?** I was thinking of `hook_preprocess_node` and adding my own template suggestion to `theme_hook_suggestions` but this didn't work as it wasn't using my suggestion on node types which have search\_result view mode applied to them. The template was only being used on the ones without any search\_result view mode configurations, and even then only normal node.tpl.php variables such as $content was passed to this DS template so I don't think it's the right way to do it.

# Answer
> 0 votes
The problem actually wasn't in `ds-1col--search-result.tpl.php`. It was when I suggested a custom template for a node when I was doing quick tests, with `print $ds_content;` in them, the nodes which didn't have the `search_result` view mode configured, weren't being preprocessed by display suite hence didn't have the $ds\_content variable set which was being printed on the custom template. Hence it gave me the impression that it wasn't working.

But to answer the question, there's no special stuff you need to do to suggest a template for display suite. First copy the template from display suite folder to your themes folder. And then all you have to do is use the normal `hook_process_node` and suggest that template for a certain view mode.

# Answer
> -1 votes
In case you have Panels installed, DisplaySuite will benefit from the numerous layouts Panels (and its extentions) have to offer. You can even choose if you want to use the DS own Field UI, or the Panels editor to arrange the fields.

If you don't have Panels installed then ignore this reply. Maybe a more specific reply will help you out.

---
Tags: 7, theming, display-suite
---


# Question
Title: joining 2 form, but submit handler can not work
I joined this 2 form and the current submit only works for the 2nd form... also it is showing an extra save button :( can anyone help me how to join the submit,preview and delete button?

here is my code :

function productform\_form\_alter(&$form, &$form\_state, $form\_id) {

```
switch ($form_id)  {
  case 'product_node_form':

    global $user;
    $uid = $user->uid;

    module_load_include('inc', 'profile2_page', 'profile2_page');
    $profile2 = profile2_by_uid_load($uid, 'main');
    $entity_form = entity_ui_get_form('profile2', $profile2, 'edit');

    $form[] = $entity_form;

    dsm($form);

    return $form;
  break;
}

```

}

# Answer
> 0 votes
I'd sugest to build your own form using FAPI and create the nodes programmatically in the submitthandler.

Looking at what you get in hook\_form\_alter has of course a good learning effect.

---
Tags: forms
---


# Question
Title: Change the front page based in the screen size of the visitor?
I use the Omega theme to make a site responsive. I need to change the **Front Page** of the site based in the screen size of the visitor.

The idea is to hide a front page which include a flash movie on mobiles devices.

**Then:**

* if the user screen is small than 740px then the front page is: **no-flash-page**
* if the user screen is bigger than 740px then the front page is: **flash-page**

Can I do this using the Omega theme setting? Maybe with **Delta** and **Context**?

# Answer
> 3 votes
The responsiveness of Omega uses CSS3 Media Queries, which are totally client side. The other thing to think about is that with true responsive design, the viewport of the client can change while viewing a single page, and the page should adapt. For example, you can load a page in Chrome, and resize the browser window, and go through the narrow/normal/wide changes and see how responsive your site is.

My suggestion is to make your front page so you employ Progressive Enhancement and not Graceful Degredation. Design the page so that it works well for users without Flash or Javascript, and make it responsive. Then, when the page loads, have some JS that checks the browser width, and then use SWFObject to add in the Flash content using the dynamic method. Depedning on your situation, you may want to add in some `min-width` and/or `display: none` on the Flash `<div>` in the narrow/normal/wide sheets to handle viewport changes.

# Answer
> 1 votes
If you want to redirect the user to another page upon detecting his/her screen width, then the answer is no, you can't do that with Omega, Delta or Context.

You can use Browscap to detect the user's device, but it requires some effort to setup and mantain. Or you can use JS to change user location after detecting the screen width (keep in mind some users don't run the browser window in full screen, so you might redirect desktop users as well).

Finally, you can use fallback content for Flash. Again, you can use JS to detect the user device and load Flash content (`<noscript>` is your friend).

---
Tags: theming
---


# Question
Title: Why doesn't Drupal use my block.tpl.php?
I want my Drupal 7 theme to use a custom block.tpl.php for my navigation bar (Defined: regions\[navigation\] = Navigation bar). So I copied block.tpl.php from the block module to my theme directory and tried to give it different names (following different guides on the web). None of them seemed to work. Then I wanted to make sure it was a naming problem so I changed the name back to block.tpl.php and changed its contents (removed the h2-tag for the title). I reloaded my site but nothing happened so there must be another problem.

Any ideas on how to fix this?

Thank

# Answer
Most likely you just need to clear Drupal's caches.

Template file implementations are cached in the theme registry so you need to clear it for new files/theme functions to get picked up.

You can do so either at http://mysite.com/admin/config/development/performance or by using Drush.
> 4 votes

# Answer
If you want to know which name must have the template for block (or regions, or other elements) you could try Devel Themer.
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: How to replicate this form with exposed filters
I'm wondering how can I achieve something like that "Browse Listing" block (on the right) with exposed filters - http://demo.rlisting.com/rlisting/result Should I create Content type for each Property type and add Listing type as a vocabulary or to use only one content type for all properties and then add property and listing types as vocabulary or as text fields with select list? And more importantly how Min & Max range could be created?

using drupal 7.14, views 3.3

# Answer
> 0 votes
You should create a view, with display page and add some exposed filters. Then you have to enable the function "Expose form in block", or something like this, that creates a block with your exposed filters.

---
Tags: 7, views
---


title: Integrate ddmegamenu in drupal menu

text:
# Question
Title: Integrate ddmegamenu in drupal menu
There is a menu plug in called ddmegamenu http://www.dynamicdrive.com/dynamicindex1/ddmegamenu.htm

I want to integrate in drupal 7 menu system. I don't know form where to begin i tried drupal megamenu module, but it is not giving same effect as ddmegamenu.

can anyone guide me how to format menu tree to apply ddmegamenu to my theme..

# Answer
Dont bother, your basically going to have create module for something like that and someones already done it. This is probably the best mega menu for drupal, just install and away you go. You can add anything you want to the dropdowns, views, blocks, etc.

http://drupal.org/project/om\_maximenu
> 0 votes

---
Tags: theming, routes
---


title: No Search form for custom theme

text:
# Question
Title: No Search form for custom theme
I am creating my first theme. I don't see the "Search form" block under structure\>block for my theme. It is present for other themes. I am not sure what I am doing wrong. Should I put something the the .info file to enable it? NB: I am working with Drupal 7.

# Answer
> 1 votes
It turned out that there was nothing wrong with my theme. I installed the theme in a new installation of drupal and the search block was available.

# Answer
> 0 votes
I had a similar problem in that it was not showing up under Structure -\> Blocks. I found it under Dashboard as a block. I then enabled it for my theme by configuring the search form block in the Dashboard. It then shows up under Structure -\> Blocks.

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


# Question
Title: Facebook Connect button in Overlay (Drupal 7)
I've been helping a friend with a site, and recently run into a road block.

I've installed FB connect, set up an app, and it's working well from the home page. However, he has an overlay installed for most of the forms and the Connect button doesn't display on the forms.

I've tried almost every variation that I can think of/find and nothing seems to be working.

Any advice?

I'm not able to post an image, but the sanbox site is at central-mining.com, just click on either of the login/registration links on the top menu.

# Answer
Make use of Facebook O auth module. It has a huge advantages over the module that you use. It will work fine with any overlay effect.
> 2 votes

---
Tags: social-network
---


# Question
Title: Is there a reason why I shouldn't be able to upload more than 95 items on to an image field?
I have an unlimited items on a simple filefield using an image widget. When a user upload more than 95 images, after saving the node, it turns it to unpublished and it removes the authoring information.

Afterwards, when you go back to edit the node it doesn't save any changes. Basically you have to go to the database and delete the extra rows until there are only 95 to be able to edit the node again.

This is critical because most of the nodes are supposed to have around 130 images.

Any suggestions?

I've already increased the php memory to 128M thinking it might be a memory problem because it looks like the save function is not executed properly.

Also, worth noting that if I change the order of the field on "manage fields" and get the image field on to the last slot, it save everything but the image field.

Thanks in advance! Any help will be greatly appreciated!

Installation:
Drupal 6
CCK - 6.x-3.0-alpha3
FileField - 6.x-3.10
ImageField - 6.x-3.10

# Answer
Solution is to increase **upload\_max\_filesize** and **post\_max\_size** in your php.ini. Because POST data can be truncated if it exceed specified limits. This can happen when you upload lot of images and send them all in one big POST.

Other way to fix this - is automatically upload image via AJAX request just after user select it - try JavaScript code from How can I automatically upload images on file selection rather than pressing the upload button?

Also try to increase **max\_execution\_time** in PHP settings. PHP may be lack of time to upload and save all 95 images during default 30 seconds.
> 3 votes

---
Tags: database, media, files
---


# Question
Title: create tabs with hook_menu() for custom module
since two hours im trying to create tabs in my custom modules backend.

I've tried severals suggestions but couldn't get any of them to work.

this is my current hook\_menu() :

```
    function social_links_menu() {
  $items['admin/config/system/social_links'] = array(
    'title' => 'social_links',
    'description' => 'Configure to fit clients needs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('social_links_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'social_links.admin.inc',
  );

  return $items;
}

```

I simply want two tabs called: 'tab1' and 'tab2'.

Can someone give me an working example? This should be really simple, but right now it seems impossible

# Answer
> 46 votes
You need to define a 'root' path which is a normal menu item, and then add another item for each of the tabs. The first of these will inherit the properties of the root item, and the second will define its own callbacks.

Combined with the `MENU_LOCAL_TASK` and `MENU_DEFAULT_LOCAL_TASK` type constants, you should get the tabs you expect:

```
function social_links_menu() {
  $items['admin/config/system/social_links'] = array(
    'title' => 'social_links',
    'description' => 'Configure to fit clients needs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('social_links_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'social_links.admin.inc',
  );

  $items['admin/config/system/social_links/tab1'] = array(
    'title' => 'Tab 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );

  $items['admin/config/system/social_links/tab2'] = array(
    'title' => 'Tab 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'some_callback',
    'access arguments' => array('some permission')
  );

  return $items;
}

```

---
Tags: 7, routes
---


# Question
Title: Creating a content type with dynamic fields
I'm trying to create a content type where the fields are updated dynamically. For example, I could have two term reference fields: Manufacturer and Product Name. When the user chooses the manufacturer in the form, the Product Name field would only display products that have the selected Manufacturer.

Whats the best way to approach this?

# Answer
> 0 votes
You could write some ajax that onchange of the select drop down, you could populate the other list with values that you grab from the database.

```
$('my-select-dropdown').onchange(function(){
   var options = get_values_from_database($(this).val());
   $.each(options, function(i, val){
     $('new-dropdown').append('<option value="'+val+'">'+val+'</option>');
   });
});

```

This may be a lot of work, someone may have made a module to do this already.. But doing it the manual way can be loads of fun!

# Answer
> 1 votes
There is Conditional fields module, but stable version is available only for D6.

# Answer
> 0 votes
I would do it with jquery.

1. Create all possible fields for the content type
2. Hide all the fields in your css (display:none)
3. Unhide the fields with jquery depending on the value chosen.

Here is a nice howto to do that, don't know if it's the latest jquery and remember that you have to address the jquery object differently in drupal. I do it the ugly way ;).

---
Tags: views, taxonomy-terms, forms, nodes
---


# Question
Title: Video file upload errors with Cloud FIles
I'm using the CloudFiles module to host my uploaded files on Rackspace Cloud Files. This is working very well for all of the photos I'm uploading, but it seems to be failing when I upload videos.

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'rcf://videos' for key 'PRIMARY': INSERT INTO {cloud_files} (uri, filemime, filesize)
VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2);
Array ( [:db_insert_placeholder_0] => rcf://videos [:db_insert_placeholder_1] =>
application/directory [:db_insert_placeholder_2] => 1 ) in drupal_write_record()
(line 7013 of /var/www/vhosts/mydomain.com/includes/common.inc).

```

I'm not sure, but it appears that when the process finally gets to the CloudFiles module and the CF module is trying to insert that into the database, the filename appears to only be "rcf://videos" when it should be something more like "rcf://videos/original/my\_test\_video.mp4" (I'm guessing).

But perhaps this is the wrong understanding of what I'm seeing. It appears that there is a directory entry in the cloud\_files db table, so perhaps the module is trying to insert entries for the intervening directories and it's accidentally trying to insert it twice or something... I don't know. I'm confused.

I'm not a drupal wizard (yet!) so I'm having real problems tracing this error down to its source. I'm assuming the issue is in the Video module since the CloudFiles module is working for image uploads.

Can you help me track down where the filename is set and/or converted?

# Answer
Found the issue, it was with the Cloud Files module (I'm using a dev version) and I've submitted a fix to the author.

The Cloud Files code was creating directory entries in the db for all of the intervening directories when mkdir() was called. The mkdir() code in the file stream wrapper was always trying to insert a row into the cloud\_files table. My guess is that it was assumed other modules would check for the existence of a directory before creating it, so he didn't want to do a redundant check. However, I think that other code would usually just blindly call mkdir() because if the directory already existed and it failed there wasn't any real downside to it.
> 0 votes

---
Tags: 7, files
---


title: Can't print breadcrumb

text:
# Question
Title: Can't print breadcrumb
I'm trying to move the breadcrumb from one part of my theme to another, and they have different template files (using an Omega subtheme). $breadcrumb seems to be an array. I've tried l($breadcrumb) and theme($breadcrumb) to no avail. How do you print out a properly themed and string-ified breadcrumb in a template?

Here's my code btw.

```
<?php
function rescue_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    if (!empty($breadcrumb)) {
    $crumbs = '<ul class="breadcrumbs">';
    foreach($breadcrumb as $value) {
       $crumbs .= '<li>'.$value.'</li>';
       }
       $crumbs .= '</ul>';
    }
      return $crumbs;
  }
$breadcrumb = drupal_get_breadcrumb();
if ($breadcrumb): ?>
  <div id="breadcrumb" class="grid-<?php print $columns; ?>"><?php print $breadcrumb; ?></div>
<?php endif; ?>

```

# Answer
`theme_breadcrumb()` would probably be the best choice:

```
print theme('breadcrumb', array('breadcrumb' => $breadcrumb));

```

It expects the `breadcrumb` variable to be an array, each item of which makes up one part of the breadcrumb trail. So this array:

```
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l('Page', 'page');
$breadcrumb[] = l('Subpage', 'page/subpage');

```

will produce:

```
Home > Page > Subpage

```

You can also use plain text instead of links for the breadcrumb items in case you need to.
> 3 votes

---
Tags: theming
---


# Question
Title: Which template or include file in Omega subtheme takes hook_form_alter()?
I want to use hook\_form\_alter in my Omega subtheme. I'm trying to put the function in the correct place but I'm getting no results after clearing caches and refreshing.

Here's the code:

```
<?php function rescue_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
  dsm($form_id);        // HTML5 placeholder attribute
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
}

```

I don't know whether to include a closing `?>` or not. I've tried it both ways. I've tried saving it as preprocess-page.inc and process-html.inc but neither has given any result. Help?

# Answer
The preprocess.inc and process.inc files are an Alpha/Omega way of organizing `template_preprocess` and `template_process` functions. Basically, if your template.php would have a `mytheme_preprocess_node`, you would put it in preprocess-node.inc and name the function `mytheme_alpha_preprocess_node`. When you clear cache, and Drupal rebuilds the registry, the Alpha hooks will scan all of these files and wire everything up.

This doesn't mean that everything else that you put in template.php goes in these includes. Your custom theme functions and alters should still stay in template.php.

This can help keep the size of template.php managable, but I always still end up with large files because typically needs lots of theme and alter functions for the projects I work on.
> 3 votes

---
Tags: theming, forms
---


# Question
Title: Multi-site: how to handle some module differences?
I have a Drupal 7 multi-site installation with some shared modules. Some of these modules declares some forms. And here comes the problem: How to make these forms look different in two different sites? For example: In one site the whole form needs to be on a single page but in another site it needs to be divided in two steps, how can I solve this without change the module code?

I tought in some solutions:

* Create a custom module for the site that needs the form to be in two steps.
* Break in two steps using javascript and handle the navigation on the client site.
* Create a configuration on the shared module (the problem here is that I'd have to create a specific configuration for every possible customization on the form).
* Create a template for the form and handle this steps in specific site theme.
* Change the module to, instead of creating a form using FAPI, creates a webform node that could be changed for the specific site when the module is installed.

What would be perfect for me is that is someway I could implement a form alter hook in the theme but it isn't possible, right?

What do you think? How you solve this problem?

# Answer
Create three modules named site1.module, site2.module and site1site2.module respectively. Store changes (hook\_form\_alters) for site1's forms (including those of your custom module) in site1.module, sites2's forms in site2.module, and forms of both sites in site1site2.module.

The module names will of course need to be swapped for more meaningful alternatives.
> 1 votes

# Answer
You can always call hook\_form\_FORM\_ID\_form\_alter (not sure about the exact hook name) in a custom module you create and change the form according to a URL that is probably different depending on the site that you are accessing:

```
function mymodule_form_myform_form_alter($form, &$form_state){
     switch(urldecode(request_uri())):
         case 'www.mywebsite1.com': $form['new_field'] = array('#type','textfield');
               break;
         case 'www.mywebsite2.com': $form['new_field'] = array('#type','textarea');
}

```
> 0 votes

---
Tags: 7, forms, multi-sites
---


# Question
Title: Providing a vocabulary in a custom module
I am about to create a module which provides a ready-to-use term vocabulary.

What would be the clean, Drupal way to do that? Is it just a matter of a bunch of queries in `hook_install()`, or should I perform some additional steps? Should I take any measures in order to make the terms translatable?

I am using Drupal 7.

# Answer
> 3 votes
You should make use of the taxonomy module's functions such as taxonomy\_save\_vocabulary() and taxonomy\_save\_term() (Drupal 6), or taxonomy\_vocabulary\_save() and taxonomy\_term\_save() (Drupal 7) to populate your custom vocabulary. Creating fields should be accomplished via the Field API. There really should be no need to directly interact with the database.

Term translation is not supported out of the box in Drupal 7, but I do believe that the internationalization module provides a module that has cobbles together support for it.

---
Tags: taxonomy-terms
---


title: Using image styles and term references

text:
# Question
Title: Using image styles and term references
I have a taxonomy called sponsors with an image field attached. Then I have a content type with a field-collection and inside of the field collection I have the term reference. So when the admin creates a content type they can choose a sponsor and I setup a view to show the image. However, they would like to have 3 different sizes to choose from when creating the content. Is it possible to provide them with a choice of image styles almost like the Insert module let's you do?

**UPDATE**: Looks like it's going to be custom code. The formatter module is nice, but it does not suite the needs for my particular use case.

# Answer
> 1 votes
The Formatter Field module was made for just that:

> The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
>
> For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

There are some steps on the module page I'd recommend reading before diving right in, it's not immediately obvious how to make this module work.

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


# Question
Title: How can I make a link from content profile node to it's user account page?
I'm trying to find out how to make a direct link from content profile node view/edit page to it's account page.

As an admin role when I check somebody's profile node I sometimes also need to check his/her account. So it would be much easier if I can make a direct link.

I need this link to be visible only to Admin role. Is there any way to make it?

# Answer
> 0 votes
Quick and easy/dirty on the view page at least, in your node template for your content profile type, let's assume it is `node-profile.tpl.php`, you could add something like

```
<?php if (user_access('administer users') && $page): ?>
  <?php print l('User Account For This Profile', 'user/' . $node->uid);
<?php endif; ?>

```

wherever you wanted that link. If you want it on the teasers of the node as well, eg, if the profiles are listed in a view or on the front page, etc, just take out the `&& $page` otherwise this will only show up in the full node pages. You can also pick any permission you want, I just grabbed the first one that made sense to me :)

ADDITION: if you actually have a role called 'Admin' you can check for it like this:

```
 <?php
   global $user;
   if (in_array('Admin',array_values($user->roles)) && $page) {
      print l('User Account For This Profile', 'user/' . $node->uid);
   }
 ?>

```

---
Tags: 6, users
---


# Question
Title: Zen subtheme: no sidebar on a given page
The overall layout of the site is composed of a 2 column layout (main content area + right sidebar). I have a /forum section on my site and I would like to have a single plain area for it and its childs.

1. Adding a forum.tpl page containing no sidebars does the trick?
2. Another way might be to prevent *.sidebar-second* being loaded as a body class for a given URL (mysite.com/forum). Is this a clean way to do it and above all will it escalade to /forum/subforums ?

I'm using a 7.x-5.x zen subtheme with D7 and Advanced Forum as the forum solution.

# Answer
After some tests which involved using arguments in page.tpl and CSS trickery to clean up after, I couldn't manage to have a proper working solution.

Although I would have prefered to find a way to do this at a template level, easiest and quickest solution I finally found, was to use Context module

Basically I created a simple context with a *Condition* on **path** option and a *Reaction* on **regions** of the concerned theme. Checked the sidebar I wanted to exclude Saved and it was done.

Good thing doing this through the Context module is that, it removed the concerned regions, but most importantly it removed also the corresponding classes from `<body>` which were the pain in the butt to begin with.
> 1 votes

---
Tags: theming
---


title: How to stop hook_menu item being called

text:
# Question
Title: How to stop hook_menu item being called
I have a function like:

```
function MYMODULE_menu() {
  $items['cars'] = array(
    'title' => 'Cars',
    'page callback' => 'section_index',
    'page arguments' => array("cars"),
    'access arguments' => array('access content'),
    'file' => 'pages/section.inc',
    'type' => MENU_CALLBACK,
  );
}

```

It works fine. Going to cars calls this page. I have a load of node pages like cars/ford and cars/volvo and they get called. However. If you go to cars/volvvvo (for example), it calls the "cars". No 404 is triggered etc.

This also seems to mean that the breadcrumb is glitchy for other pages called by hook\_menu which have cars in the path, e.g.

```
 $items['cars/help'] = array(
    'title' => 'Cars Help',
    'page callback' => 'cars_help',
    'access arguments' => array('access content'),
    'file' => 'pages/help.inc',
    'type' => MENU_CALLBACK,
  );

```

Has a mangled breadcrumb with additional paths to "cars" in it.

Am I missing something? Is there a way to stop additional arguments being just silently pased through via hook\_menu?

# Answer
> 3 votes
No, you can't, see the following question/answer: https://drupal.stackexchange.com/a/33493/31

If you only want to allow certain arguments, you need to validate the argument and return MENU\_NOT\_FOUND. Or you can use a named argument, e.g. cars/%brand, which will automatically call the brand\_load() function, pass the value of the parameter to it and if that function returns FALSE, then it's automatically returned as 404. This is used for node/%node, user/%user and so on.

---
Tags: 7, routes
---


title: jQuery Mobile in a custom theme

text:
# Question
Title: jQuery Mobile in a custom theme
I have built a Drupal 7 website that contains a mobile theme. What I want to do is run the newest version of Jquery Mobile - http://jquerymobile.com/ which requires Jquery 1.7.1. Drupal by default is using an older version of Jquery.

I want Jquery Mobile to load "last" and be used for all screen elements (it changes the way form elements, the way the page is scrolled etc). I've already excluded a bunch of the default Drupal js and css (that won't be needed in the mobile theme) and if I stick this in the html.tpl.php of my test theme.

```
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>

```

It works exactly the way I want it to, but this does not seem like a good Drupal friendly implementation. What is a better implementation of this that will work better with Drupal and reduce risk of conflicts?

I've tried Jquery update http://drupal.org/project/jquery\_update/, and jQuery Multi modules http://drupal.org/project/jqmulti, but without modifications the theme won't load (it loads perfectly if I use those 2 lines above).

Also please do not point me to http://drupal.org/project/jquerymobile or to this http://drupal.org/project/mobile\_jquery

I have a site using that module and theme and I do not want / desire/ require, the extra functions thqat module works with (plus it uses an old version of jquery mobile) and the theme has lots of issues which make it not work for my purpose.

# Answer
> 3 votes
The issue with updating jQuery manually in Drupal is that the potential arises for parts of Drupal core (and contrib modules) to break because of the change in jQuery version. The main benefit of the jQuery Update module is that it corrects the things that break in Drupal core when jQuery is updated.

Thus, your best option is to utilize the 7.x-2.x-dev version of jQuery Update, which includes rudimentary support for jQuery 1.7.x. Keep an eye on the issue queue related to this version so that you can report and/or investigate any issues that may arise in utilizing jQuery 1.7.x in Drupal 7.

---
Tags: 7, javascript
---


# Question
Title: What hook for installing a large list of field options?
If a custom module installs a dropdown-style field, using a large internal list of options (about 200 items), should this list be populated in `hook_install` or `hook_init` for greatest efficiency? Yes, I know, with such an extensive list, I should provide an ajax-driven widget for ease of use, but at this stage of development and my skills this is a side issue :)

# Answer
I would probably use the List field predefined options module.
> 0 votes

---
Tags: 7, hooks, entities
---


# Question
Title: Extra "mystery" markup being printed to page
I have a strange thing happening. If you see this page:

http://morningsidecenter-teachablemoment.org/teachable-moment

you will see a pretty much broken super fish nav (that until earlier tonight was working.) If you inspect the element you will find numerous empty `<a></a>` being printed to the page...

I went through and undid all the work i had done, but to no avail. Has anyone ever encountered this sort of thing? I've combed over my .tpl files to see if there is anything strange going on, but I cannot see anything (though it is late). Also, when I am logged in the error does not present itself, nor does it on interior pages for that section; click on any item in the sub menu, and you will see the nav is not broken, and no extra markup in the form of empty `<a></a>` tags...

thoroughly flummoxed...

# Answer
If I view source on the page you can see there is a unclosed anchor tag in this chunk:

```
<div class="view-footer">
      <a href="teachable-moment/lessons?field_area_tid=12&field_topic_tid=All&field_grade_level_tid=All">
<h4 class="TMlandingTitle">Posted in Classroom Ideas & Resources</h4>
<a/>    </div>

```

Is this a hard-coded chunk of html in a view? Looks like you have mixed around the closing `<a>`
> 1 votes

# Answer
I don't know about the additional anchor tags (tested in Firefox and IE8 for windows), but there a bunch of other problems that might be causing oddities.

There's a div inside your head tags at line 89

```
 <div id="fb-root"></div>

```

Basically, I'd recommend running your site through http://validator.w3.org/unicorn/ and fixing as many of those issues as you can. Then see if your problem still exists.
> 0 votes

---
Tags: navigation, theming
---


# Question
Title: Date with an option for end date being either a date or "ongoing"
I have a content type that contains relevant information of a project. It should hold the projects start date and the end date OR the status "ongoing". How do I make this happen? With the date field type I can only specify the starting and ending dates.

# Answer
You can create an additional field named *Project status* with 2 options *Done* and *ongoing*. Then using the Conditional fields module, show the date field when *Done* is selected and hide it when *ongoing* is selected.
> 0 votes

---
Tags: entities
---


title: Webform duplicate entry on edit

text:
# Question
Title: Webform duplicate entry on edit
Webform creates a duplicate entry on edit, instead of editing the entry, is there a way to make it work the way it should (by not creating a new entry)?

Using Drupal 7 and Webform 7.x-3.17+3-dev.

# Answer
> 1 votes
I've never had this problem and I use Webform in pretty much every project.

I would suggest your problem is based on the fact you're using a dev version of the module. Webform has a stable release of 7.x-3.18 whereas you're using 7.x-3.17+3-dev. The first thing I'd do is upgrade to the stable version, clear the caches, and see if the problem persists.

If it does, or you want to stick with the dev version for whatever reason, then you should report any problems to the module issue queue in the first instance.

---
Tags: webforms
---


# Question
Title: How to add points using User Points in Drupal 6
I want users to be able to give points to other users through "User Points"

I think it's the API: http://drupalcontrib.org/api/drupal/contributions!userpoints!userpoints.module/6 http://drupalcontrib.org/api/drupal/contributions!userpoints!userpoints.views.inc/6

I don't want to use views module, I'm looking for a PHP code to place it in template and to give point.

Thanks

# Answer
Check nodevote module. It does something similar. You may use it directly or base your code on it.

If you want to use a more sofisticated solution with VotingAPI you can use userpoints\_votingapi and use rate module for the widgets

Cheers.
> 0 votes

---
Tags: 7, theming, rating, userpoints
---


# Question
Title: PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined:
I get "PDOException: SQLSTATE\[HY093\]: Invalid parameter number: parameter was not defined" using the below `db_query()` call.

```
db_query("SELECT image.:field1_fid as fid, image.:field2_data as file_data, image.:field3_list AS list FROM {content_:field4} AS image WHERE vid = :vid AND nid = :nid", array(':field1' => array_values($field), ':field2' => array_values($field), ':field3' => array_values($field), ':field4' => array_values($node_type), ':vid' => array_values($vid), ':nid' => array_values($nid)));

```

I also tried like this.

```
db_query("SELECT image.:field1_fid as fid, image.:field2_data as file_data, image.:field3_list AS list FROM {content_:field4} AS image WHERE vid = :vid AND nid = :nid", array(':field1' => $field, ':field2' => $field, ':field3' => $field, ':field4' => $node_type, ':vid' => $vid, ':nid' => $nid));

```

Wny idea what's wrong in my query?

# Answer
> 1 votes
You cannot use parameters instead of field names. If the field name is contained in a variable, you should use something similar to the following one, or use dynamic queries, as suggested from Clive. (Dynamic queries make more sense in this case, though.)

```
db_query("SELECT " . db_escape_field($field1_fid) . " AS fid, /* … */ FROM {" . db_escape_table($field4) - "} WHERE /* … */");

```

`$field1_fid`, and `$field4` contains strings, not arrays.

In your query there is also something else that is wrong: If you have an array of possible values for a database field, then you should use the `IN` operator, such as in the following example, not the `=` operator.

```
SELECT * FROM {node} WHERE nid IN :nids

```

# Answer
> 2 votes
A parameter to a query is something that will go in the `WHERE`/`HAVING` clause, it can't be used to substitute text into the `SELECT` or `FROM` (or any other part) part of the query. As you've only got two proper parameters in the query (those after the `WHERE` clause), and you're passing several more as the arguments, you get an error informing you of the count mismatch.

You're also trying to pass in arrays as single string parameter replacements to the `SELECT` and `FROM` parts of the query, which will just never work (even if you *could* use parameter replacement in those part of the query). When cast to a string, the array will simply be the string `Array`, which is pretty much definitely not what you're looking for.

If you want to build those parts of your query dynamically you'll need to use `db_select()` instead. This code isn't a complete representation of your example but should get you going:

```
$query = db_select('content_' . $table_name, 'image');

$query->addExpression('image.' . $field_name);
$query->addExpression('image.' . $field2_name);
// etc...

$query->condition('vid', $vid);

$results = $query->execute();

```

# Answer
> 0 votes
In your example, `$field` is an array, when `db_query()` expect an array of strings, not an array of arrays.

---
Tags: 7, database
---


title: Encapsulate fields in div

text:
# Question
Title: Encapsulate fields in div
I need to encapsulate in Drupal 7 some fields intro a div and other fields in another div. How can I do that?

Thanks.

# Answer
> 1 votes
You can change the way the html is genereated for a field by overwriting the apropriate theme method.

Tho find the method you can use the theme developer module. After enabling the module you can click on the appropriate field to see the theme methods which are important for you.

Have a lookg at the themeing giude if this is all new for you.

# Answer
> 1 votes
Another way to do this is to use the Field Group module. This allows you to add a "group" of fields from the *Manage fields* screen in the same way that you add fields.

By choosing "Fieldset" as the type of the group, you can add only a div. Field Group is primarily designed to allow you to add different kinds of tab groups, but you can also use it to add just a custom div.

# Answer
> 0 votes
You can use theme suggestions : field--\[type|name\[--content-type\]|content-type\].tpl.php

See http://drupal.org/node/1089656

---
Tags: entities
---


title: Clone Colorbox Image Link with JQuery

text:
# Question
Title: Clone Colorbox Image Link with JQuery
I need to clone a colorbox image link (the first of all colorbox links on the loaded page) and add it onto a div-tag. how could I do that with javascript/jquery? thnx!

# Answer
> 1 votes
I found this solution:

```
        $('#main-stuff').append('<div id="bgImgOverlay"></div>').css("cursor","pointer");
        $('#bgImgOverlay').click(function() {
            $("a[rel='gallery-all']").colorbox({open:true});
         });

```

---
Tags: 7, javascript
---


# Question
Title: Composite Primary Key for a Content Type
Is there any way to create a composite primary key or equivalent for a content type in D7? I really need a way to stop the duplicate content for the same content type.

Thanks

# Answer
An easy way to do this is with the Unique Field. This provides a WYSIWYG interface for adding node validation to the node save form to check one or more fields' uniqueness.

The module is not bulletproof, though. There are some scenarios where you can get around it.

> This module is intended to function when a node is being validated prior to being created or updated. It does not prevent nodes from being programmatically saved with duplicate values (including when a node is reverted to an earlier revision).

The reason is that the check is done at the code level via validation and is not a database enforcement via composite keys.

A similar module, that also provides a lot more features in addition to the uniqueness check, is Field Validation.

If you want to give the composite key thing a shot, I would make a test site and edit one of the field tables by hand to make the composite key. Then install/enable Unique Field and see what happens with the cases that the module doesn't cover.
> 3 votes

# Answer
The field data is stored in separate database tables (or even in a completely different storage system) so not really, no.

As an *extremely* low tech solution you could attach a validation handler to the node form, which checks to see if a node with the same details has already been added. If it has, you can set an error and ask the user to fix the problem.

This is just skeleton code and will need a fair bit of customising:

```
function MYMODULE_node_form_validate($form, &$form_state) {
  $field_first_field = $form_state['values']['field_first_field'][LANGUAGE_NONE][0]['value'];
  $field_second_field = $form_state['values']['field_second_field'][LANGUAGE_NONE][0]['value'];
  // etc...

  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'my_content_type')
    ->fieldCondition('field_first_field', 'value', $field_first_field)
    ->fieldCondition('field_second_field', 'value', $field_second_field);

  $results = $query->execute();

  if (!empty($results['node'])) {
    form_set_error('', 'A piece of content with the same first field and second field has already been added. Please revise these fields.');
  }
}

```
> 2 votes

# Answer
Even more lowe tech als Clive's answer would be to add a unique index to the value column of the field tables in the DB.

However fields default storage isn't meant to be used that way. You will get db errors when it commes to save different revisions or language versions of a field.

But this solution makes 100% sure that you'll never have duplicate values of a vield value.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to correctly handle date formats that needs i18n
Suppose you have a date format that looks like this: `"Some text Y-m-d other text H:i"`. Please ignore that the text needs some escaping.

What is the correct way of outputting this in a i18n friendly way? I see that format\_date attempts to do some sort of translation work, but I don't understand entirely what.

My best guess:

```
implode(' ', array(
  t('Some text'),
  format_date($timestamp, NULL, 'Y-m-d'),
  t('other text'),
  format_date($timestamp, NULL, 'H:i'),
);`

```

Is this the correct/best way?

# Answer
Try something like:

```
$text = t("Some text @date more text @time", array(
  '@date' => format_date($timestamp, NULL, 'Y-m-d'),
  '@time' => format_date($timestamp, NULL, 'H:i'),
));

```

More info at:
> 5 votes

---
Tags: datetime, i18n-l10n
---


title: All the additional tags Drupal 7 adds

text:
# Question
Title: All the additional tags Drupal 7 adds
Not being a developer per say, I am responsible for converting the PSDs into HTML, CSS & Js. Our Drupal Web Developer doesn't know the answer to this question so I hope someone here can answer it for me.

After handing over the HTML, CSS & Js file to the developer, this is what he brought back. All the lines of code you see in the firebug that is not green highlighted is Drupal 7 generated (we are using Adaptive Theme with sub-theme Sky which we are further modifying).

I dont understand what all these (& they are a lot) divs do, what purpose they serve.

Are they generated in every Drupal website & is code we should not be worrying about or are we doing it all wrong?

# Answer
Drupal is notorious for producing way, way too much markup in an attempt to make absolutely every individual page element individually themeable. Whether you think this is 'good' or 'bad' completely depends on your opinion, there are probably as many advantages as disadvantages.

I would say it definitely is something you should be worrying about though. A page stuffed with extraneous tags is bad for SEO, bad for javascript performance, and (arguably) can make the document less semantically correct.

Every time I build a new theme these days I first drop in some heavily stripped-down template overrides.

For example my standard node.tpl.php simply looks like this:

```
<?php echo render($content); ?>

```

field.tpl.php file looks like this:

```
<?php foreach ($items as $delta => $item): ?>
<?php echo render($item); ?>
<?php endforeach; ?>

```

and region.tpl.php:

```
<?php if ($content): echo $content; endif; ?>

```

Those are the absolute extremes in stripping out the tags, my template files very rarely stay this basic once the project gets going. But using this method I can build upon the bare content output and just wrap what I need to to style that particular theme. It gives me enough control over the markup while keeping as clean a DOM as I can manage.

The downside to this method is that some contributed modules contain their own CSS files that target the generic classes that Drupal outputs. These will obviously stop working if you've stripped those tags out, so there's a good amount of manual intervention required.

A good example of this are the field types provided by the media module. They rely on the surrounding tags for styling, and look awful when removed. I usually get around this by making field specific template files (e.g. `field--media.tpl.php`) which have all of the original markup in them.
> 2 votes

# Answer
This is standard Drupal behaviour, but you can change it using one of the following modules:

they both allow you to override the amount of outputted html tags
> 3 votes

---
Tags: 7, nodes, theming
---


# Question
Title: Is there a way to clone a feature in Drupal/Open Atrium?
I want to create a clone of the Notebook feature and would like to do it without copying the files and doing a find/replace on the text. Is there an easy/built-in way to clone a feature and provide it with a new name?

# Answer
Try http://drupal.org/project/features\_clone. From the project page:

> Features Clone is a Drush command that allows quick cloning of a Feature. It can be used to rename or fork (e.g. to start a new feature off of an existing one) a Feature installed on a Drupal site.
> 1 votes

---
Tags: features, distributions
---


# Question
Title: Which is better approach "taxonomy_get_term" or using SQL to display term name on template file
I have a View page with term id in its URL as argument and I have found two ways to display term names on Views template file.

One is using `taxonomy_get_term()`; the other one is querying the database.

```
$explode_vocubulary=explode("/",$_GET['q']);
$vocubulery1=$explode_vocubulary[1];
$sqlvoc1="SELECT *  FROM `term_data` WHERE `tid` =".$vocubulery1;
$rowvoc1=db_query($sqlvoc1);
while($resultvoc1=db_fetch_object($rowvoc1)) {
  echo  $resultvoc1->name;
}

```

I'm not a coder and don't understand the difference very well but it seems that using Drupal API seems to be cleaner. What the difference between these two approaches or which is the better way?

# Answer
Literally the only difference between you calling `taxonomy_get_term()` and running the query yourself is that `taxonomy_get_term()` statically caches and serves term objects that have been loaded previously in the same page load.

You'll only get performance increases, not decreases, if you use the API function so I'd thoroughly recommend using that instead of going directly into the database.

Since you're running an identical query anyway, it's just repetition of code otherwise.

This is the code from `taxonomy_get_term()`, it should help illustrate the above:

```
function taxonomy_get_term($tid, $reset = FALSE) {
  static $terms = array();

  if ($reset) {
    $terms = array();
  }

  if (!isset($terms[$tid])) {
    $terms[$tid] = db_fetch_object(db_query('SELECT * FROM {term_data} WHERE tid = %d', $tid));
  }

  return $terms[$tid];
}

```
> 3 votes

---
Tags: 6, taxonomy-terms, theming, database
---


# Question
Title: Fatal error when restoring PostGreSQL DB from dump: undefined function system_run_automated_cron
I'm trying to simply install Drupal 7.8 on PostGreSQL 9.1, backup the DB, and then restore from it ... nothing else, just to test out backing up my sites, but the site will not come back up!

Here are my steps:

1. install Drupal & get through configuration to the "you're done" screen
2. dump the DB (pg\_dump \> file.sql)
3. drop the DB (dropdb)
4. create a new DB with the same info (createdb)
5. restore the DB (psql \< file.sql)

No steps in between (except when I've tried to avoid the error by putting the site into maintenance mode and/or clear the cache). No adding content, no nuthin'!

But when I access my site, I get the following error message:

```
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [<a href='function.unserialize'>function.unserialize</a>]: Error at offset 0 of 1009 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [<a href='function.unserialize'>function.unserialize</a>]: Error at offset 0 of 38585 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Warning:  Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 185
[22-Nov-2011 17:07:44] PHP Warning:  array_keys() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 89
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [<a href='function.unserialize'>function.unserialize</a>]: Error at offset 0 of 38585 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Warning:  Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 185
[22-Nov-2011 17:07:44] PHP Warning:  array_keys() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 89
[22-Nov-2011 17:07:44] PHP Fatal error:  Call to undefined function system_run_automated_cron() in /Applications/MAMP/htdocs/drupal-postgres/includes/common.inc on line 2573

```

Anyone have any thoughts? This CAN'T be this hard!

Thanks a million!

# Answer
After looking into this a bunch, I just decided to move the DB to MySQL. I hated to have to do it, but support for sql-dump in drush is limited to MySQL, and Backup and Migrate is as well. Kills me to have to run two DB servers (all my other applications use PostGres), but desperate times call for desperate measures.

I would hope some day that these modules would support PostGres. As Drupal supports both, so should the modules.

Some notes to others when using Backup and Migrate and Backup and Migrate Files

* File ownership travels with the files, so I've had to "chown apache" files that get moved
* It looks like the Temporary Directory setting is stored as a machine-specific folder, so be sure to update this on the destination machine
* Clear the cache on the destination machine. I had a case where a tpl.php file wasn't being used until I did this.
> 2 votes

# Answer
Check this up: http://drupal.org/node/926636

I have got almost the same errors while migrating to a different server as well as upgrading from postgres 8.4 to 9.0. Altering the bytea setting does the job so far!
> 1 votes

# Answer
You can also changed settings in the postgresql.conf so you don't have to altering the table each time you make a backup

bytea\_output = 'escape' # hex, escape
> 1 votes

# Answer
Shot in the dark here, but I would take your backup a different way. You have two options:

One is to the Backup and Migrate module. I would set up the profile to ensure that tables are locked and drop into maintenance mode during backup to ensure that it is consistent. I would also exclude all of the content from the cache tables. While you are at it, set up a backup schedule.

The other is to use drush and it's sql-dump command. The author mentions that the proper options are used to ensure a backup, and you can also exclude table contents.

You could also try restoring your backup file and manually doing a `TRUNCATE TABLE` or `DELETE FROM` on all of the cache tables.
> 0 votes

---
Tags: 7, backups, database
---


# Question
Title: Is inheritance between content types possible?
I just read Should I use a seperate content type?, and it's got me thinking.

Say I had a site with twenty-five content types, with some of the content types sharing enough of the features of some of the other content types to make some kind of "inheritance" worthwhile: I'm thinking in terms of object-oriented PHP here. Is content type inheritance possible in Drupal 6? Is it possible in Drupal 7? Or 8? Could a module be written to make it possible?

# Answer
> 6 votes
For Drupal 7 there's the Bundle Inherit module.

# Answer
> 2 votes
You might consider using References module which is exactly what it sounds like, the ability for one node to reference another node for which you can easily retrieve the information of the referenced node/user/etc. through Views or the PHP API. This is very similar to using taxonomies except they are treated as a node would generally be treated.

You can set up automatic back references with a module or simply do a back reference through views computationally upon request.

edit: This references system is less like inheritance and more like composition which is generally the preferred method in object orientation computer science theory.

---
Tags: entities
---


# Question
Title: Dependent dropdown values up to 4 select boxes
We are working on the form API which having 4 dependent drop downs, and also the dependent drop down having the option to Add one more (Adding 4 drop downs once again)or remove one set. The values of the drop down are pulled form DB.

The issues we are facing are:

1. When we select the parent drop down the values are loading correctly in respective child drop down. Once select the 4 drop downs, after if we change the value in the first drop down. The second drop down value only alone changing. we are unable to reset the values in the third and Fourth drop downs.
2. All the four drop downs are required fields Please find the code for reference, in-case of any questions ask me freely..

```
            <?php

        function company_form($form, $form_state) {

            // Build the fieldset with the proper number of names. We'll use
            // $form_state['num_names'] to determine the number of textfields to build.
            if (empty($form_state['field_of_study_num'])) {
                $form_state['field_of_study_num']  = 1;         // For Field of studies
                }

        //Field of studies Field Set
            $form['#tree'] = TRUE;
            $form['field_of_studies_fieldset'] = array(
                '#type' => 'fieldset',
                '#title' => t('Field of Studies'),
                '#prefix' => '<div id="div_names-fieldset-wrapper">',
                '#suffix' => '</div>',
            );

        for ($i = 0; $i < $form_state['field_of_study_num']; $i++) {

        $form['field_of_studies_fieldset'][$i]['labels'] = array(
                    '#prefix' => '<div id="set'.$i.'"><h1 id = "company_form_label">',
                    '#type' => 'item',
                    '#title' => t('Form :'.($i+1)),
                    '#suffix' => '</h1>',
                );

        // field_of_studies Drop down box
        $options_fieldOf_Studies = _get_field_studies_mstr(0);  //Loading Values in the DB
        // First Dropdown Box
        $form['field_of_studies_fieldset'][$i]['field_of_studies1'] = array(
                '#prefix' => '<div id = "fieldset'.$i.'"><div class="container-inline bottom_space field_of_studies_drop_down">',
                '#options' => $options_fieldOf_Studies,
                '#type' => 'select',
                '#title' => t('Field of Studies'),
                '#required' => '1',
                '#suffix' => '</div></div>',
                '#ajax' => array(
                        'callback' => 'ajax_example_dependent_dropdown_callback1',
                        'wrapper' => 'dropdown-second-replace-'.$i,
                ),
        );

        // Loading values in the 2nd dropdown depends on the value selected in the First Dropdown
        if((isset($form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies1']) && ($form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies1']  != 0)))
        {
            $firstVal = $form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies1'];
            $options_fieldOf_Studies2 = _ajax_example_get_second_dropdown_options1($firstVal);
        }
        else
        {// Loading values as "Select" intially
            $options_fieldOf_Studies2 = _ajax_example_get_second_dropdown_options1(0);
        }

        // Second Dropdown Box values are dependent with First dropdown
        $form['field_of_studies_fieldset'][$i]['field_of_studies2'] = array(
                '#type' => 'select',
                '#title' => t('Field of Studies2'),
                '#prefix' => '<div id="dropdown-second-replace'.$i.'"><div class="container-inline bottom_space field_of_studies_drop_down">',
                 '#required' =>     (isset($form_state["values"]['field_of_studies_fieldset'][$i]['field_of_studies1']) ? ($options_fieldOf_Studies2 != '' ? TRUE : FALSE) : FALSE),
                '#suffix' => '</div></div>',
                '#options' => $options_fieldOf_Studies2,
                '#ajax' => array(
                    'callback' => 'ajax_example_dependent_dropdown_callback2',
                    'wrapper' => 'dropdown-third-replace'.$i,
                ),
            );

        // Loading values in the 3rd dropdown depends on the value selected in the second Dropdown
        if((isset($form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies2']) && ($form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies2']  != 0)))
        {
            $secondVal = $form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies2'];
            $options_fieldOf_Studies3 = _ajax_example_get_second_dropdown_options1($secondVal);
        }
        else
        {// Loading values as "Select" intially
            $options_fieldOf_Studies3 = _ajax_example_get_second_dropdown_options1(0);
        }

        // Third Dropdown Box values are dependent with second dropdown
         $form['field_of_studies_fieldset'][$i]['field_of_studies3'] = array(
                '#type' => 'select',
                '#title' => t('Field of Studies3'),
                '#prefix' => '<div id="dropdown-third-replace'.$i.'"><div class="container-inline bottom_space field_of_studies_drop_down">',
                '#suffix' => '</div></div>',
                '#required' =>      (isset($form_state["values"]['field_of_studies_fieldset'][$i]['field_of_studies2']) ? ($options_fieldOf_Studies3 != '' ? TRUE : FALSE) : FALSE),
                '#options' => $options_fieldOf_Studies3,
                '#ajax' => array(
                            'callback' => 'ajax_example_dependent_dropdown_callback3',
                            'wrapper' => 'dropdown-four-replace'.$i,
                        ),
            );

        // Loading values in the 4th dropdown depends on the value selected in the third Dropdown
        if((isset($form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies3']) && ($form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies3']  != 0)))
        {
            $thirdVal = $form_state['input']['field_of_studies_fieldset'][$i]['field_of_studies3'];
            $options_fieldOf_Studies4 = _ajax_example_get_second_dropdown_options1($thirdVal);
        }
        else
        {// Loading values as "Select" intially
            $options_fieldOf_Studies4 = _ajax_example_get_second_dropdown_options1(0);
        }

            $form['field_of_studies_fieldset'][$i]['field_of_studies4'] = array(
                '#type' => 'select',
                '#title' => t('Field of Studies4'),
                '#required' =>      (isset($form_state["values"]['field_of_studies_fieldset'][$i]['field_of_studies3']) ? ($options_fieldOf_Studies4 != '' ? TRUE : FALSE) : FALSE),
                '#prefix' => '<div id="dropdown-four-replace'.$i.'"><div class="container-inline bottom_space field_of_studies_drop_down">',
                '#suffix' => '</div></div></div>',
                '#options' => $options_fieldOf_Studies4,
            );
        }

        // Creating Remove Button
            if ($form_state['field_of_study_num'] > 1)
            {
                $form['field_of_studies_fieldset']['remove_name'] = array(
                        '#type' => 'submit',
                        '#value' => t('Remove one Field of Studies'),
                        '#limit_validation_errors' => array(),
                        '#submit' => array('remove_one_field_of_studies1'),
                        '#ajax' => array(
                            'callback' => 'add_more_callback_field_of_studies1',
                            'wrapper' => 'div_names-fieldset-wrapper',
                        ),
                );
            }

        // Creating Add One more Button
            $form['field_of_studies_fieldset']['add_name'] = array(
                '#type' => 'submit',
                '#value' => t('Add one more Field Of Studies'),
                '#limit_validation_errors' => array(),
                '#submit' => array('add_one_field_of_studies1'),
                '#ajax' => array(
                    'callback' => 'add_more_callback_field_of_studies1',
                    'wrapper' => 'div_names-fieldset-wrapper',
                ),
            );

                $form['submit'] = array(
                '#type' => 'submit',
                '#value' => t('Submit'),
                '#prefix' => '<div style="text-align:center;">',
                '#suffix' => '</div></div>',
             );
            return $form;
        }
        /**
         * Callback for both ajax-enabled buttons.
         *
         * Selects and returns the fieldset with the names in it.
         */
        function add_more_callback_field_of_studies1($form, $form_state) {
            return $form['field_of_studies_fieldset'];
        }

        function add_more_callback_language2($form, $form_state) {
            return $form['languages'];
        }

        /**
         * Submit handler for the "add-one-more" button.
         *
         * Increments the max counter and causes a rebuild.
         */
        function add_one_field_of_studies1($form, &$form_state) {
            $form_state['field_of_study_num']++;
                $form_state['rebuild'] = TRUE;
        }

        function add_one_language2($form, &$form_state) {
            $form_state['language_num']++;
            $form_state['rebuild'] = TRUE;
        }
        /**
         * Submit handler for the "remove one" button.
         *
         * Decrements the max counter and causes a form rebuild.
         */
        function remove_one_field_of_studies1($form, &$form_state) {
            if ($form_state['field_of_study_num'] > 1) {
                $form_state['field_of_study_num']--;
            }
            $form_state['rebuild'] = TRUE;
        }

        /////////////////////////   Field of studies Dependent dropdown functions////////////////////////////////////

        function ajax_example_dependent_dropdown_callback1($form, $form_state) {

                $commands = array();
                $indexKey = substr($_POST['_triggering_element_name'], 26, 1); // Getting Iterations value $i value

                $commands[] = ajax_command_replace("#dropdown-second-replace".$indexKey, render($form['field_of_studies_fieldset'][$indexKey]['field_of_studies2']));

                    return array('#type' => 'ajax', '#commands' => $commands);
        }

        function ajax_example_dependent_dropdown_callback2($form, $form_state) {

                $commands = array();
                $indexKey = substr($_POST['_triggering_element_name'], 26, 1);  // Getting Iterations value $i value

                    $commands[] = ajax_command_replace("#dropdown-third-replace".$indexKey, render($form['field_of_studies_fieldset'][$indexKey]['field_of_studies3']));

                return array('#type' => 'ajax', '#commands' => $commands);

        }

        function ajax_example_dependent_dropdown_callback3($form, $form_state) {

                $commands = array();
                $indexKey = substr($_POST['_triggering_element_name'], 26, 1);  // Getting Iterations value $i value

                    $commands[] = ajax_command_replace("#dropdown-four-replace".$indexKey, render($form['field_of_studies_fieldset'][$indexKey]['field_of_studies4']));

                return array('#type' => 'ajax', '#commands' => $commands);

        }

        function _ajax_example_get_second_dropdown_options1($key)
        {

                if($key != 0)
                    {
                        $option_Ajax_Values = _get_field_studies_mstr_ONE($key);
                    }
                else
                    {
                        $option_Ajax_Values =  array('Select' => t('Select'));
                    }
                return $option_Ajax_Values;
        }

```

# Answer
> 3 votes
The function specified in the **#ajax\['callback'\]** can only return one element of the form (not including subsidiaries):

```
function test_form($form, $form_state) {
  $form['ajax_element'] = array(
    ...
    '#ajax' = array(
      'callback' => 'test_form_ajax_callback',
      'wrapper' => 'element1-wrapper', // or element2-wrapper, but not both at once
    ),
  );

  $form['element1'] = array(
    ...
    '#prefix' = '<div id="element1-wrapper">',
    '#suffix' = '</div>',
  );

  $form['element2'] = array(
    ...
    '#prefix' = '<div id="element2-wrapper">',
    '#suffix' = '</div>',
  );

  return $form;
}

function test_form_ajax_callback($form, $form_state) {
  return $form['element1']; // or $form['element2'], but not both at once
}

```

That's why you should use a common div-wrapper or fieldset for all child elements you want to update. For example:

```
    function mymodule_test_form($form, $form_state) {
          // div wrapper
          $form['terms'] = array(
            '#tree' => TRUE,
            '#prefix' => '<div id="terms">',
            '#suffix' => '</div>',
          );

          $values = isset($form_state['values']['terms']) ? $form_state['values']['terms'] : array();
          $values += array('term' . (count($values)+1) => 'none');
          $parent = 0;
          foreach ($values as $input_name => $tid) {

        if ($parent === 'none' || !($terms = taxonomy_get_tree(1, $parent, 1))) {
          break;
        }

        // Data for Select
        $options = array('none' => '<none>');
        foreach ($terms as $term) {
          $options[$term->tid] = $term->name;
        }

        // Creating Select
        $form['terms'][$input_name] = array(
          '#type' => 'select',
          '#options' => $options,
          '#default_value' => $tid,
          '#ajax' => array(
            'callback' => 'mymodule_test_form_ajax_callback',
            'wrapper' => 'terms',
          ),
        );

        $parent = isset($options[$tid]) ? $tid : 'none';
      }

      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
      );

      return $form;
    }

    /**
     * AJAX callback
     */
    function mymodule_test_form_ajax_callback($form, $form_state) {
      return $form['terms'];
    }

```

But it's possible not always. So, in such case you should use **#ajax\['callback'\] with set of commands** instead of **#ajax\['wrapper'\]**:

```
function test_form($form, $form_state) {
  $form['ajax_element'] = array(
    ...
    '#ajax' = array(
      'callback' => 'test_form_ajax_callback',
    ),
  );

  $form['element1'] = array(
    ...
    '#prefix' = '<div id="element1-wrapper">',
    '#suffix' = '</div>',
  );

  $form['element2'] = array(
    ...
    '#prefix' = '<div id="element2-wrapper">',
    '#suffix' = '</div>',
  );

  return $form;
}

function test_form_ajax_callback($form, $form_state) {
  $commands[] = ajax_command_insert('#element1-wrapper', drupal_render($form['element1']));
  $commands[] = ajax_command_insert('#element2-wrapper', drupal_render($form['element2']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

And when you select your 1st element you should update all your next elements, not only 2nd

---
Tags: forms
---


# Question
Title: node/[nid]/edit does nothing. how to troubleshoot?
I'm trying to edit a node in Drupal 6. The edit tab is visible and clickable and everything, and directs to the proper path (/node/\[nid\]/edit) but... nothing happens. How do I troubleshoot this? I don't see any weird edit page templates in the theme or anything. I didn't develop this site or this theme but am now maintaining it. How do I begin troubleshooting something like this?

# Answer
> 0 votes
My first step would be to watch the request with Firefox's Live HTTP Headers. This will tell you if the request is actually going out or not.

If it is, then you need to check server logs to see if the request is being processed. You may also need to add some `watchdog()` calls in the core node.module to track it down.

If the request isn't going through, then I suspect you have some rogue Javascript that is intercepting the click. Disable JS and retest. Another possibility could be that you have a CSS positioned element over the tab, and that is actually catching the click event. Go through the body with Inspect Element and double check all of that.

---
Tags: 6, nodes
---


title: Insert into List(Text) Field

text:
# Question
Title: Insert into List(Text) Field
I have a Drupal content type that includes Zip Codes (Postal Codes). An unlimited number of Zip Codes is allowed, and the Zip Codes are defined in the "**Allowed Values List**" in the field definition. I have many Zip Codes that I need to insert, and have them staged them and their relationship to nodes in a temporary database table.

I do the following insert to both "**field\_data\_field\_zip\_codes**" and "**field\_revision\_field\_zip\_codes**", but I still do not see the values in the online Content.

Has someone done this type of thing before, and know what I am missing? I looked at using "Feeds" but that module doesn't seem to support multi-value fields, just flat tables.

```
INSERT INTO  field_revision_field_wp_zip_codes
SELECT c.entity_type                     AS entity_type
      ,'wp_content_component'            AS bundle
      ,0                                 AS deleted
      ,c.entity_id                       AS entity_id
      ,c.entity_id                       AS revision_id
      ,'und'                             AS language
      ,(@rownum:=@rownum+1) - 1          AS delta
      ,z.zip                             AS field_wp_zip_codes_value
FROM field_data_field_wp_cc_id c
  INNER JOIN cc_zips z
     ON z.cc = c.field_wp_cc_id_value,
     (SELECT @rownum:=0) r
 WHERE z.cc = '1039'
 AND c.entity_id = '3699';

```

# Answer
> 0 votes
As for any application, unless you are perfectly sure of what you are doing, are comfortable with it and have a good understanding of the inner working of the Field API and the SQL storage engine for fields, you shouldn't try to do your insert directly in SQL.

Instead, you should use the Node or Entity APIs to load your contents, update them and save them back in PHP code. This will be more expensive performance-wise, but much more easier to implement and maintain.

---
Tags: entities
---


# Question
Title: Do a render foreach loop on a regular field?
I have a regular field with multiple values, If i do

```
render( $fields['field1'] )

```

It prints

```
Field1_value1
Field1_value2
Field1_value3
etc

```

Am trying to get it to output like this

```
[Field1_value1]
[Field1_value2]
[Field1_value3]
etc

```

To add `[` and `]` to the output. I thought of using a foreach loop, but the field array is like such

```
'#title' => 'xxxx',
'#type' => 'xxxx',
...
'0' => <array>,
'1' => <array>,
'2' => <array>,

```

How can I get it to loop throught the `[0], [1], [2] etc` only?

Note: I have no control on how many multiple values the field may have, so I have to loop.

---

Another solution that worked well for me: Display comma-separated list of taxonomy terms?

You can make use of the power of field.tpl.php.

# Answer
```
$field_values = element_children($fields['field1']);
foreach($field_values as $field_value) { ... }

```

I was looking for the answer to this too, and ended up hunting through the `render()` function. It wasn't too far down the chain: `drupal_render()` calls element\_children().

> ## element\_children
>
> Identifies the children of an element array, optionally sorted by weight.
>
> The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal\_render() for details.
> 1 votes

# Answer
Why don't you try a regular expression loop after the print? See here.

If you're really experiencing problems with the loop, check out the documentation for preg\_replace\_callback().
> -1 votes

---
Tags: entities
---


# Question
Title: How to set $base_url when running a site in a subdomain?
I just uploaded a site to a remote server. The url is a subdomain: mySubdomain.myDomain.com.

The site just shows the front page. If I tried to navigate to other page (ex.: el-graner) I get this message:

```
Not Found

The requested URL /ca/el-graner was not found on this server.

```

I set the $base\_url variable in sites/default/settings.php in this way, then clear all caches...but not working at all.

```
$base_url = 'http://mySubdomain.myDomain.com';

```

What are the settings I need to do when running a drupal site in a subdomain?

# Answer
In the .htaccess file, you should also uncomment the following line. (Remove the *#* character.)

```
# RewriteBase /

```
> 0 votes

# Answer
Have you tried clearing cache after uploading to remote server?

If it didn't help, you could try installing Global Redirect module. It may resolve your problem, or at least can help reduce the possibility of problems created by path aliases.
> 1 votes

---
Tags: uri
---


title: enable viewing access to anonymous user

text:
# Question
Title: enable viewing access to anonymous user
I have the Content Access 7.x-1.2-beta1 module installed. I would like to enable access to a few basic pages, not all of them, for everyone including unauthorized users. I only see how to change the access for control for specific users or for all nodes of one type. How would I fix this? thanks!

# Answer
> 1 votes
Content Access has "Per content node access control settings" available for each content type.

If you navigate to the "Access control" tab for your content type (or navigate to admin/structure/types/manage/content\_type/access) you should see the following fieldset:

As the description suggests, once you've enabled that setting each piece of content of that content type will have an 'Access Control' tab. From there you can decide which roles should be able to access that individual piece of content.

This is what the 'Access Control' tab looks like once you've enabled that setting:

---
Tags: users
---


title: page visible to unathenticated users

text:
# Question
Title: page visible to unathenticated users
> **Possible Duplicate:**
> enable viewing access to anonymous user

I can't remember how to make certain pages visible to the public, only blocks. My site is private but I would like for 3-4 pages to visible to ALL users. How would I go about implementing this? Thanks!

# Answer
> 0 votes
Here's a screenshot of clean install with Content access module and Rubik admin theme:

---
Tags: users
---