# Question
Title: How can I #ajax in multiple elements on a single custom field widget?
I have created a custom field type that has 3 columns – **product, color, and quantity**.

Ideally, the user will only see 1 dropdown from which to pick a **product**. Picking a product should then load the 2nd dropdown showing only the **colors** available for that product. Picking a color should then show a textfield where the user can enter a **quantity**. If the user picks a different product, the 2nd dropdown would reload with the colors available for that product.

In a normal FAPI form I can do this kind of thing just fine by using the #ajax properties of an element and doing `return drupal_rebuild_form('my_form_name', $form_state);` in the callback, and then in the original form constructor actually checking the `$form_state['values']` array to see what needs changing (i.e. if a "product" has been chosen, I can use that value to pre-fill the "colors" dropdown). In a widget this same logic doesn't seem to apply, mainly because you can have a multi-value field (in my current case its *unlimited*) and because doing something like `return drupal_rebuild_form(...)` doesn't run my hook\_field\_widget\_form().

The only thing that I've gotten to work is using the `#element_validate` property on the `#ajax` element to run a validation function which invokes `$form_state['rebuild'] = TRUE;` and then throws some dummy content into the `$form` via something like `$form['my_custom_namespace'][$delta_or_something]['product'] = $value_chosen_by_user;`, then in the original form constructor I can check `if (isset($form_state['my_custom_namespace'][$delta_or_something]['product'])) { ... }`.

This is wacky, this is a lot of extraneous code, and it feels like a straight hack. I pulled the `#element_validate` trick from the addressfield module, which make me think this is the best method folks are currently using to do this. Is that really the case? Are there any other D7 modules that provide fields like this that I can use as an example?

My current code is below. This doesn't work with a multi-value field – there is a validation error that is occurring when multiple products and colors are chosen :( Regardless, maybe someone can help...

**field\_supplemental\_item.install:**

```
/**
 * Implements hook_field_schema().
 */
function field_supplemental_item_field_schema() {
  $columns = array(
    'product' => array('type' => 'int', 'not null' => FALSE),
    'color' => array('type' => 'int', 'not null' => FALSE),
    'qty' => array('type' => 'int', 'not null' => FALSE),
  );
  return array(
    'columns' => $columns,
  );
}

```

**field\_supplemental\_item.module:**

```
<?php

/**
 * Implements hook_field_info().
 */
function field_supplemental_item_field_info() {
  return array(
    'field_supplemental_item' => array(
      'label' => t('Supplemental Item'),
      'description' => t('A field that references additional products to add to an order.'),
      'settings' => array(),
      'instance_settings' => array(),
      'default_widget' => 'field_supplemental_item_default_widget',
      'default_formatter' => 'field_supplemental_item_default_formatter',
    ),
  );
}

/**
 * Implements hook_field_settings_form().
 */
function field_supplemental_item_field_settings_form($field, $instance, $has_data) {
  $form = array();
  return $form;
}

/**
 * Implements hook_field_instance_settings_form().
 */
function field_supplemental_item_field_instance_settings_form($field, $instance) {
  $form = array();
  return $form;
}

/**
 * Implements hook_field_formatter_info().
 */
function field_supplemental_item_field_formatter_info() {
  return array(
    'field_supplemental_item_default_formatter' => array(
      'label' => t('Default'),
      'field types' => array('field_supplemental_item'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function field_supplemental_item_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  foreach ($items as $delta => $item) {
    $element[] = array('#markup' => "here i am!");
  }
  return $element;
}

/**
 * Implements hook_field_widget_info().
 */
function field_supplemental_item_field_widget_info() {
  return array(
    'field_supplemental_item_default_widget' => array(
      'label' => t('Default'),
      'field types' => array('field_supplemental_item'),
      'settings' => array(),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function field_supplemental_item_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element_key = drupal_html_id('field-supplemental-item');

  $element['#prefix'] = "<div id='{$element_key}'>";
  $element['#suffix'] = "</div>";
  $element['element_key'] = array(
    '#type' => 'value',
    '#value' => $element_key
  );

  if (isset($form_state['field_supplemental_item'][$element_key]['product'])) {
    $product_id = $form_state['field_supplemental_item'][$element_key]['product'];
  } else if (isset($items[$delta]['product'])) {
    $product_id = $items[$delta]['product'];
  } else {
    $product_id = NULL;
  }

  // Product
  $element['product'] = array(
    '#type' => 'select',
    '#title' => 'Product',
    '#options' => array('_none' => '- Select -') + _field_supplemental_item_get_data('products'),
    '#default_value' => $product_id,
    '#ajax' => array(
      'callback' => 'field_supplemental_item_field_widget_product_callback',
      'wrapper' => $element_key,
      'method' => 'replace',
    ),
    '#element_validate' => array('field_supplemental_item_field_widget_product_validator'),
    '#limit_validation_errors' => array(), // Don't validate any element when the product is changed.
  );

  // Color
  $element['color'] = array(
    '#type' => 'select',
    '#title' => 'Color',
    '#options' => (($product_id)) ? _field_supplemental_item_get_data('colors', $product_id) : array(),
    '#limit_validation_errors' => array(), // Don't validate any element when the product/color is changed.
  );

  // Quantities
  // ...

  return $element;
}

/**
 * Element validate callback: rebuilds the form on value change and stores the current value in the $form_state for retrieval on rebuild.
 */
function field_supplemental_item_field_widget_product_validator($element, &$form_state) {
  // If the product was changed, rebuild the form.
  if ($element['#default_value'] != $element['#value']) {
    $form_state['rebuild'] = TRUE;
  }

  // Store the value in the form state for retrieval by the
  // widget form regardless of where the widget sits in the $form array.
  $form_state['field_supplemental_item'][$element['#ajax']['wrapper']]['product'] = $form_state['triggering_element']['#value'];
}

function field_supplemental_item_field_widget_product_callback($form, $form_state) {
  $product_id = $form_state['triggering_element']['#value'];

  // The target element is one element below the triggering selector.
  $array_parents = $form_state['triggering_element']['#array_parents'];
  array_pop($array_parents);

  // Iterate over the form parents to find the element.
  $element = $form;
  foreach ($array_parents as $name) {
    $element = &$element[$name];
  }

  $element['product']['#default_value'] = $product_id;
  $element['color']['#options'] = _field_supplemental_item_get_data('colors', $product_id);

  // Return the element, but remove the '_weight' element inserted
  // by the field API.
  unset($element['_weight']);

  return $element;
}

/**
 * Implements hook_field_validate().
 */
function field_supplemental_item_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {}

/**
 * Implements hook_field_widget_error().
 */
function field_supplemental_item_field_widget_error($element, $error, $form, &$form_state) {}

/**
 * Implements hook_field_is_empty().
 */
function field_supplemental_item_field_is_empty($item, $field) {
  return (empty($item['product']));
}

```

**EDIT 9/16/12:** Let me add that I'm currently able to achieve this by replacing the entire form, which feels completely ridiculous and can be quite intensive on a large and bulky entity edit form – and requires looking through the $form\_state to get the data I need for all $deltas...:

```
function hook_field_widget_form(...) {
  $form['#prefix'] = '<div id="mymodule-field-widget-form-wrapper">';
  $form['#suffix'] = '</div>';
  ...
}
function mymodule_field_widget_form_ajax(&$form, &$form_state) {
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

```

# Answer
Hierarchal Select module is the perfect solution for the problem you are facing. I have done this to list Categories in First Select Box and In Second Select box list of Groups associated with categories using HS plugin.

Please see below code:

```
function category_groups_hr_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $account = clone($user);
  if ($form_id == "question_node_form") {
    $category_group_hs = array();
    $group_categories = taxonomy_get_tree(3, 0, 1, FALSE);
    asort($group_categories);
    foreach ($group_categories as $item) {
      $category_group_hs[$item->tid]['label'] = $item->name;
      $query = db_select('taxonomy_index', 't');
      $query->addTag('node_access');
      $query->join('node', 'n', 'n.nid = t.nid');
      $query->join('og', 'og', 'n.nid = og.etid');
      $query->condition('t.tid', $item->tid);
      $query->condition('n.type', 'groups');
      $query->addField('t', 'nid');
      $query->addField('t', 'tid');
      $query->addField('n', 'title');
      $query->addField('og', 'gid');
      $query->addField('n', 'uid');
      $result = $query->execute();
      while ($group = $result->fetchObject()) {
          $category_group_hs[$item->tid]['children'][$group->nid] = array('label' => $group->title);
      }
    $category_id = '';
    $group_nid = '';
    $title = t('Select Category > Group :');
    $form['hs_category_group'] = array(
      '#type' => 'hierarchical_select',
      '#title' => $title,
      '#size' => 1,
      '#required' => TRUE,
      '#config' => array(
        'module' => 'hs_smallhierarchy',
        'params' => array(
          'hierarchy' => $category_group_hs,
          'id' => 'hs-category-group',
          'separator' => '|',
        ),
        'save_lineage' => 0,
        'enforce_deepest' => 0,
        'entity_count' => 0,
        'require_entity' => 0,
        'resizable' => 1,
        'level_labels' => array(
          'status' => 0,
          'labels' => array(
            0 => t('Group Category'),
            1 => t('Group')
          ),
        ),
        'dropbox' => array(
          'status' => 0,
          'title' => t('All selections'),
          'limit' => 0,
          'reset_hs' => 1,
        ),
        'editability' => array(
          'status' => 0,
          'item_types' => array(),
          'allowed_levels' => array(
            0 => 0,
            1 => 0,
            2 => 1,
          ),
          'allow_new_levels' => 0,
          'max_levels' => 2,
        ),
        'animation_delay' => 400,
        'exclusive_lineages' => array(),
        'render_flat_select' => 0,
      ),
      '#default_value' => $category_id . '|' . $group_nid,
    );
    $form['#validate'][] = 'hs_category_and_group_validate';
    $form['#submit'][] = 'hs_category_and_group_submit';
  }
}

```

I am using `hs_smallhierarchy` module to do heavy lifting... For more information on HS Plugin API CHECK API.txt file inside hierarchical\_select module....

Hope you can able to crack it using HS module..
> 2 votes

---
Tags: 7, entities, ajax
---


# Question
Title: How to create statistical reports about data contained in various content types?
I have page in drupal for hockey league. Till now, there was only nodes, some specific content types, simple views, but now, they want to create full statistics for the entire league. I was looking for some modules, but unsuccessfully.

My friends from this league want to type final score of match and system will know who is winner, credit points and calculate any other statistics data for team. I was trying to create something like this with rules, but I failed. I dont know ho to get SUM of fields from one content type, then calculate some value and get it to another content type, filter some values in views and get it to another view for his filtering.

I think that rules, views are insufficient for this. I need help, what way to choose.. trying do this in modelus or best way is to learn module development and create my own module to do this?

# Answer
You may want to look at Computed field. You can use PHP to do calculations from information from other fields and show display the result. If you want, you can also save it to databse for use elsewhere. You can also try to do it in Views with Views calc. I think Views would be your better bet.
> 0 votes

---
Tags: 7, log-messages
---


# Question
Title: Access view exposed filter arguments in field view
My problem is that I can't access `$view->filter['my_filter_field']` from my `views-view-fields.tpl.php` file.

In `views-view.tpl.php` I get my correct View object with the arguments sent via AJAX as exposed filter parameters, but how can I get this information without using the field's template file?

# Answer
You have to use object methods (functions) to get and set exposed filter inputs.

E.g.

Use `$views->get_input_filter` and `$views->set_input_filter($filters)`. The format for filters is as follows:

```
$filters = array(
  'identifier' => '[your ident name]',
  'value' => '[your value']
);

```
> 0 votes

---
Tags: 7, views
---


title: How to test a sandbox module

text:
# Question
Title: How to test a sandbox module
I found a sandbox module that I want to test.

What should I do to use it on my site?

# Answer
The easiest thing to do is to get a version of git for your machine. On Windows, TortiseGIt works reasonably well. You can then use that to checkout a version of the sandbox module. If there are patches, you can apply them to the module. Then you just need to upload the module to your Drupal site with your normal methods (don't forget to run update.php).

A lot of this is made easier if you are using an IDE, as newer ones are well integrated with git.
> 3 votes

---
Tags: community-official-site
---


title: Allow user to pick a location

text:
# Question
Title: Allow user to pick a location
I would like to add a field to my node that allows the user to search for a location like a city and pinpoint that location on the map or pick a location on a map but without having to zoom in from viewing the whole world (like the problem I am having using the geofield). Cheers

# Answer
> 0 votes
The geolocation field module solved this problem.

---
Tags: location
---


# Question
Title: Server side Drupal install as git local repo
I have a Drupal install on a shared server and would like to do some version control on it, namely git.

I'm a beginner at Drupal and only just starting with git so I've become a bit overwhelmed with any instructions on the web for doing this, as they assume you're proficient with one or the other.

What I want my setup to be is

* The hosted Drupal install is my git's "local" repo.
* Make changes, commit
* Push to github

The problem is that as it is a shared server, I don't think I can install git. So, firstly, is this workflow possible without installing git on the server? And, if so, secondly, could somebody please point me in the right direction for setting this up.

As always, if somebody has a better way of doing it, please say!

# Answer
Fair warning, I don't know Drupal, so it's possible you're describing a common workflow. All the same I know a thing or two about git, and what you describe is a bit backwards. The problem is here:

> * The hosted Drupal install is my git's "local" repo.
> * Make changes, commit
> * Push to github

By treating your production environment, the hosted Drupal install, as your local repository, you basically circumvent the benefits of versioned deployment. If you break that local, you break the site. If you want to work on a test feature branch (maybe new content you're still creating), you have to expose it to the world. A more canonical approach might be:

* Commit to the site locally (on your computer) as well as a clone on your hosted site. Use github to push and pull between them. The Drupal docs have a solid example of this.
* Commit to the site locally (on your computer), and use a post-receive hook to deploy the Drupal site, if your hosting provider supports git installation. This is a common setup in web application deployment.

In either case, note that you want a truly local copy, some place to experiment around, rather than the live website.
> 2 votes

---
Tags: 7, workflows, version-control
---


# Question
Title: Display a view of geolocation fields with lat lon on a google (or equiv) map
I have a geolocation module installed with a field that geolocates and gives a lat lon value. Then I want to use a view of these values to show them in google maps or equivalent. If there is a quick and dirty solution would be good, otherwise I would spend time coding one solution.

# Answer
I used this sandbox module geolocation views with geolocation field module. http://drupal.org/sandbox/xandeadx/1782036
> 0 votes

---
Tags: location
---


# Question
Title: How do I get the (date)timestamp since last cron run?
I'm building a module but am stuck.. I need the timestamp from the previous cron as I run a hook\_cron job so I can check which nodes are new and email those.

So I need the date/time stamp from the last cron run but how do I get there'?

# Answer
A UNIX timestamp of the last cron run can be fetched with:

```
variable_get('cron_last');

```

If you need to, you can easily manipulate a UNIX timestamp with PHP's date function.
> 20 votes

# Answer
hook\_requirement() function can help you.

Check this out: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_requirements/7

In your module file write hook\_requirement() function.

```
function hook_requirements($phase) {
if ($phase == 'runtime') {
    $cron_last = variable_get('cron_last');

    if (is_numeric($cron_last)) {
      $requirements['cron']['value'] = $t('Last run !time ago', array('!time' => format_interval(REQUEST_TIME - $cron_last)));
    }
    else {
      $requirements['cron'] = array(
        'description' => $t('Cron has not run. It appears cron jobs have not been setup on your system. Check the help pages for <a href="@url">configuring cron jobs</a>.', array('@url' => 'http://drupal.org/cron')),
        'severity' => REQUIREMENT_ERROR,
        'value' => $t('Never run'),
      );
    }

    $requirements['cron']['description'] .= ' ' . $t('You can <a href="@cron">run cron manually</a>.', array('@cron' => url('admin/reports/status/run-cron')));

    $requirements['cron']['title'] = $t('Cron maintenance tasks');
  }
}

```
> 3 votes

---
Tags: 7, cron
---


# Question
Title: How to pass extra information to search results page using hook node_api
I want to show some extra information on the search result page in Drupal. I want to implement it in a module (and not in the theme).

I am using this code in my custom module:

```
function custommodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op){
     case 'search result':
      return 'TEST';
      break;
    }

```

When I debug the statement, the line return 'Test' is executed. I would expect this extra information to show up at: search-result.tpl.php in the variable $info.

However this extra information is not included. Has anyone got a clue how to pass this extra information so it shows up at the result page?

# Answer
You could try this

```
<?php

function your_custom_module_name_preprocess_search_results(&$variables){
    $var['info'] = 'the_value_you_want_to_include';
}
?>

```

Now you can use the variable $info in search-result.tpl.php.
> 1 votes

---
Tags: search, nodes
---


# Question
Title: Adjust a view so there is one image of size normal and other images are thumbnails
I have created a gallery for every user. I would now like to alter the view so that one of the images is a medium size and the other images are thumb nail size. I know you can adjust the layout in a view but I am not sure how to change the size of one image and keep the others as the default thumbnail.

# Answer
> 2 votes
Check out the View Nodes Split module.

> This module allows site administrators or builders to have a different view mode for the first nodes of a view result.
>
> If you ever had (or currently have) this scenario: you have a view of nodes but you want that the first node (or first X nodes) to have a different view mode, then this module is for you. The module can split the results from a view into 2 lists. It actually does not make 2 separate lists, it just uses a a different view mode to render the first X nodes from a view.

You can also use a view attachment to display a node and attach more nodes to it. Make sure you offset your attached view by 1.

---
Tags: views, media
---


title: fboauth get user info

text:
# Question
Title: fboauth get user info
I implemented fboauth module. It works fine and I can to link my site's account with facebook account.

I need if user logged in and his account is linked with facebook, show his picture at some block, else don't show picture or show some other picture.

Can you help me?

# Answer
If you use the function `fboauth_fbid_load()` you get facebook id or FALSE. With the facebook id you can obtain profile picture.
> 2 votes

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


# Question
Title: Removing second copy of ctools module from filesystem
I have a site where two version of ctools are on the filesystem.

The first version is in sites/all/modules - this is correct and where I want it The second version is in sites/all/modules/contrib - this isn't correct and was placed there by custom formatters make file.

The registered path in the system table is sites/all/modules/contrib. I want to remove the contrib folder as it shouldn't exist and is causing issues when I want to upgrade ctools using make files.

Removing the folder gives an undeclared function error as drupal expects it in that contrib folder. Using drush registry rebuild isn't an option as the error still appears because ctools is embedded so deep.

Changing the paths in the system table still brings up the undeclared function error, this could be caused by APC caching though.

Is there a simple way of removing references to this folder and using the copy of the module in sites/all/modules without causing such a huge impact?

# Answer
> 2 votes
Unless you have `apc.stat = 0`, then APC caching is likely not the problem. You can always set `apc.enabled = 0` as a temporary measure until you get the problem fixed.

What version of Drupal?

If you are on Drupal 7, you could try deleting the extra copy and then running Registry Rebuild via drush. Follow the instructions on the project page.

The other method that should work for Drupal 6 and 7 would be to take a database backup, and then hand edit the `{system}` table. If it has both "sites/all/modules/coots" and "sites/all/modules/contrib/coots" in it, delete out the contrib entries. If it just has the "sites/all/modules/coots" entries, edit them to take out contrib. Then manually clear out all of the cache tables.

Make sure you backup your database no matter what you do. Both of these are dangerous operations.

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


# Question
Title: Module development - Layout of dynamic content
I am creating a drupal module that receives content from a Web Based XML API. The module takes some search parameters from a user and embeds these into a XML command. I am at the point where I am receiving back a response and am able to process the returned data and display it on the page using a simple return statement. At the moment I am simply returning a html table that is created in the module.

What I would like to do is make content available to other Drupal modules such as Views or Display Suite. But as this data is not coming from the database but being created on the fly I am not sure where to start. Any help would be much appreciated.

Thanks Simon

# Answer
Some pointers:

Try getting the data in your database somehow. You could import the data into nodes or you could use the Entity API. That way, you could expose your data to modules such as Views. The only thing you'll need to do left is to synchronize the data in your database with the XML data that you're receiving.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to make a multi-site instance aware of shared module directory?
My team inherited a Drupal 7 multi-site installation that was originally built with a custom installation profile and Drush make. I have all these sites running correctly in our environment now and want to bring an additional Drupal 7 standalone instance we support under this new multi-site configuration. I copied the database and created a corresponding subdirectory in the sites tree along with the proper edits to the sites.php file. The site does appear correctly when tested in a browser but the modules visible to the other instances are not seen by this site. Those modules are located under the profiles tree. I don't expect to need to use the install profile again and am inclined to copy the profiles/myprofile/modules directory contents to sites/all/modules to address this situation but am concerned about potential database dependencies. What is the best way to clean this up and have all multi-site instances aware of the same common modules?

# Answer
> 1 votes
Quick way...Run

```
variable_set('install_profile', 'name_of_custom_install_profile');
drupal_flush_all_caches();

```

from somewhere in the new site.

That'll trick your new site into thinking it was installed with the custom profile, and it should start checking that folder for contrib modules.

---
Tags: 7
---


title: Can't get javascript to load

text:
# Question
Title: Can't get javascript to load
I am trying to load a javascript file in my .info file, but I can't tell if it is loading or not. What is the best way to find out if it is loaded and if it is the right path?

# Answer
> 3 votes
Some things you can try:

The easiest way, in my opinion, is to look at the source of your page. Right click the page of your website and click "View source" (or something similar). Try searching for the reference to the javascript file in there.

This could be somewhat more difficult if you're using Javascript aggregation, which means that your file might be concatenated with other Javascript files into one big file. In that case: open the files you see in your source and search for something that's in your Javascript file.

You could also try to display an alert by appending `alert('It works!')` to your file.

Edit:

As said by Clive in the comments: you might need to clear your cache for the Javascript file to be included. You can clear the cache at `/admin/config/development/performance`.

---
Tags: javascript
---


# Question
Title: Drupal 7 user register form in overlay on page load
One of my requirements is to show the user registration form in an overlay kind of interface.

From the Examples module issue queue, comment #14 http://drupal.org/node/930058 I found a module, learned the hook\_admin\_paths() and hook\_admin\_paths\_alter(). I installed that module in my local test site. Added `"user/register"` path to `$paths` of `hook_admin_paths()` and granted permissions to use overlay. It works pretty much as expected with the click event however my requirement is to trigger the overlay for onpageload event.

I tried calling a js script which would trigger click event from `hook_overlay_parent_initialize()` and module's info file by settings `scripts[] = myoverlay.js`.

The js script looks as below,

```
(function ($) {

Drupal.behaviors.loginLoad = {
  attach: function (context, settings) {
    alert("trigger client event"); // works
    $(".menu-589 a").attr("title", "click"); // works
    $(".menu-589 a").trigger("click");
    // This one didn't work. Tried triggerHandler() and click() as well.
  }
};

})(jQuery);

```

My jQuery expertise is very limited. I'm trying to figure out how the overlay fires for onclick event.

From what I learned the paths to be opens in overlay are defined in `Drupal.settings.overlay.paths.admin`. And overlay-parent.js and jQuery BBQ does some tricks to show things in modal window.

Any help to figure out this will be appreciated.

On a side note : For Drupal 6 projects I have used modal frame api module often with onclick event. This module doesn't seems to be available for Drupal 7 and it is going to be deprecated in favor of overlay in core. Is overlay an API module ? It doesn't appear to be the case from my experience.

# Answer
I you need something like this site http://www.hospitalsreview.com/ has done for the sign up then you should try my module it will surely help you as you can see it is working on my site.

Sign Up Module
> 1 votes

# Answer
For Flocknote, I had to put the registration form/page inside an overlay that loads for users who are not logged-in on certain pages. Here's an example: http://www.flocknote.com/community

You'll notice that, when you visit that page as an anonymous user, there are some URL params added, namely `?reg=true#overlay=register/overlay/246`. Adding the '#overlay=path/to/node' should make a page open in the overlay. (I can't remember if what else I was doing with the 'reg' variable.)

I basically run a bit of code inside a custom module's `hook_init()` implementation that says: "If the user is anonymous, and this is a network node home page, `drupal_goto()` the same URL, but with the fragment `overlay=register/overlay/[nid]` added on."

This seems to work great for me.
> 1 votes

---
Tags: 7, users, modal-dialogs, javascript
---


# Question
Title: Create email everytime a webform is sent off (in custom module)
I'm trying to write some code that sends off an email every time a webform is submitted/edited.

I tried using `hook_webform_component_presave()` figuring I could just stick some mail code in this function and it would work... it didn't.

This is what I have

```
mymodule_webform_component_presave(&$component){
  mail('test@mail.com', 'subject', 'message');
}

```

I am aware that this can be done through a webforms setting, but that's not what I need.

# Answer
> 2 votes
I've solved this issue in Drupal 6 by adding a secondary submit function to the webform. In that submit function, I use webform's email handler to send my email.

In hook\_form\_alter:

```
function custom_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
        case 'a_form': // the value we stole from the rendered form
        case 'another_form_form': //Fall through, instead of trying to do case A OR B:
        case 'the form I want to send emails from':
            $form['#submit'][] = 'my_submit';
            break;
    }
}

```

Then the secondary submit function:

```
function my_submit($form, &$form_state) {
    module_load_include('inc', 'webform', 'includes/webform.submissions');
    module_load_include('inc', 'webform', 'includes/webform.components');
    global $user;

    $node = $form['#node'];
    $sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);

    //Build the custom email array for the webform email handler
    $email = array(
     array(
      'nid' => $node->webform['nid']
      ,'eid' => count($node->webform['emails']) + 1
      ,'email' => $form_state['values']['submitted'][3]
      ,'subject' => 'Your Custom Subject Line!'
      ,'from_name' => 'default'
      ,'from_address' => 'default'
      ,'template' => '<table "style=width:100%">
              <tr><td>Hello '.$form_state['values']['submitted'][1].',</td></tr>
              <tr><td><b>More HTML goes here</b></td></tr></table>'
      ,'html' => 1
      )
     );
     webform_submission_send_mail($node, $submission, $email);
 }

```

You could also probably just use the drupal\_mail function to send the email in your custom submit function. I just haven't tested that option.

For further info, take a look at webform\_client\_form\_submit and webform\_submission\_send\_mail

---
Tags: 7, webforms
---


# Question
Title: How do I unset a region in template.php AND have it alter the body classes
In some cases I need to programmatically remove the sidebar\_first region in template.php. So, I'm doing something like:

```
function template_preprocess_page(&$variables) {
  if(my_condition){
    unset($variables['page']['sidebar_first']);
  }
}

```

this does, indeed, remove the sidebar, however, it does NOT alter the body classes. So, I still have a class of

```
body.two-sidebars

```

...even though I unset one of them (so the proper class would be body.one-sidebar).

How can I programmatically remove a sidebar AND have it alter the body classes properly?

(please, for various reasons dont suggest creating a new template suggestion and altering the sidebar there. that won't work in my case. I am asking specifically how to remove a region programmatically)

# Answer
> 1 votes
I basically figured out that the problem is that you have to do this in two different template.php functions: template\_preprocess\_page (to kill the sidebar) AND template\_preprocess\_html (to get rid of the body class I didn't want).

so first in preprocess\_page:

```
$variables['page']['sidebar_first'] = NULL;

```

then in preprocess\_html I had to get node info with menu\_get\_object(), check the node data for my condition, then parse the $variables\['classes\_array'\] to manually replace the 'two-sidebars' class and add anything else I want.

*Sheesh. Should be much easier, but I thank the guys in the other answers for helping me confirm it's not as simple as it should be.*

# Answer
> 3 votes
If you look at the default `template_preprocess_html`, you will see

```
  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-first';
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-second';
  }
  else {
    $variables['classes_array'][] = 'no-sidebars';
  }

```

If you don't want this behavior, you should implement your own version which will run after. Then, you just check your condition and muck with `$variables['classes_array']` as needed.

# Answer
> 2 votes
You should be able to find the information you need in `$variabless['classes_array']`, which contains an array of body classes. Just remove the one whose value is two-sidebars.

---
Tags: theming
---


# Question
Title: How do I  keep the sum of related nodes' specific field values in a field?
I have two different content types: "Parent" and "Child".

On Parent nodes, there is a multi-value reference field where I keep some Child nodes of this node. Every child node has a field "Integer" and I keep some integer values in it.

What I want is keeping the sum of those Integer values of all child nodes of a Parent inside a field "Sum".

So I will have:

* Parent 1 (sum=11)
    + Child one (integer=3)
    + Child two (integer=6)
    + Child three (integer=2)

Is it possible?

# Answer
> 0 votes
I managed to do this with Rules module, to keep it short.

1. By default, gave 0 to the value of integer for Parent content type.
2. Added a rule to calculate the value of Parent's integer field by summing up the values of child nodes and setting it to Parent's integer value. Event is creating new content
3. Added a rule to recalculate the value of Parent's integer field when adding or updating a Child content. For this, I am calculating the difference of new and old integer values of Child node. Then, adding this value to Parent's integer value.

If anyone is interested, I can also give the details of the rules.

Below is an export of the second rule:

```
{ "rules___aa_test" : {
"LABEL" : "__aa_test",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_update" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_parent_story" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_time_left" } },
  { "entity_has_field" : { "entity" : [ "node:field-parent-story" ], "field" : "field_time_left" } }
],
"DO" : [
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-time-left" ],
        "op" : "-",
        "input_2" : [ "node-unchanged:field-time-left" ]
      },
      "PROVIDE" : { "result" : { "difference" : "Difference" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-parent-story:field-time-left" ],
        "op" : "+",
        "input_2" : [ "difference" ]
      },
      "PROVIDE" : { "result" : { "result" : "Calculation result" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-parent-story:field-time-left" ],
      "value" : [ "result" ]
    }
  }
]

```

} }

---
Tags: 7, nodes
---


# Question
Title: Cache problems with Varnish and FBOauth module
I'm troubleshooting a problem with Facebook (FB) login on my site using the Facebook OAuth module.

Reproduction steps:

1. Be logged out of Facebook and my site
2. Log into my site using Facebook login button
3. Log out of my site (using site logout link). I'm still logged into FB
4. Use FB login button on my site to log in

I expected to end up at the home page logged in. Instead, I get redirected to the home page, but a cached version of it (so it appears I'm not logged in). Refreshing the browser causes the home page to reload logged in and I'm set from here.

The issue is the home page is being loaded from cache, but I'm not sure why. The site runs Drupal 7, Varnish, and the 7.x-1.5 version of the Facebook OAuth module.

Here are the headers from the initial FB login button click. Since I'm already logged into Facebook I'm redirected right away back to my site (this is expected).

```
Request URL:https://www.facebook.com/dialog/oauth?client_id=407390309287595&redirect_uri=http%3A//www.zujava.com/fboauth/connect&scope=email%2Cuser_about_me%2Cuser_website
Request Method:GET
Status Code:302 Found

Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:c_user=3413203; csm=2; datr=bq8bT_JILi0PrW8H9GZ5BMy6; fr=0MYU2YYrkDuegxlUi.AWVgxOkdsHe9zhvPJdDW7h70n48; lu=RgWtdyxDRmUr6dOIqyRyPhtg; s=Aa45lsbBS4F1Oll2.BQBsO2; xs=67%3AuZMhOYBden1YIw%3A2%3A1342620598; p=5; act=1342620710713%2F3%3A0; presence=EM342620710EuserFA23413203A2EstateFDutF0EsndF1EnotF0Et2F_5b_5dEuct2F134262011B0Elm2FnullEtrFnullEtwF2196532340EatF1342620710745Esb2F0CEchFDp_5f3413203F1CC; locale=en_US
Host:www.facebook.com
Referer:http://www.zujava.com/user/login
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11
Query String Parametersview URL encoded
client_id:407390309287595
redirect_uri:http://www.zujava.com/fboauth/connect
scope:email,user_about_me,user_website

Response Headers
Cache-Control:private, no-cache, no-store, must-revalidate
Connection:keep-alive
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Wed, 18 Jul 2012 14:18:46 GMT
Expires:Sat, 01 Jan 2000 00:00:00 GMT
Location:http://www.zujava.com/fboauth/connect?code=AQBbeDeOf-cd6HCy6GALaDqESzcfgTJNmh_i5iIx2IpG-KOWBTJHcylhigo82ZGR_X2SOJVzkwcvIKa7rD4dxcg2CLLDa3eZJMkDlP6D3UIU6c-iCFu_TZg6LkfLM4cOGKtu5HraaQUrLUPJd96hOsmpDuW9lzTLuBeMH4fwI7m7p3Jybig1GE06098OJCGuGos#_=_
P3P:CP="Facebook does not have a P3P policy. Learn why here: http://fb.me/p3p"
Pragma:no-cache
Set-Cookie:locale=en_US; expires=Wed, 25-Jul-2012 14:18:46 GMT; path=/; domain=.facebook.com
X-Content-Type-Options:nosniff
X-FB-Debug:GPh2t018FPktnIalVO4RrxjZAQ3onlvvFyAEgI6g08U=
X-Frame-Options:DENY
X-XSS-Protection:0

```

Next are the headers that complete the FB login on my site's side. You can see the session cookie being created in the response headers:

```
Request URL:http://www.zujava.com/fboauth/connect?code=AQBbeDeOf-cd6HCy6GALaDqESzcfgTJNmh_i5iIx2IpG-KOWBTJHcylhigo82ZGR_X2SOJVzkwcvIKa7rD4dxcg2CLLDa3eZJMkDlP6D3UIU6c-iCFu_TZg6LkfLM4cOGKtu5HraaQUrLUPJd96hOsmpDuW9lzTLuBeMH4fwI7m7p3Jybig1GE06098OJCGuGos#_=_
Request Method:GET
Status Code:302 Moved Temporarily

Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:ctools-collapsible-state=views-ui-advanced-column-petting_zu_graduates%3A1%2Cviews-ui-advanced-column-newly_published_content%3A1%2Cviews-ui-advanced-column-test%3A1%2Cviews-ui-advanced-column-html_sitemap%3A1; Drupal.tableDrag.showWeight=0; __atuvc=31%7C25%2C4%7C26%2C0%7C27%2C5%7C28%2C5%7C29; has_js=1; __utma=249598093.1349651830.1327187978.1342578105.1342618991.600; __utmb=249598093.64.9.1342621126771; __utmc=249598093; __utmz=249598093.1341848548.567.26.utmcsr=facebook.com|utmccn=(referral)|utmcmd=referral|utmcct=/l.php
Host:www.zujava.com
Referer:http://www.zujava.com/user/login
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11
Query String Parametersview URL encoded
code:AQBbeDeOf-cd6HCy6GALaDqESzcfgTJNmh_i5iIx2IpG-KOWBTJHcylhigo82ZGR_X2SOJVzkwcvIKa7rD4dxcg2CLLDa3eZJMkDlP6D3UIU6c-iCFu_TZg6LkfLM4cOGKtu5HraaQUrLUPJd96hOsmpDuW9lzTLuBeMH4fwI7m7p3Jybig1GE06098OJCGuGos
URL fragment
#:_=_

Response Headers
Age:0
Connection:keep-alive
Content-Length:0
Date:Wed, 18 Jul 2012 14:18:47 GMT
Location:http://www.zujava.com/
Via:1.1 varnish
X-Pantheon-Edge-Server:10.183.199.123
X-Varnish:181771624
cache-control:no-cache, must-revalidate, post-check=0, pre-check=0
content-type:text/html
etag:"1342621126"
expires:Sun, 19 Nov 1978 05:00:00 GMT
last-modified:Wed, 18 Jul 2012 14:18:46 +0000
server:nginx/1.0.15
set-cookie:SESS650d63be2a9c0113cd1740e78b8184ed=961WQoY1iwAJSjEBiuglfI_TDsz3VA8BReyLK2wnz44; expires=Fri, 10-Aug-2012 17:52:07 GMT; path=/; domain=.zujava.com; HttpOnly
x-drupal-cache:MISS

```

The final home page request:

```
Request URL:http://www.zujava.com/#_=_
Request Method:GET
Status Code:200 OK (from cache)
URL fragment
#:_=_

```

I believe this indicates the home page is being loaded by the local browser cache, and no request is actually being made to the server. If so, I'm confused as to why. I assume the problem would be in how I'm telling browsers to cache the home page?

Here are the response headers for a logged out page load of the home page:

```
HTTP/1.1 200 OK
Server: nginx/1.0.15
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
x-drupal-cache: HIT
Etag: "1342622308-0"
Content-Language: en
x-generator: Drupal 7 (http://drupal.org)
Cache-Control: public, max-age=10800
Last-Modified: Wed, 18 Jul 2012 14:38:28 +0000
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Content-Encoding: gzip
Content-Length: 8686
Date: Wed, 18 Jul 2012 14:50:55 GMT
X-Varnish: 658648930 658583362
Age: 295
Via: 1.1 varnish
Connection: keep-alive
X-Pantheon-Edge-Server: 10.183.199.163

```

Any hints or ideas would be welcome.

# Answer
> 1 votes
we ran in the same issue during regular login/registration and have implemented a javascript "hack" to:

* on login set “user” cookie (session only)
* on all anonymous pages include a javascript that will check for the “user” cookie.
* if a cookie is found then a logged in user is on a cached page. Force reload of the page with javascript.
* on logout clear the “user” cookie.

The code is available here: http://drupal.org/sandbox/clivelinsell/1751804

You can read more of the history about it here.

---
Tags: 7, users, proxies, social-network
---


title: Drupal form API date popup

text:
# Question
Title: Drupal form API date popup
> **Possible Duplicate:**
> How to remove format description in date\_popup form field?

Hi I am creating a drupal 6 module and I have used drupal form API date popup fields to allow users to enter date. Everything is going on fine but I am getting a format description for date popup field as FORMAT 23/05/2012. I don't know how to remove this description.As shown in the image below

# Answer
> 1 votes
To make a correct format you can make use of `#default_value`

See here

> **Description**: Format a date selection box. The #default\_value will be today's date if no value is supplied. The format for the #default\_value and the #return\_value is an array with three elements with the keys: 'year', month', and 'day'. For example, array('year' =\> 2007, 'month' =\> 2, 'day' =\> 15)

# Answer
> 0 votes
try CSS to remove it. insert some body and page classes.

---
Tags: 6, forms
---


# Question
Title: Getting libraries to load with newer jQuery using jqmulti
I'm kind of a newbie to this so I could be missing something really obvious, but I'm having trouble getting specific libraries to load with jQuery 1.7 in noconflict mode using jqmulti. I'm working on a theme based off twitter\_bootstrap, and the bootstrap.js library is dependent on more recent jQuery. I've got jqmulti recognizing and loading 1.7 if I check "load even if no libraries are assigned" but when I have that unchecked and attempt to use hook\_jqmulti\_files() to assign particular libraries, nothing happens.

This is what I have in my template.php:

```
function regent_jqmulti_files() {
    return array(
        'sites/all/themes/regent/bootstrap/js/bootstrap.js',
        'sites/all/themes/regent/bootstrap/js/bootstrap.min.js'
    );
}

```

but when I look at my rendered html, the library is loaded, but nothing about noconflict mode, and jQ 1.7 is nowhere to be found. I'm sure I'm missing something basic and stupid, this being the first time I've tried to set something like this up.

# Answer
If you have checked "load even if no libraries are assigned", jQuery 1.7 should load regardless of anything else you do. So in your HTML you should see Drupal's jQuery loading, and you should also see jQuery1.7 loading, and also a script called `switch.js`, which takes care of the `noConflict()` mode. If you don't see those loading, there is a problem that's not related to your hook. Check the jQuery Multi settings page, does it list the jQuery version it's using?
> 1 votes

# Answer
As you are talking of a template.php file, I get you are talking of theme code. The only hooks a theme can implement are alter hooks (the ones called with `drupal_alter()` and with a name ending in `_alter`), in Drupal 7. (Theme functions are not hooks.)

If you look at the code of drupal\_alter(), you will notice it contains the following lines.

```
// Allow the theme to alter variables after the theme system has been
// initialized.
global $theme, $base_theme_info;
if (isset($theme)) {
  $theme_keys = array();
  foreach ($base_theme_info as $base) {
    $theme_keys[] = $base->name;
  }
  $theme_keys[] = $theme;
  foreach ($theme_keys as $theme_key) {
    $function = $theme_key . '_' . $hook;
    if (function_exists($function)) {
      $functions[$cid][] = $function;
    }
    if (isset($extra_types)) {
      foreach ($extra_types as $extra_type) {
        $function = $theme_key . '_' . $extra_type . '_alter';
        if (function_exists($function)) {
          $functions[$cid][] = $function;
        }
      }
    }
  }
}

```

Differently, module\_implements() (used from any function that invokes hooks) doesn't check hooks implemented by themes.
> 0 votes

---
Tags: javascript
---


# Question
Title: GMaps page with a marker pin on your location based on address we supply
i want to add marker directly on Gmaps on location based on address we supply. Or else i want the location based on name, longitude and latitude what we supply. FYI: i am using gmap and locatin modules for druapl 7. Please help on the same. Thank you in adavance

# Answer
> 1 votes
To make a marker for a corporate contact page, I think it will be good to put just HTML code provided by Google Map in the template file.

Or else you can create a block and put script in block body and render it using **Full HTML**.

To generate HTML code create marker on Google map, Click on the Button right to **Print** and it will give you the code for **iframe**

# Answer
> 0 votes
The basic method isn't very hard, just not obvious in spots.

1. Download the Location and Gmap modules. Enable at a minimum, Location, Location CCK and Gmap.
2. Get a Google maps API key at http://code.google.com/apis/maps/signup.html
3. Configure GMAP at admin/config/services/gmap and enter the key that you received in the previous step. If you save the configuration at this stage the Gmap configuration page should show the default map so you know if you've entered in the key correctly.
4. Go to configure content types at admin/structure/types and create a new content type or edit an existing content type adding a new field of type 'Location'. Configure what detail you want to gather for a location.
5. Add some address detail for an existing or new node.
6. Add the Location Map block at admin/structure/block to the desired region.
7. View node with google maps goodness!

I'm not sure why but using the manage display options of the content type don't seem to have any effect. If it's a big issue I would raise an issue in one or the other's issue queue, but that's always been enough for me and it's there if you want to template it. The Gmap is also available as an attachment in views which can map multiple nodes.

HTH.

---
Tags: 7, google-maps
---


# Question
Title: Is there any convention about the name to use for a file containing a class definition?
I have a static class I want to call in my module.

Does the file containing the class definition need to have a special name convention, such as MyStaticClass.class.php? The file is in my module folder.

# Answer
> 7 votes
The only part of the Drupal coding standards that talks of filenames doesn't say how to name PHP files containing class definitions.

Files containing PHP code, which are not the main module file, or the installation file, usually use the extension .inc, in Drupal 7 and previous versions. As there isn't any possibility of conflict between files used from different modules, you can decide the rest of the filename.

Note that Drupal 7 uses a registry, which contains a list of files defining classes. If you have a file defying a class, you just add a line similar to the following one, on the .info file.

```
    files[] =

```

In this way, the file will be automatically loaded by Drupal when you reference the class, such as when you instance an object of that class, or you call a method defined in that class.

Drupal 8 uses .php as extension for PHP files containing a class, such as Node.php, Uuid.php, and Database.php.

# Answer
> 2 votes
I'd go with `[literal class name].inc`. That's how most modules do it.

The class names themselves are Drupal coding standardized: CamelCased. Views, however doesn't follow those standards, so if you're making a Views plugin, I wouldn't call it `MyViewsPlugin`, but `my_views_plugin`, to keep in line with Views itself.

---
Tags: 7
---


# Question
Title: Custom php in rules how to check users' geolocation lat lon field and return only users in certain area
I have some custom php, sending privatemsgs to users who have some term\_reference field terms that match node term\_reference field terms. I need to add into this so that it only contacts users who are within a certain range of area based on their lat lon that they entered on sign up. I am sure this is a very common thing to do e.g. showing users nearby etc. If you can point me in the right direction, would be great.

# Answer
How about using javascript? You could submit it with ajax and write it to the db.

Here is a good example of a javascript geolocation function to get long and altitude:

```
window.onload = function(){
    if(navigator.geolocation)
        navigator.geolocation.getCurrentPosition(handleGetCurrentPosition, onError);
}

function handleGetCurrentPosition(location){

    location.coords.latitude;
    location.coords.longitude;
}
function onError(){...}

```

More complete demo: http://od-eon.com/labs/geolocation/

For the calculation of the distance with php: http://www.dzone.com/snippets/distance-calculation-using-1
> 0 votes

---
Tags: location
---


# Question
Title: Is it possible to use a path like that : user/%user/word with MENU_NORMAL_ITEM instead of MENU_LOCAL_TASK
i hope you understood the title of my topic because i have difficulties to express this problem in english.

I would like to change the menu item which is a tab (saved searches) and put it on my menu block.

So i went to the files of the module and found this:

`search_api_saved_searches.module`

```
$items['user/%user/saved-searches'] = array(
'title' => 'Saved searches',
'description' => 'View and edit your saved searches.',
'page callback' => 'search_api_saved_searches_user_listing',
'page arguments' => array(1),
'access callback' => 'search_api_saved_search_edit_access',
'access arguments' => array(1),
'weight' => 5,
'type' => MENU_LOCAL_TASK,
'file' => 'search_api_saved_searches.pages.inc',
);

```

I know that `MENU_LOCAL_TASK` is a generally a tab, so i tried `MENU_NORMAL_ITEM` but it didn't work.

I tried some other thing and removed %user `$items['user/saved-searches']` but after that i had many error, i tried to debug them but after many hours i stopped, it was clearly not a good solution to change code directly on a module.

**So my question is**: Is there a easy way to move a menu item from a tab to a menu block when the path has a wildcard components ? If it's not possible, do you think there is, maybe, a workaround to accomplish what i want to do?

Thanks,

# Answer
i used views to achieve what i wanted to do but it was not easy because :

* Fields was not the same and didn't have the good format
* There was no filter "current user" So i create a custom template using `views-view-table.tpl.php`.

I don't know if what i did is very good:

* I call `global $user` in my template, maybe it's a mistake, i don't know if we can do that **Thxs to criticguy, i improved the following code by removing current user test**

```
 <?php foreach ($rows as $row_count => $row): ?>
    <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
    <?php foreach ($row as $field => $content): ?>
     <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
     <?php if($field == 'last_execute') : ?>
       <?php $last_execute = t('@time ago', array('@time' => format_interval(REQUEST_TIME - $content))); ?>
         <?php print $last_execute; ?>
       <?php elseif($field == 'created'): ?>
         <?php $created = format_date($content, 'short'); ?>
         <?php print $created; ?>
       <?php elseif($field == 'notify_interval'): ?>
         <?php $interval = format_interval($content, 1); ?>
          <?php print $interval; ?>
       <?php elseif($field == 'results'): ?>
          <?php $tab = explode(',', $content); ?>
          <?php $x = 1 ?>
          <ul>
          <?php foreach($tab as $value): ?>
            <li>
            <?php print '<a href="'.url().'node/'.$value.'">Resultat '.$x.'</a>'; ?>
            </li>
            <?php $x++ ?>
          <?php endforeach ?>
          </ul>
       <?php else: ?>
        <?php print $content; ?>
       <?php endif ?>
  </td>
<?php endforeach; ?>

```

Final result: I'm always interested by my question about MENU\_NORMAL\_ITEM and MENU\_LOCAL\_TASK.
> 1 votes

---
Tags: 7, uri, routes
---


# Question
Title: User registration form at a new menu path got error after submit
I'm creating an employee directory. I created a menu path which renders user registration form with profile fields. When I submit the form, I got some unknown errors. I did fill out every fields in the form, but drupal shows "required" errors.

> **Error**
> The website encountered an unexpected error. Please try again later.
>
> * Password field is required.
> * You must enter a username.
> * You must enter an e-mail address.
> * Notice: Undefined index: array\_parents in field\_default\_form\_errors() (line 369 of D:\fakepath\testsite\modules\field\field.form.inc).
> * Recoverable fatal error: Argument 2 passed to drupal\_array\_get\_nested\_value() must be an array, null given, called in D:\fakepath\testsite\modules\field\field.form.inc on line 369 and defined in drupal\_array\_get\_nested\_value() (line 6490 of D:\fakepath\testsite\includes\common.inc).

I have `hook_form_alter` in which some fields are made hidden. Here is my code snippet in my custom module.

```
<?php
/*
 * Implementation of hook_menu()
 */
function mymodule_menu(){
    $items['employee/create'] = array(
        'title' => t('Create Directory'),
        'page callback' => 'drupal_get_form',
        'access callback' => 'mymodule_access_directory',
        'page arguments' => array('mymodule_employee_create_form'),
        'type' => MENU_NORMAL_ITEM,
        'weight' => 0,
    );
    return $items;
}
/*
 * Implementation of access callback for the menu
 */
function mymodule_access_directory(){
    global $user;
    # administrator can only access this
    if( in_array('administrator', $user->roles) ){
        return TRUE;
    }
    return FALSE;
}
/**
 * Home page which shows latest entered ten legs with cheapest tickets
 */
function mymodule_employee_create_form(){
    drupal_set_title('Create Employee Directory');
    return drupal_get_form('user_register_form');
}

/**
 * Implementation of hook_form_alter
 * Override form structure
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'user_register_form'){
        if($_GET['q'] == 'employee/create'){ # admin only can access this page
            # hide drupal default role selection; default role is employee
            $form['account']['roles']['#default_value'] = array(6);
            _mymodule_hide_elem($form, 'roles', 'account');
            # hide auto assign role selection; default role is employee
            $form['autoassignrole_user']['user_roles']['#default_value'] = 6;
            _mymodule_hide_elem($form, 'autoassignrole_user');
            # hide Status
            _mymodule_hide_elem($form, 'status', 'account');
            # hide Notify
            _mymodule_hide_elem($form, 'notify', 'account');

            # Change "Create new account" to "Create"
            $form['actions']['submit']['#value'] = 'Create';
        }

    }
}

function _mymodule_hide_elem(&$form, $name, $group=NULL){
    if($group){
        $form[$group][$name]['#prefix']     = '<div style="display:none">';
        $form[$group][$name]['#suffix']     = '</div>';
        $form[$group][$name]['#required']   = FALSE;
    }else{
        $form[$name]['#prefix']     = '<div style="display:none">';
        $form[$name]['#suffix']     = '</div>';
        $form[$name]['#required']   = FALSE;
    }
}
?>

```

# Answer
My mistake in my hook\_menu(). The `page arguments` should be `array('user_registration_form')` and I removed the custom page callback `mymodule_employee_create_form()`. It did work as expected.

```
function mymodule_menu(){
    $items['employee/create'] = array(
        'title' => t('Create Directory'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_register_form'),
        'access callback' => 'mymodule_access_directory',
        'type' => MENU_NORMAL_ITEM,
        'weight' => 0,
    );
    return $items;
}

```
> 1 votes

---
Tags: 7, users
---


# Question
Title: Product Bundles & referenced products in Drupal Commerce
What is the preferred way of retrieving referenced products when using hook\_commerce\_checkout\_complete on a line item that is of type Product Bundle.

As an example, the customer has added Product ID 5 (which is a bundle consisting of Products 3 & 4).

How can find it's referenced products at the point of checkout completion?

# Answer
> 0 votes
In case anyone stumbles across this, you can use the following function:

```
function commerce_product_bundle_get_sub_line_items(&$parent_line_item, $reset = FALSE){
    //...
}

```

---
Tags: commerce
---


# Question
Title: get error field is required when #access is false with field permission  in image field
With `fieldpermission` module I set some permission on some fields(fields are in profile type (I used `profile2` module)) ,some of them are `required` , showing of field is ok ,(they are not showend and `#access` property of them is `false` ). but when I save node get `field is required` error to me. any idea?

**update:** after some debugging find out this problem not issued from profile2 module, problem is a bug(maybe) with `image` cck field and `field permission`. when you have image cck field and restrict it with field permission even it not showed(by `#access=false` ) but in submit (if it `reqired`) , return the image field name is required. any idea?

# Answer
This fieldpermission bug with image and file cck field.

You can get all element in `form_alter` and if `#access` set `false` remove `#require` of it

```
    if ($profile_type == 'profile_main') {
    foreach($form[$profile_type] as $index=>$value) {
          if (preg_match('/^field_/', $index)){
                if ($form[$profile_type][$index]['#access'] == FALSE)
                  $form[$profile_type][$index]['und'][0]['#required']=FALSE;
          }
        }
    }

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Add a class to the first teaser on /blog page
On a site I'm developing the first blog teaser on the blog index page */blog* is displayed bigger than the other teasers. I do this with a class *'featured'*, can I add a function in *template.php* to add this class to the first blog teaser on the */blog* page?

Thanks for your time

# Answer
> 3 votes
In the template\_preprocess\_node hook you can use `$vars['id']` to get the array index in the order that the nodes are printed.

You'll need to replace **COND\_FOR\_BLOG** with whatever logic you have for checking that.

Example to get you started:

```
function THEME_OR_MODULE_preprocess_node(&$vars) {
  if (COND_FOR_BLOG && $vars['id'] == 1) {
    $vars['classes_array'][] = 'featured';
  }
}

```

**Edit:** Note that `$vars['id']` is not zero-based so `$vars['id'] == 1` actually gives the first post.

---
Tags: 7, nodes
---


# Question
Title: Create a dynamic Tabbed View from Group By
I created a View which show all the content tagged with user flagged terms and group the content by Term Name.

Right now I am trying to make each group appear in a tab, I don't know how to achieve it.

For example if the user "X" flagged terms "A", "B" & "C", Currently, The view come back with all content tagged with terms "A", "B" & "C" and group them by Term Name in this case "A", "B" & "C". I want these groups "A", "B" & "C" to be tabs. I need to auto generate them because I don't know either the number or which terms are flagged by the current user.

If I can't achieve it with views only, Is their anyway to achieve it with another modules e.g. Panels.

At the same time, I will try to trace the views template files to see If I can do it with jQuery Tabs and views template files. If you have any other suggestion please feel free.

# Answer
Quicktabs module is the answer.
> 5 votes

---
Tags: views, routes
---


title: Default .htaccess problem in FilesMatch

text:
# Question
Title: Default .htaccess problem in FilesMatch
I installed Drupal 7 on a web server and can;t access the root domain. When I comment the following lines in the .htaccess file I can load the site without any problem:

```
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

```

I don't want to comment the complete FilesMatch tag as I understand that it protects from unwanted access to files and server resources.

What should I change?

# Answer
if you use one.com

I just find out, that you can remove or commenting

```
Options -IndexesOptions
Options +FollowSymlinks

```

in the htaccess file, and then it should work. I don't know why.
> 1 votes

---
Tags: 7, .htaccess
---


title: populating nid in a custom field

text:
# Question
Title: populating nid in a custom field
When creating a new node, I need to populate/fill a custom field with a value of the current node's id. What hook should I use to fill my custom field with newly created nid ($node-\>nid)?

I tried to use `hook_node_presave` but it was NULL, currently I am thinking to use `hook_node_insert` but as documentation says :

> after the node is inserted into the node table in the database,

Does that mean if I assign the new value to my custom field it will be/not be saved to database?

# Answer
> 1 votes
I guess I found a solution for this problem:

```
function mymodule_node_insert($node) {
  $node->field_custom_field['und'][0]['nid'] = $node->nid;
  node_save($node)
}

```

I saved the changes to database with node\_save()

# Answer
> 0 votes
if you are drupal 6 use `hook_nodeapi`

```
function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      $nid=$node->nid;
       // $nid  is exist and you can put it in your field
       //something like this
       $node->field_yourfieldname['und'][0]['value'] = $node->nid;
       // this parameters related your field name and field type I suggest you in here ou print $node first and according it accompolish
      break;
   }
  }

```

and if you are using drupal 7 use `hook_node_insert`

```
function hook_node_insert($node) {
    $nid = $node->nid;
   // $nid  is exist and you can put it in your field
              //something like this
       $node->field_yourfieldname['und'][0]['value'] = $node->nid;
       // this parameters related your field name and field type I suggest you in here ou print $node first and according it accompolish
   }

```

---
Tags: nodes, hooks, entities
---


# Question
Title: Programmatically manipulate content type select list
I have a content type called Car which have several field two of them are select lists which I want to make some operations on them. When the user select a value form the first select list a bulk of values should be populated in the other select list, my question is WHERE to do this programmatically and some tips for HOW doing this? I hope my question is clear

best

# Answer
You need to use hook\_form\_alter to add AHAH/AJAX to your field. The hook should be placed in either a custom module or in your theme's settings.php file.

Drupal has many examples about this. Here's for Drupal 6 and here's for Drupal 7.

This specific example from the links above seems to be what you are looking for.
> 1 votes

---
Tags: entities
---


# Question
Title: using drush for upgrade drupal 6 to 7 - create alias problem
I want to use drush for upgrade my drupal 6 to drupal7. i read this document. i have a problem with create alias. i have been doing this

1- create a subdomain in my plesk (create sub.domain.com)

2- go to /var/www/vhosts/domain.com/httpdocs and download this file and rename this to "aliases.drushrc.php"

3- remove aliases.drushrc.php content and replace with

`<?php
$aliases['sub'] = array(
 'root' => '/var/www/vhosts/domain.com/sub',
 'uri' => 'sub.domain.com',
);
?>`

4- run command: drush @sub status and i get this error:

`The drush command '@sub status' could not be found. Run`drush cache-clear drush`to clear the commandfile cache if you have installed new extensions`

# Answer
> 3 votes
Although the Drupal root is a valid place to store alias files, Drush will not be able to find the alias records described there until the Drupal root as been specified. Therefore, `drush @sub status` has a chicken-and-egg problem; you want to use @sub to specify the Drupal root, but Drush won't load the alias file that defines @sub until the Drupal site it is defined in is bootstrapped.

To resolve this problem, move your aliases file to $HOME/.drush/aliases.drushrc.php. Once you do that, then your status command will work.

You may define your 'onward' alias either in $HOME/.drush/aliases.drushrc.php, or in /var/www/vhosts/domain.com/httpdocs/aliases.drushrc.php, per your preference.

# Answer
> 0 votes
Drush Site Upgrade needs to be installed first.

You can download the module and upload it to drush/commands/core folder. Now you will be able to run this command

If you are getting some problems when Drush tries to create a new database, create it first and enter it in the alias file.

---
Tags: drush
---


# Question
Title: Any way to create a permissions-like sea of checkboxes?
Basically I am looking for something like this (square brackets are checkboxes):

```
  A  B  C  D  E
1 [] [] [] [] []
2 [] [] [] [] []
3 [] [] [] [] []

```

# Answer
> 0 votes
It looks like the only way is to create a FAPI checkboxes array then theme it.

# Answer
> 1 votes
Are you looking for Node Permission Grid module ?

This will give permission grid like

---
Tags: forms
---


title: Allow anonymous users to custom menus

text:
# Question
Title: Allow anonymous users to custom menus
I recently inherited a legacy project that I've been trying to work with. I defined a custom menu using the menu hook but it looks like anonymous users can't access that menu and instead gets redirected to the user login page. This is a fairly large project and I'm trouble figuring out where exactly the call is intercepted and redirect. Any help would be great.

This is what the redirected looks like if it helps: localhost/user?destination=results

```
function test_results_menu() {
  $items = array();
  $items['results'] = array(
    'page callback' => 'display_test_results',
    'access callback' => 'test_results_resource_access'
  );
  return $items;
}

function test_results_resource_access() {
  return TRUE;
}

function display_test_results() {
  //  TODO Display results
  return "hi";
}

```

Update: The odd thing for me is that the project also recently got a rest endpoint using the services module which allows anonymous users to see the data there.

# Answer
If you want your menu access by everyone set `access callback` TRUE(not need determine function and it pass TRUE,(maybe this is test and you want in future have condtional menu)).

```
function test_results_menu() {
  $items = array();
  $items['results'] = array(
     'title' => 'your title',
     'description' => 'menu description',
    'page callback' => 'display_test_results',
    'access callback' => TRUE,
  );
  return $items;
}

function display_test_results() {
  //  TODO Display results
   print "hi";
}

```

This will be work . **please after any change in `hook_menu` clear your drupal cache.**
> 2 votes

---
Tags: 7, routes, users, services
---


# Question
Title: Blog entries and blog listing page are different content types?
So I've noticed that Drupal sets the blog listing page as a different content type to the blog articles. This is a bit awkward because I want to set blocks that are specifically for the blog section.

In admin I can choose to restrict by content type: News Articles (the blog entries), or choose the pages on which the block displays displays: so list the page */blog* which is the Blog listings page.

How can I have harmony and set a block for blog listing and blog entry pages excluding the rest of the site?

Thank you

# Answer
> 1 votes
One way to do this is to use the Pathauto module to automatically set your blog URLs. Set URLs for content of type blog to be blog/\[node:title\]; then, on the blocks configuration page, you can simply set the pages to be blog and blog/\*, which will then show the block only on your blog pages and index but nothing else.

---
Tags: 7, nodes
---


# Question
Title: How can i show only content type fields in block or how can i call a add content type page in a block
How can i call a add node "content type" in a block. I have upload an image below Image1.

I have a content type : `Upload Resume` ie `upload_resume`

Anomynous users can also only `create` this content type.

I want this fields in a block where user can upload resume not in page style bcos of below image shows other factors ie Image2

## Updated Image after Oscar answer

# Answer
> 1 votes
here is your module: Form Block. And here is a quote about it from the module's project page):

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

---
Tags: entities, blocks, nodes
---


# Question
Title: Issue with Registration codes module in Voucher mode, trying to fix
I am having serious issue with Registration codes module and searching for solution to fix it. It is described here: http://drupal.org/node/797602

There is a patch to the issue, but author of the code stated that it may be "serious regression and borked a bunch of other modules, like simplenews and profile, anything that expects data to be in $edit."

That patch is very simple:

```
-  regcode_user('insert', $edit, $account);
+  user_save($account,$edit);

```

Module works well when used in normal mode, but in "voucher" mode, it does not apply role to user who submits it. To greater misfortune, the rule that this module came with, which could help do it another way, is also broken.

I think this module is not actively maintained as i do not recieve response for about an month on series of my request.

I would be very grateful if someone knows what approach i could take to resolve the issue, knowing how to rewrite patch to avoid harm to other modules functionality.

Thanks for clues!

# Answer
> 1 votes
This is more of an advice than a clean solution to the problem: hack the module and apply the patch if it works for you without interfering with other modules.

As you said, the module isn't maintained well and it is not updated recently (last commit was almost a year ago). If you don't have enough time to go over everything yourself, it is better to just fork it than hope that the maintainer will fix it.

Create a new folder under "sites/all/modules" called "fork" and move the module there. This will make sense later on for you or anybody else working on the site.

---
Tags: 7, debugging
---


# Question
Title: When entering taxonomy terms are new ones added with different pk even if term is already in the dictionary
I was expecting taxonomy terms to only be added if they weren't already in the dictionary. However, it seems that I have multiple terms added with different tid's or pk which I wasn't expecting. What is happening here?

# Answer
Drupal allows you to enter multiple terms with the same name. If you want to have unique term names, use the Taxonomy dupecheck module.

> Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: InnoDB gone missing as database type - has anyone seen this error before?
I'm working on the Drupal 7 site that's currently on Dreamhost.

Since this morning, the site is showing the following error message:

> Error
> The website encountered an unexpected error. Please try again later.
> Error message PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1286 Unknown table engine 'InnoDB': SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( \[:name\] =\> variable\_init ) in lock\_may\_be\_available() (line 167 of /home/mysite.com/includes/lock.inc). Uncaught exception thrown in shutdown function.
>
> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1286 Unknown table engine 'InnoDB': DELETE FROM {semaphore} WHERE (value = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 7584349655055df9b66b5c9.36234254 ) in lock\_release\_all() (line 269 of /home/mysite.com/includes/lock.inc).

Has anyone seen this sort of error before? Yesterday, my database showed as InnoDB in PHPMyAdmin; today there's nothing showing as "type."

# Answer
On Debian 6, this can also happen when you change the innodb\_log\_file\_size parameter. Sometimes mysql does not start; other times, it just starts up, but the InnoDB engine is not enabled. The solution is to remove ib\_logfiles from /var/lib/mysql and restart mysql.

See this issue in drupal.org.
> 1 votes

---
Tags: database
---


# Question
Title: Checkbox so user can decide whether image should be displayed or not
I would like to add a checkbox yes / no whether the image field should be displayed or not in a node.

# Answer
Mh, there are several ways.

One of this is to add a boolean field to the content type. Then you can create a template for the node, or the field, and display it only if the value of the boolean field is "on".

What do you think?
> 1 votes

---
Tags: media
---


# Question
Title: Applying Updates to Multiple Drupal Sites
I have over 100 drupal 7 websites on my single server. Applying updates to each site individually is a lengthy task.

Is there any simple way through which we can update all the websites at once, or can we use a single module folder for multiple Drupal websites?

# Answer
> 1 votes
Please remember that *testing* is a very important part of every site upgrade. It would not be difficult to write a script to copy code & db from live to stage for all sites, and then run *drush -y pm-update* on each site in turn; however, you should include a manual testing phase after the pm-update, and then push each tested site back to the live site as they are found to be working.

For the deploy step, you will want to copy the code from stage to live, and then run updatedb on the live site. The live site should be offline during this operation. See also drush\_deploy for scripting stage-to-live deployment.

---
Tags: drush, updating
---


title: Drupal 7.14 image upload unstable

text:
# Question
Title: Drupal 7.14 image upload unstable
I am setting up a site in Drupal 7 for a photographer which includes uploading a large number of photos to the server. My problem is that image upload is extremely unstable. Sometimes it works, sometimes it does not. It seems I am hitting some kind of memory or bandwidth limit, but I don't get any errors.

I created a custom content type for photo albums, with each category (e.g. "portrait", "wedding" etc.) as a node with a number of attached images that I display using views slideshow. Everything works on the front end.

Image upload is handled by an image field and the Media file selector widget. The problem is that sometimes during upload the page will just refresh and the image does not show up in the list of attached images.

I also tried using the Plupload widget that allows uploading several images at once. With this I get a slightly different behavior. The images will "break" after two or three images meaning that they show up as corrupted images with part of the image missing. Sometimes refreshing the page or clearing all Drupal caches will allow me to upload maybe four images at once.

It looks like this

What is strange is that the same exact image file will sometimes upload, and sometimes not.

I am not uploading huge images. They are all manually resized to less than 1600x1600px before uploading, with file sizes between 200 and 600 KB.

---

Drupal 7.14

Media 7.x-1.2

Plupload library 1.5.4

Plupload integration module 7.x-1.0

Plupload widget 7.x-1.0-alpha1

---

PHP settings:

PHP version 5.3.10

Max upload size: 5M

Memory limit: 1024M (increased from 128M using ini\_set() in settings.php)

---

Any help will be greatly appreciated! I have been googling for days trying to solve this

:::UPDATE::: I found a temporary workaround. The module Multiupload Imagefield Widget allows multiple image uploads that seem to work for me apart from a few error messages. At least this makes it possible to load my images on to the server effortlessly.

However, this module does not show thumbnails for uploaded images which is crucial for this particular project.

# Answer
I believe you are experiencing a problem that Plupload has with PHP 5.3.x. I built a site for a client that uses photo galleries (Media and Media Gallery), and via the Pupload Integration Module galleries could be built by simple drag-and-drop of multiple image files. The site is hosted on Rackspace Cloud, which recently upgraded from PHP 5.2.x to PHP 5.3.14. That's when the problems began.

There is a bug report for the Plupload Integration module that shows the error I'm now getting. If you're getting the same error message, I'd recommend that you also take part in the thread, as I just did.
> 1 votes

---
Tags: media, files
---


title: Modules for media management

text:
# Question
Title: Modules for media management
I am looking at the ability to management off and online video content. I need to be able to add media using text filters and to search for media within the cms. What is a good module for a modal style background when playing video? I need to arrange videos into playlists by artists and create gallerys.

On my research I have come up with the following:

Media Searching Media http://drupal.org/project/apachesolr\_media http://drupal.org/project/apachesolr http://drupal.org/project/apachesolr\_file

http://drupal.org/project/media (for managing media) http://drupal.org/project/media\_gallery (for managing galleries of images and videos) http://drupal.org/project/mediaelement (for local files) http://drupal.org/project/multiform

More info:http://www.slideshare.net/G\_N/drupal-7-media-modules

If you can give me any more information that would be great.

# Answer
You also needs views and taxonomy to build the lists. I'll add also shadowbox or colorbox to play videos in a modalframe.
> 2 votes

---
Tags: files, media
---


# Question
Title: Drupal 7 views join two profile2 profiles together
I would like to join two profile2 profiles so they appear as one row in the view module and not two rows like the example below. Can this be done?

### Fields

* User: Name
* Content: image\_profile\_image

### Relationships

* User: Profile
* User: Content authored

# Answer
Have you tried Display Suit.

Also panels is a good solution for this.

Oskar
> 0 votes

---
Tags: views, users
---


# Question
Title: Overwriting database with backup from older Drupal version?
I have a database from a live site I need to bring over to a development site.

live site = d7.7, outdated modules, but is obviously up to date with all the recent ubercart orders

dev site = d7.15, all modules updated, but is missing the latest ubercart orders

I had been migrating the live DB over to the dev site periodically, but now that the dev site is running newer modules and core, I'm wondering if its still safe to move migrate the database from the live 7.7 site.

can I migrate the database and simply run update.php afterward to catch up?

ubercart orders are really the only thing im concerned about. also, ubercart is one of the modules that has been updated on the dev site.

Complete list of modules that have been updated on the DEV site. Some of these required the running of update.php

Drush CTools Ubercart Views Entity Token Securepages Rules Admin Menu Node Export UUID Pathauto Gallery formatter Twitter Pull

# Answer
Yes - in most cases, this should be a fairly straightforward operation. You should be able to migrate your updated modules from dev over to the live site and just run update to get everything running again. If there are going to be issues with this (for ex. a module that requires a little more configuration to get working), you can isolate these issues before-hand on your dev server (and it sounds like you've already done this successfully).

Most of the top contrib modules (ex. the ones you cite above) will be very careful at upgrading their structure without impacting any new data (or orders).
> 0 votes

---
Tags: database, updating, migrations, installation
---


# Question
Title: Linking taxonomy terms that appear in content
Is there a way to find and link to taxonomy terms that appear within content?

# Answer
You mean automatically? You probably want something like the glossary module

> The glossary module scans posts for glossary terms (including synonyms). The glossary indicator is inserted after every found term, or the term itself is turned into an indicator depending on the site settings. ... The glossary uses Drupal's built in taxonomy feature, so you can organize your terms in a Drupal vocabulary.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: Altering all urls to include extra information
What hooks are available for altering the urls? For example, there are language modules that, when enabled, provide urls such as `/en/node/1` rather than leaving it as `/node/1`.

I want to have something similar in the url, that I can have access to without having other functionality compromised.

How is this accomplished?

# Answer
> 4 votes
So you're looking for a way to modify a link URL as it is being written? I looked into this recently and was surprised at how much hunting was required.

I went with `hook_url_outbound_alter( &$path, &$options, $original_path )`, which allows you to alter link URLs that are being written by the Drupal URL system.

There's also `hook_url_inbound_alter( &$path, $original_path, $path_language )`, which might be better as it includes the path's specific langauge - it depends on where you want the alteration to take place. I personally find `hook_url_outbound_alter()` reliable and simple to work with - it changes all appropriate URLs as they are written, and using $options you can reliably add and edit query strings (...?query=string&foo=bar) and hash frangments (...#someId).

Modify $path and it'll update the actual path that gets written into the URL href. Of course, this runs on all links, so you'll want to start by checking that it's a link you want to modify.

It's executed before aliasing, so it'll be based on the Drupal defaults. To give two very simplistic examples, if you want to modify only taxonomy paths:

```
function some_module_url_outbound_alter( &$path, &$options, $original_path ) {
  if(strpos($original_path, 'taxonomy/term') === 0) {
    // do stuff
  }
}

```

And/or if you only want it to run on particular pages, e.g. node edit pages:

```
function some_module_url_outbound_alter( &$path, &$options, $original_path ) {
  $current_path = explode("/", current_path() );
  if (count($current_path) >= 3 && $current_path[0] == "node" && $current_path[2] == "edit") {
    // do stuff
  }
}

```

---
Tags: 7, routes
---


# Question
Title: Create new content type with a user reference
I have a process of adding contents where user1 has to search for user2, when user2 is found, there is a button that adds a specific content type (i.e. "Create a report for this user") for the searched user. then it goes to a page where i can enter information and save the content. how can i do this?

# Answer
Your user selection/search process may need some custom work to implement the various node-reference modules in the way you've described, but there are several modules that may do what you need out of the box. The References module will be easier to implement while creating new content, but the Relation module may be more agile as you can add fields to your relations, 'user report' for example.

I would be happy to elaborate if you'll clarify your user selection process.

---

**1 - References**

This adds a field to an already created content type. Generally simpler to implement.

> This project provides D7 versions of the 'Node reference' and 'User reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts. See http://drupal.org/node/533222 for details.

Video Series (NodeOne) Using the Reference module

**2 - Relation**

Rather than being a 'field' on an already created content type this is for all intents and purposes a new content type. Relations are fieldable as well, so adding the 'report' fields you need will be easy.

> Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.

Video Series (NodeOne) Learn the Relation Module
> 3 votes

---
Tags: users, nodes
---


title: Use hook to remove height from img tag?

text:
# Question
Title: Use hook to remove height from img tag?
The theme I am building is responsive and so many images have `max-width:100%;` applied in CSS. Can I use a hook in *template.php* to strip the height attribute from `img` tags because it is causing lots of distortion issues, and how would I go about this?

Thanks for your time!

# Answer
> 3 votes
Assuming that your images are being built by `theme('image',...)` you can override its default...

```
function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';

```

}

...in your template.php file along the lines of this:

```
function YOURTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';

```

}

and now those pesky `height=`s and `width=`s should be gone.

# Answer
> 0 votes
Rather than editing Drupal behavior can also just set `img` CSS to `height:auto`

---
Tags: 7, hooks
---


# Question
Title: What is the database relationship between node_type and taxonomy_vocabulary tables?
I have 3 content types. I have 3 vocabularies - one for each content type.

Recently I have created a script to save nodes programatically based on batch files clients send me. I am very happy with it, and it works fine.

However, I currently have to manually manage a separate file for a huge multidimensional array. Here is an excerpt from the file.

```
$query['baby_clothes']['category']['id'][] = 1;
$query['baby_clothes']['category']['id'][] = 2;
$query['baby_clothes']['category']['id'][] = 3;
$query['baby_clothes']['category']['id'][] = 4;
$query['feeding']['category']['id'][] = 26;
$query['feeding']['category']['id'][] = 28;

```

The first dimension represents the content type and the others the id. There is one entry per unique taxonomy term id in the array. Basically I loop through the IDs; extract the content type from key \[0\]; save accordingly.

As the taxonomy grows and changes this becomes very inefficient to manage, and i would like to create these arrays dynamically, but I am having trouble understanding the database relationships to create this part of the code.

Basically it would work like this: "Get an array of content types. For each content type get the taxonomy IDs for the one vocabulary that is associated with the content type. Dynamically create the array."

Or, how about this? Would this be easier? "Get a list of taxonomy IDs. Get the content type with which this term is accociated. Now I have my content type and my id - save node accordingly."

I can see the node\_type and taxonomy\_vocabulary in the mysql database, but I am not sure how they relate to each other, or how to relate them so I get the desired result. I would prefer option two, but any direction is appreciated as well as are alternate suggestions. Pseudocode is fine. Thanks!

# Answer
> 3 votes
Not to discourage database deep-diving, but if you're bootstrapped into the Drupal system with your system (i.e. programmatically creating nodes), then you don't have to necessarily understand how the DB works to get this working. Just use the functions in the node and taxonomy API to generate your array.

Specifically, lets say you wanted to try for option #1. You could use

node\_type\_get\_types()

to pull a list of all of your content types, and then iterate through that to generate a list of taxonomy terms for each vocabulary. Here is a function I've used before to that effect, from VicTheme.com

```
/**
 * Helper function return all the taxonomy terms of a given node type
 * @param $type
 * The array of machine name of the content type that the function should look for taxonomy terms
 * the array format should be : array('machine_name');
 * @return
 *   An array of taxonomy terms containing tid => human name.
 */
function vt_commerce_api_get_vocabulary($type = array()) {
  // break if there are no types specified
  if (empty($type) || !is_array($type)) {
    return FALSE;
  }

  $output = array();
  foreach (field_info_fields() as $field) {
    if ($field['type'] == 'taxonomy_term_reference' && is_array($field['bundles']['node'])) {
      foreach ($field['bundles']['node'] as $content_type) {
        if (in_array($content_type, $type)) {
          foreach ($field['settings']['allowed_values'] as $value) {
             $output[$value['vocabulary']] = $value['vocabulary'];
          }
        }
      }
    }
  }

  return $output;
}

```

---
Tags: 7, database
---


# Question
Title: Use Webform Results in another webform content type
I am creating a website for my department at work using Drupal 7. I have a webform designed in a page named Registration in the website. When a user fills this form in and submits, it sends a confirmation to me. I am also able to view the submissions using the Results tab in the webform using admin rights.

Now I am creating an other page(named 'approve request') for an editor role who approves the submission of the user. This Approve request page has been created in the content type that enables the webform. Now, I need the webform results from the Registration page to appear in the Approve request page. This will enable the Editor to view the Registration results and approve them.

How do I retrieve the results from the registration page to the Approval page? I looked at various sources and could not find a good answer. Please let me know.

Thanks in advance!

# Answer
> 0 votes
You can programmatically modify the form of **Approve Request** webform using **hook\_form\_alter()** function. In this form you can retrieve the previous webform submission entries and append in the **Approve Request** form.

You can retrieve previous webform submission using following snippet:

```
include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1); // need to hard-code nid if this is a custom page you can manage dynamically also
$sid = $_GET['sid'];
$submission = webform_get_submission($nid, $sid);

```

---
Tags: webforms
---


# Question
Title: How can i change the html generated of filter field of views?
Mi problem is that my field (Filter Date-Popup of views) have the following html:

```
<div class="date-clear form-item"><div class="description">
  <div class="container-inline-date form-item date-clear-block"><div class="form-item" id="edit-date-filter-value-wrapper">
    <div class="form-item" id="edit-date-filter-value-datepicker-popup-0-wrapper">
    <input type="text" maxlength="30" name="date_filter[value][date]" id="edit-date-filter-value-datepicker-popup-0" size="20" value="" class="form-text">      <div class="description"> Format: 2012-09-17</div>
  </div>
  </div>
</div></div>
</div>

```

But, in only need the following portion of this html:

```
<div class="form-item" id="edit-date-filter-value-datepicker-popup-0-wrapper">
    <input type="text" maxlength="30" name="date_filter[value][date]" id="edit-date-filter-value-datepicker-popup-0" size="20" value="" class="form-text">      <div class="description"> Format: 2012-09-17</div>
  </div>

```

I try to do with create a template of the filter. With the Theme Information and rewrite the output of this HTML but doesn't work.

I work with Drupal 6 and Views 2

How can i do this? Thanks :D

# Answer
On Drupal 6, if you don't want to work with tpl, you can use Semantic Views.
> 1 votes

---
Tags: 6, views, theming
---