title: CSS sprites and pop up windows

text:
# Question
Title: CSS sprites and pop up windows
I have just implemented a **css sprite** for a list of items. The purpose of this was that when a user **hovers** over an item, the **image changes**... What I have been asked to do now is to **add a pop up** for each of those list items. How would I go about doing this?

Is there any way by using aFancybox module to achieve this?

The pop up would consist of a **page title, image and a close button**.

At the moment the list items are hard coded in the **page.tpl.php** template.

I use drupal 7

This is the sort of thing I am trying to achieve. So a set of images which change on hover, and when clicked on a little pop up appears.

# Answer
> 0 votes
You should probably follow webkenny's approach. However, you could simplify this by creating a unique node type that accommodates the display info you need.

As for the css sprites go through **this**. While the sprites offer benefits, I wouldn't get dogmatically insistent on using sprites either, since you'll have to hard-wire the coordinates as per hover, if part of your goal is passing off the site to a non-technical. The performance gain is offset by the preparation time (unless you're using SASS which has excellent sprite-assisting facilities). Regardless, your content type for the popup information can contain either the coordinates for the hover sprite or image file fields for the hover and non-hover images which views manages when building that horizontal element. Finally, I'd go with Colorbox, as Fancybox's community is much smaller. I don't see where fancybox has a feature that CB doesn't for your requirements.

# Answer
> 1 votes
I wouldn't approach it this way. Hardcoding list items, with content, in a tpl.php is generally frowned upon and will ultimately require more work than this should entail.

Instead use Views and the Colorbox module. Create a view with the list of nodes you want to display, pop it in a block on the page in the region you'd like it to display, and use the Colorbox plugin to Views show the popover on click. Use CSS to style the colorbox however you please. This can be handled strictly with configuration and a touch of CSS. This way, when the theme changes someday, the functionality is maintained.

See http://drupal.org/project/views and http://drupal.org/project/colorbox for more details.

---
Tags: javascript
---


# Question
Title: Elysia cron Execution time vs Shutdown time
While looking to the Cron Status Tab, I can see this information above every cron channel :

```
Last run: 14/06/2013 - 02:00
Last execution time: 597s (Shutdown: 597s) (Avg total: 307.16s, Max total: 834s)
Execution count: 137

```

What does the `Shutdown` seconds stands for ?

# Answer
> 2 votes
The documentation surrounding that variable is pretty much non-existent. This is how it's calculated, in `elysia_cron_completed()`:

```
time() - $cron_completed_time

```

Where `$cron_completed_time` is a global, presumably a timestamp indicating exactly when an associated cron job ended.

I'm afraid you'll need to infer exactly what that timestamp is from the above; I *think* it refers to the gap between when a cron job was completed, and the time it was logged in the database.

---
Tags: 7, cron
---


title: Adding options to Drupal search

text:
# Question
Title: Adding options to Drupal search
I've been working on a site and I need to change the search.

I've changed the search form with hook\_form\_alter(), added some checkboxes, ... Now I need to get the new data to the hook\_search\_execute() function?

How would I achieve that?

# Answer
I found the answer to my problem. I alway wanted to use Search API, but wasn't sure how to do it.

I figured it out with: https://stackoverflow.com/questions/8575289/extending-drupal-7-search
> 0 votes

# Answer
Drupal's search platform is rudimentary one. You can't really extend it, best you can do is to replace it. Most popular free platform now seems to be Apache Solr, connected to Drupal with Apache Solr Search Integration.

If Solr's to much, Search API integrates with views pretty neat, you can have one field for search and other as Views filters.
> 1 votes

---
Tags: forms, search
---


title: Render Array Javascript with Variables

text:
# Question
Title: Render Array Javascript with Variables
I'm creating a custom block and I'd like to add some Javascript to it. I'm using a Render Array to add the Javascript to the page, which works fine, I'm then trying to add some variables to the Render Array for the Javascript to use.

This is what my Render Array looks like

```
$content = array(
  '#slides' => $slides,
  '#theme' => 'slider_block',
  '#attached' => array(
    'js' =>
      array(
        drupal_get_path('module', 'single_slider') . '/js/test.js' => array(
          'type' => 'file',
        ),
      )
  )
);

$content['#attached']['js'][] = array(
  'data' => array('word' => 'world'),
  'type' => 'setting'
);

return $content;

```

I'm then trying to access the variable in the Javascript (test.js) file using the following.

```
console.log(Drupal.settings);

```

At the moment this just returns with an empty object. If someone could point me in the right direction I'd appreciate it very much.

Thanks in advanced.

# Answer
Ok I've managed to solve it myself.

For anyone that is interested my Render Array now looks like this.

```
    return array(
        '#slides' => $slides,
        '#theme' => 'slider_block',
        '#attached' => array(
            'js' => array(
                array('data' => array('word' => 'world'), 'type' => 'setting'),
                drupal_get_path('module', 'single_slider') . '/js/tes.js'
            ),
        )
    );

```

And my Javascript file (test.js) now looks like this.

```
(function($)
{
    //console.log(Drupal.settings.word) //This won't work and will return with undefined.
    $(function()
    {
        alert('Hello ' + Drupal.settings.word);
    });
}(jQuery));

```
> 4 votes

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


# Question
Title: Feeds: How to import images using CSV Node Import?
I try to use Node Import clone with an extra image field to import nodes with images attached.

Without success, I try to upload content from a local file (s).

I use CSV parser and Node Processor. My content type has a image field called Photo I mapped to the csv format using the mapper.

I am using Windows as a local feeds source and Drupal 7 as a server.

How to import images using CSV Node Import ? What should be exactly the image file path in the csv file ?

# Answer
> 3 votes
I don't think it will work based on local files. The way I understand it, feeds is made to work off CSV data, with files that are already on the server.

It will take a bit of playing around on your part, but your best bet is to upload a single product/node with an image. Find the path to that image. Once you find the folder where your image is being stored, upload your images to that folder.

Then give the direct path to the image on your server in your CSV file, in the image section. The path will probably look something like this, depending on the how you configured the image field. This example is from a Drupal Commerce site:

example.com/sites/default/files/styles/uc\_product\_big/public/image-you-want-to-use.jpg

If your server runs some sort of post processing (image-resizing, cropping, scaling), and then saves in multiple folders, I'm afraid you're out of luck with this method.

# Answer
> 0 votes
I am not entirely clear on what you are doing, but I had similar problems trying to read a text file in a custom module. Any file used in Drupal must be imported using drupals api using `file_save_upload` or `file_save` ( I believe this puts the files in the database for handling by Drupal). These files are saved within the Site directory structure (your download error message suggests yours are not). You may want to check the modules you are using to see if Drupal is saving the file. This process is necessary because browsers do not let outside sites access a users files without their permission.

# Answer
> 0 votes
To extend upon commercebythegradeo's answer. There's a module available called:

```
Feeds Image Grabber
https://drupal.org/project/feeds_imagegrabber

```

What this module does is allow you to import the specified image from the URL into the node, rather than simply referencing it. This way all your post processing can be one, which as I see it was the only real flaw in the answer provided by commercebythegradeo.

---
Tags: 7, feeds
---


# Question
Title: How to send an email that always contains all fields of entityform, without manually updating when fields are changed?
I have a client with an entityform with over 100 fields (trust me, I begged with them to lessen it). I need to send an email using rules with all of the fields exactly as they appear on the form. I don't want to have to manually add all of these tokens to the email and I also don't want to have to manually update the email with new and/or removed fields every time they change the form. Is there any way of using a token that calls all of the fields on the form and maybe even uses the view mode?

# Answer
> 5 votes
This is already handled in the Entityforms Notifications sub-module the way you are describing.

There is a view mode called "Email". That view mode controls which fields show up in the email. This is done via a token in Rules.

In Entityform 1.x this token is controlled via the Entityform module itself. In Entityform 2.x this is controlled via the Entity to Text Module.

I think there is some problem in Entityform 1.x with showing fields with multiple values. But this should work in Entity To Text. You could also just use Entity To Text with Entityform 1.x. Just replace Entityform 1.x token with the Entity To Text token in the Rule.

If you are interested this handbook page should probably updated with this information: https://drupal.org/node/1679794

# Answer
> 1 votes
1. I guess you have an Email Template with all your fields/tokens, so that you can call that template in Rules module Rules.
2. Refer Previewable email templates. With the help of this module, you can create a template with N number of fields/tokens.
3. This module has integration with Rules, you can trigger any action, whenever you wish to any event to occur.

It's very handy.

---
Tags: rules, tokens
---


title: How can i post my data to facebook

text:
# Question
Title: How can i post my data to facebook
I am a new Drupal user, and have the Drupal for Facebook module installed on a Drupal 7 site.

Right now, I have one template file in use, and would like share this data with Facebook.

Is this possible? I do not see how to do this with the FB module.

# Answer
Just use the social media module

> The social media module helps integrate your website with social media sites such as Twitter, Facebook and Google+. It provides an centralized way of managing social media profile information and plug-in widgets such as follow and share buttons.

or sharethis

> Integration with the ShareThis social bookmarking utility on selected node types.
> 0 votes

# Answer
You could simply use the **Facebook OAuth module**.

> This module provides authentication services and an API to perform actions against Facebook. This module allows users to login to Drupal through the service commonly known as "Facebook Connect". This module is built with simplicity and flexibility in mind, it provides login services (and does it well), and an API for performing any other actions you may want to write yourself to query against Facebook's APIs.

Features:

1. One-click login through Facebook.
2. Automatic import of user e-mail and profile information during initial login.
3. Integration with Profile module to map Facebook data to Profile fields. (Drupal 6)
4. Integration with Field module to map Facebook data to fields on users. (Drupal 7)
5. A flexible and direct API for modules to get authenticated and query Facebook's APIs (plus extensive documentation).
6. Extensive permission settings for Facebook data retrieval.
7. The ability to de-authenticate or unlink a Facebook account from a Drupal account.
8. Does not require any external libraries or downloads.

For more detail about the module you could go through the README.txt of this module.
> 0 votes

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


title: hook_views_data and DECIMAL columns

text:
# Question
Title: hook_views_data and DECIMAL columns
I have an external database that I am wiring into views with `hook_views_data()`. This particular database is making use of `DECIMAL` data type. What are the proper field, filter, etc, handlers to use with this?

# Answer
> 13 votes
The 'numeric' type classes handle both integers and floats/decimals:

It's not that obvious at face value, but if you look at the comments for `views_handler_field_numeric`:

> Definition terms:
>
> * float: If true this field contains a decimal value. If unset this field will be assumed to be integer.

So setting `'float' => TRUE` on your field definition, and using the `numeric` handlers, is all you need to do. e.g

```
$data['some_table']['msrp'] = array(
  'title' => t('MSRP'),
  'help' => t('MSRP of the product.'),
  'field' => array(
    'handler' => 'views_handler_field_numeric',
    'click sortable' => TRUE,
    'float' => TRUE,
  ),
  'filter' => array(
    'handler' => 'views_handler_filter_numeric',
  ),
  'sort' => array(
    'handler' => 'views_handler_sort',
  ),
);

```

# Answer
> 2 votes
Implementation of `hook_view_data()` for all type of data type other than just numeric and related fields is explained in the code below.

```
function hook_views_data() {
  // This example describes how to write hook_views_data() for the following
  // table:
  //
  // CREATE TABLE example_table (
//   nid INT(11) NOT NULL         COMMENT 'Primary key; refers to {node}.nid.',
//   plain_text_field VARCHAR(32) COMMENT 'Just a plain text field.',
//   numeric_field INT(11)        COMMENT 'Just a numeric field.',
//   boolean_field INT(1)         COMMENT 'Just an on/off field.',
//   timestamp_field INT(8)       COMMENT 'Just a timestamp field.',
//   PRIMARY KEY(nid)
  // );

  // First, the entry $data['example_table']['table'] describes properties of
  // the actual table – not its content.

  // The 'group' index will be used as a prefix in the UI for any of this
  // table's fields, sort criteria, etc. so it's easy to tell where they came
  // from.
  $data['example_table']['table']['group'] = t('Example table');

  // Define this as a base table – a table that can be described in itself by
  // views (and not just being brought in as a relationship). In reality this
  // is not very useful for this table, as it isn't really a distinct object of
  // its own, but it makes a good example.
  $data['example_table']['table']['base'] = array(
    'field' => 'nid', // This is the identifier field for the view.
    'title' => t('Example table'),
    'help' => t('Example table contains example content and can be related to nodes.'),
    'weight' => -10,
  );

  // This table references the {node} table. The declaration below creates an
  // 'implicit' relationship to the node table, so that when 'node' is the base
  // table, the fields are automatically available.
  $data['example_table']['table']['join'] = array(
    // Index this array by the table name to which this table refers.
    // 'left_field' is the primary key in the referenced table.
    // 'field' is the foreign key in this table.
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

  // Next, describe each of the individual fields in this table to Views. This
  // is done by describing $data['example_table']['FIELD_NAME']. This part of
  // the array may then have further entries:
//   - title: The label for the table field, as presented in Views.
//   - help: The description text for the table field.
//   - relationship: A description of any relationship handler for the table
//     field.
//   - field: A description of any field handler for the table field.
//   - sort: A description of any sort handler for the table field.
//   - filter: A description of any filter handler for the table field.
//   - argument: A description of any argument handler for the table field.
//   - area: A description of any handler for adding content to header,
//     footer or as no result behaviour.
  //
  // The handler descriptions are described with examples below.

  // Node ID table field.
  $data['example_table']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    // Define a relationship to the {node} table, so example_table views can
    // add a relationship to nodes. If you want to define a relationship the
    // other direction, use hook_views_data_alter(), or use the 'implicit' join
    // method described above.
    'relationship' => array(
      'base' => 'node', // The name of the table to join with.
      'base field' => 'nid', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
    ),
  );

  // Example plain text field.
  $data['example_table']['plain_text_field'] = array(
    'title' => t('Plain text field'),
    'help' => t('Just a plain text field.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  **// Example numeric text field.**
  $data['example_table']['numeric_field'] = array(
    'title' => t('Numeric field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  // Example boolean field.
  $data['example_table']['boolean_field'] = array(
    'title' => t('Boolean field'),
    'help' => t('Just an on/off field.'),
    'field' => array(
      'handler' => 'views_handler_field_boolean',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_boolean_operator',
      // Note that you can override the field-wide label:
      'label' => t('Published'),
      // This setting is used by the boolean filter handler, as possible option.
      'type' => 'yes-no',
      // use boolean_field = 1 instead of boolean_field <> 0 in WHERE statment.
      'use equal' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  // Example timestamp field.
  $data['example_table']['timestamp_field'] = array(
    'title' => t('Timestamp field'),
    'help' => t('Just a timestamp field.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

  return $data;
}

```

Source: https://api.drupal.org/api/views/views.api.php/function/hook\_views\_data/7.x-3.x

---
Tags: views
---


# Question
Title: How to switch view before render current view?
I am using Field Collection Views module which allowed to create field widget as a view.

My requirement is to allow content author to choose widget for output this field (Field Collection). I added select field to article type to choose widget from two Field Collection Views views.

Field Collection is using views\_embed\_view for rendering this field, so I am trying to use hook\_views\_pre\_view to switch to different view if author choose other than default view (display formatter)

```
/*
 * Implements hook_views_pre_view()
 */
function wzp_gallery_views_pre_view(&$view, &$display_id, &$args) {
    $node = menu_get_object();
    if (! $node->type == 'article') {
        return;
    }
    $field_name = FIELD_GALLERY_VIEW_FIELD_NAME;
    if (! $node->$field_name) {
        return;
    }
    $value = array_shift($node->$field_name);
    $view_info = explode('#', $value[0]['value']);
    if (! $view_info) {
        return;
    }
    $name = $view_info[0];
    $id = $view_info[1];
    if ($view->name == $name && $display_id == $id) {
        return;
    }
    $display_id = $id;
    if ($view->name == $name) {
        return;
    }
    drupal_set_message('<pre>' . print_r($name, 1) . '</pre>');
    drupal_set_message('<pre>' . print_r($id, 1) . '</pre>');
    $view = views_get_view($name);
    $view->set_display($id);
    $view->preview = TRUE;
}

```

but I am end up always with default view rendered.

Code form Field Collection Views module:

```
/**
 * Implements hook_field_formatter_view().
 */
function field_collection_views_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'field_collection_views_view':
      //debug($items);
      $args = '';
      $i = 1;
      foreach ($items as $delta => $item) {
        if ($i == 1) {
          $args .= $item['value'];
        }
        else {
          $args .= '+' . $item['value'];
        }
        $i++;
      }
      $view_name = isset($settings['name']) ? $settings['name'] : 'field_collection_view';
      $display_id = isset($settings['display_id']) ? $settings['display_id'] : 'default';
      $content = views_embed_view($view_name, $display_id, $args);
      $element[0] = array(
        '#markup' => $content,
      );
      if (empty($items)) {
        field_collection_field_formatter_links($element, $entity_type, $entity, $field, $instance, $langcode, $items, $display);
      }
      break;
  }
  return $element;
}

```

Could someone give me any advice?

# Answer
> 1 votes
**Answer**

You can't switch view during render process but current display id.

# Answer
> 1 votes
The answer is to use hook\_views\_pre\_view, see the documentation here:

https://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_view/7

Hope this helps, I had a similar use case. Note: you should use

```
$view->set_display()

```

To actually change the view display.

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


# Question
Title: Views gives 200 instead of 404 if incorrect argument and a pager is present
I am using with success the global null variable as described here How do I set my views to return a 404 using Global: Null under contextual filters?

The solution by Kiam works fine, until a pager is added.

So, myviews/mybadarg returns 404, but myviews/mybadarg?page=2022 returns 200

Any tips why?

I tried enabling and disabling pager but no luck.

# Answer
> 1 votes
I found a solution: I had to set "Show page not found" in the Global Null argument "When the filter value is not in the URL."

---
Tags: views, paging, 7
---


# Question
Title: adding image field to "Taxonomy term view"
I try to create a product catalog instead of using drupal commerce in drupal 7 with current updates. I create product types related to categories which are taxonomy terms. I create a menu as taxonomy terms. If select a taxonomy terms from menu , it is listed all products under that terms. Listing is controlled by taxonomy term view. There we can control only node title. I want to find a way to add image related to that node also. Is there a module for that purpose? Or how could it be achieved? Regards,

# Answer
> 1 votes
when you click on term you see teasers of nodes. few solutions for you:

1. You can change teaser of node in node display settings.
2. You can enable taxonomy/term/% view and customize it as you want
3. Also here is some article

# Answer
> 0 votes
I found a solution on below link ; https://stackoverflow.com/questions/15012999/how-to-display-all-taxonomy-term-fields-when-adding-node-in-drupal

I had already have entity reference module , but no entity reference view widget. After i installed "entity reference view widget" , i could view image field in taxonomy term view.

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


# Question
Title: Content organization for complex website
I know this is a trivial question but before to continue I would like to hear some opinions from You experts. I am organizing my content in D7 website in two section "Activities" and "Our Projects". The "Activities" will have the bellow pattern:

```
activities/public-buildings/schools/project-1.

```

I've created a CCK for company projects (aka project-1,2,3 etc) However for each category I would like to have a landing page which will show its sub-directories. For example a landing page for "public-buildings" will include a text with images and also a list with "schools" etc. A landing page "schools" will include a text with images and also a list with "projects". Last, "Our Projects" section will again include projects. So the question is, which way should I proceed (taxonomy) or node reference or?

# Answer
> 2 votes
Taxonomy is the way designed just for this. You can override taxonomy term pages with Views, and in view settings you can easily add your own content. Or use any other approach. Nodereference feels awkward to me, but would work.

If you want to go taxonomy way, just do what feels natural for your kind of data. Make things as simple as possible, and not simpler! That said, if one tree is a subtree of another, yes, keep it as one hierarchical vocabulary. It makes sense and will allow you to filter more effectively in the future.

---
Tags: views, 7, nodes
---


# Question
Title: Need a Best Video Player For My Video Hosting Site
I am creating a video sharing and hosting site on drupal but I am having difficulties in finding a good video player which can play almost all files. I have used media element but that is playing some mp4 files and some are not being played.

Secondly I want the video player to generate thumbnails by itself.

# Answer
> 0 votes
check that : jw\_player.

For thumnbails you can use that : DailyMotion, Youtube. its very simple to use it.

---
Tags: files
---


title: Setting value to checkboxes in a form

text:
# Question
Title: Setting value to checkboxes in a form
I've been having troubles with form\_set\_value(). I've extended the Search form, everything works, but after submission, the form values for those fields added by me return to default (see the code).

What am I doing wrong?

Thank you!

```
<?
/**
 * implementation of function hook_form_FORM_ID_alter
 */
function myModule_form_search_form_alter( &$form, &$form_state, $form_id ){

    $form['myM_options']['entity'] = array(
                                            '#type' => 'radios',
                                            '#title' => 'Search by',
                                            '#default_value' => 'gene',
                                            '#options' => array(
                                                                "gene" => "Genes",
                                                                "ortholog" => "Orthologs",
                                                                "microarray" => "Microarray Features"
                                                            ),

                                        );
    $form['myM_options']['plant'] = array(
                                            '#type' => 'checkboxes',
                                            '#title' => 'Choose plants',
                                            '#options' => formatPlants(),
                                            // select all checkboxes by default
                                            '#default_value' => array_keys(formatPlants()),
                                        );
    $form['#validate'][] = 'myModule_search_validate';
    $form['#submit'][] = 'myModule_search_form_alter_submit';
}
/**
 * validation functoin
 */
function myModule_search_validate( $form, &$form_state ){
    // this works as expected
    form_set_value($form['basic']['processed_keys'], trim($form_state['values']['keys']), $form_state);

    // this doesn't !!!
    form_set_value($form['myM_options']['entity'], $form_state['values']['entity'], $form_state);
    form_set_value($form['myM_options']['plant'], array( 'id_1', 'id_2' ), $form_state);
}

```

# Answer
> **$form**: An associative array containing the structure of the form, which is ***passed by reference***. Form validation handlers are able to alter the form structure (like #process and #after\_build callbacks during form building) in case of a validation error. If a validation handler alters the form structure, it is responsible for validating the values of changed form elements in $form\_state\['values'\] to prevent form submit handlers from receiving unvalidated values.

So your form validation function should be as the following:

```
/**
 * validation functoin
 */
function myModule_search_validate( &$form, &$form_state ) {
  // function body
}

```

Then in your form submit function you need to set `$form_state['rebuild'] = TRUE` as following:

```
/**
 * submit functoin
 */
function plant_Ontlogy_search_form_alter_submit( &$form, &$form_state ) {
  // function body

  $form_state['rebuild'] = TRUE;
}

```

If setting state rebuild to TRUE didn't work with you by itself, try to set default value as the following example to each additional field:

```
$form['myM_options']['entity'] = array(
  '#type' => 'radios',
  '#title' => 'Search by',
  '#default_value' => isset($form_state['values']['entity'])? $form_state['values']['entity'] : 'gene',
  '#default_value' => 'gene',
  '#options' => array(
    "gene" => "Genes",
    "ortholog" => "Orthologs",
    "microarray" => "Microarray Features"
  ),
);

```
> 0 votes

---
Tags: forms
---


# Question
Title: 'og:url' meta property displaying wrong path, messing up posting on external sites
I'm trying to post a link to a landing page on my Drupal site, like `http://me.mysite.com/aboutme`. When I post it to Facebook, the link that pops up is to `http://me.mysite.com/node/xyz`. `node/xyz` is an actual node on my site, and content from it appears in a panel that's on `http://me.mysite.com/node/xyz` but it's only like 1/16 of the content of the page, and I have a lot of other panels on that page too. Why is it picking this one? How do I get it to link to the actual page I'm giving the URL for?

Here's a screenshot of my meta tags config:

# Answer
> 2 votes
Assuming your permissions are correct, you can override the settings for anything.

In your case, override **Content**, and expand the **Open Graph** section. Then, you can pick the proper token. I use `[current-page:url:absolute]`

---
Tags: panels, path-aliases, social-network, subsites
---


# Question
Title: Where can I tell if my Drupal 7 database is using InnoDB?
I have a Drupal 7 site and was wondering how can I tell if my database is using InnoDB ?

If its not using InnoDB, would I be able to just switch over easily? I just recently switched to MariaDB if that makes a difference.

# Answer
To find out which tables are InnoDB and MyISAM

# COUNTS

```
SELECT ENGINE,COUNT(1) TableCount FROM information_schema.tables
WHERE table_schema NOT IN ('information_schema','mysql','performance_schema')
GROUP BY engine;

```

Since MyISAM is a non-transactional storage engine, it has no foreign key referential integrity to enforce. You could change all MyISAM tables to InnoDB, but with one exception: Before MySQL 5.6, FULLTEXT indexes are only available for MyISAM tables.

Here is how to find all tables using FULLTEXT indexes.

```
SELECT tbl.table_schema,tbl.table_name FROM
(
    SELECT table_schema,table_name
    FROM information_schema.tables
    WHERE engine='MyISAM' AND table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) tbl
INNER JOIN
(
    SELECT table_schema,table_name
    FROM information_schema.statistics
    WHERE index_type='FULLTEXT'
) ndx
USING (table_schema,table_name);

```

If this comes back with no rows, you can convert all MyISAM tables to InnoDB without worry. If you have any tables with FULLTEXT indexes and you do not use them, you could drop the FULLTEXT indexes then convert the tables to InnoDB.

# CONVERSION SCRIPTS

Here is a script to convert all MyISAM tables that do not have FULLTEXT indexes to InnoDB:

```
SQLSTMT="SELECT CONCAT('ALTER TABLE ',tbl.table_schema,'.',tbl.table_name,' ENGINE=InnoDB;')"
SQLSTMT="${SQLSTMT} FROM (SELECT table_schema,table_name FROM information_schema.tables"
SQLSTMT="${SQLSTMT} WHERE engine='MyISAM' AND table_schema NOT IN"
SQLSTMT="${SQLSTMT} ('information_schema','mysql','performance_schema')) tbl"
SQLSTMT="${SQLSTMT} INNER JOIN"
SQLSTMT="${SQLSTMT} (SELECT table_schema,table_name FROM information_schema.statistics"
SQLSTMT="${SQLSTMT} WHERE index_type='FULLTEXT') ndx USING (table_schema,table_name)"
mysql -uroot -p -ANe"${SQLSTMT}" > ConvertMyISAMToInnoDB.sql
mysql -uroot -p -A < ConvertMyISAMToInnoDB.sql

```

If you know for a certainty that there are no FULLTEXT indexes in use, you can do this:

```
MYSQL_CONN="-uroot -prootpassword"
SQLSTMT="SELECT CONCAT('ALTER TABLE ',table_schema,'.',"
SQLSTMT="${SQLSTMT} table_name,' ENGINE=InnoDB;') InnoDBConversionSQL"
SQLSTMT="${SQLSTMT} FROM information_schema.tables WHERE engine='MyISAM' AND"
SQLSTMT="${SQLSTMT} table_schema NOT IN ('information_schema','mysql','performance_schema')"
SQLSTMT="${SQLSTMT} ORDER BY (data_length+index_length)"
MYSQL_OPTIONS="-AN"
mysql ${MYSQL_CONN} ${MYSQL_OPTIONS} -e"${SQLSTMT}" > ConvertMyISAMToInnoDB.sql
mysql ${MYSQL_CONN} ${MYSQL_OPTIONS} < ConvertMyISAMToInnoDB.sql

```

I have suggested this in the past : How do I convert a database from MyISAM to InnoDB?

# CAVEAT

Changing all tables to InnoDB will change the needs for MySQL's memory usage. Why?
> 4 votes

# Answer
```
SHOW TABLE STATUS WHERE Name = 'table_name';
```
where a column with engine will appear showing you the engine type.
Converting should not be a problem The MySQL converting innodb reference can be used (Please backup your db before trying anything like this).
> 1 votes

---
Tags: 7, database
---


title: Writing to a custom field in PHP

text:
# Question
Title: Writing to a custom field in PHP
In Drupal 7, using the Field module, Field SQL Storage and Field UI I've created several custom user fields. I can display them in PHP like this:

```
global $user;
$account = user_load($GLOBALS['user']->uid);
if ($items = field_get_items('user', $account, 'field_keys_available')) {
   $keys_remaining = $items[0]['value'];

```

The above example displays the custom keys\_available field, a field we use to determine if the user is entitled to software license keys. I need to decrement field\_keys\_available in the PHP that issues a license key to a user. Can someone help with the syntax on this? I've discovered fifty ways to generate white screens, but haven't landed on the right syntax.

# Answer
It should be something as simple as

```
$account = user_load($GLOBALS['user']->uid);
$edit['field_keys_available'][LANGUAGE_NONE][0]['value'] = 'new value';
user_save($account, $edit);

```

The comments in the `user_save()` docs have some more details and examples.
> 0 votes

---
Tags: entities
---


# Question
Title: How to get forms to save variables to the correct place
I maintain a contrib module, and I'm in the process of porting it from Drupal 6 to Drupal 7. The module (http://www.drupal.org/project/csm) adds fields to the edit form for each content type (i.e., the form at admin/structure/types/manage/\[node-type\], so part of the porting process involves displaying those fields as new vertical tabs (see "Submit message settings" and "Node creation page title" in the screenshot below).

The problem is, when the fields are changed to be part of the vertical tabs, I seem to lose control over how the data that is entered into those fields is saved to the variable table. I've stepped through the submission of the form with a breakpoint set in variable\_set(), but only one variable seems to be set for each vertical tab that I've added: previously, each new field was added separately to the variable table, and I was able to control the name of the variable by setting the name of the field. This is what I'd like to do now.

Am I missing something? Is there some good documentation somewhere that covers what I'm trying to do? Here's the code that I'm using to add the new vertical tabs (and the fields in those tabs):

```
function csm_form_node_type_form_alter(&$form, $form_state) {

  // We need to know the current site language in order to present the form with
  // appropriate sections expanded.
  global $language;
  $current_lang = $language->language;

  // Build the form section that allows the user to change the submit messsages.
  $form['csm'] = array(
    '#type' => 'fieldset',
    '#title' => t('Submit message settings'),
    '#access' => user_access('change ' . $form['#node_type']->type . 'submit messages'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'additional_settings',
    '#tree' => TRUE,
    '#weight' => 100,
    '#attributes' => array('class' => array('csm-form')),
  );

  // Add submit message subsections for each language
  foreach (language_list() as $lang => $details) {
    $form['csm'][$lang] = _csm_lang_fieldsets($lang, $form['#node_type']->type);
    $form['csm'][$lang]['#title'] = t($details->name);
    if ($lang == $current_lang) {
      $form['csm'][$lang]['#collapsed'] = FALSE;
  }

  // Add token help section
  $form['csm']['view']['token_help'] = array(
    '#title' => t('Replacement patterns'),
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    );

  $form['csm']['view']['token_help']['help'] = array(
    '#theme' => 'token_tree',
    '#token_types' => array('node'),
    '#global_types' => TRUE,
    '#click_insert' => TRUE,
  );

  // Build the form section that allows the user to change the node creation
  // page title.
  $form['cnpt'] = array(
    '#type' => 'fieldset',
    '#title' => t('Node creation page title'),
    '#access' => user_access('change ' . $form['#node_type']->type . ' creation page title'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'additional_settings',
    '#tree' => TRUE,
    '#weight' => 101,
    '#attributes' => array('class' => array('csm-form')),
  );

  // Add create form title subsections for each language
  foreach (language_list() as $lang => $details) {
    $form['cnpt'][$lang] = _csm_lang_fieldsets($lang, $form['#node_type']->type, 'title');
    $form['cnpt'][$lang]['#title'] = t($details->name);
    if ($lang == $current_lang) {
      $form['cnpt'][$lang]['#collapsed'] = FALSE;
    }
  }

  // Add token help section
  $form['cnpt']['view']['token_help'] = array(
    '#title' => t('Replacement patterns'),
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    );

  $form['cnpt']['view']['token_help']['help'] = array(
    '#theme' => 'token_tree',
    '#token_types' => array('node'),
    '#global_types' => TRUE,
    '#click_insert' => TRUE,
    );
  }
}

```

\_csm\_lang\_fieldsets() is a helper module that does some of the form building (a new form section has to be added for each language that is enabled on the site):

```
function _csm_lang_fieldsets($lang = NULL, $form_type, $type = 'message') {

  if ($lang == NULL) {
    global $language;
    $lang = $language->language;
  }

  $fields = array(
    '#type' => 'fieldset',
    '#title' => t($lang),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    );

  switch ($type) {
    case 'message':
      $fields['csm_insert_msg_' . $lang] = array(
        '#type' => 'textfield',
        '#title' => t('Create message'),
        '#default_value' => t(variable_get('csm_insert_msg_' . $lang . '_' . $form_type, '')),
        '#description' => t('Override the default message displayed when a user creates a node of this type. Use <em><none></em> to display no message, or leave blank to use the default message ("[node:content-type:name] [node:Title] has been created.").'),
        '#size' => 60,
        '#maxlength' => 4096,
        '#required' => FALSE,
      );

      $fields['csm_update_msg_' . $lang] = array(
        '#type' => 'textfield',
        '#title' => t('Update message'),
        '#default_value' => t(variable_get('csm_update_msg_' . $lang . '_' . $form_type, '')),
        '#description' => t('Override the default message displayed when a user updates a node of this type. Use <em><none></em> to display no message, or leave blank to use the default message ("[node:content-type:name] [node:Title] has been updated.").'),
        '#size' => 60,
        '#maxlength' => 4096,
        '#required' => FALSE,
      );

      $fields['csm_delete_msg_' . $lang] = array(
        '#type' => 'textfield',
        '#title' => t('Delete message'),
        '#default_value' => t(variable_get('csm_delete_msg_' . $lang . '_' . $form_type, '')),
        '#description' => t('Override the default message displayed when a user deletes a node of this type. Use <em><none></em> to display no message, or leave blank to use the default message ("[node:content-type:name] [node:Title] has been deleted.").'),
        '#size' => 60,
        '#maxlength' => 4096,
        '#required' => FALSE,
      );

      return $fields;
      break;
    case 'title':
      $fields['csm_form_title_' . $lang] = array(
        '#type' => 'textfield',
        '#title' => t('Node create form title'),
        '#default_value' => t(variable_get('csm_form_title_' . $lang . '_' . $form_type, '')),
        '#description' => t('Override the default title for the node creation page. Use <em><none></em> to display no title, or leave blank to use the default title ("Create [node:content-type:name]").'),
        '#size' => 60,
        '#maxlength' => 4096,
        '#required' => FALSE,
      );

      return $fields;
      break;
  }
}

```

For comparison, here's the code that generates the vertical tab that comment.module adds to the form. It adds variables called comment\_anonymous\_article, comment\_article, comment\_default\_mode\_article, comment\_default\_per\_page\_article, comment\_form\_location\_article , comment\_page, comment\_preview\_article, and comment\_subject\_field\_article to the variable table. These names seem to be taken from form elements, and it is how I'd expect my own code to work.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function comment_form_node_type_form_alter(&$form, $form_state) {
  if (isset($form['type'])) {
    $form['comment'] = array(
      '#type' => 'fieldset',
      '#title' => t('Comment settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
      '#attributes' => array(
        'class' => array('comment-node-type-settings-form'),
      ),
      '#attached' => array(
        'js' => array(drupal_get_path('module', 'comment') . '/comment-node-form.js'),
      ),
    );
    // Unlike coment_form_node_form_alter(), all of these settings are applied
    // as defaults to all new nodes. Therefore, it would be wrong to use #states
    // to hide the other settings based on the primary comment setting.
    $form['comment']['comment'] = array(
      '#type' => 'select',
      '#title' => t('Default comment setting for new content'),
      '#default_value' => variable_get('comment_' . $form['#node_type']->type, COMMENT_NODE_OPEN),
      '#options' => array(
        COMMENT_NODE_OPEN => t('Open'),
        COMMENT_NODE_CLOSED => t('Closed'),
        COMMENT_NODE_HIDDEN => t('Hidden'),
      ),
    );
    $form['comment']['comment_default_mode'] = array(
      '#type' => 'checkbox',
      '#title' => t('Threading'),
      '#default_value' => variable_get('comment_default_mode_' . $form['#node_type']->type, COMMENT_MODE_THREADED),
      '#description' => t('Show comment replies in a threaded list.'),
    );
    $form['comment']['comment_default_per_page'] = array(
      '#type' => 'select',
      '#title' => t('Comments per page'),
      '#default_value' => variable_get('comment_default_per_page_' . $form['#node_type']->type, 50),
      '#options' => _comment_per_page(),
    );
    $form['comment']['comment_anonymous'] = array(
      '#type' => 'select',
      '#title' => t('Anonymous commenting'),
      '#default_value' => variable_get('comment_anonymous_' . $form['#node_type']->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT),
      '#options' => array(
        COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'),
        COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'),
        COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information'),
      ),
      '#access' => user_access('post comments', drupal_anonymous_user()),
    );
    $form['comment']['comment_subject_field'] = array(
      '#type' => 'checkbox',
      '#title' => t('Allow comment title'),
      '#default_value' => variable_get('comment_subject_field_' . $form['#node_type']->type, 1),
    );
    $form['comment']['comment_form_location'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show reply form on the same page as comments'),
      '#default_value' => variable_get('comment_form_location_' . $form['#node_type']->type, COMMENT_FORM_BELOW),
    );
    $form['comment']['comment_preview'] = array(
      '#type' => 'radios',
      '#title' => t('Preview comment'),
      '#default_value' => variable_get('comment_preview_' . $form['#node_type']->type, DRUPAL_OPTIONAL),
      '#options' => array(
        DRUPAL_DISABLED => t('Disabled'),
        DRUPAL_OPTIONAL => t('Optional'),
        DRUPAL_REQUIRED => t('Required'),
      ),
    );
  }
}

```

# Answer
I remove the setting of "#tree" to FALSE, and everything works fine again.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Image upload not working for "AUTHENTICATED USER"
Media module is awesome! But I can not understand why AUTHENTICATED USERS are unable to Upload images from CKEditor( http://drupal.org/project/ckeditor ) module.

I have set permission: `Import media files from the local filesystem` for the AUTHENTICATED USER, but still the uploader doesn't seem to work, except for the admin!

Here is a screenshot showing the Media Module inline uploader works with CKEditor while logged in as Admin:

Here is a another screenshot showing the Media Module inline uploader do not working with CKEditor while logged in as AUTHENTICATED USER:

Please give me ideas to fix this.

# Answer
> 1 votes
**Do not** give your authenticated users the *Import media files from the local filesystem* permission. It's actually different functionality that could open you up to security risk.

Looking at media\_media\_browser\_plugin\_info(), we can see that in order to use the upload plugin, the user has to either have the *Edit media* or the *Administer media* permission. Likely you'll want to assign the former.

I'll file an issue to correct that the import permission is misleading, and improve the description of the *Edit media* permission to be clear this is necessary to upload files in the browser.

---
Tags: wysiwyg, media
---


# Question
Title: "syntax error, unexpected end of file" Upon enabling modules
I'm getting a syntax error when enabling modules. This is happening intermittently and it isn't specific to any module in particular, which is making it impossible for me to track down. Here is the error I'm receiving today:

> Parse error: syntax error, unexpected end of file in sites/all/modules/contrib/headerimage/headerimage.module on line 821

Line 821 is the very last line of the file, and the syntax looks fine to me. When I get a similar error when enabling modules, it's always complaining about the last line. There are never any missing brackets. I've disabled any custom modules I wrote thinking that it could be my code causing this, but I've had no success.

I was wondering if anyone has run into this, if they have any suggestions, or possibly a method to troubleshoot this.

-- EDIT --

I was able to resolve the syntax errors for this particular module (headerimage). I had to delete the very last line in two of the files and re-add them manually. They were closing brackets "}".

I'm not convinced that this is the correct fix. Maybe it's some kind of encoding issue? Any thoughts?

# Answer
> 2 votes
I figured out what this was. It wasn't necessarily related to Drupal or PHP syntax, but the answer might save someone else some stress.

I had VMWare Fusion on my Mac running a Linux VM with Apache/MySQL/PHP server. The webroot for Apache was a shared directory on my host machine which contained my Drupal install. I did this so I can have the benefit of a Linux web server while being able to edit my code locally on my host.

This works when serving up the site, but whenever I used Drush on the VM to install a module, there was always a hidden line appended to the module's files that Vi didn't pick up, which is why the syntax error was *always* on the last line. I'm assuming it had to do with the hgfs filesystem used for sharing between my host and the VM.

Once I removed the VM sharing and modified everything on the VM itself, all of my problems went away. Downloading modules with Drush no longer produces these syntax errors.

Here is a related thread on the Drush issue queue where people are having similar issues.

https://drupal.org/node/1948962

Thanks to those who gave their feedback. --richard

# Answer
> 1 votes
This is a parse error which occurs when php is still looking for something and reaches the end of the file without finding it. It could be a quote or bracket which is unclosed, and php is still treating the file contents as a part of the quote.

Yes line 821 is the last line of the file. Php is just telling you it was unexpected.

Errors like this are not intermittent, but you might have to do some work to find how to reproduce it. Once you do that, you can start eliminating modules to try to find the source.

Good luck.

# Answer
> 0 votes
It could be as simple as removing the last closing PHP tag (`?>`), if one exists, at the end of the file(s). Generally no files should end with a closing PHP tag, although they should have a starting tag (`<?php`) at the very beginning.

---
Tags: debugging
---


# Question
Title: Book: Drupal 7 Module Development (directions caused weirdness)
I'm reading a book, Drupal 7 Module Development, and I'm hitting some very weird outputs.

I created a folder:

```
mysite/sites/default/module/first

```

Inside this folder I created two files.

**first.info**

```
;$Id$

name = First
description = A first module
package = Drupal 7 Development
core = 7.x
files[] = first.module

;dependencies[] = autoload
;php = 5.2

```

**first.module**

```
<?php

// $Id$

/**
 * @file
 * A module exmplifying Drupal coding practices and API's.
 *
 * This module provides a block that lists all of the
 * installed modules. It illustrates coding standards,
 * practices, and API use for Drupal 7.
 */

/**
 * Implements hook_help().
 */
function first_help($path, $arg) {
    if ($path == 'admin/help#first') {
        return t('A demonstration module.');
    }
}

```

But when I activate the module, I get the contents of the first.module file spashed across the top of my page? Can someone advise me on what I am doing wrong?

This is my very first module for Drupal.

# Answer
> 2 votes
You just have to follow the steps which I am writing below to create a module.

* Go to folder **SITES/ALL/MODULES**
* Create a folder for module, suppose *`mymodule`*
* Inside that folder create a file name *`mymodule.info`*
* Write these lines in there:

*name = My Custom Module*

*core = 7.x*

*description = Custom module created for testing.*
* Create another file named *`mymodule.module`*
* Just open the PHP tag like `<?php` and save the created `.module` file
* Visit your module list & you will find this module in the list over there. If not then clear the cache for once.

Problem with your process which I saw is with the path which you followed for creating the folder for your module which **SITES/DEFAULT/MODULES**, which is not correct.

# Answer
> 1 votes
Is that the exact code that is in the book? My copy is at the office.

It looks like you have simple PHP error. The opening line should read

```
<?php

```

and not

```
<$php

```

Make that change, and things should start working again.

---
Tags: 7, .info
---


# Question
Title: How to prevent Drush pm-update from backing up symbolic links?
In my Drupal installation folder, I have symlinks to external folders with 80+ GB of data. When I backup/update Drupal using Drush, Drush also archives the 80+ GB of data. How do I prevent Drush from backing up the contents of symlinks?

Also, when Drush restores the backup, the symlinks are not preserved as well. Drush replaces symlinks with the actual content. So after the backup/update of Drupal core is done, my Drupal installation folder ends up being too huge.

Can you please suggestion solution to both of the above problems? I am okay even if I have to write code to patch Drush or anything else. Just need help pointers in correct directions.

# Answer
This should probably be in the Drush issue queue. Maintainers can help you work through issues if you want to make a patch. Be sure you are using the latest version of Drush. By intention, it looks like Drush should only behave as you describe if the --dereference option is specified; without that, it should not follow and archive symlinks. Run Drush with --simulate to see what actual tar commands, etc. Drush is running. Post results and followup questions to the issue queue.
> 2 votes

# Answer
I found a way to exclude certain directories including symbolic links from Drush core update.

Since core update command does not provide a way to exclude directories. We should first take a routine backup of our Drupal site, and then ask Drush to run update in-place i.e. without taking additional backup. We need to add --no-backup option in Drush update command. This way symbolic links are preserved too!

We need to execute sequence of following two commands to update Drupal core containing symbolic links. You can just execute first command if you are only interested in taking backup of your Drupal site.

```
$ drush ard --tar-options="--exclude=symlinkfolder --exclude=.git" --root="/path/to/drupal/" -v

$ sudo drush up drupal --no-backup --root="/path/to/drupal/" -v

```
> 0 votes

---
Tags: drush
---


# Question
Title: What is best for setting up the vocabulary for ubercart products?
I'm setting up an Ubercart store on drupal 7.

I've created a new product class "tire" and I'm adding custom fields to the "tire" content type. Some of these fields such as brand and speed rating should to pull their values from a vocabulary.

What is best for setting up the vocabulary?

```
Option 1)
Tires -> Type -> All-Season, Winter, etc...
Brand -> Good Year, Dunlop, etc...
Speed Rating -> S, T, H, etc...

Option 2)
Tires -> Type -> All-Season, Winter, etc...
Tire Properties -> Brand -> Good Year, Dunlop, etc...
Tire Properties -> Speed Rating -> S, T, H, etc...

Option 3)
Tires -> Type       -> All-Season, Winter, etc...
Tires -> Properties -> Brand        -> Good Year, Dunlop, etc...
Tires -> Properties -> Speed Rating -> S, T, H, etc...

```

I've started with option 3 already, but I've noticed that when I go to add a new tire the drop-downs are allowing values from the entire vocabulary, not just a specific child-node such as everything below "brand".

I'm not really sure what the best-practice is for setting vocabularies for custom fields using the CCK module.

# Answer
The way your describing it cannot be used as a vocabulary taxonomy as each term is related to one another. What your describing is a type of content. Since each tire has an attribute of:

* type
* brand
* speed rating

Your vocabulary should be those 3 separate ones, with each appropriate term under them. From there you would create a product in ubercart and those would be the 3 ATTRIBUTES and you would then add OPTIONS to those attributes. Ubercart's architecture isn't very appropriate for your type of setup last i tried. Technically you are only creating 1 product in ubercart and have 3 attributes for it with a bunch of options.

My suggestion would be to use Drupal Commerce as it would work perfectly for you as it will represent each product properly. Each unique tire will be represented as a product item. It will be alot of them as you have 3 attributes for each.
> 0 votes

---
Tags: taxonomy-terms, entities, ubercart
---


# Question
Title: Define multiple variables in a custom module using hook_variable_info()
Im using the `Variable module` and need to define a variable with the type `"multiple"` in my custom module. I've been googled whole my day searching for any documentation or just an example and haven't found anything.

There are plenty examples how to set the variable in such type like: `string`, `number`, `radios`, but nothing about the "`multiple`" type.

**My "multiple" variable should look like this:**

**How can I build this kind of variable using hook\_variable\_info() ?**

# Answer
I figure out this on my own. Hope will be useful for someone.

```
/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {

    // Use '[custom]' as a placeholder for the variable name.
    // It will set these properties ('type' and 'multiple') automatically.
    $variables['custom_vars_[custom]'] = array(
        'title'     =>  t('Custom multiple variable'),
        'group'     =>  'site_information',
        'repeat'    =>  array('type' => 'string', 'default' => 'some default value'),
    );

    // if you need to expose your custom variable as token
    // you have to set 'token' key as TRUE,
    // and ought to set the properties (name, description and type)
    // Notice that 'first' it's a name of variable defined in custom_variable_options().
    $variables['custom_vars_first'] = array(
                    'token' => TRUE,
                    'title' => 'Custom variable',                       // name
                    'description' => 'My first variable description',   // description
                    'type'  => 'string'                                 // type
                    );
  return $variables;
}

/**
 * Implements hook_variable_type_info().
 * @return
 *  An array of information defining variable types.
 *  The array contains a sub-array for each variable type
 *  with the variable type as the key.
 *  The possible attributes are the same as for hook_variable_info().
 */
function MY_MODULE_variable_type_info() {
    $type['custom'] = array(
        'title' => t('Custom variables'),
        'type'  => 'select',
        'options callback' => 'custom_variable_options',
    );
    return $type;
}

/**
 * Callback for custom options.
 * @return
 *  An array of variables with the variable name as the key.
 */
function custom_variable_options($variable, $options) {
  return array(
    'first'  => t('My first variable', array(), $options),
    'second' => t('My second variable', array(), $options),
    'third'  => t('My third variable', array(), $options),
  );
}

```

**Want to see how it works?**

1. Install Variable module
2. Enable: Variable, Variable store, Variable Admin
3. Place this code in your custom module (replace 'MY\_MODULE' to your module name)
4. Clear caches.

Results:

**admin/config/system/variable -\> site information**

**admin/config/system/variable/group/site\_information**

**admin/config/search/path/patterns**
> 4 votes

# Answer
You can do that with a regular system\_settings\_form form, just wrap the elements in a fieldset and set

$form\['#tree'\] = TRUE;

The variables will then be stored as an array inside a single conf variable.
> 3 votes

---
Tags: hooks, configuration
---


title: Like dislike user

text:
# Question
Title: Like dislike user
I'm working in a project for my clients and they want to add like/dislike buttons to the users profiles that for the users can rate each others. Have you guys worked on something similar? Can you tell me the guidelines to do this? Thank you.

# Answer
check the Voting API module. It is solid and does exactly what you want. From the module description:

> Rating of any content (comments, nodes, users, fish, whatever) Multi-criteria voting (rate a game based on video, audio, and replayability) Automatic tabulation of results (with support for different voting styles, like 'percentage' and '+1/-1').

You just may need to write few lines of code to reach your objective.
> 3 votes

---
Tags: users
---


# Question
Title: Drush command to delete content going out of memeory. What can I do?
I have implemented drush hooks to build a drush command that deletes a lot of legacy nodes. It basically does a node\_delete on a lot of nodes in a loop. However, I have the memory limit set to ~380MiB in settings.php and when I run the command to delete large number of nodes, say 100 000, drush terminates abnormally with an error indicating that it ran out of memeory. This happens by the time it deletes 20000 nodes. I have looked around and checked the definition of node\_delete. In the definition there is a comment about the possibility of going out of memory.

I tried unsetting variables, and I tried doing node\_load(NULL,NULL,TRUE)-- as suggested one drupaler on this forum-- hoping to release some memory every number of iterations but this did not work. So is there anything I can do? I am trying to avoid breaking it into chunks for ease of release.

# Answer
If you look at the code for `node_delete_multiple()` it does a `node_load_multiple()`. While this seems strange, it has to do this so that it can invoke all of the proper hooks so that other modules have the full `$node` object in order to do their thing (eg, delete the attached field data).

Because Drupal uses aggressive static caching to avoid redundant database accesses, memory usage can swell. This can't be freed or disabled. If this becomes an issue, you can do temp edits to the EntityControllers to comment out the static caches. You could also make a temp edit to `drupal_static()` to effectively disable it.

I would come up with a good `EntityFieldQuery` to get the list of nodes to delete. This will just give you back the nids.

Suck out the nids, and trim the array to some limit.

Call `node_delete_multiple()` on the result.

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', $bundle)
  ->addCondition(...)
  ->execute();

$nids = array_slice($entities['node'], 0, 1000);

print 'Deleting ' . count($nids) . ' nodes ... ';

if (!empty($nids)) {
  node_delete_multiple($nids);
}

print "done\n";

```

Put this in a standalone PHP and execute is from drush, eg

```
drush -u 1 scr nuke_everything.php

```

Run it until everything is gone.

The above solution is for Drupal 7, but the approach is essentially the same for Drupal 6. You would do a `db_query()` to get the nids, and then loop through and call `node_delete()` on each. However, Drupal 6 also does a full `node_load()`, too. In this instance, it does bypass its static cache, but this doesn't mean that modules aren't also doing any static caching. For Drupal 6, you would need to chase all of the possible `hook_nodeapi('delete')` and look for static caching and static caching in any functions that get called, and do temp edits.
> 1 votes

# Answer
You have to increase the memory\_limit for PHP cli.

If you're in Ubuntu-based you have to update this file

`/etc/php5/cli/php.ini`

Search for `memory_limit` and increase the value.
> 0 votes

---
Tags: drush, nodes
---


# Question
Title: how create then trigger ajax action with D7 ajax API in js
i modified views\_load\_more module and create a custom ajax command:

```
Drupal.ajax.prototype.commands.custom_views_ajax_command = function(ajax, response, status) {
    //append new content has been loaded to old (scroll auto load: slimScroll + waypoints)
};

```

and this's my behaviors:

```
Drupal.behaviors.cva_autoLoad = {
    attach: function(context, settings) {
        $.each(Drupal.settings.cva_autoLoad, function(i, st) {
        //if scroll down to last row: $(views li.pager-next a).click();
    }
}

```

everythings work fine, but i dont know how to trigger the next link click event if height of views is shortern than window.height()

when views is initial, if its height is shortern than scroll bound height, i want to trigger ajax load automatically

i tried this, but no luck

```
if(/*this height < window height*/)
    $(next_link).click();

```

even without condition, nothing happens

i call drupal\_add\_js in function render($input) (views\_plugin\_pager)

how to fix this? or does anyone have any better ways?

sorry about my urgly english

EDIT

maybe my question is so stupid. if yes, plz let me know.

i really need help

i found this when read ajax drupal core and views:

```
var setting = Drupal.settings.views.ajaxViews['views_dom_id:'+st.view_dom];
setting.page = 1;
$.ajax({
    url: Drupal.settings.views.ajax_path,
    type:'POST',
    data: setting,
    dataType: "json",
    success: function(response) {
        console.log(response);
        /*call Drupal.ajax.commands here ( it should be custom_views_ajax_command above*/
    },
});

```

does anyone know how to call Drupal commands or some ways are more legal?

# Answer
> 1 votes
yeah. thank askibinski so much! in this post: XHR2 upload using Drupal 7's ajax framework

and this is my solution:

```
if($(viewDom).height() < height ) {
    var element_settings = {};
    element_settings.progress = { 'type': 'none' };
    element_settings.event = "click";
    element_settings.setClick = false;
    element_settings.url = Drupal.settings.views.ajax_path;
    element_settings.selector = viewDom;
    var setting = Drupal.settings.views.ajaxViews['views_dom_id:'+st.view_dom];
    setting.page = setting.page || 0;
    ++setting.page;
    element_settings.submit = setting;
    new Drupal.ajax(null, $(viewDom), element_settings).eventResponse($(viewDom));
    return;
}

```

and my real question is: how create then trigger ajax action with D7 ajax API in js

thank everybody alot.

---
Tags: 7, views, ajax, javascript, rules
---


# Question
Title: How to fix incorrect average ratings for Fivestar?
I am using Voting API with Fivestar. On my site users can comment on a node and leave a rating with the comment. These are aggregated and an average vote is displayed at the top of the node. The average rating for some of my nodes does not match what the average would be if you summed up the comment ratings and divided by the number of comments. Also the count is wrong.

I believe this happened because I manually converted an old Drupal 6 site to Drupal 7 so I manually entered some old reviews. Because I entered them from the same IP and within the threshold of time I believe the module does not count them.

I'm comfortable running SQL queries to fix this. I was able to enter the correct average and count records in the `votingapi_cache` table. This temporarily fixed the problem, but later I deleted some spam comments, and then the rating was messed up again (I guess maybe deleting causes the `votingapi_cache` table to be rebuilt?)

What is the correct way to fix this?

**UPDATE**

So there is more to the story. I just spent some time manually adding the records into the `votingapi_vote` table. Then I added a new comment with a vote through my drupal site. This caused the `votingapi_cache` to be rebuilt and I saw the the average vote and vote count were correct. I thought great problem solved.

Then I deleted my test comment and immediately the average and vote counts went to zero. Examining the `votingapi_vote` table which I had just manually added records to, I saw that all records for that node id were gone. So deleting a comment deletes all records in `votingapi_vote` table. Seemed fishy so I searched and found it's a bug in the fivestar module: Deletion of Anonymous Comments with Fivestar rating results in deletion of all votes for entity.

Pretty horrendous bug if you ask me. Don't think it's fixed in the module but that bug link has a patch for it which I will try out.

# Answer
Truly correct way to fix it would be to salvage original IP addresses of voters from original database.

If you cannot do it, randomize. Assign each vote an IP from 127.0.0.0/8 range, that way you will not interfere with future votes and large number laws says you'll have pretty small number of duplicates, so averages should be about right.
> 2 votes

# Answer
FYI I'm using fivestar 7.x-2.0-alpha2

Ok I was able to apply the patch I mentioned in my question: Deletion of Anonymous Comments with Fivestar rating results in deletion of all votes for entity. and now it appears to be working.

Applying the patch was not without issue, although I'm not that familiar with the process. This is what I did:

* `cd mydrupaldirectory/sites/all/modules/fivestar`
* downloaded the patch file to that folder: `wget http://drupal.org/files/fivestar-Deletion_of_anonymous_comments_deletes_all_comments-1674120-5.patch`
* I tried `git apply -v fivestar-Deletion_of_anonymous_comments_deletes_all_comments-1674120-5.patch` but this gave me an error:

> $ git apply -v fivestar-Deletion\_of\_anonymous\_comments\_deletes\_all\_comments-1674120-5.patch
>
> fivestar-Deletion\_of\_anonymous\_comments\_deletes\_all\_comments-1674120-5.patch:35: trailing whitespace.
>
> fivestar-Deletion\_of\_anonymous\_comments\_deletes\_all\_comments-1674120-5.patch:65: trailing whitespace. $target = \_fivestar\_field\_target($entity, $field, $instance, $item, $langcode); Checking patch fivestar.info... error: while searching for: configure = admin/config/content/fivestar files\[\] = test/fivestar.base.test files\[\] = test/fivestar.field.test
>
> error: patch failed: fivestar.info:6 error: fivestar.info: patch does not apply Checking patch fivestar.module... Checking patch includes/fivestar.field.inc... Checking patch widgets/basic/basic-rtl.css... Checking patch widgets/basic/basic.css... Checking patch widgets/craft/craft-rtl.css... Checking patch widgets/flames/flames-rtl.css... Checking patch widgets/hearts/hearts-rtl.css... Checking patch widgets/minimal/minimal-rtl.css... Checking patch widgets/outline/outline-rtl.css... Checking patch widgets/outline/outline.css... Checking patch widgets/oxygen/oxygen-rtl.css... Checking patch widgets/oxygen/oxygen.css... Checking patch widgets/small/small-rtl.css...

* I don't really know why it wouldn't apply but instead I ran this: `$ patch -p1 < fivestar-Deletion_of_anonymous_comments_deletes_all_comments-1674120-5.patch` which also gave an error:

> $ patch -p1 \< fivestar-Deletion\_of\_anonymous\_comments\_deletes\_all\_comments-1674120-5.patch
>
> patching file fivestar.info
>
> Hunk #1 FAILED at 6.
>
> 1 out of 1 hunk FAILED -- saving rejects to file fivestar.info.rej patching file fivestar.module Hunk #1 succeeded at 130 (offset -19 lines). Hunk #2 succeeded at 147 (offset -19 lines). Hunk #3 succeeded at 400 (offset -19 lines). patching file includes/fivestar.field.inc

To me it looks like only patching the `fivestar.info` file failed which doesn't seem that important because it's just meta information.

I re-added the rows in the `votingapi_vote` table and added and deleted a comment and now the averages and counts are correct. So far so good.

**UPDATE**

Actually this doesn't seem to have completely fixed the problem. I just received a lot of spam comments which I deleted. After deleting them the averages and counts still reflected those now deleted spam comments. Examining the `votingapi_vote` table I could still see the records corresponding to the spam comments. I manually deleted those rows and then added and deleted a comment through the drupal interface to force recalculation of the `votingapi_cache` table. So the above patch has the benefit that fivestar will no longer completely wipe out all records for a node in the `votingapi_vote` table. However now it won't delete deleted comments. I'll take this behavior over the former because manually deleting a few records beats re-entering old vote data. Still a PITA

**UPDATE 2**

Just realized that the reason the patch probably didn't apply properly is that I have the wrong version of fivestar. I'm using 7.x-2.0-alpha2 and I should be using the dev version 7.x-2.0-alpha2+5-dev. Will check it out and report back.
> 1 votes

---
Tags: 7, rating
---


# Question
Title: How do I pass a value from the url to a custom field in the registration form?
*I know variations of this question have been asked but I haven't found any with this specific set of characteristics. Also, the only programming language I know is python. I don't know PHP at all.*

I want to be able to pass the value from a url parameter into a custom hidden field in the registration form.

I've tried using theme functions, template files, and hook\_form\_alter() but I haven't been able to get any of these to work.

So far, I've been able to add the custom field but I can't seem to hide it, let alone be able to pass the value to it. I am able to add html to the form via the template file but that's about it.

I based my attempts on this site: themery

This is the code I tried to see if I could alter the label for email.

```
function acq_dmc1_form_user_register_form_alter(&$form, &$form_state) {

$form['mail']['#title'] = t('E-mailzzzzzz');
$form['field_recipientid']['#title'] = t('QualID'); //this is the custom field

}

```

...but it didn't work.

this is the form id:

```
<input type="hidden" name="form_id" value="user_register_form" />

```

this is the HTML that's rendered for the custom field:

```
<input class="text-full ckeditor-mod form-text" type="text" id="edit-field-recipientid-und-0-value"
name="field_recipientid[und][0][value]" value="[url:path]" size="90" maxlength="25">

```

EDIT: June 17, 2013 Someone gave me this code as a solution but I don't understand if it will work or how it will work:

```
function passval_user_presave(&$edit, $account, $category) {
    $fields = array(
    'RecipientID' => array('fieldname'=>'field_recipientid', "type"=>'complex'),
        'mail' => array('fieldname'=>'mail', "type"=>'simple'),
    );
    $urlargs = drupal_get_query_parameters();
    foreach($fields as $key=>$field) {
        if(isset($urlargs[$key])) {
            $value = ($urlargs[$key]);
            $value = intval($value);
            if($field['type'] == 'complex') {
            $edit[$field['fieldname']] = array('und'=>array(0=>array('value'=>$value, 'format'=>'', 'safe_value'=>$value)));
        }
        else {
            $edit[$field['fieldname']] = $value;
            }
        }
    }
}

```

# Answer
> 2 votes
You can create hidden form elements in drupal simply by setting the type to hidden. So in your case, it could be achieved like so:

```
$form['field_recipientid']['#type'] = 'hidden';

```

You can access URL arguments in drupal via the arg() function. So if you want to pass something to the user register page and set it in your field\_recipientid, you could do it by sending the user to the registration page via "http://example.com/user/register/MLRP\_8UByesUEfeeIA".

Then from your same form alter function, just call arg(2) to get the third item in the path and set the value like so:

```
if (isset(arg(2))) {
  $form['field_recipientid']['#value'] = arg(2);
}

```

Note for anyone else thinking of doing this on other form elements that aren't hidden (e.g. text fields), use #default\_value. If you set #value on text fields, drupal forcable only accepts that value, and disregards any edits to the text field value, the user might have made.

For more information on drupal's form api, see the forms api reference page on the drupal api site.

# Answer
> 0 votes
show us how you try to do this on hook\_form\_alter().

You need to change '#default\_value' in hook\_form\_alter() for your field.

# Answer
> 0 votes
I think this is the module you want Node Reference URL. Create a field in your content type called RecipientID and set it to use the "Node Reference from URL" widget. You can then pass your variable via URL "node/add/MLRP\_8UByesUEfeeIA" and the module populates your RecipientID field automatically.

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


# Question
Title: Add (create) content access control with Reference from URL
I have created a node photo gallery. The display of the images is provided by an EVA view. Two content types were created: One photo gallery and one image upload node. To the image node were added an image field (for uploads) and one node reference from URL field that references back to the photo gallery. The result being that when someone is viewing the gallery, there is a visible link to add an image. Clicking the link brings up the image upload widget. The user is returned to the gallery after uploading and saving the image. That works well.

All authenticated users have a photo gallery, and they can all visit the galleries belonging to others. But as it stands now, all can see the add image links on all galleries and use it to upload images to someone else's account. The reason for this being that the link is not part of the view but part of the content type (even when the view is deleted, the link still shows.) So the contextual filters in the view do not work in this case.

The link to the referenced node can be disabled in the *Reference from URL* field settings and could most likely be replaced by a direct link to the image upload node. But this does not prevent a smart user to upload an image to someone else's account directly from the URL.

Is there a way to implement a variety of access controls on the creation of content? All the access control modules I have seen use roles and/or view/edit/delete permission only. Core allows control of node creation but on a role basis only. The ideal would be a filter like in a view that only allows the author of the gallery to add new pictures but unfortunately the *Reference from URL* link is not part of a view.

Any pointer on how to solve this riddle?

Thanks. :)

# Answer
> 1 votes
The Field Permissions module allows site administrators to set *field-level* permissions to edit, view and create fields on any entity.

This means that you can set the `Enter own value` for the add image field for the authenticated user only.

The image below shows the settings screen in the module for a field named *Nationality*.

---
Tags: nodes, entities, users
---


# Question
Title: Display total count number of view all node create by user
how can i create views of number of total viewed statistic of all node by create by user. for example:

uid=1
total:2500
today:500
yesterday:1000
last week: 5000
last month: 15000

# Answer
Node View Count module allows to **count node views**. It records each view of node with user uid and time-stamp. So now you can know how many times a user viewed node by day, week, month and etc.

You can integrate this module with views and you can use it to create different statistics pages, output new not viewed nodes for user and many more.
> 1 votes

---
Tags: 7, views, nodes
---


title: How to delete an image I uploaded?

text:
# Question
Title: How to delete an image I uploaded?
When I delete an image I previously uploaded into an Image field, the file stays on my server. It takes up space and remains publicly viewable.

Is there an easy way to get Drupal to clean up after itself by deleting uploaded files that are no longer in use?

# Answer
Images should be deleted automatically during cron runs, if they are not used anymore. Meaning, their file\_usage count is 0.
> 4 votes

# Answer
My workaround is to use https://drupal.org/project/imce, since cron fails to do it.

Just delete the image from imce dialog( eg. plugin for ckeditor), with admin privileges in order to see all files

This is safe....If the image is used by another entity in drupal, imce prevents the deletion with the message *image is used by another application*
> 1 votes

---
Tags: 7, media
---


# Question
Title: How replace a node term programmatically?
I have a vocabulary (this is a workflow vocabulary) and another vocabulary attach to a node.

How can I replace workflow term by single another workflow term without change some other vocabulary ?

Something like this ?

```
$old_terms = taxonomy_node_get_terms_by_vocabulary($node, 23);
foreach($old_terms as $tid => $old_term){
  unset($node->taxonomy[$tid]);
}
$new_term = taxonomy_get_term(30);
$node->taxonomy[$new_term->tid] = $new_term;
node_save($node);

```

# Answer
> 1 votes
you can add term using term id(tid) `$node->field_yourfield_name[$node->language][0]['tid'] = $tid` in D7

# Answer
> 0 votes
To get the node:

```
$node = node_load($X); // $X is the node ID.

```

To attache a term ID - note that this is very different in D7:

```
$node->taxonomy[$tid] = taxonomy_get_term($tid); // $tid is the node ID.

```

To save the node - if the node is new:

```
node_submit($node);
node_save($node);

```

or, to save the node if it's an existing node:

```
node_save($node);

```

---

In Drupal 7, terms are attached as normal field items so field\_first\_name\[0\] means the first occurrence of the field. Don't confuse that functionality with terms. You can add as many as terms you want.

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


# Question
Title: How do I change/modify an update content message
When someone edits a node, or a profile content type there is a message set with `drupal_set_message()` that appears at the top of the page. It can look something like this:

> Education 45971 has been updated.

How do I change/modify this message before it is displayed to the user? Is there any hook I can use?

# Answer
> 2 votes
On Drupal 6 you have Status Messages Alter, a port for D7 sits in the issue queue.

> Status Messages Alter provides developers with a new hook called "hook\_message\_alter." This hook enables developers to alter the text that is displayed in status messages before the messages are themed.

# Answer
> 1 votes
Using your own code, there are essentially two methods.

* Add the following code at the bottom of the settings.php file:

```
// Drupal 6.
$conf['locale_custom_strings_en'] = array(
  '@type %title has been updated.' => 'The string you want to use',
);

// Drupal 7.
$conf['locale_custom_strings_en'][''] = array(
  '@type %title has been updated.' => 'The string you want to use',
);

```
* You can override theme\_status\_messages(), implementing hook\_theme\_registry\_alter(), and filtering out the messages you don't want. In a module, you use code similar to the following one:

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['status_messages'])) {
    $theme_registry['status_messages']['function'] = 'theme_mymodule_status_messages';
  }
}

```

`theme_mymodule_status_messages()` is the function that the module implements to change the messages that would appear to the user, and that modules add through `drupal_set_message()`.

The difference is that with the first method you change the string before the placeholders are replaced with their arguments, while with the second method the string that is passed to the theme function doesn't contain any placeholders.

# Answer
> 1 votes
https://drupal.org/project/csm

> Allows users to set custom submit messages for different node types via the Drupal UI. So, rather than being stuck with "Page title has been saved", "Page title has been updated" and "Page title has been deleted" the user can set custom submit messages. In addition to this, CSM allows you to change the title of the node creation page. CSM allows both of these things to be set separately for each language your Drupal site is running in.

Also includes a Drupal 7 version of Status Messages Alter

---
Tags: hooks
---


# Question
Title: How to add javascript to theme_preprocess_user_login
I have working code in my theme's template.php file that adds "autofocus" to my modal login form, but Firefox ignores ajax autofocus fields (only applies autofocus on pageload). So I'm trying to add some js to set focus when the modal login form is called. I currently add autofocus via:

```
function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['rendered'] = drupal_render_children($variables['form']);
}

```

And I'm trying to add js to set focus as a fallback this way:

```
function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['form']['#attached'][js][] = path_to_theme() . "/js/focus.js";
  $variables['rendered'] = drupal_render_children($variables['form']);
}

```

but this doesn't seem to add the js as expected. How can I add either inline or external javascript to my modal login form?

# Answer
A preferred solution I would use for adding/editing forms would be to use a module hook.

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

  $form['#attached']['js'] = array(
    drupal_get_path('theme', 'THEME') . '/js/focus.js',
    '/* inline js here */' => array( 'type' => 'inline')
  );
}

```
> 1 votes

# Answer
I couldn't get any of the dynamic insertion of javascript to work at all, so I ended up adding the following to my site-wide javascript file:

```
$(document).delegate(
  'form#user-login',
  'DOMNodeInserted',
  function(){ $('input#edit-name').focus();
});

```

This is, of course, wrapped in the proper `(function ($) { Drupal.behaviors.mytheme = { ...` namespacing, etc.
> 0 votes

# Answer
Use the standard drupal\_add\_js https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_js/7

```
drupal_add_js(drupal_get_path('theme', 'THEME') .'/js/focus.js', 'file');
drupal_add_js('(function ($) { ... })(jQuery);', array('type' => 'inline', 'group' => JS_THEME));

```
> -1 votes

---
Tags: javascript, theming, forms
---


title: How to test for Entity Type

text:
# Question
Title: How to test for Entity Type
In Drupal you can use the following in template.php to test for a node type:

```
function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT TYPE HERE') {
    // include code
  }
}

```

How do you test for an entity that is attached to a node?

# Answer
The fully loaded node object should be available as a variable. You then need to know the field name that it is attached as (ie, the machine name from the manage fields tab on the content type). Once you have that, you should be able to use `field_get_items()` to check for actual values on that field

```
function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];

  if (field_get_items('node', $node, 'field_foo') !== FALSE) {
    // do something
  }
}

```

Just note that this checks for an actual value in the field, not that the field is on the particular content type. For that, you need to use `field_info_instances()`.

```
function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $fields_info = field_info_instances('node', $node->type);

  if (isset($fields_info['field_foo']) {
    // do something
  }
}

```
> 1 votes

---
Tags: theming, entities
---


# Question
Title: What is the proper way to return the results of custom module's form submission?
After spending hours and hours online researching, I'm more confused than ever about something that seems like it should be a very straight-forward task - Using my module's custom form, How do I display the results of a form submission that queries the db?

Here on d.se, Clive and Kiamlaluno provide 2 approaches. Clive suggests using a multistep form, and Kiamlaluno suggests making values globally accessible by storing them in the $\_SESSION variable.

Clive's approach doesn't make much sense to me. I'm not trying to print the value of a form field (after checking if it has been submitted), I'm trying to print a list of items retrieved from a database.

Kiamlaluno's approach seems a bit more workable. Indeed I could query a db, store the results in the session, and return those as the return value of a page callback on another page. Ultimately, however, this seems awfully convoluted. First, if this were indeed a best practices way, then why don't more tutorials discuss details about it? What logic would be used to set and unset the variable? PHP is horrible at handling large arrays - what if I have a large result set? How do I handle pagination if I want to divide up the result set across pages? Also, isn't the session variable available only to logged in users?

Looking at Views, Views exposed filters seem to use URL query strings. Is this the correct way? After a form submits redirect to another page, append the query string to that page, pass those parameters 'page arguments', and then query and return data in the page callback based on those arguments?

On Drupal.org there is a thread that has almost 4 years of activity from people confused about this very topic. This comment says that you have to create a $form\_state\['storage'\] variable and "then print it in your form definition." What in the world does that mean?!?!?!?

So, I'll pose my question again. I want to query a database using a form in my custom module, and I want to return a list of results (preferably paginated).

How can I accomplish this? I'm looking for an extremely thorough answer that I can play with in practice.

# Answer
> 4 votes
As JimaJamma noted in the comments the search module contains an excellent example of one way to do this. The `search_view()` function is where the magic happens, this is a custom version of that logic which should help explain the process:

```
function MYMODULE_menu() {
  $items['query'] = array(
    'title' => 'Query',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_results_page',
  );

  return $items;
}

function MYMODULE_results_page($parameter = NULL) {
  // Even if 'page arguments' isn't defined in a hook_menu() item, Drupal breaks
  // up the URL and passes arguments through to the callback function implicitly.
  // So if the page requested is 'query/123', out item defined at
  // 'query' will be used, and '123' will be passed as the first argument, in
  // this case into the $parameter var.
  //
  // If the parameter is empty, we need to check the GET/POST request to see if
  // the form has been submitted with a new search parameter.
  if (empty($parameter)) {
    if (!empty($_REQUEST['parameter'])) {
      // Build up a new path based on the submitted parameter.
      $path = 'query/' . $_REQUEST['parameter'];

      // And re-direct there. The request will come straight into this function
      // again, but this condition won't fire.
      drupal_goto($path);
    }
  }

  // Now we're in a position to query for results if there's a non-empty
  // parameter. Otherwise we just show the form (like the search page we'll
  // show the form unconditionally).
  $results_build = array('#markup' => '');
  foreach (MYMODULE_get_results_by_parameter($parameter) as $result) {
    $results_build[] = MYMODULE_build_result_render_array($result);
  }

  $build = array(
    'form' => drupal_get_form('MYMODULE_query_form'),
    'results' => $results_build,
  );

  return $build;
}

function MYMODULE_query_form($form, &$form_state) {
  // Make we're submitting to the right path.
  $form['#action'] = 'query';

  $form['parameter'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter query here'),
  );

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

  return $form;
}

```

I haven't tested that or anything so excuse any small bugs. If there are any bugs hopefully the comments, and the comments in the `search_view()` function, will do enough to help explain what should be happening :)

---
Tags: 7, forms
---


# Question
Title: Which mysql tables contain the URL Alias path data?
Im looking to manually change a node's URL path as my edit button throws me an error upon clicking it since this was due to orphaned data left over from some other uninstalled modules. Which tables contain the URL alias path data in Drupal 7?

# Answer
> 18 votes
Table i was looking for was **url\_alias**

---
Tags: 7, path-aliases
---


title: display default values in node form

text:
# Question
Title: display default values in node form
Can you help me please with node form in the Drupal 7?

I have a three forms (node/add/A, node/add/B, node/add/C). Values in the node/add/A are created after registration.

How to display a values with node/add/A to the node/add/B like default values a field?

Sorry for my English. Thank you everyone for your help

# Answer
well based on your comment:

Use the Computed Field module

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: Menu item path saved as node/nid instead of alias
An alias supplied to the \[Path\] attribute of a Menu Link is converted to node/nid when saved, (along with a nice message: "The menu system stores system paths only, but will use the URL alias for display".) This is implemented in core: function menu\_edit\_item\_validate of menu.admin.inc. (Drupal 7.22)

When moving nodes around between instances of the same site with node-export and uuid, node/nid is no longer valid, and results in menu links being dropped, or pointing to the wrong node.

A similar question was raised earlier:

How do I use URL aliases in menus?

But the solutions I think are for different use cases. The suggestion of adding the alias and menu item together on node creation does not seem to work. Our concern has nothing to do with how the node url is displayed.

UUID\_path or maybe UUID\_features seem to imply a solution, but if there is a resolution there, I don't understand it, and will appreciate any insight into how to handle this.

In the end, we need to have exportable menu links with path attributes that, one way or another stay, linked to an alias, regardless of nid.

# Answer
> 1 votes
Both nid and aliases are not guaranteed to be stable and unchanged, nid being a bit less prone to mutation. What you seem to really need, are UUID Links. It should allow you to store links by the unchangeable UUID, not localised nid.

There was also a sandbox project UUID Menu for just the case, but it seems it was never properly initiated.

The other approach is to export both content and menu as a Feature. This problem is in Features' issue queue and in UUIDs for Menu Links issue queue, unresolved yet. But in the second one patches exists.

# Answer
> 0 votes
This turned out to be pretty easy, once I finally understood what's going on. We implemented our menu in an install hook, where we resolve uuid to normal path (node/nid):

```
function _get_normal_path_for_uuid($uuid) {
  $nid = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.uuid', $uuid, '=')
    ->execute()
    ->fetchField();
  return 'node/' . $nid;
}

```

and here, and example of a single menu\_link,

```
$normal_path = _get_normal_path_for_uuid('8674c2c0-9ee4-4628-8666-e7eee4167250');
$menu_link = array(
  'menu_name' => 'products-menu',
  'link_path' => $normal_path,
  'router_path' => 'node/%',
  'link_title' => 'Resources',
  'options' => array(
    'attributes' => array(
      'title' => '',
    ),
  ),
  'module' => 'menu',
  'hidden' => 0,
  'external' => 0,
  'has_children' => 0,
  'expanded' => 0,
  'weight' => -48,
  'plid' => $some_plid,
);
menu_link_save($menu_link);

```

Now our menu links are pinned to specific nodes via uuid, in code, and content is fully portable between various site instances. Whenever we import node\_export content from one site instance to another (which results in the "normal path" changing), we simply reinstall this menu module.

---
Tags: routes, path-aliases, entities
---


# Question
Title: Why do I get errors abot undefined variables and errors with unserialize()?
Sometimes I get these errors on my site that I'm developing with the distribution of Commerce Kickstart:

> Notice: Undefined index: title\_value en link\_field\_update\_instance() (línea 1305 de /home/content/90/9397890/html/a/profiles/commerce\_kickstart/modules/contrib/link/link.module).
> Notice: Undefined index: title\_value en link\_field\_update\_instance() (línea 1305 de /home/content/90/9397890/html/a/profiles/commerce\_kickstart/modules/contrib/link/link.module).
> Notice: unserialize() \[function.unserialize\]: Error at offset 10301 of 11637 bytes en views\_db\_object-\>load\_row() (línea 2243 de /home/content/90/9397890/html/a/profiles/commerce\_kickstart/modules/contrib/views/includes/view.inc).

Do you have any suggestion about how to avoid these notices are reported?

# Answer
The best way to get the issue resolved would be to file an issue for the Commerce Kickstart project on drupal.org.

The reason you're receiving those notices is because ideally, in a perfect world, line 1305 would say something like this (to avoid such notices):

```
  if (function_exists('i18n_string_update') && isset($instance['widget']) && isset($instance['widget']['type']) && $instance['widget']['type'] == 'link_field' && isset($prior_instance['settings']) && isset($prior_instance['settings']['title_value']) && isset($instance['settings']) && isset($instance['settings']['title_value']) && $prior_instance['settings']['title_value'] != $instance['settings']['title_value']) {

```

But as you can probably see, that `if` statement is now twice as big. And since it's only a notice you're receiving, chances are the developer(s) won't put that issue as a top priority.

The easiest way to resolve the issue on your own though is to set the value of `error_reporting` to `E_ALL & ~E_NOTICE` inside your `php.ini` file, like so:

```
error_reporting = E_ALL & ~E_NOTICE

```

That should suppress all notices that you might be seeing, including the third notice regarding `unserialize`.

Hope that helps... :)
> 1 votes

---
Tags: commerce
---