# Question
Title: How to make filter criteria fieldset in a view to be collapsible by clicking on a link using tpl file overriding default file?
I am trying to create a collapsible fieldset of filter criteria on click of a link the code I tried is as follows: '; ?\>

```
<fieldset class="collapsible collapsed">
<legend class="collapse-processed">
<a href="#">Error : Uncaught TypeError: Object [object Object] has no method 'drupalGetSummary' jquery.min.js:16</a>
<a href="#">Edit Search Criteria</a>
</legend>
<fieldset>

```

But when I click on the link I dont get the collapsed or collapsible feature

The error I am getting is as follows: **Error : Uncaught TypeError: Object \[object Object\] has no method 'drupalGetSummary' jquery.min.js:16**
In the resources of the page the collapse.js is present which indicates that the js file is loaded.
After updating the jquery version from 1.5 to 1.7 the old error disappears and new error is displayed as follows:
**Uncaught TypeError: Object \[object Object\] has no method 'drupalGetSummary' collapse.js:70**

# Answer
> 1 votes
I got the above working by writing a function in the module as shown in the link

```
/**
 * Implements hook_preprocess_views_view().
 */
function my_module_preprocess_views_view(&$vars) {
  if ($vars['view']->name === 'my_view') {
    // Wrap exposed filters in a fieldset.
    if ($vars['exposed']) {
      drupal_add_js('misc/form.js');
      drupal_add_js('misc/collapse.js');
      // Default collapsed
      $collapsed = TRUE;
      $class = array('collapsible', 'collapsed');
      if (count($_GET) > 1){
        // assume other get vars are exposed filters, so expand fieldset
        // to show applied filters
        $collapsed = FALSE;

    $class = array('collapsible');
  }
  $fieldset['element'] = array(
    '#title' => 'Refine your search',
    '#collapsible' => TRUE,
    '#collapsed' => $collapsed,
    '#attributes' => array('class' => $class),
    '#children' => $vars['exposed'],
  );
  $vars['exposed'] = theme('fieldset', $fieldset);
}
  }
}

```

# Answer
> 0 votes
This happened often because collapse js files not loaded there,mybe by adding the js library it get work

Try this

```
drupal_add_js('misc/form.js');
drupal_add_js('misc/collapse.js');

```

or

```
drupal_add_library('system', 'drupal.collapse');

```

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


title: Get the image path

text:
# Question
Title: Get the image path
may be this question has been asked earlier but i have not found an appropriate answer for this. I have image uri path and i want to create a web services in drupal. From android when i call this webservices i will send the uri then i want to get the image url that will return me my custom image style url. But when i am passing the url with file extension giving me `Could not find the Controller`.this is servieces\_resources function

```
'image_url' => array('operations' => array('retrieve' => array(
  'help' => t('The resource to retrive the image of the given url/uri.'),
  'callback' => '_fieldinsync_image_url_retrieve',
  'args' => array(
      array(
            'name' => 'url',
            'optional' => FALSE,
            'source' => array('path' => 'url'),
            'type' => 'string',
            'description' => 'The url/uri of the image.',
     )),
  'access callback' => 'services_access_menu',
),),),

```

This is my function that will return the url of the image::

```
function _fieldinsync_image_url_retrieve($imgUrl){
 $value;
 $value[]=array(
 'vname'=> 'session_id',
 'sname' => 'session_name');
 $value['uri'] = image_style_url('mobile_product_image', $imgUrl);
  return $value;
  }

```

Uri is :`public://Tab - A2107.jpg`

# Answer
> 1 votes
I take your problem is converting a URI like public://filename.extension in a URL that can be used outside Drupal. That can be accomplished replacing the call to `image_style_url('mobile_product_image', $imgUrl)` with the following code.

```
$uri = image_style_url('mobile_product_image', $imgUrl);
$obj = file_stream_wrapper_get_instance_by_uri($uri);
$value['uri'] = $obj->getExternalUrl();

```

---
Tags: services
---


title: Use of tmp folder in drupal

text:
# Question
Title: Use of tmp folder in drupal
All of our Drupal installations have a /tmp folder at the root of the installation (ie, in parallel with the core files).

What does Drupal use the temporary directory for?

# Answer
> 0 votes
Your temporary directory holds files before they actually move to the appropriate position in your files directory.

Not sure but I think one the example can be the time we upload a file in a content type it first goes to tmp directory before you actually save the node. Also you might have image cache working if file type is image so the file must exist on server before it crops or scale, so tmp is that directory.

Also the tmp folder is always need to be in drupal root directory, the place is configurable from settings.

---
Tags: files
---


# Question
Title: How to set shipping price to 0 when a specific field of product is enabled or has specific value
I am using Drupal Commerce 7. I need to set the shipping price to zero when a field of product is enabled/checked (for example free ship field).

I know I should use Rules and **Collecting shipping rates for an order** event is suitable for my job, but I really don't know how to set up a condition to check if my field is enabled or has a specific value.

I can set the free ship field widget as check box with enable/disable or select box with 2 value, whichever fits my needs. But my problem is how to set the condition according the value of product field.

Thanks for your attention

# Answer
> 0 votes
How about this: In shipping calculation rule see if can get the following conditions.

1. Use execute php code, check in the php if can use $commerce\_order
2. If can then loop through all product line items in the order load them check the field value.
3. On basis of condition return True so implement the action or false to not.

---
Tags: 7, rules, commerce
---


# Question
Title: Rotating Banner Module Shrinks Banner Image When It Should Not
I am using drupal 7.23, and the module Rotating Banner https://drupal.org/project/rotating\_banner I have the banner size set to " The banner will shrink to fit the page. " Unfortunately it is shrinking the banner when there is no change in page size.

All I have to do is load the page. The banner is initially fully expanded to the max size of the screen, but as it rotates, it will change to have a very small width. This appears to be random, in that it just happens with enough image rotations.

Here is the css for the regular image before it becomes travel size

Here is the css for the image after it smalls down

It appears that the internal code for the module thinks the screen size shrunk down big time, but I don't know why.... I would appreciate anyones advice on this matter....

Thanks so much,

david

# Answer
I think the module is a bit buggy. I changed it to not have the dynamic size setting, but went with static but just didn't put in a height/width. Since I am using bootstrap with drupal I surrounded the image with a

...

Which then forces the image to dynamically respond properly. So, a hack.
> 0 votes

---
Tags: 7, theming, media
---


title: problem using ajax callback in form

text:
# Question
Title: problem using ajax callback in form
I have a very simple form that has a select box of the terms in a vocabulary, and renders the selected term below it. It seems that the first time I change the value in the select it renders the appropriate term, however every subsequent "change" event it uses what ever term I selected the first time.

The code is as follows

```
function jms_industry_lens_form($form, &$form_state) {
    $values = array();

    // Load the vocabulary and collapse into an array that form api understands
    $vocabulary = taxonomy_vocabulary_machine_name_load('industry_lens');
    $terms = taxonomy_get_tree($vocabulary->vid);

    foreach($terms as $term) {
        $values[$term->tid] = $term->name;
    }

    $form['industry_lens'] = array(
        '#type'             => 'select',
        '#options'          => $values,
        '#default_value'    => 0,
        '#required'         => TRUE,
        '#ajax'             => array(
            'callback'  => 'jms_industry_lens_form_ajax',
            'wrapper'   => 'edit-industry-lens-term',
        ),
    );

    $form['industry_lens_term'] = array(
        '#type'     => 'item',
        '#markup'   => _jms_render_term($terms[0]->tid),
    );

    return $form;
}

/**
 * Ajax callback to change the rendered industry lens taxonomy term
 */
function jms_industry_lens_form_ajax(&$form, &$form_state) {
    $form['industry_lens_term']['#markup'] = _jms_render_term($form_state['values']['industry_lens']);
    $form_state['rebuild'] = TRUE;

    return $form['industry_lens_term'];
}

```

# Answer
> 0 votes
So try to use

```
function jms_industry_lens_form($form, &$form_state) {
    $values = array();

    // Load the vocabulary and collapse into an array that form api understands
    $vocabulary = taxonomy_vocabulary_machine_name_load('industry_lens');
    $terms = taxonomy_get_tree($vocabulary->vid);

    foreach($terms as $term) {
        $values[$term->tid] = $term->name;
    }

    $form['industry_lens'] = array(
        '#type'             => 'select',
        '#options'          => $values,
        '#default_value'    => 0,
        '#required'         => TRUE,
        '#ajax'             => array(
            'callback'  => 'jms_industry_lens_form_ajax',
            'wrapper'   => 'edit-industry-lens-term',
        ),
    );

    $form['industry_lens_term'] = array(
        '#type'     => 'item',
        '#markup'   => _jms_render_term($terms[0]->tid),
        '#prefix'   => '<div id="edit-industry-lens-term">',
        '#suffix'=> '</div>'
    );

    return $form;
}

/**
 * Ajax callback to change the rendered industry lens taxonomy term
 */
function jms_industry_lens_form_ajax($form, &$form_state) {
    $form['industry_lens_term']['#markup'] = _jms_render_term($form_state['values']['industry_lens']);

    return $form['industry_lens_term'];
}

```

---
Tags: forms, ajax
---


# Question
Title: How to theme multiple entities on the same page?
I am trying to write a module that displays several entities in one page, but I don't see how I should theme them.

I've found (an mostly followed) this: https://drupal.org/node/1238606.

But the point where I get stuck is the return value of the page callback. The link above suggests:

```
function my_entity_page_view($entity, $view_mode='full') {
  $entity_type = $entity->entityType();
  $entity_id = entity_id($entity_type, $entity);

  $entity->content = array();
  $entity->title = filter_xss($entity->title);

  field_attach_prepare_view($entity_type, array($entity_id => $entity), $view_mode);
  entity_prepare_view($entity_type, array($entity_id => $entity));
  $entity->content += field_attach_view($entity_type, $entity, $view_mode);

  $entity->content += array(
    '#theme'     => $entity_type,
    '#element'   => $entity,
    '#view_mode' => $view_mode,
    '#language'  => LANGUAGE_NONE,
  );
  return $entity->content;
}

```

I however try to load several entities at once and have no fields, so I tried this:

```
$entities = // Array of entities keyed by id;

entity_prepare_view('entity_type', $entities);

$return = array(
  '#theme'     => 'entity_type',
  '#element'   => $entities,
  '#view_mode' => 'full',
  '#language'  => LANGUAGE_NONE,
);

return $return;

```

Since `entity_prepare_view()` accepts an array of entities, I'd suppose there should be a way to theme several entities at once as well. Or am I wrong?

# Answer
> 0 votes
After a bit more fiddling, this worked for me. I've tried a similar approach earlier, but I guess there was something wrong. I've commented out the field functions, but these are the places in case you need them.

```
$entities = // Array of entities keyed by id;

// Prepare all entities at once. Attach fields if desired.
//field_attach_prepare_view('entity_type', $entities, 'full');
entity_prepare_view('entity_type', $entities);

// Expose all entities individual to hook_theme.
foreach($entities as $key => $entity) {
  $entity->content = array();
  //$entity->content += field_attach_view('entity_type', $entity, 'full');
  $entity->content += array(
    '#theme'     => 'entity_type',
    '#element'   => $entity,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  $entities[$key] = $entity->content;
}

return $entities;

```

---
Tags: entities, theming
---


# Question
Title: CAS Authentication disable drupal invitation
I am using the CAS module to authenticate my users. That is working fine and dandy, but I want CAS to be the only way a user can authenticate. Currently when the user goes to /login, it shows a page where it gives them the redirection notification message, a drupal login invitation message, and a log in button. Only when they click the login button, is CAS authentication conducted. Is there a way to have it so that the only way to authenticate would be using CAS?

# Answer
> 1 votes
I do not know the CAS module but I do know a very generic way to hide / replace any page with another: add an alias! De-aliasing happens before routing. So if CAS has a page say `/cas` you'd like to see when someone visits `/user/login` simply add an alias with a system path of `cas` and alias `user/login`.

---
Tags: 7, users, redirection
---


# Question
Title: Setting date-based filter criteria in Views
All,

I have created a Content Type which includes a field of type Date. I would like to create a Views filter such that only those nodes whose date falls within the current month are selected. Can someone please show me how to accomplish this.

Thank you.

I did some more digging and believe that the best approach is to use PHP Views. I installed the module, wrote my 'challenging' code, but am not getting the expected results.

For debugging purposes, I created the following output field code:

```
<?php
$field_forumdate = $data->_field_data['nid']['entity']->field_forumdate['und']['0']['value'];
$forumdate=strtotime($field_forumdate);
$currdate=time();
$nc = date('n', $currdate);
$nf = date('n', $forumdate);
$tflag = 'false';
if ($nc == $nf) {
  $tflag = 'true';
}
print 'Current month: ' . $nc . ', Forum month: ' . $nf . ', tflag: ' . $tflag;
?>

```

I created three Content types, and set the ForumDate fields to dates in October, November, and December. Looking at the preview, I see the following:

```
Current month: 12, Forum month: 12, tflag: true
Current month: 12, Forum month: 11, tflag: false
Current month: 12, Forum month: 10, tflag: false

```

Next, I created my filter code - which is identical to the above:

```
$field_forumdate = $data->_field_data['nid']['entity']->field_forumdate['und']['0']['value'];
$forumdate=strtotime($field_forumdate);
$currdate=time();
$nc = date('n', $currdate);
$nf = date('n', $forumdate);
if ($nc != $nf) {
  return TRUE;
}

```

The problem is that all three nodes are still being returned, i.e., the filter does not seem to be filtering. Please help!

# Answer
Hope this will help,Create a view, Add a **FILTER CRITERIA** on content date field select the following option

It will return all content which is lies on current month for the respective date field. Good luck
> 0 votes

---
Tags: views
---


# Question
Title: How to render input fields in a custom page template page
Running into a development wall here. How does one render form/fields in a custom page?

*e.g.*

I've created a custom page called `page--node--add--article.tpl.php` (a custom page to style the editing of the article content type) though I cant render any individual input/forms as part of my overall site design.

All I can do is do `<?php print render($page['content']); ?>` which loads the entire content and does not allow me to style between the different fields.

Objective: Split the article creation into two DIVs for a mobile theme that gives me a part one and then via jQuery fade (or slide) to the part 2.

# Answer
> 1 votes
You can customize your form using #prefix and #suffix in hook\_form\_alter(). They will add wrapper HTML markup into your form and then you can customize them with your custom CSS and JS attached to the form.

Here is an example code:

```
function MYMODULE_form_alter(&$form, &$form_state, &$form_id){
    if($form_id == 'article_node_form'){
        $form['title']['#prefix'] = '<div id="group1">';
        // more fields here
        $form['body']['#suffix']  = '</div>';

        $form['field_1']['#prefix'] = '<div id="group2">';
        // more fields here
        $form['field_5']['#suffix'] = '</div>';

        // attach additional css/js to this form page for your customization
        $form['#attached']['css'][] = drupal_get_path('module', 'mymodule'). '/mymodule.css';
        $form['#attached']['js'][] = drupal_get_path('module', 'mymodule'). '/mymodule.js';
    }
}

```

You can also add additional HTML using #markup.

```
$form["unique_id"] = array(
    '#markup' => "<div>some html</div>"
);

```

# Answer
> 0 votes
`page--node--add--article.tpl.php` is for a page level template.

The template just the form, you'd be better to look into a form level template.

If you're just wanting to split the form into two divs, checkout the module:

## field\_group

> Available group types:
>
> * Fieldsets
> * Horizontal tabs
> * Vertical tabs
> * Accordions
> * Divs
> * Multipage steps: (client side)

# Answer
> 0 votes
Other than fields, if you want to arrange your nodes, views, comments, user data etc.. you can go for Display Suite.

**Advanced options**

* Exportables
* Add your own custom fields in the backend or in your code
* Add custom layouts in your theme (D7 only)
* Change labels, add styles or override field settings (semantic fields).
* Full integration with Views and Panels
* Extend the power of your layouts by installing Field Group
* Optimal performance with Object cache (D6) or Entity cache (D7) integration

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


# Question
Title: How to add a javascript function after uploading file
I make a form using FAPI, and this form contains a file managed field. I want to show an alert after uploading the file ("uploaded successfully"), and a confirmation ("Are you sure you want to delete file") when deleting the file.

This my code.

```
$form['my_file_fid'] = array(
  '#type' => 'managed_file',
  '#title' => t('Files'),
  '#default_value' => variable_get('my_file_fid', ''),
  '#upload_location' => 'public://',
);

```

I tried to add #file\_value\_callbacks, but I don't know how to use it.

I tried to make a javascript just to alert when I click upload,remove button but it doen not work I tried to make it general to all input to check that js is correct now all inputs are clickable but upload and remove button not

```
jQuery(document).ready(function() {
         jQuery('input').bind('click',function() { alert("hi") });
 });

```

I make this js to check jquery ajaxSuccess function

# Answer
You could just bind something to the jQuery ajax success event on the page where your form is displayed.

You can bind ajaxSuccess to any jQuery object, try something like this if you're experimenting:

```
<script>
  (function ($) {
    $(function () {
      jQueryObject = $({});
      jQueryObject.ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions) {
        /* do something whenever an ajax call is successful */
      });
    });
  })(jQuery);
</script>

```
> 0 votes

# Answer
Hope this will help, use hook\_file\_presave inside that you can use drupal set message.

```
/**
 * implementing hook_node_presave
 */
function mymodule_file_presave($file) {
//dpm($file);
//
 if (isset($file->source) && $file->source=='field_preview_image_file_und_0')//make condition like this for ur file
{
//use the drupal set message or java script alert  on successful upload
drupal_add_js(drupal_get_path('module','mymodule') . '/test.js');
}
}

```

create a js file on same module folder as **test.js**

```
(function ($) {
$(document).ready(function(){
alert('this is alert message');
});
})(jQuery);

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: AJAX callback fails using form_alter on two fields
I have content type with two text fields field1, field2 so i'm using hook\_form\_alter() to alter my form and i'm added for the first field

* # autocomplete\_path path
* # ajax callback and wrraper

and for the second field i'm added

* # prefix : with id ind the wrraper of first field
* # suffix

I want to add a AJAX callback to check the value of a first field and added this value to check a value of second with autocomplete .

The code:

```
function ajax_callback($form,$form_state) {
        return $form['field_annonceur']['und']['0']['value'];
    }

    function newsletter_form_alter(&$form, &$form_state, $form_id) {
        //dpm($form['field_annonceur']['und']['0']['value']);
        if ($form_id == 'newsletter_node_form') {
            $form['field_annonceur']['und']['0']['value']['#autocomplete_path'] = 'admin/get_path/autocomplete_field1';
            $form['field_annonceur']['und']['0']['value']['#ajax'] = array(
                'callback' => 'ajax_callback',
                'wrapper' => 'autocomplete_id',
            );

            $form['field_campagne']['und']['0']['value']['#disabled'] = TRUE;
            $form['field_campagne']['und']['0']['value']['#prefix'] = '<div id="autocomplete_id">';
            $form['field_campagne']['und']['0']['value']['#suffix'] = '</div>';

            if (isset($form_state['values']['field_annonceur']['und']['0']['value'])) {
                ['field_campagne']['und']['0']['value']['#disabled'] = FALSE;
                ['field_campagne']['und']['0']['value']['#autocomplete_path'] = "admin/publicite/autocomplete_field2/{$form_state['values']['field_annonceur']['und']['0']['value']}";
            }
            return $form;
        }
    }

autocomplete_field1($value_field1){};
autocomplete_field2($value_field1,$value_field2){};

```

but i get the same field when i select a first field , the second field is hidden !!

before input on field 1

after input on field 1

What am I missing? Thanks in advance!

# Answer
the solution is to return the target field in the ajax callback so the code is :

```
function ajax_callback($form,$form_state) {
        return $form['field_campagne']['und']['0']['value'];
    }

```
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: How to change views exposed filter default value
So I have this view with exposed filter of taxonomy terms with depth, I had selected some of the terms to limit the selection.

everything works just fine but the issue is that the default value of the exposed filter (combo-box) is set to the latest entry (taxonomy term), and I want to set it to that -All- thing.

I know that if I don't select any of the terms to limit the selection, it'll be set on -All- as default value for the exposed filter, but I don't wanna do that!

the question seems quite simple but I couldn't figure this out! thanks.

# Answer
> 2 votes
in template.php:

```
function MY_THEME_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'MY_EXPOSED_FORM_ID') {
    // Modifications go here.
    // example: (change the field name to yours)
    // $form['field_adv_cat_1_tid']['#default_value'] = 'All';
  }
}

```

then clear the cache.

---
Tags: 7, views
---


# Question
Title: How to alter Fields of Field Collection?
I have a field collection in a custom Content Type.

I wanted to do form alter.

I'm unable to locate the fields of field collection in hook\_form\_alter(), do we have any other way ?

# Answer
> 2 votes
try to use `$form['YOUR_field_collection']['und']['0']['sub_field']['und']['0']['value']` for ex : to add \['#autocomplete\_path'\] would : `$form['YOUR_field_collection']['und']['0']['sub_field']['und']['0']['value']'#autocomplete_path']=''`

# Answer
> 1 votes
It is available in the hook\_form\_alter(). I missed them

```
   /*
   * Implements hook_form_alter()
   */
   function digitaliq_user_form_alter(&$form, &$form_state, $form_id){
   // Id of the field collection 'field_bck_fld1'
   $form['field_bck_fld1'][LANGUAGE_NONE][0]

   }

```

---
Tags: entities
---


# Question
Title: Why is search disabled by default for anonymous users?
I noticed that search is only permitted to logged in users on drupal.org and I'm wondering why. Apparently it's also disabled for anonymous by default in Drupal 7, and I see people discussing how to enable it to anonymous users, but no-one explains *why* this default setting exists.

I assume there's a performance issue or opening for a DOS attack?

I'm particularly interested at the moment because we're currently having DB issues (overloading the max permitted connections) and we have D7 with search enabled for anonymous users.

# Answer
> 0 votes
In Drupal almost all permissions other than `access comments`, `view published content` and exceptionally `use text format filtered_html` are disabled by default for anonymous users. There is no specific reason for search other than the rest.

It is up to you and the purpose of the site you want to build, which permissions you want to give the users.

---
Tags: 7, database, search, performance
---


title: Problem with favicon and theme settings

text:
# Question
Title: Problem with favicon and theme settings
I'm having an insane problem enabling shortcut icon in my theme. When I dpm `theme_get_setting('favicon')` and `theme_get_setting('toggle_favicon')` \- I get null strings, even though in the `Shortcut icon settings` section of `admin/appearance/settings` I have the `favicon.ico` as the value of the path to custom icon (obviously, the default shortcut icon checkbox is blank).

This lead me to inspecting other themes setting pages (eg. `admin/appearance/settings/bartik`) and I found out that all of them display a full set of options while my theme has only one checkbox. See the attachments below:

**Bartik theme settings**

**My theme settings**

Comparing the info files does not lead me to any findings.

The following is the info file of my theme:

```
name = SI 2012
description = SI Startup Theme
package = Core
version = VERSION
core = 7.x

features[] = main_menu

stylesheets[all][] = [...]
scripts[] = [...]

regions[offtop] = Off top
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer
regions[offbottom] = Off bottom

```

# Answer
> 1 votes
OK, problem solved. Removing the `features[]` line from the theme info kind of reset the settings page. I also read this post about theme settings and providing default values. Problem solved, although I don't quite know why the `features[]` stuff affected the whole form. Will probably learn with time.

# Answer
> 0 votes
features\[\] list the settings that should be available for your theme. In your case only the main menu settings should be present.

If you wanted eg. the favicon setting to be available too inside theme settings, you should add 'features\[\] = favicon' on a separate row in the .info file.

However the default behavior is to display all settings, so when you remove the 'features\[\] = main\_menu' line from your .info-file the theme goes back to showing all settings.

---
Tags: files
---


title: theme table from drupal 6 to drupal 7

text:
# Question
Title: theme table from drupal 6 to drupal 7
I try to rewrite the node output and i don\`t get it. This script produce only

```
<table></table>

```

without any content.

```
$rows = array();
$cols = array();

$cols[] = '<div id="node-title">' . $node->title[0]['value'] . '</div>';

$colnum = 0;

foreach($node->field_body as $col){
  $colnum++;
  $cols[] = '<div class="description" id="description-' . $colnum . '">' . $col['value'] . '</div>';
}

$rows[] = array('data' => $cols);

print theme('table', $rows)

```

# Answer
> 3 votes
Variables to theme functions must be named:

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

```

See the documentation for more details.

---
Tags: theming
---


title: Alter fields on add more

text:
# Question
Title: Alter fields on add more
I'm used Field collection to add content type as field with unlimited but i want to alter this form fields for adding #autocomplete\_path on each field so i'm added the autocomplete for the first field as `$form['field_1']['und']['0']['field_1']['und']['0']['value']['#autocomplete_path'] = 'admin/path/autocomplete';`

when i add more field collection field i want to added the same autocomplete for the next fields any solution for this ? Thanks in advance!.

# Answer
After one day search i'm found solution in https://api.drupal.org/api/examples/form\_example!form\_example\_tutorial.inc/function/form\_example\_tutorial\_9/7 this example adds default values so that when the form is rebuilt, the form will by default have the previously-entered values.
> 0 votes

---
Tags: entities
---


# Question
Title: How can I get a user's language from their e-mail address in PHP?
I'm using the Mime Mail module to send HTML e-mails to my users. I have created a template, `mimemail-message.tpl.php`, and placed it in my theme's directory. This template defines header and footer links and is applied to every outgoing e-mail.

However, I have a multilingual site and I want to customize these footers per language. My PHP skills are limited but I'm fairly confident I can do this with a switch statement if I can get the e-mail recipient's language.

I'm having trouble figuring out how to get the user's language. The Mime Mail module provides a variable, `$recipient`, which is set to the e-mail address of the user. Is it possible to load a user based on the e-mail address and then get the user's language?

# Answer
I don't think there's an API function to do exactly that, but a single database query would get you that information:

```
// Query the database
$args = array(':email' => $email_address);
$lang = db_query('SELECT language FROM {users} WHERE mail = :email', $args)->fetchField();

// If there's no language string use LANGUAGE_UNDEFINED instead.
// This is also a fallback method to use the default language
// if the user is not found in the database.
if (!$lang || empty($lang)) {
  $lang = LANGUAGE_UNDEFINED; // Or whatever your default language is
}

```

If you need the user object itself for whatever reason, you can use a slight variation on the above:

```
$args = array(':email' => $email_address);
$uid = db_query('SELECT uid FROM {users} WHERE mail = :email', $args)->fetchField();

if ($uid) {
  $account = user_load($uid);
  $lang = $account->language;
}

```

You could also take advantage of the `$conditions` parameter of `user_load_multiple()`, but this method has been deprecated so it might not be the best idea to use it:

```
$users = user_load_multiple(array(), array('mail' => $email_address));
if (!empty($users)) {
  $account = array_shift($users);
  $lang = $account->language;
}

```

Last but not least, you could use an `EntityFieldQuery`, although this would probably be overkill for this particular task. It is a useful thing to know though:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('mail', $email_address);

$results = $query->execute();
if (isset($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
  if (!empty($users)) {
    $account = array_shift($users);
    $lang = $account->language;
  }
}

```
> 3 votes

# Answer
I'm doing it this way in the mimemail-message.tpl.php, much simpler, not sure if it's the correct way but it works.

```
global $language;
switch ($language->language)  //detect the interface language
{
 case "zh-hant":   // for chinese taiwan
   $header = " ";
   $footer = " ";
   break;

 case "zh-hk":     // for chinese hong kong
   $header = " ";
   $footer = " ";
   break;

 case "zh-sg":     // for chinese singapore
   $header = " ";
   $footer = " ";
   break;

 case "zh-hans":   // for chinese china
   $header = " ";
   $footer = " ";
   break;

 default:  // for english and other languages
   $header = " ";
   $footer = " ";
}

print $header;
print $body;
print $footer;

```
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: create a webform node with multi lingual language
How to create a webform node with multi lingual language like french,spanish in drupal 6. so that when i hit the url it should display in particular language? webform localization is not supporting in drupal6. is there any other way around to do this. pls help?

# Answer
You can use Internationalization module to achieve this functionality.

> This is a collection of modules to extend Drupal core multilingual capabilities and be able to build real life multilingual sites. Some features:
>
> * Taxonomy translation (both, per language terms and translatable terms) Multilingual variables
> * Multilingual blocks (control visibility per language and translate title and content)
> * Language selection (when you switch the site language you'll see only the content for that language)

Edit:

You need to set up *translate* of each node. If you create `node/2` as defualt language *French*, then you edit the node and click on *translate* tab in top of page and set up translate node in *spanish* language.

If you view `node/2` and select *spanish* language, then it will display the trasnlated node of `node/2` in *spanish* language.

Setting language:

* Go to the Languages page (`Administration > Settings > Language` in Drupal 6, or `Administration > Configuration > Regional and language >
Languages` in Drupal 7) and add and enable desired languages.

Setting Multilingual for content type.

* Go to the Content types administration page (`Administration >
Content > Types` in Drupal 6, or `Administration > Structure > Content
types` in Drupal 7).
* Select a *content type* you want translated, and select "edit", then "Workflow settings" for Drupal 6 or "Publishing options" for Drupal
* At the "Multilingual support" section, select "Enabled, with translation". Be sure to save each content type after enabling multilingual support.
> 1 votes

---
Tags: nodes, webforms, uri, i18n-l10n
---


title: #states on exposed filter form

text:
# Question
Title: #states on exposed filter form
I have a #states on the exposed filter form as follow:

```
If field_a == 'b' then field_b show, field_c hidden;

else if field_a == 'c' then field_c show, field_b hidden;

```

All fields here are Select list.

The states is working fine, problem is the value of the hidden filter is affecting the view result, which i dont want.

Questions:

1) How to change the hidden field value back to default(to -Any- in Select List)? JQuery maybe?

2) How to avoid the hidden filter affecting the view result and to remove the filter (?...&field\_b=xxx) in the query string?

updates: working code for states.

```
 $field_state = array( 'visible' => array(':input[name="field_a"]'
 => array( array('value' => 'a') )),       );

 $form['field_a']['#states']   = $field_state

```

# Answer
Though you have custom solutions in place, but a try for views\_dependent\_filters can be worth, this might be hint as well for your custom solution.

views\_dependent\_filters module:

> Allows the presence of exposed filters on a view to be controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.
>
> The module is compatible with both the Views basic and the Better Exposed Filters form plugins.
> 0 votes

---
Tags: 7, views, javascript
---


# Question
Title: Add jQuery to exposed filter form on drupal 7
I've been searching around how to add jQuery to Drupal 7, but i couldn't make it work. Here is my steps:

Step 1: I create a javascript file and put into my module under js directory.

Step 2: I added the file to my module .info

```
 scripts[] = js/xxx.js

```

Step 3: The contents of the xxx.js

```
(function ($)
{
  Drupal.behaviors.mymodule =
  {
    attach: function(context, settings) {

    $("#edit-field_a",context).change(function(){
      currentValue = $(this).val();
      alert(currentValue); // no fire at all
      if(currentValue == 'a')
        {
            $('#edit-field_b').val('All');
        }
    }

}
};

})(jQuery);

```

All the fields are on exposed filter form. I wish to do something like the value of the field\_b select list changed based on field\_a select list.

What did i miss? Is my jQuery correct?

Updates: Previous js is wrong, corrected here.

```
 (function ($)
{
  Drupal.behaviors.mymodule =
  {
    attach: function(context, settings) {

    $("#edit-field_a",context).change(function(){
      currentValue = $(this).val();
      alert(currentValue); // no fire at all
      if(currentValue == 'a')
        {
            $('#edit-field_b').val('All');
        }
    });

}
}

})(jQuery);

```

# Answer
> 2 votes
Do like this:

```
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'FORM-ID') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'MY_MODULE') . '/js/SCRIPT.js' => array(
        'type' => 'file',
        'group' => JS_LIBRARY, // or JS_DEFAULT, JS_THEME.. read this -  https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7
      ),
    );
  }
}

```

---
Tags: javascript, views
---


title: Force no cache for unregistered users

text:
# Question
Title: Force no cache for unregistered users
Is there a way to force a fresh page to be served to unregistered users every time instead of the local cached version?

# Answer
You can turn off caching by going to Configuration \> Performance, and uncheck "Cache pages for anonymous users." That will turn off page caching for the whole site.

If you only want to keep specific pages from being cached you can use Cache Exclude.

You can also (**but it is not recommended**; see the comments) enter this PHP snippet into the page's template, for example node--123.tpl.php.

```
// Keep the page from being cached
$GLOBALS['conf']['cache'] = FALSE;

```
> 1 votes

# Answer
The expression *local cache* suggests that op is referring to the browser cache. If this is the case then navigate to *Administration » Configuration » Development » Performance* and set **Expiration of cached pages** to **none**.

Before testing the new configuration reset your browser cache.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Ajax in textfield adding extra div in markup
I have created a form using a custom module. I am working on `ajax` functionality and updating `markup` when user enter text in `textfield` of the form.

Creating form in module

```
/**
 * Implements hook_form().
 */

  $form['name'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter your name',
    '#title' => 'Name',
    '#size' => 50,
    '#ajax' => array(
        'callback' => 'custom_print_ajax_name_callback',
        'wrapper' => 'custom-print-name',
        'method' => 'replace',
  ),
  );

  $form['name_msg'] = array(
    '#type' => 'item',
    '#markup' => (!empty($form_state['input']['name']) ? $form_state['input']['name'] : ''),
    '#prefix' => '<div id="custom-print-name">',
    '#suffix' => '</div>',

  );

```

Ajax submit callback:

```
/**
 * Ajax callback
 */
function custom_print_ajax_name_callback($form, &$form_state) {

  return $form['name_msg'];
}

```

Everything is working correctly except that when I checked `HTML` of the page, an extra `div` is added in `HTML` of markup after updating `ajax` as shown in below image.

I do not have any idea why is this extra `div` rendering with `markup`.

Thanks in advance.

# Answer
I have checked `ajax.js` in `Drupal` site and I have found that extra `div` is added as `ajax` wraps new content inside an empty div after a successful ajax request.

Comment Mentioned in `ajax.js`:

> We don't know what `response.data` contains: it might be a string of text without HTML, so don't rely on jQuery correctly iterpreting `$(response.data)` as new HTML rather than a CSS selector. Also, if response.data contains top-level text nodes, they get lost with either `$(response.data)` or `$('<div></div>').replaceWith(response.data)`.

Code:

```
var new_content_wrapped = $('<div></div>').html(response.data);
var new_content = new_content_wrapped.contents();

```

Check this also.
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Remove width and height from img tag in Drupal output (for certain content type)
I want to remove width and height properties from img tags in certain content type

Currently it show's like this

```
<img src="http://somesite.com/dostavka-slider-ng.jpg?itok=KDymQiug" width="938" height="300" alt="blablabla" title="blablabla" />

```

but I want

```
<img src="http://somesite.com/dostavka-slider-ng.jpg?itok=KDymQiug" alt="blablabla" title="blablabla" />

```

# Answer
> 3 votes
Here are some ways how to achieve this:

* Override it with CSS !important (something like `width: auto !important;`);
* Override field.tpl.php
* Copy node.tpl.php to the theme folder and rename it, like node--MY\_CONTENT\_TYPE.tpl.php.

Example:

```
/* node--MY-CONTENT-TYPE.tpl.php */
...
<?php
$img_url = image_style_url('large', $node->field_image['und'][0]['uri'];
?>
<img src="<?php print $img_url; ?>" />
...

```

# Answer
> 8 votes
```
function mytheme_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    unset($variables[$key]);
  }
}

```

copy this on `template.php` (replace "mytheme" to ur theme name) but you need to control over this because it will remove dimensions of all images in your theme.

# Answer
> 2 votes
Sorry, i can't use comment function -\> need min. 50 points :-/

Do you want to display images in image field, you can use field template function. You can create .tpl file with the field name in you theme folder and edit the code.

The templates that are possible to override include:

* field.tpl.php
* field--field-type.tpl.php
* field--field-name.tpl.php
* field--content-type.tpl.php
* field--field-name--content-type.tpl.php

---
Tags: theming, media
---


# Question
Title: How to theme the edit page of a form and retrieve $form variable from the hook_form_alter into the template for theming purposes?
I have a content type A How can I add custom theme to **edit** page of that content type A in drupal 7 only for specific role ?
In my module,

```
function hook_form_alter(&$form,&$form_state,$form_id) {
if (form_id == 'content_type_a') {
global $user;

if (in_array('rad',$user->roles)) {
$form['#theme'][] = 'custom_content_type_a_node_form';
}
}
}

```

In my template.php file I have the following code

```
function hook_theme() {
  return array(
    'custom_content_type_a_node_form' => array(
      'variables' => array('form' => NULL),
    );
  );
}

function THEMENAME_custom_content_type_a_node_form($form) {
// When I check here for $form I get an empty value
// I want to get the $form value derived from the form_alter function's $form //variable . How can I achieve it?

}

```

How can I retrieve the $form value from the hook\_form\_alter's $form variable?

# Answer
Try something like this:

```
function hook_theme() {
  return array(
    'custom_content_type_a_node_form' => array(
      'render element' => 'form',
    );
  );
}

function THEMENAME_custom_content_type_a_node_form($variables) {
  dpm($variables);
}

```
> 2 votes

---
Tags: 7, forms, theming
---


# Question
Title: Export and import content from one drupal site to another?
I want to export content with comments and user data with content relation from one Drupal site to same version of another site. In another site there is no content and users data it has only some new module installed and it's configuration.

For this which is best way migrate/ node\_export/ Backup and Migrate

# Answer
The Migrate module can migrate anything you want from the most databases.

Depending on how your content is put together this might be relevant for you.

Links:

Also be sure to look into the Migrate module folder. It contains a Beer.inc file, which is an example of how you can do simple mappings. For more complicated migrations you can look into Wine.inc.
> 10 votes

# Answer
If you're exporting into an empty site, the Backup and Migrate module is the one you want. It will let you clone all contents on a Drupal site, including comments. (Or only certain tables such as thos associated with nodes and comments, if that is what you want).

The Node Export module will only let you import/export nodes. Comments, for instance, is not nodes.

The Migrate module is a more *general* framework for migration (including migration data not originating from Drupal into a Drupal site). It gives you a lot more control over the process, but I think it is overkill if all you want to do is to export and then inport into an *empty* site with the same version of Drupal. Incidently, if you still want to use Migrate, check out Drupal-to-Drupal data migration. It is based upon Migrate, but designed to specifically migrate (and refactor) data from one Drupal site into another.
> 13 votes

# Answer
I would recommend you to use Features module and UUID Features. Using these tools you can export not only content but also other components, like: views, content types, etc.

If you want to export site variables you can use Strongarm module.

Hope this helps.
> 1 votes

---
Tags: 7, importing-exporting, migrations
---


# Question
Title: drupal contextual filter (URL argument) OR operator
So, I have a view which filters content from 3 different content types: Books, photos and articles and outputs in the same view.

All three content types have an independent "issue number" field. The view basically filters content based on the issue number. Now in order to create views for each issue, I was individually creating views for each issue. In order to pull content from multiple content types, the OR operator in the filter menu came in handy. The OR relationship is as follows (Let's take Issue 5.1 as an example) in the second group:

1. Content published = yes AND 2.Content type is one of Article,books,photos

AND

1. field\_books\_issue\_number = 5.1 OR
2. field\_photos\_issue\_number = 5.1 OR
3. field\_articles\_issue\_number = 5.1

Now, this works perfectly fine, with the only downside that I had to create a view for each issue.

Now, I want to pass the issue number as a URL argument, so that I don't have to create a view for each issue. It would rather be a wildcard path such as: /issue/% and the wildcard value would take the value from the URL (using contextual filter). To do this, I changed the filters to:

1. Content published = yes AND 2.Content type is one of Article,books,photos

AND

1. field\_books\_issue\_number = Not empty OR
2. field\_photos\_issue\_number = Not empty OR
3. field\_articles\_issue\_number = Not empty

and added the following contextual filter:

1. field\_books\_issue\_number = Value from URL
2. field\_photos\_issue\_number = Value from URL
3. field\_articles\_issue\_number = Value from URL

But as we know, contextual filters have a default AND relationship, which means that only the first condition will satisfy, since the other 2 fields in the contextual filter are from different content types and the other two conditions will automatically fail for every content being filtered.

Now, my question is this: 1. Can different content types share a common field? 2. If not, can the normal filter take values from the URL? 3. If not, can we add an OR operator to the contextual filters? 4. If not, is there an easier way to do what I'm trying to do without having to create an individual view for each issue?

Hope the question is clear. Thanks in advance.

Kaushik

# Answer
> 0 votes
> Can different content types share a common field?

In drupal 7 (maybe also in drupal 6) yes you can. When you add a new field to your content type, you've the possibility to add a field that already exist: "Add existing field".

Then filtering on the field should work for any content type using it.

Basically, I would add to the three content types Books, Photos and Article the same field "field\_issue\_number".

I think that will make your life easier :)

---
Tags: uri, views
---


# Question
Title: OG group content notification for group administrators
I'm using Drupal 7.12 with OG 7.x-1.3 and Rules 7.x-2.0.

There is a pre-installed rule that I'm using for group notifications which is "OG group content notification". This sends out an email to all group members when new group content is created. I want to modify this so it only sends out emails to group members who have an "administrator" role for that group.

Does anyone know how I can achieve this?

I did see that it's possible for me to get a list of group managers instead of group members but I don't want just the manager I want all the group administrators.

Many thanks.

# Answer
Your task cannot be done in an obvious way. A piece of content can be content of several groups. If a user is admin in the first group, but not in the second group, should he receive the email or not? If a user is an admin in both groups, should he receive the email twice? You'll have to think about that first before one can give a precise answer.

Either way, my guess is that one should create either a rule component "Send email if group admin" that receives a user and a group as variables, or one should create a view of group admins that the rule loops over. Do ask me for details if you still need the advice.
> 1 votes

---
Tags: 7, rules, organic-groups
---


title: Validate user required fields

text:
# Question
Title: Validate user required fields
I'm using Drupal 7 and I have some PHP pages that depends on my Drupal site.
In the PHP page, I tried to add a user programmatically in order the check the exception:

```
try {
  $new_user = array(
    'name' => 'user'
  );
  user_save('', $new_user);
} catch (Exception $e) {
  echo $e->getMessage();
}

```

I didn't give all the required field, like email and some custom fields that I set in *Home » Administration » Configuration » People » Account settings*, but Drupal still added this user.

I need the following:

1. Get all user field(s) and check if they are required or not
2. Get error on exception when I'm trying to add user without required fields

How should I do that?

# Answer
> 0 votes
I think you shouldn't create user this way, as it's bypassing all the controls made by drupal.

You can retrieve registration form this way:

```
drupal_get_form('user_register_form');

```

And print it like this:

```
print(drupal_render(drupal_get_form('user_register_form')));

```

---
Tags: 7, users
---


# Question
Title: How to filter a view by "Group administrators" ?
In OG 7.x-2.x you can assign roles to group members and you can override roles for a specific group. I am trying to create a view of all admin members. I am filtering the view with PHP.

**Option #1:** Use $roles = og\_get\_user\_roles('node', $row-\>gid, $row-\>uid); and then check for role '3' (normally the admin role in OG). -\> the obvious problem is that if a group has overridden the default roles, its "admin" role has an other (undefined) id

**Option #2:** Check with the 'Administer group' permission: $administrator = og\_user\_access('node', $row-\>gid, 'Administer group ', $account); -\> However I will get all the site administrators that can administer all the group, while I am looking in this context only those explicitly accounted as group admin (that in some cases could be site admin too).

Any hint on how to filter for an user that has explicitly be granted administer group permission ?

# Answer
You can add a relationship to "OG roles from membership" in your view and then filter on the OG role. No need for custom code.
> 0 votes

---
Tags: organic-groups
---


title: Render Menu using embed token

text:
# Question
Title: Render Menu using embed token
Is it possible to render a menu in a block or a node's body using \[embed\] or any similar token?

What I want to achieve is to render the main menu in a custom block. I don't want any solution that involves PHP or changes in source code. Token seems like a good option but I'm unable to find a token to render the main menu.

Thanks for the help in advance!

# Answer
> 1 votes
There is no way to achieve that without coding, you have to create your own module, which will create this token (implementing hook\_token\_info and hook\_tokens) - see example here - http://www.taggartjensen.com/code-snip/drupal-7-create-custom-token-module.

EDIT: I created a simple module out of this - Token Menu Render.

---
Tags: routes, tokens, nodes
---


# Question
Title: How do I get a view of all flaggable nodes?
I have a custom flag defined only on certain content types and I want to make a convenient list of all nodes that the flag is being displayed on, that is, nodes of all the content types that the flag is defined on.

# Answer
If these content types are never going to change, the quick and dirty would be to just create a View filtering on those content types.

If this is not the case, then you are going to have to get down into some coding as I am not aware of any built in Views/Flags integration on this level. Sure, you can list all flagged or not flagged content, but I don't see a way to list flaggable content.

So, to get the node types, you should be able to do something like this:

```
$flag=flag_get_flag('NAME_OF_THE_FLAG');

```

and now

```
$types=$flag->types;

```

should be an array of node types this flag can be applied to. So now you need to tell Views about this.

So, using the quick and dirty View created above, you could then alter it up with something along these lines:

```
function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='NAME_OF_THE_VIEW') {

    $flag=flag_get_flag('NAME_OF_THE_FLAG');

    $filters = $view->display_handler->get_option('filters');
    // you may want to dpm() or drupal_set_message() or watchdog() or otherwise look at $filter to see what you have to deal with on your system
    $filters['type']['value'] = $flag->types;

    $overrides = array();
    $overrides['filters'] = $filters;

    foreach ($overrides as $option => $definition) {
      $view->display_handler->override_option($option, $definition);
    }

  }

}

```

which on my box here, changes the types filtered to those in the flag.

Your `$flag` and `$filters` may/will most probably vary, so check to see what you have to work with as these are the broad strokes.

Lots of information about flags here: Flag 3.x PHP API

Information about Views hooks here: Views Hooks
> 1 votes

# Answer
Are you using a custom field or the Flag module?

In both cases, you should be able to create a view and then add filter either on your custom field or on your flag.
> 0 votes

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


title: Using CSS Sprites with Drupal

text:
# Question
Title: Using CSS Sprites with Drupal
I ran a Page Speed review of my website and got a suggestion that I should combine some images on my site into a single image using CSS sprites. I assume it is the mistake of the person who coded the theme, and I cannot recode it due to lack of knowledge. Is there any easier way of achieving this in Drupal? What I am looking for is solutions like this and this that would make the process easy for Drupal 7.

# Answer
Drupal's primary role is a CMS. For development tooling, it's probably more effective and more efficient if you build sprites without the use of Drupal. Drupal itself already has a very large memory footprint.

## How to produce CSS sprites (2013/2014 Edition)

With today's rapid growth in development tooling and technology, here are just some ways of which one can produce sprites for your theme today:

* **Manually** Manually edit them in photoshop and place them accordingly in the same file and write css for it. If this isn't clear to you. There's a plethora of information on how to do this: here, here, here, and yes there's plenty of more articles out there. Just search for "css sprites" in your favorite search engine.
* **Use Compass** Compass, a Ruby Gem, allows one to automatically generate sprites. It's very well used and integrated in some themes today. For example, Zurb Foundation.
* **Grunt Spritesmith** If you're familiar with using Grunt and have node already setup on your local machine Spritesmith is a viable option. Spritesmith allows you to create sprites within a folder for use of your theme.
* **CSS Sprite Generator** \- I quickly googled 'css sprite generator' and found this particular tool. Not sure if it's helpful but it seems as to allow you to build sprites online via upload.

Again, IMHO i'm pretty skeptical and think that outdated Drupal 5 sprite module will improve your front performance when you have to load one more module.
> 2 votes

# Answer
A quick and dirty alternative to CSS sprites is embedded images in CSS. https://drupal.org/project/css\_emimage is the module to use. Be sure to use it along with AdvAgg
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Drupal 7: Webform: Send Email Custom PHP on Webform submit
0 down vote favorite

I have a webform and I want to send an email to a user on submit action on this webform.

Note: I do not want to use the inbuild emails module for webform as it has some limitations related to the functionality that i want to achieve. Hence I want to send a test email on Submit action via a custom PHP.

I know how to write PHP for a webform but I need some guidance on how to use it for sending emails.

Also I want to send emails on submit action only if user selects a select option on this form.

How can I do this? Please help I am stuck on this for a long time now.

I tried using Rules module but I can not check the webform field values in rules.

# Answer
It's possible that you could use either hook\_webform\_submission\_presave or hook\_webform\_submission\_insert in a custom module, check for the your webform component value (i'd assume it's in $submission) and then fire your email.

In a custom module, add your hook like so.

```
function mymodule_webform_submission_insert($node, &$submission){
  // Use devel to investigate the variable
  dsm($submission);
}

```

Creating custom modules for Drupal 7 or Drupal 6. Tutorial.

Use Devel module to investigate your variables, as seen in my example above.

Jason.
> 1 votes

---
Tags: webforms, emails
---


title: print field in views row template

text:
# Question
Title: print field in views row template
I try to make a custom view using templates. I need to print one certain field at the last row, after all other fields have been printed like so:

```
--1st row
field1
field2
--2nd row
field1a
field2a
--last row
myfield

```

I can manage to display a custom field inside field template like so:

```
<?php print $fields['title_1']->content; ?>

```

However there are few problems:
1/to display the field as needed, I should print the field inside row template - but above code doe's not work inside row template, only inside field template.
2/the field get's printed twice - as normal field and as a field called directly from template as well.

The questios are 1/how can I print a field called from other than field template? 2/To prevent printing the field twice, I assume I need to exclude it from display, but after that it is not available inside template.
I found this article https://drupal.org/node/687046 where people say it is possible. I used following code but it is not working

print\_r($view-\>result\[$id\]node\_data\_field\_title\_1\_field\_title\_1\_value)

can anyone point me to right direction?

Thank you

ANSWER: the correct code to put inside row template is

```
print $view->result[$id]->node_title

```

this displays excluded field

# Answer
> 0 votes
I can't comment yet, or I would to inquire further about your use case.

Instead, I'll just provide an answer in hopes it helps.

Do you absolutely need to use a template file? In Drupal 7 Views 3, there are options for each field to customize the html for the field label and value if desired. See attached view field style settings to see how this is configurable.

Optionally, you can set the html to none and rewrite the output to include your specific markup. See second attachment.

Hope that helps, Jason.

# Answer
> 0 votes
Whoops, I did not see the drupal 6 tag. I left my previous answer anyway.

You can also rewrite the output in drupal 6 to include your special markup, but being you have to use a template file, you do not want to exclude the field in the ui settings. If you exclude it, it will not make it to the theme layer.

You can use the a field template file and you can wrap `<?php print $output; ?>` with your additional markup. However, this will include the default markup as well, which is provided by the row style output template.

Based on your question including `<?php print $fields['title_1']->content; ?>`, I'd guess you're using a row style template file. In this file, I think you would need to add an if statement to check that you have the correct field. If true, adjust your markup accordingly, else, keep the default markup.

Something like

```
<?php if($field->handler->field_alias == 'node_title'): ?>
  <<?php print $field->element_type; ?> class="field-content my-class"><?php print $field->content; ?></<?php print $field->element_type; ?>>
<?php else: ?>
  <<?php print $field->element_type; ?> class="field-content"><?php print $field->content; ?></<?php print $field->element_type; ?>>
<?php endif; ?>

```

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


# Question
Title: dynamic fields are not retaining values on form validate (refresh)
I have dependent select list (dynamic dropdown) in my form. When I change a value of the first select list, the second select list is automatically pouplated using ajax callback. Both select fields are required! All works fine, except validation.

There are 3 scenarios when submiting form:

1. If I do not change any values of my select lists (leaving default "- select -"), and just click submit button; page refreshes and displays message about required fields - This is working fine!
2. If I set values in both lists, click submit, validation passes, form is saved - This is working fine as well!
3. **If I set value of just one select list** and click submit button: BOOM! - All options from that select list are gone.

If I do `dsm($form_state['values'])` in validate function I can see that all values are set correctly.

Below is my code:

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

    if ($form_id == 'registration_form' && $form['#bundle'] == 'free_registration_volunteer_call') {

            $options_first = custom_first_dropdown_options();
            $value_field_event_1 = isset($form_state['values']['field_event_1']) ? $form_state['values']['field_event_1']['und'][0]['value'] : key($options_first);

            // Setup field_event_1 select and bind ajax
            $form['field_event_1']['und']['#options'] = $options_first;
            $form['field_event_1']['und']['#default_value'] = $value_field_event_1;
            $form['field_event_1']['und']['#ajax'] = array(
                    'event' => 'change',
                    'callback' => 'custom_ajax_callback',
                    'wrapper' => 'field_event_1_role_replace',
            );

            // Setup field_event_1_role select
            $form['field_event_1_role']['und']['#prefix'] = '<div id="field_event_1_role_replace">';
            $form['field_event_1_role']['und']['#suffix'] = '</div>';
            $form['field_event_1_role']['und']['#options'] = custom_second_dropdown_options($value_field_event_1);
            $form['field_event_1_role']['und']['#default_value'] = isset($form_state['values']['field_event_1_role']) ? $form_state['values']['field_event_1_role'] : '';

            $form['#validate'][] = 'custom_form_validate';

    }

}

/**
* Ajax callback for Event roles dropdown
*/
function custom_ajax_callback($form, $form_state) {
    return $form['field_event_1_role'];
}

/**
 * Helper function to populate the first dropdown.
 */
function custom_first_dropdown_options() {
    $node = node_load(arg(1));
    $i = 0;
    if(!empty($node->field_events_for_volunteering['und'])) {
        foreach ($node->field_events_for_volunteering['und'] as $event) {
            if (!$i) $events_list_options['_none'] = '- Select Event -';
            $events_list_options[(string)$event['node']->nid] = $event['node']->title;
            $i++;
        }
        return $events_list_options;
    }
}

/**
 * Helper function to populate the second dropdown.
 */
function custom_second_dropdown_options($key = '') {
    if ($key) {
        $node = node_load($key);
        $i = 0;
        if(!empty($node->field_volunteer_roles['und'])) {
            foreach ($node->field_volunteer_roles['und'] as $role) {
                if (!$i) $role_list_options['_none'] = '- Select Volunteer Role -';
                $role_list_options[(string)$role['value']] = $role['value'];
                $i++;
            }
            return $role_list_options;
        }
    }
    return array();
}

    /**
     * Validate form
     */
function custom_form_validate($form, &$form_state) {
    if (empty($form_state['values']['field_event_1']['und'][0]['value'])) {
        form_set_error('field_event_1', t('Event 1: field is required'));
    }
    if (empty($form_state['values']['field_event_1_role']['und'][0]['value'])) {
        form_set_error('field_event_1_role', t('Role for event 1: field is required'));
    }
    if (empty($form_state['values']['field_event_2']['und'][0]['value'])) {
        form_set_error('field_event_2', t('Event 2: field is required'));
    }
    if (empty($form_state['values']['field_event_2_role']['und'][0]['value'])) {
        form_set_error('field_event_2_role', t('Role for event 2: field is required'));
    }
    dsm($form_state['values']);
}

```

submit handler:

```
/**
* Custom Form Submit Handler (for free registration)
*/
function custom_form_submit(&$form, &$form_state){
    $registration_id = $form_state['build_info']['args'][0]->registration_id;
    entity_registration_custom_confirm_registration($registration_id); //Process registration - Set registration state to 'complete'
    $node = node_load(arg(1)); // Load current node
    $form_state['redirect'] = 'event/registration/success/' . $node->nid; // Redirect to success msg
}

```

# Answer
> 1 votes
I resolved this finally!

`arg(1)` returns `ajax` on ajax request, so I added:

```
$node_id = arg(1) == 'ajax' ? $form_state['build_info']['args']['0']->entity_id : arg(1);

```

There was another issue as well. For some strange reason `node_load` does not return all collections on ajax request. So I had to pull event's title using another `node_load` call in foreach loop.

This was not working:

```
/**
 * Helper function to populate the first dropdown.
 */
function custom_first_dropdown_options() {
    $node = node_load(arg(1));
    $i = 0;
    if(!empty($node->field_events_for_volunteering['und'])) {
        foreach ($node->field_events_for_volunteering['und'] as $event) {
            if (!$i) $events_list_options['_none'] = '- Select Event -';
            // $event['node'] is NULL here on ajax request?!?!
            $events_list_options[(string)$event['node']->nid] = $event['node']->title;
            $i++;
        }
        return $events_list_options;
    }
}

```

So I replaced it with this:

```
/**
 * Helper function to populate the first dropdown.
 */
function custom_first_dropdown_options($node_id) {
    $node = node_load($node_id);
    $i = 0;
    if(!empty($node->field_events_for_volunteering['und'])) {
        foreach ($node->field_events_for_volunteering['und'] as $event) {
            if (!$i) $events_list_options['_none'] = '- Select Event -';
            $node2 = node_load($event['nid']);
            $events_list_options[(string)$event['nid']] = $node2->title;
            $i++;
        }
        return $events_list_options;
    }
}

```

---
Tags: ajax, forms
---


# Question
Title: Lose ability to use node load with an argument in ajax form submit
I have a basic form like this, that is literally just a submit button:

```
function mymodule_form($form, &$form_state) {
    $form = array();

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

    return $form;
}

```

The form uses Drupal's built in #ajax feature, and calls back to itself because nothing is supposed to change after the submit button is clicked.

I also have this form submit function that submits that form:

```
function mymodule_form_submit(&$form, &$form_state) {
    $node = node_load(arg(1));

    $query = db_merge('mydatabase')
    ->key(array('nid' => $node->nid))
    ->fields(array(
        'nid' => $node->nid,
        'column1' => 'value1',
    ))
    ->execute();
}

```

This form submit should, in theory, add the current nodes ID to the 'nid' column of mydatabase, and 'value1' to the 'column1' column. The form submit correctly adds 'value1' to my 'column1', however it adds NULL to my 'nid' column every time. But ONLY when ajax is enabled on the form. When ajax is disabled, it correctly submits the node ID. Which leads me to believe there is either an issue with using node\_load in an ajax form submit, or using arg(1) in an ajax form submit.

Any advice would be appreciated.

# Answer
I ended up finding a solution to this. Essentially, instead of trying to load the arg(1) inside the mymodule\_form\_submit (because apparently you can't do that when the submit is triggered via ajax), I instead passed the node ID to the form submit through a hidden form field. See below:

```
function mymodule_form($form, &$form_state) {
    $form = array();

    $form['node'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

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

    return $form;
}

function mymodule_form_submit(&$form, &$form_state) {
    $node = node_load($form['node']['#value']);

    $query = db_merge('mydatabase')
    ->key(array('nid' => $node->nid))
    ->fields(array(
        'nid' => $node->nid,
        'column1' => 'value1',
    ))
    ->execute();
}

```

And now it works just fine.
> 1 votes

# Answer
I had the same problem. You can pull `entity_id` from `$form_state`:

Something like this:

```
// arg(1) returns 'ajax' on ajax request instead node id
$node_id = arg(1) == 'ajax' ? $form_state['build_info']['args']['0']->entity_id : arg(1);
$node = node_load($node_id);

```
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Main page colorbox and facebook like box
In my CakePHP site when user is first entered to my site, I check for a cookie. And if I can't find the cookie, after document load from my js file, I show Facebook like box to my visitors. I show a "div" that in invisible in my page.

I can't imagine how can I implement this in my Drupal 7 site. Should i put the invisible div into one of my node. If so, how can I load it from main node that includes only links to inner nodes?

I would be very happy if you can write the steps or show an example of this issue.

# Answer
You can use the hook\_boot() to set/unset the visitor's cookie. You can then use hook\_init() to check the value of the cookie and execute some javascript to construct your div. Your javascript can be inserted in the page during hook\_init() through drupal\_add\_js().
> 1 votes

# Answer
Just a suggestion; Load your form or div that you want to display in the colorbox into a block region that would in any case be there. Then in `template.php` you can use an override function

```
function THEME_preprocess_block(&$variables){

  if($variables['block']->region == 'sidebar_second' && $variables['block']->delta == 6){
    //Do This
  }
}

```

OR create a block template file.
> 0 votes

# Answer
If you want to put invisible `div` into each page, then you can add `div` in `page.tpl.php` file into your theme directory.

Or If you want to put invisible `div` into *front* page of the site, then you can put `div` into `page-front.tpl.php` file into your theme directory.
> 0 votes

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


# Question
Title: How are the 4 tables for revisionable and translatable entities in Drupal 8 meant to be used?
There are 4 tables for each type of entity,

1. entity
2. entity\_revision
3. entity\_field\_data
4. entity\_field\_revision

How exactly are the individual tables meant to be used?

# Answer
The issue queue always covers the decision making process and git blame usually shows the node ids. In this case:

https://drupal.org/node/1498674 https://drupal.org/node/2057401

This is suboptimal and the multilingual team is working on removing SQL queries touching entity table so that the entity storage class can make decisions on the schemas. This is happening at https://drupal.org/node/2068325
> 5 votes

---
Tags: entities, 8
---


# Question
Title: how to add [node:title] field in drupal view?
I have use path auto module ,and I am trying to get url path using title node. exp: ,if space is coming in title path auto module remove space and put " - " but when I put \[title\_1\] filed I am not getting same pattern as compere to path auto module .

# Answer
As I can remember node title is the first thing we see, after creating a view of content type.Answer to question "it is possible to add node title as field in view", would be yes.Though I am not sure if this was sure issue,might be if you can post a screenshot of your view can be of some help.

If in case you want node title as token to be used as replacement pattern.You can simply add the title field and keep the field exclude form display. And later you can use \[node:title\].
> 0 votes

---
Tags: views
---


title: hook_mail dosen't work?

text:
# Question
Title: hook_mail dosen't work?
I have these two functions, the first is to send the email via drupal\_mail() function :

```
function example_function_name($what) {
  drupal_mail('MYMODULE', 'some_mail_key', 'myaddress@gmail.com', language_default());
}

```

And the second is the hook\_mail function :

```
function MYMODULE_mail($key, $message, $params){
    switch ($key){
        case 'some_mail_key':
            $message['subject'] = 'test subject';
            $message['body'] = 'test body message';
            break;
    }
}

```

But I recieve a blank email in spam without neither subject, or body message. Is there somthing missing here ?

Thanks in advance.

# Answer
> 7 votes
`hook_mail` is supposed to take message by reference. The way you do it, you are modifying a local copy, and your modifications cannot ever leave the function's body. It should look like this:

```
function MYMODULE_mail($key, &$message, $params){
    switch ($key){
        case 'some_mail_key':
            $message['subject'] = 'test subject';
            $message['body'] = 'test body message';
            break;
    }
}

```

This little ampersand is what makes all the difference. You cannot omit them. If API defined hook with reference argument, keep it a reference argument, or expect problems.

---
Tags: 7, hooks, emails
---


# Question
Title: Cron task with Elysia cron module run only manually?
Im using the cronapi coming with Elysia cron module and here is my code :

```
function MYMODULE_cronapi($op, $job = NULL) {
  $items['example_news_cron'] = array(
    'description' => 'Send mail with news',
    'rule' => '*/5 * * * *', // Every 5 minutes
    'callback' => 'example_news_fetch'
  );
  return $items;
}
function example_news_fetch() {
  // Do something here
}

```

the cron works only when I run it manually in the admin section(Elysia cron configuration), but I need it to be runing every some specific periode !

Is there some configuration missing, or system requirements

# Answer
As you said "the cron works only when I run it manually in the admin section (Elysia cron configuration), but I need it to be runing every some specific periode !", it tells your codes are working fine.

By default Drupal cron runs when site is accessed and it evaluates when was the last time cron ran, so if the prescribed time is passed cron will run again, but for that site needs to be accessed, so you have a task which is supposed to run at fix period, you can not wait for Drupal site to be accessed by some one, instead you need to set a crontab on your server which means your server will ping your `cron.php` at the scheduled time.

Check How to setup cron tab on Linux based system or as an alternate option you can use drush while setting up cron tab (see: cron.html).
> 7 votes

---
Tags: 7, cron
---


# Question
Title: What does data column do in both {someentity} and {someentity_type} base tabels?
It is my first time that I actually want to make use of Entity API module. I looked at different modules like profile2 which has implemented their module with Entity API. I do not exactly understand what "data" column does in both for example, profile and profile\_type base tables for profile2 module? As far as I see, it's a common habit in modules developed by Entity API.

```
/**
 * Implements hook_schema().
 */
function profile2_schema() {
  $schema['profile'] = array(
    'description' => 'Stores profile items.',
    'fields' => array(
      'pid' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique profile item ID.',
      ),
      'type' => array(
        'description' => 'The {profile_type}.type of this profile.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'uid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
        'default' => NULL,
        'description' => "The {users}.uid of the associated user.",
      ),
      'label' => array(
        'description' => 'A human-readable label for this profile.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'created' => array(
        'description' => 'The Unix timestamp when the profile was created.',
        'type' => 'int',
        'not null' => FALSE,
      ),
      'changed' => array(
        'description' => 'The Unix timestamp when the profile was most recently saved.',
        'type' => 'int',
        'not null' => FALSE,
      ),
    ),
    'indexes' => array(
      'uid' => array('uid'),
    ),
    'foreign keys' => array(
      'uid' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
      'type' => array(
        'table' => 'profile_type',
        'columns' => array('type' => 'type'),
      ),
    ),
    'primary key' => array('pid'),
  );

  $schema['profile_type'] = array(
    'description' => 'Stores information about all defined profile types.',
    'fields' => array(
      'id' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique profile type ID.',
      ),
      'type' => array(
        'description' => 'The machine-readable name of this profile type.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
      ),
      'label' => array(
        'description' => 'The human-readable name of this profile type.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'weight' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'The weight of this profile type in relation to others.',
      ),
      'data' => array(
        'type' => 'text',
        'not null' => FALSE,
        'size' => 'big',
        'serialize' => TRUE,
        'description' => 'A serialized array of additional data related to this profile type.',
      ),
      'status' => array(
        'type' => 'int',
        'not null' => TRUE,
        // Set the default to ENTITY_CUSTOM without using the constant as it is
        // not safe to use it at this point.
        'default' => 0x01,
        'size' => 'tiny',
        'description' => 'The exportable status of the entity.',
      ),
      'module' => array(
        'description' => 'The name of the providing module if the entity has been defined in code.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('id'),
    'unique keys' => array(
      'type' => array('type'),
    ),
  );
  return $schema;
}

```

# Answer
The **data** column is not required and is not exclusive to entity modules. It is primarily used to add *metadata* to records by the module itself or by other modules. The data stored here is usually in the form of a serialized array, as such can contain a number of different small bits of info (e.g. IP of the creator, size of the file). This can be particularly helpful for modules to attach small bits of info related to entities or records without having the need to create a table or add new columns.

There is, however, a downside to implementing a data column - it can be overused / abused. Due to convenience or laziness, important info are sometimes just saved in the data column. This causes some problems like:

1. Migration - as in the case of D6/Ubercart where important info such as the attribute of the ordered product are saved in the data column of the orders table making it hard to migrate to D7/Commerce.
2. Makes queries complex - since the data column is usually a blob or large text data type, the only option you have to query this column is to use LIKE or REGEXP.

In summary, the data column is used to store metadata, but it can also be used for business logic (although I strongly advise against using the data column in this way).
> 0 votes

---
Tags: entities
---


title: Ajax in drupal 7 dont return values

text:
# Question
Title: Ajax in drupal 7 dont return values
Im in drupal 7, i need to make a select with many options, depends of the option taken, in a textarea will be loaded several values in a string.

After hours of test i come here for help.

Im working on a basic page:

```
function ajax_load_all_admins($form, &$form_state) {
    $form = array();
    $form['changethis'] = array(
        '#type' => 'select',
        '#options' => array(
            '' => '',
            '1' => 'Cargar todos los admins'
        ),
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'ajax_load_all_admins_callback',
            'wrapper' => 'listaCorreos-div'
        )
    );

    $form['listaCorreos'] = array(
        '#type' => 'textarea',
        '#prefix' => '<div id="listaCorreos-div">',
        '#suffix' => '</div>'
    );

    if (!empty($form_state['values']['changethis'])) {
        $payments_list = db_query('QUERY WORKING WELL');

        $value = '';
        foreach ($payments_list as $payment) {
            $value .= $payment->admin . ',';
        }
        trim($value, ',');
        $form['listaCorreos']['#default_value'] = $value;
    }

    return $form;
}

function ajax_load_all_admins_callback($form, $form_state) {
    return $form['listaCorreos'];
}

$form = drupal_get_form('ajax_load_all_admins');
print drupal_render($form);

```

The Ajax call is working but i only recibe:

```
0: {command:settings, settings:{basePath:/, pathPrefix:,…}, merge:true}

```

No other one position.

I think it can be for the drupal\_render, but dont know why?

Thanks in advice.

# Answer
> 0 votes
After 1 week searching and trying things at home i decide to make a separate module for the form.

When i pass the code to a module all works fine with the same code.

I think for any reason Drupal needs to render form by his own, not forced like i was doing with the next code in a simple view:

```
$form = drupal_get_form('ajax_load_all_admins');
print drupal_render($form);

```

Hope this help, **dont try to make Ajax calls inside a simple view** like i tried.

---
Tags: views, ajax
---


# Question
Title: webform submission details not getting displayed
i have multiple nodes each per language and the default is English(node/1). For french node(node/2) after submitting the details of the contact form, the details not getting displayed in Webform-Confirmation.tpl.php page, however when i do the same in default English node, it is getting displayed. any configuration should i do for this please help

# Answer
> 0 votes
You should set *Redirection location* of `webform` in form settings.

* Edit your `webform` node.
* Click on *webform* tab in top of page and it will redirect you to webform configuration of the node.
* Click on *form settings* link in webform
* Checked *Confirmation page* radios in *Redirection location* field-set and save the form.

---
Tags: nodes
---


# Question
Title: How to add a css class to sidebar first render
I am new to drupal theme development . I am customizing a sub theme of `zen` and wants to change the background of `sidebar-first`. So I want to know where this `sidebar_first` render array is defined and how can I add the CSS class to whole `sidebar-first` also to the nodes within the `sidebar_first` render array ?

I tried within my templates `template.php` :

```
function zensub_page_alter(&$page) {
 $page['sidebar_first'] = array(
 '#attributes' => array('class' => 'page-columns')
 );
}

```

But this causes the `sidebar-first` remove !

# Answer
Create a template file with name `region--sidebar-first.tpl.php` in side the your theme template folder. Copy below code to inside the newly created template file

```
<?php if ($content): ?>
     <div class="my_class <?php print $classes; ?>">
       <?php print $content; ?>
     </div>
  <?php endif; ?>

```

replace my\_class with you desire class name, clear the drupal cache. It will wrap a new class on the sidebar first region. Good luck
> 3 votes

---
Tags: 7, theming
---


title: How to hide a view from certain roles?

text:
# Question
Title: How to hide a view from certain roles?
I am trying to hide some views (and their menu links) from anonymous users and some other roles i have created, how this can be done ?? Thanks.

# Answer
On the views you have page settings option

In that there is access option

You can change the access to role and
by changing the settings u can assign roles who has the permission to access the view.
> 3 votes

---
Tags: views, users
---


# Question
Title: Show Active terms from vocabulary using taxonomy menu
**What i want**: *Active* terms of vocabulary in main menu.

**What i have done** so far:

1. I have used taxonomy\_menu module.
2. Created taxonomy(Category).
3. Added "Status" field having boolean values (0 = Inactive, 1 = Active).
4. Added two terms in Category(Cat1 and Cat2).
5. Cat1 = Active, Cat2 = Inactive.
6. Configured menu from "Edit vocabulary" section.

**Problem**: All terms of vocabulary are included in main menu. I want that only those terms whose `Status = Active` should be displayed in main menu.

Community, please help. Any hint would be helpful.

# Answer
> 1 votes
You can do this by using hook on taxonomy insert and update inside a custom module.

Here is a sample of code (needs refactoring/cleaning/checking but that's a start and it works for me) :

```
function custom_module_taxonomy_menu_insert(&$item) {
  //load taxonomy to access fields
  $tax = taxonomy_term_load($item['tid']);
  //get your field display (here i called it field_status)
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  //check your value
  if($display == 0) {
    //I don't want to display this element
    $item['remove'] = TRUE;
    return $item;
  }
}

function custom_module_taxonomy_menu_update(&$item) {
  //IDEM without comments
  $tax = taxonomy_term_load($item['tid']);
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  if($display == 0) {
    $item['remove'] = TRUE;
    return $item;
  }
}

```

\[Edit to add some details\]

The menu will not update automatically, you'll have to save/update your terms to update the menu (hook\_taxonomy\_menu\_update). For new terms, it's going to work automatically (hook\_taxonomy\_menu\_insert).

---
Tags: taxonomy-terms
---


# Question
Title: On node view page show a link or button that executes an action?
The closest that comes to this for D5: http://drupal.org/project/node\_operations\_block

I am familiar with creating VBO Actions, but not sure how to create it for a node operation. Such as a link or a button, that creates a new node with default values for example.

# Answer
> 5 votes
You can use the Flag module to put that "button" on the node. Then using Rules you could execute a VBO or simply use rules to create that content. Don't forget to look at Rules Bonus Pack for more goodies.

# Answer
> 1 votes
http://drupal.org/project/button\_field may be useful. From its description:

> Adds a button field type for use with CCK and Rules. \[...\] When the button is clicked, an AJAX call is made that runs the Rules event. An optional URL can be specified for the button to redirect to after the AJAX call is complete.

# Answer
> 1 votes
Ended up using https://drupal.org/project/rules\_link "This module lets you create links which trigger arbitrary functionality with the help of Rules."

---
Tags: rules, actions
---


# Question
Title: How to change the theme programmatically?
I've just applied a theme and got an error such that I cannot even change the theme back to a working one (like Bartik).

I've read other threads but I could use hook\_custom theme but I don't know how to get it to work.

What I'm doing is to edit the system.api.php and change the original lines of hook\_custom\_theme to this:

```
function hook_custom_theme() {
  // Allow the user to request a particular theme via a query parameter.
  if (1)) {
    return 'bartik';
  }
}

```

I've tried several variations but I don't know what I'm missing. Can anyone help me with this please?

**Edit**: I've realised that I need to write my own module to run that line of code, is it true? Is there a simpler way to just change the default theme or the weight of the themes programmatically somewhere?

# Answer
> 0 votes
You can install drush on your system and then from drush command you can change the theme using

```
drush vset theme_default <theme_name>

```

You can do the changes from database also. Either on the commandline, or via an administration interface (eg PHPMyAdmin) enter the following query

```
UPDATE system SET status=1 WHERE name = '<theme_name>';

```

Then either:

```
UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';
TRUNCATE cache;
TRUNCATE cache_bootstrap;
TRUNCATE cache_block;

```

Source: https://drupal.org/node/200774

---
Tags: theming
---


# Question
Title: Not all content showing up after uploading to live server
I have been working on a site for a client and I have ran into a bit of an issue. I built the site locally and then pushed it to a staging server to show the client and everything is running fine. When we got to the point of launching the site, we did what our team normally does and everything seems to be working fine until you look at the page content... It only shows the first sentence.

Here is an example of what's going on:

staging server:

live server:

My head is hurting from trying to figure this one out. I am using a custom theme and using to display the data on the left hand side like we always do, so that shouldn't be the problem. I am just at a loss, any little help would be awesome!

# Answer
It could be a control character that would remain or be not there when moving from one platform to another. Line breaks in Windows, UNIX and Macintosh text files all are different. If you have moved the database from one platform to another care should be taken to insure cr lf couplets are considered.

A similar situation could result from a database conversion that did not take into account these differences.
> 2 votes

# Answer
I think the problem isn't about themes, I think the problem occur form database's data, If you can export live database and test it in another instance of local version and if them problem exist in it, I tell you upload good version of database version to live database again.
> 0 votes

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


# Question
Title: How do I completely unpublish a node (not just change revision state) when using Workbench Moderation with rules?
I am attempting to use rules scheduler to automatically 'archive' content after a set period. Essentially, I want the content to disappear for everyone except administrators. Ordinarily, I would just use the standard 'unpublish node' action, but I have installed workbench moderation and this does not unpublish the node. If I attempt to simply change the revision state to Draft, the state changes but the node is not unpublished. Is there any way I can unpublish the node programatically? Should I look at some kind of access control module instead?

# Answer
Well, I suppose it's a bit late, but this issue is discussed in and should be mostly solved by https://drupal.org/node/1436260 once the issue is fixed. You should be able to unpublish the node, and as long as the code calls node\_save, workbench moderation should set the state back to draft. If you want a different state, e.g. "archived", you'll probably have to come up with something custom.
> 1 votes

---
Tags: 7, nodes, workbench, rules
---


# Question
Title: How do you message/email the purchaser an order update?
Previously in ubercart 3.x you were able to send messages and log admin notes on each order page. How can this be done using Drupal Commerce? I want to be able to message the purchaser in the order invoice page and also add internal notes if necessary. Which module(s) would I need to achieve this? Can you provide a screenshot of it in action?

# Answer
Since Drupal Commerce is based on the Rules module, you can simple create a custom rule which watches order status and react when one is changed.

Assuming you have Rules UI enabled you can go to: `admin/config/workflow/rules/reaction/import`

Here is a simple Rule which you can import:

```
{"rules_admin_order_update" : {
    "LABEL" : "Admin order update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "commerce-order:status" ],
          "value" : [ "commerce-order-unchanged:status" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "admin@domain.dk",
          "subject" : "Update",
          "message" : "The order changed to [commerce-order:status-title]."
        }
      }
    ]
  }
}

```

You can then change the add more info, change parameters etc.

Hope this can get you going. :)
> 3 votes

---
Tags: 7, commerce
---


title: Adding drop down divs to content

text:
# Question
Title: Adding drop down divs to content
I have search and searched and have not found this question yet. Nor have I found a way to do it.

I want to have a page built where it has a few fields, Objectives, Audience, Credits, Location, etc. I want the user to be able to type in all content on one edit screen.

When you view the page I want a horizontal bar with the fields listed - Objectives, Audience, Credits, Location - and when you click on the name Objective, the information for objective pops down in a div. When you click on Audience - text for audience pops down. This would be below the main body copy of the page.

I was thinking maybe fields group or conditional fields for forms however I do not see how those would work.

Does anyone have any ideas? a tutorial to send me too? a module to review?

Thanks Tim

# Answer
> 1 votes
It sounds like you could use something like Field Group and use Horizontal Tabs, seems like it would work the way you want.

1. Under **Manage Display** of the content type, add a **Horizontal Tabs Group**.
2. Then a **Horizontal Tab Item** for each field or section you want. The label you put in will be what shows up on the tab.
3. Nest the tabs underneath, and then put the fields you want underneath each tab.

The result will should look something like this. With a bit of CSS, you can make it look different.

## Manage Display

## Final Result

---
Tags: entities
---


# Question
Title: Views Slideshow only displaying first slide in IE
I have Views Slideshow working fine on Chrome 24.0.1312.56 m, and Firefox 18.0.1. But for some reason Views Slideshow only display the first slide (of five) in IE9.

I'm using Views Slideshow 7.x-3.0, Views Slideshow Cycle 7.x-3.0 and my jQuery.cycle file is version 2.9999.81. I also have "JavaScript Aggregation" turned OFF.

Like I said, the slider has no issues in Chrome, or Firefox, only IE9 where it will display the first slide and then just blank space for the other slides. The preview of the View works in IE, but then no longer works when you save the View.

*EDIT*
I found something interesting. It looks like IE is not giving the other slides div-container any width or height? I've attached a picture:

# Answer
> 0 votes
Please update your `jquery.js` file by using Jquery Update module.

# Answer
> 0 votes
I guess this problem is solved in IE10 . I installed this module and tested it using IE10, there was no problem.

---
Tags: 7, views, javascript
---


# Question
Title: Fatal error message after installng drupal
I get this error message when uploading the site on the server. I really need help.

> Fatal error: require\_once(): Failed opening required '/home/mydomain/public\_html/includes/drupal/includes/database/select.inc' (include\_path='.:/usr/local/share/pear') in /home/mydomain/public\_html/includes/bootstrap.inc on line 3160

# Answer
This error say that can not the specified file '/home/mydomain/public\_html/includes/drupal/includes/database/select.inc' , It may happened by 2 reason , one permission and another reason ( with more probability ) The file not exist, please make sure that the file exist or have permission .
> 1 votes

---
Tags: bootstrapping
---