# Question
Title: how to use parent field in child view in views field View
I am using Views Field View module. I need to filter the child view using the parent field. Can anyone experienced in it please share.

# Answer
> 3 votes
You will have to send a contextual filter from your parent view and catch it in your embedded view. There are plenty of tutorials on contextual filters, but this one should get you started: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

**UPDATE** you can set a contextual filter from your parentview by editing the embedded view in 'fields' and define it in the view-settings drop-down.

# Answer
> 3 votes
As I had a lot of trouble setting context filters properly for Views Field View, and couldn't find any documentation on the subject or proper answers, I'll provide more detailed walk-through here:

I want to have a list generated like this from different content types:

* First group of things
* Some data about that group

+ name of first thing from that group
    + name of second thing from that group
* Second group of things
* Some data about that second group

+ name of first thing from the second group
    + name of second thing from the second group

---

1. I've created parent view "my\_group\_of\_things" showing fields from content type "my\_group"
2. I've created child view "list of things" showing fields from content type "thing"
3. The content type "thing" has a field ("field\_my\_group") of type node reference that references to selected "my\_group" and has a label "Content: MyGroup"
4. In parent view ("my\_group\_of\_things") I add field Content: Nid
5. In the same parent view I add field Content: View and set it to "list of things"
6. While setting the Content: View field I enter \[!nid\] in the CONTEXTUAL FILTER text box
7. Don't forget to apply the Content: View and save the View
8. In child view ("list of things"), in ADVANCED tab, I add a CONTEXTUAL FILTER
9. While setting this contextual filter I choose Content: MyGroup (field\_my\_group)
10. In the same contextual filter I set WHEN THE FILTER VALUE IS NOT AVAILABLE to "Hide view"
11. Apply and save. It should work now.

Very simple, but without documentation and arrogant answers like "yeah, i got it now", or "just set up contextual filter" it took me a whole day to figure out.

---
Tags: views
---


# Question
Title: Custom text output for entity reference fields
In my content type I have an entity reference field. With this field editors can create internal links effordlessly with the autocomplete function.

What I want to achieve is that editors can now customize the text to output the referenced node. E.g. The editor creates a reference to a node and in a different field creates the "title" of the reference, she has just created. Thus references can have custom display titles.

I have tried the token formatters module (http://drupal.org/project/token\_formatters) but to no avail.

In my particular case I have a field reference\_text and have set the format of my entity reference field to "Tokenized text". In the "Text to output" field I have tried the following: 1) \[node:reference\_text\] 2) \[current-page:reference\_text\]

With 1) an empty field is displayed. With 2) I get an error message: Text output uses the following invalid tokes: \[current-page:reference\_text\]

Not sure what else to try. Any help would be greatly appreciated. Big thanks in advance.

# Answer
Two different options here (there are probably more!):

1. Use the linkit module in combination with wysiwyg and, say, the tinyMCE editor. This allows users to insert node reference links into wysiwyg text areas.
2. a. Create a textfield for the link text in addition to the entity reference field.

b. In the template file for the content type (node--CONTENT\_TYPE.tpl.php), output the links manually, something like:

$path = 'node/' . $node-\>YOUR\_ENTITY\_REF\_FIELD\['und'\]\[0\]\['target\_id'\];

```
$link_text = $node->YOUR_LINK_TEXT_FIELD['und'][0]['value'];

print l($link_text, $path);

```
> 1 votes

---
Tags: entities, tokens, display-suite
---


# Question
Title: Link items from Feeds module to original blog
I am using the Feeds module to publish the contents from a Wordpress blog to my site's home page. I'd like to have the items on the home page link directly back to the original blog rather than the nodes that the Feeds module creates. Is this possible? If so, how do I do it?

# Answer
> 0 votes
I'm assuming you're using an RSS/Atom feed, and that you're using the node processor in your feed importer. In your feed importer settings, you can edit the node processor mappings. Add a mapping from the "Item URL (link)) to some text field in the content type you import to. Then you can use that field to create links back to the external url in views, and in the template files for the content type.

Once you have the url field, go through the following steps.

1. create a view of feed items. /admin/structure/views/add

a. select "show CONTENT of type Feed Item". You can create a block or a page. Either way:

b. select "display unformatted list of fields"

c. click "continue and edit"
2. add fields.

a. add Feed item URL. select "exclude from display".

b. add content title. Make sure it appears *after* the feed item url in the fields list. Select "rewrite results", then "output this field as link". Click on "replacement patterns" to reveal the tokens you can use. Insert the token for "feed item URL" in the "link path" field, and select "external URL". Save the view.
3. if you've created a page, you'll need to give it a path. If you've created a block, you need to go to structure \> blocks and assign the block to a region.

Hope that helps.

---
Tags: feeds
---


# Question
Title: How to check programatically whether a comment is new?
I'd like to make some changes to a **new** comment programatically. I'm using the following code:

```
function MYMODULE_comment_presave($comment) {
    $user = user_load($comment->uid);
    $uid = $user->uid;
    // if ($comment->is_new) {
        $comment->field_image['und'][0]['fid'] = $user->field_image['und'][0]['fid'];
        }
    // }
}

```

I don't know how I can check whether the comment that's about to be saved is new or edited. `$comment->is_new` doesn't work.

How can I solve this?

# Answer
> 0 votes
Use hook\_comment\_insert() instead, that should work.

---
Tags: 7, hooks, comments
---


# Question
Title: drupal zen theme using sass - sub folder dont get regenerated
i have followed these instructions to install ruby and compass and sass, everything is ok and works. However, do i need to do a 'compass watch' at a lower level for the component and layout folders in my zen theme folders as well? for example, if i change .../sass/layouts/fixed.scss it doesnt automatically regenerate the equivalent ...css/layouts/fixed.css

# Answer
`compass watch` should only need to be run from your subtheme folder. Files in the components and layout folders should use partials (files beginning with underscore). Then you have to make sure to use `@import "components/fixed";` inside your `styles.scss` for each partial you want to include.

When compass compiles the `styles.scss` file, the partials that you have `@import`'s for will be automatically included in `style.css`
> 1 votes

---
Tags: theming
---


# Question
Title: Use form_alter to change description under reset password field for user_pass form
I'd like to change the text below the reset password field. I took a look at this answer, and it talks about changing the button, but I need a bit of help to change the text.

Here is the debug output and it looks like I need to access #description

```
[name] => Array
  (
    [#type] => textfield
    [#title] => E-mail
    [#size] => 60
    [#maxlength] => 254
    [#required] => 1
    [#default_value] =>
    [#description] => A password reset message will be sent to your e-mail address.
    [#input] => 1
    [#autocomplete_path] =>
    [#process] => Array
      (
        [0] => ajax_process_form
      )

```

This is how I would change the button:

```
function footheme_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_pass') {
    $form['actions']['submit']['#value'] = t('reset password');
    print "boom";
  }
}

```

# Answer
Got it!

```
if ($form_id == 'user_pass') {
  $form['name']['#description'] = t('This is a test');
}

```
> 0 votes

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


# Question
Title: Why do I get a backup file that has three different sizes?
I am using Drupal 7 site on a remote server (bluehost). I cleared the cache before the backup.

* When I am using the backup and migrate module, and use admin -\> config -\> back up - the size of the file is 456 kb.
* When I am using the my php admin interface, and Export the specific database - the size of the file is over 22 MB.
* When I am looking at the database interface of bluehost, it's written that the same database is over 176 MB.

I know that I am missing something, but I can't figure out the answer.

What is the difference between the databases? Which one should I save?

# Answer
* 456kb does sound very small, maybe you don't have much content/field data? Backup and migrate will exclude data from core cache tables, and the sessions and watchdog tables (though not cache tables installed by contrib modules) by default; so that might account for it. It's also probably gzipped.
* An export through phpmyadmin will *include* all those tables (and perhaps isn't gzipped), so it should be larger than the backup and migrate version
* The size of the database on disk, on the server, isn't and can't be proportional to the size of an SQL dump file. There are indexes and other meta data which take up space, so it will almost always have a larger footprint.

You don't need the cache table data, so as soon as you've confirmed that the dump from backup and migrate has the content you need in it (always a good idea to check), you should use that one going forward.
> 8 votes

---
Tags: 7, backups
---


# Question
Title: user_access( ) - Printing list 'variables' you can plug into?
Something I have seen many times, but never fully understood is what exactly to plug into `user_access()` (Want to get the correct terminology here too, do you just call them variables?). I have seen some basic ones like `user_access('manager access')`, manager being a made user? Another using `user_access('access nodes links')`, which I assume is just seeing if they can see/access the tab links on a node.

If there an easy way to get a common list of what you can plug into user\_access()?

Thanks in advance

# Answer
> 0 votes
You can see all the permissions on the /admin/people/permissions page.

---
Tags: users
---


# Question
Title: How do I remove the author textfield from the comment form?
How do I remove the Author textfield from the Comments form. I added a couple new fields:

* First Name
* Last Name

But now in addition to asking for First Name and Last Name, there is a 'Your Name' field which is confusing.

So it looks like this:

* Add New Comments
* First Name (text box)
* Last Name (text box)
* Your name (text box)
* Subject (text box)
* Comment (text box)

I'd like to remove the 'Your name (text box) from all comments since it is a repeating field.

This is the code I am using.

```
function onviasupport_preprocess_page(&$vars) {
    //modify taxonomy pages breadcrumbs
    if (!empty($vars['template_files'][0]['page-taxonomy'])){
            //pull term id from variable templates list
            foreach($vars['template_files'] as $key => $value){
                if(substr_count($value, 'page-taxonomy-term-') > 0){
                    $tid = explode('-', $value);
                    $tid = $tid[3];
                }
            }
            if (!empty($tid)){
                //We're on a taxonomy term page.
                $term = taxonomy_get_term($tid);
                $link = getLinkByPath();
                $bc = '<div class="breadcrumb"><a href="/">Home</a>  › '.$link;
                $vars['breadcrumb'] = $bc. ' › '. $term->name .'</div>';
            }
    }

    //var_dump($vars['page']['content']['system_main']['nodes']);

    if (!empty($vars['node'])){
        // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
        $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
        $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type.'__'.$vars['node']->nid;

        //modify resource page & article breadcrumbs..
        //$lnk = getLinkByType($vars['node']->type);
        $lnk = getLinkByPath();

        $bc = '<div class="breadcrumb"><a href="/">Home</a>';
        if ($lnk) { $bc .= ' › '.$lnk;}

        //add the first taxonomy term associated with this node
        $tid = _get_node_taxonomy_tid($vars['node']);
        $term = taxonomy_term_load($tid);
        if(!empty($term)) {
            $bc .= ' › '.l($term->name, drupal_get_path_alias('taxonomy/term/'.$tid));
        }

        $vars['breadcrumb'] = $bc . ' › '.$vars['node']->title .'</div>';

        //insert the title emphasis
        //$vars['head_title'] = cleanTitle($vars['head_title']);
        $vars['title'] = lowerG(insertEmTrig($vars['node']->title));
        //$vars['node']->title = insertEmTrig($vars['head_title']);

        if ($vars['node']->type == 'primary_landing' || $vars['node']->type == 'resource_landing'){
            $vars['title'] = lowerG(insertEmTrig($vars['node']->title, '<br />'));
        }
    }
}

//given a node, return the first taxonomy tid assigned
function _get_node_taxonomy_tid($node) {
    $tkeys = array();
    foreach($node as $key => $val) {
        if(substr_count($key, 'taxonomy')) {
            $tkeys[] = $key;
        }
    }
    foreach($tkeys as $tvoc){
        if(!empty($node->$tvoc)) {
            $tx = $node->$tvoc;
            return $tx['und'][0]['tid'];
        }
    }
}

//create a list of clickable letters to glossary pages.
function glossary_letters($term = array(), $nodeTx = array()){
    $output = '';
    /*
    //if we're on a node, grab the term id
    if(!empty($nodeTx)){
        foreach($nodeTx as $nt){
            if($nt->vid == "5"){  //the glossary
                $tid = $nt->tid;
                break;
            }
        }
    }
    */

    //make sure this is a term in the glossary vocabulary
    if ($term->vid == "5") {
        //search through the nodes assigned to this term, and strip off the letter from their title.
        //$sql = taxonomy_select_nodes(array($tid),'or', 0, false, 'n.title DESC');
        // - not working well due to it's running db_query_range(), fine for a limited range but not this.

        $result = db_query('SELECT DISTINCT(n.nid), n.title, n.created FROM {node} n
            INNER JOIN taxonomy_index tn ON n.nid = tn.nid
            WHERE tn.tid = :tid AND n.status = 1', array(':tid' => $term->tid));

        $nodes = array();
        foreach ($result as $node){
            $ltr = explode(' - ', $node->title);
            $ltr = strtoupper($ltr[1]);
            $nodes[$ltr] = $node->nid;  //letter is now matched to the nid
        }
        if(!empty($nodes)) {
            $output .= '<div class="clr letters">';
            foreach(range('A','Z') as $letter){
                if(array_key_exists($letter, $nodes)){
                    $path = url('node/'.$nodes[$letter]);
                    $output .= '<a href="'.$path.'">'.$letter.'</a>  ';
                } else {
                    $output .= $letter.'  ';
                }
            }
            $output .= '</div>';
        }
    }
    return $output;
}

//given a vocabulary object, return the link to the correct primary page
function getVocabLink($voc){
    $link = '';
    if(is_array($voc->nodes)){
        foreach($voc->nodes as $key => $val){
            if (empty($link)) {
                $link = getLinkByType($key);
            }
        }
    }
    return $link;
}
function getLinkByPath() {
    $link = '';
    $pth = drupal_get_path_alias();
    if (substr_count($pth, 'product-guide') > 0){
        $link = l('Product Guide','product-guide');
    }
    if (substr_count($pth, 'resources') > 0){
        $link = l('Resources','resources');
    }
    if (substr_count($pth, 'your-account') > 0){
        $link = l('Your Account','your-account');
    }
    return $link;
}
function getLinkByType($type){
    if ($type == 'product_guide_page'){
        $link = l('Product Guide','product-guide');
    }
    if ($type == 'resource_page'){
        $link = l('Resources','resources');
    }
    if ($type == 'your_account_page'){
        $link = l('Your Account','your-account');
    }
    if ($type == 'user_guide'){
        $link = l('Product Guide','user-guides');
    }
    return $link;
}

function swapTitle($title){
    //now change the default Drupal page title, put brand at beginning
    $t = str_replace(' | Onvia', '',$title);
    return 'ONVIA | '.$t;
}

/* function to force lowercase "g" on gBusiness  */
function lowerG($gtext){
    //Don't lowercase the content, as that could be bad for IDs and classes, so I test for all variances.
    $gtext = str_replace('GBUSINESS','<span class="g">g</span>BUSINESS', $gtext);
    $gtext = str_replace('GBusiness','<span class="g">g</span>Business', $gtext);
    $gtext = str_replace('gBusiness','<span class="g">g</span>Business', $gtext);
    $gtext = str_replace('gBUSINESS','<span class="g">g</span>BUSINESS', $gtext);
    return $gtext;
}

function onviasupport_breadcrumb($vars){
    if (!empty($vars)) {
        $crumbs = '<div class="breadcrumb">'.implode(' › ', $vars['breadcrumb']).'</div>';
        $crumbs = str_replace('^','', $crumbs);
        return $crumbs;
  }
}

/**
*  insert the <em> tag into title using trigger ^
*/
function insertEmTrig($title, $tag=''){
    $title = explode('^',$title);
    if(count($title) > 1) {
        return $title[0].$tag.' <em>'.$title[1].'</em>';
    } else {
        return $title[0];
    }
}

/**
*  clear the trigger ^ for head title
*/
function cleanTitle($title){
    $title = str_replace('^','', $title);
    return $title;
}

/**
*  insert the <em> tag half-way through the title, auto = no trigger
*/
function insertEmAuto($title, $tag = ''){
        $title = explode(' ',$title);
        $half = (floor(count($title) / 2));
        array_splice($title, $half, 0, $tag.'<em>');
        $title = implode(' ',$title). '</em>';
        return $title;
    }

//return a list of node titles as links from array of nodes. Used in articles.
function get_title_list($rel_nodes){
    if (empty($rel_nodes[0]['nid'])){
        return '';
    } else {
        $filter = '';
        foreach($rel_nodes as $item){
            if (strpos($filter, 'AND') > 0){
                $filter .= ' OR nid = '.$item['nid'];
            } else {
                $filter .= ' AND nid = '.$item['nid'];
            }
        }
        $query = db_query('SELECT nid, title FROM {node} WHERE status = 1 '.$filter.' ORDER BY created DESC');
        $list = '';
        while ($result = db_fetch_object($query)){
            $itemtitle =  cleanTitle($result->title);
            $list .= '<dd>'.l($itemtitle, 'node/'.$result->nid).'</dd>';
        }
        return $list;
    }
}

/**
* This is a theme override of the theme_table function from Drupal's  theme.inc file.
* Only thing I'm doing here is stripping out any ^ symbols
*/
function onviasupport_table($variables) {
  $header = $variables['header'];
  $rows = $variables['rows'];
  $attributes = $variables['attributes'];
  $caption = $variables['caption'];
  $colgroups = $variables['colgroups'];
  $sticky = $variables['sticky'];
  $empty = $variables['empty'];

  // Add sticky headers, if applicable.
  if (count($header) && $sticky) {
    drupal_add_js('misc/tableheader.js');
    // Add 'sticky-enabled' class to the table to identify it for JS.
    // This is needed to target tables constructed by this function.
    $attributes['class'][] = 'sticky-enabled';
  }

  $output = '<table' . drupal_attributes($attributes) . ">\n";

  if (isset($caption)) {
    $output .= '<caption>' . $caption . "</caption>\n";
  }

  // Format the table columns:
  if (count($colgroups)) {
    foreach ($colgroups as $number => $colgroup) {
      $attributes = array();

      // Check if we're dealing with a simple or complex column
      if (isset($colgroup['data'])) {
        foreach ($colgroup as $key => $value) {
          if ($key == 'data') {
            $cols = $value;
          }
          else {
            $attributes[$key] = $value;
          }
        }
      }
      else {
        $cols = $colgroup;
      }

      // Build colgroup
      if (is_array($cols) && count($cols)) {
        $output .= ' <colgroup' . drupal_attributes($attributes) . '>';
        $i = 0;
        foreach ($cols as $col) {
          $output .= ' <col' . drupal_attributes($col) . ' />';
        }
        $output .= " </colgroup>\n";
      }
      else {
        $output .= ' <colgroup' . drupal_attributes($attributes) . " />\n";
      }
    }
  }

  // Add the 'empty' row message if available.
  if (!count($rows) && $empty) {
    $header_count = 0;
    foreach ($header as $header_cell) {
      if (is_array($header_cell)) {
        $header_count += isset($header_cell['colspan']) ? $header_cell['colspan'] : 1;
      }
      else {
        $header_count++;
      }
    }
    $rows[] = array(array('data' => $empty, 'colspan' => $header_count, 'class' => array('empty', 'message')));
  }

  // Format the table header:
  if (count($header)) {
    $ts = tablesort_init($header);
    // HTML requires that the thead tag has tr tags in it followed by tbody
    // tags. Using ternary operator to check and see if we have any rows.
    $output .= (count($rows) ? ' <thead><tr>' : ' <tr>');
    foreach ($header as $cell) {
      $cell = tablesort_header($cell, $header, $ts);
      $output .= _theme_table_cell($cell, TRUE);
    }
    // Using ternary operator to close the tags based on whether or not there are rows
    $output .= (count($rows) ? " </tr></thead>\n" : "</tr>\n");
  }
  else {
    $ts = array();
  }

  // Format the table rows:
  if (count($rows)) {
    $output .= "<tbody>\n";
    $flip = array('even' => 'odd', 'odd' => 'even');
    $class = 'even';
    foreach ($rows as $number => $row) {
      // Check if we're dealing with a simple or complex row
      if (isset($row['data'])) {
        $cells = $row['data'];
        $no_striping = isset($row['no_striping']) ? $row['no_striping'] : FALSE;

        // Set the attributes array and exclude 'data' and 'no_striping'.
        $attributes = $row;
        unset($attributes['data']);
        unset($attributes['no_striping']);
      }
      else {
        $cells = $row;
        $attributes = array();
        $no_striping = FALSE;
      }
      if (count($cells)) {
        // Add odd/even class
        if (!$no_striping) {
          $class = $flip[$class];
          $attributes['class'][] = $class;
        }

        // Build row
        $output .= ' <tr' . drupal_attributes($attributes) . '>';
        $i = 0;
        foreach ($cells as $cell) {
          $cell = tablesort_cell($cell, $header, $ts, $i++);
          $output .= _theme_table_cell(cleanTitle($cell));
        }
        $output .= " </tr>\n";
      }
    }
    $output .= "</tbody>\n";
  }

  $output .= "</table>\n";
  return $output;
}

```

# Answer
You could do use a hook\_form\_alter(), eg, something like this:

```
function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  global $user;

  if (!$user->uid) {
    unset($form['author']['name']);
  }

}

```

to remove that field for anonymous users. If you want that field gone for everyone, then just remove the `if` :)

Note: you could also `unset()` the whole `$form['author']` but then you would not be able to allow other contact information, eg, the homepage and email address, when you use:
> 1 votes

# Answer
You have several options. One is to simply hide the field by using CSS. As the author field is not required it should work like this without problems.

The other is to do some form altering. You can do this in template.php on the theme level or in a custom module.

There is a pretty good description here: http://planken.org/2013/10/drupal-remove-your-name-elements-comment-form

It boils down to this in template.php:

```
function YOURTHEME_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['#access'] = FALSE;
}

```

or to this in a custom module:

```
function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['#access'] = FALSE;
}

```
> 0 votes

---
Tags: comments
---


# Question
Title: Is there a module for creating images and labelling and placing them in a document?
I am looking for a module which allows me to place images with additional information to the text of a page using a filter connected to the image's node id.

I need a content type with something with fields like this:

1. The image itself
2. A description
3. Additional fields with some information about the image, like source, size, attribution, date, license, etc

What I need is something like a filter that allows me to embed the image in a document displayed with some of the additional fields in a properly formatted manner.

Is there a module for doing this?

# Answer
> 0 votes
No such module exists. The default *Article* content type in Drupal 7 already has an image field, but not the fields you request for holding metadata.

However, with **Fields** in core in Drupal 7, it is trivial to add the required fields to any content type. If you're not familiar with **Fields**, you may want to look at this tutorial.

After adding the field for the image itself, and the metadata you want, you may want edit the template for the content type to make sure all the fields are rendered nicely.

---
Tags: media, input-formats
---


# Question
Title: Looking to embed node links within CKEditor
I would like to be able to embed node links within CKEditor but have the plugin use a view or table to display the content of the type of my choosing.

Linkit picker looked like exactly what I wanted but I found it was not compatible with version 3.x or even 2.x of Linkit. \[I tried the 2.x dev version of linkit picker as well.\]

Another similar module was CKEditor Link, but this uses auto-complete and I would like paged display, or something that uses views so I can customize the output.

# Answer
I don't believe there's anything out there that works exactly how you're describing. The only thing that is similar is https://drupal.org/project/nodepicker but it doesn't have a stable release any more and may have the same compatibility issues as Linkit picker. You may be able to pick it up and get it working if you're up to the challenge though.

It sounds to me though that you're just trying to make your new site built with Drupal behave like your old site made in something else. It's like complaining that your new car doesn't stall at the traffic lights like your old car did. ;)

I'd install ckeditor link and ckeditor 4.x and just convince the people you are huilding it for that this is the most efficient way to link up your content.

Otherwise I suspect you'll be building something custom.
> 0 votes

---
Tags: wysiwyg, nodes, navigation
---


title: How to translate page titles?

text:
# Question
Title: How to translate page titles?
I'm using the awesome Internationalization Module for managing the translations of my multilingual website. The name of each menu item also becomes the page title (the HTML TITLE tags). When switching languages everything works perfectly except the page titles. The page title shows correctly the name of the page, but in the LAST language I translated that menu link into. The last added translation of the menu is Chinese, so the page titles are always Chinese, regardless wheter you are on the Swedish or French version of that page.

* Using Drupal 7.18
* Using Internationalization module 7.x-1.7, fully enabled.
* The multilingual options of the menu are set to 'Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.'

What could I try to fix this?

# Answer
The solution is to update to version 7.x-1.8 of the Internationalization Module. This was a bug in version 7.x-1.7. Thank you developers! Drupal FTW :D
> 0 votes

# Answer
while translaing page, there is an option at bottom 'provide a menu link'. check this field with title...
> 1 votes

# Answer
You cant try it out this module Title for drupal 7.Hope this will give you good solution.
> 0 votes

# Answer
You can translate the page titles with string override methods.

for that you needs to edit in page.tpl

```
      <?php print $title; ?> will be <?php print t($title); ?>

```
> 0 votes

---
Tags: routes, 7, i18n-l10n
---


# Question
Title: Does [Cache blocks] in Performance means that blocks generated by Views are also cached?
I am working on an old Drupal 6 project.
My goal is to boost the performance of the website as much as I can.
Among other things I have done, I have already enabled cache

Configuration \> Development \> Performance

My question is, does \[Cache blocks\] in Performance means that blocks generated by Views are also cached **or** I have to enable caching inside Views?

# Answer
In D6 views caching you have two kinds of options

1. Cache your query results -- Length of time your raw query results should be cached
2. Rendered Output -- Rendered HTML Output to be cached

In Block Cache in Performance settings

Block Rendered HTML Output to be cached which will be same as view setting.

For best performance you should use Views Caching option since it provides query level caching as well as rendered output caching.
> 0 votes

---
Tags: views, blocks, caching
---


# Question
Title: Guidelines For Features as building blocks
Any guidelines on how to use features module as building blocks for a consolidated drupal site from a prototypic approach, so that most of the functionality is just a plug and play using feature.

I am afraid my question might be too broad to answer, but looking for initial pointers basically the important things need to be taken into account while building features so there can be least chances of conflicts.

# Answer
> 2 votes
Some of my thoughts coming from my experience:

* Features should be logical and separated functionality blocks - each feature should be standalone as much as possible and there should be no overlaps to prevent one feature overriding other.
* You can safely put your custom code in features - if you write something into your .module file (or any other that is not filled with features exports), next time you recreate the feature it will be respected and it will stay there - this fact is not so often used but it can be very helpful to achieve the first point.
* More smaller features are easier to manage than few big ones - this is just because bigger features are more error prone when creating (e.g. you add something without noticing) and you need to inspect more code when searching for stuff.
* It's good practice to put features in separate folder (e.g. sites/all/modules/features)
* You can use Features Extra (https://drupal.org/project/features\_extra) to export some additional entities, especially blocks.
* Use Context (http://drupal.org/project/context) or Panels (https://drupal.org/project/panels) for powerful exportable layouts.
* Everything can be exported only once, features UI will not even allow to export duplicities.
* Use drush to make your life easier (see drush help, section features)
* Use Advanced Options to replace your existing features when recreating (instead of downloading it and copying it manually)
* Keep everything clean 1 - install Diff (https://drupal.org/project/diff) to see overrides of your features code and revert when necessary.
* Keep everything clean 2 - recreate you features often, to keep your code updated and to avoid unclear situations when you are not sure what *should* be in code, what *actually is* in code and what is overriden in database.

*I will update my answer when I come up with additional stuff*

---
Tags: features
---


# Question
Title: Views exposed filter auto submit loses focus
I have setup a view with ajax enabled. I have also added an exposed filter with autosubmit on so that as the user types in the text field the view will automatically update. The problem is that when the form autosubmits, the text box loses focus.

I have read that I need to separate the exposed form into a separate block, however this option is not available as my view is a block itself.

Any help would be appreciated, as it is a real pain having to keep clicking in the text box to keep typing.

# Answer
You really only have one choice here.

One way or another you need to (re)move your form out of the views.

The reason why the exposed filter looses focus is because the entire view is being replaced on ajax. If your form is being render by the same view there's just no way you're going to be able to keep focus.

Solutions (All involve moving your form out of the view):

Below are some options you should avoid, but mentioning here as a last resort.

* You can always just "hack" your views.tpl.php to move your expose form out of the main view div. I use "hack" here because this is not a nice option. This will place the form right above your view, but views JS code is only going to replace the view div. That being said the JS isn't going to just work. You'll need to fix that.
* Then as a last resort you can always just use JS to move your form. This one is highly discourage. Because again the form is going to loose the JS behaviors after views updates the display
> 3 votes

# Answer
Also a workaround for the core problem, but including this js in my theme solved this problem for me.
> 3 votes

---
Tags: 7, ajax, views
---


# Question
Title: How can I send HTML mail when a new content is created with attachments using these modules?
In my project, I need to send HTML mail when a new content is created with attachments using the Mimemail, Mail System, SMTP, and Rules modules. Plain text mail is working fine with rules module but problem is with HTML mail.

Can you please tell me the procedure to configure Mail System and Mime mail with SMTP?

# Answer
> 3 votes
First you need to create a Rule to send a HTML email via Mimemail:

Once you've configured the rule correctly and have entered your HTML email content, you need to ensure the correct mail system class is being used by Drupal to send your emails:

If you don't select the MimeMail class within these settings, the default Drupal mail system will be uses and your HTML emails will be sent in plain text.

---
Tags: 7, rules, mimemail
---


title: Template name does not take effect

text:
# Question
Title: Template name does not take effect
I got a field with xyz as machine name, and I created a field--field-xyz.tpl.php template file, but it does not take any effect.
I used the template file to add views-field and views-field-field-xyz as CSS classes, but they don't show up.

What did I do wrong? Is it because I am using the Adaptive theme?

# Answer
> 0 votes
Does xyz field name contain underscores?

> Note that underscores in a Field's machine name are replaced by hyphens. Also remember to include "field-" in custom field names, e.g: field--field-phone.tpl.php.

https://drupal.org/node/1089656

EDIT: Add a `hook_preprocess_field(&$vars)` in your theme and dpm($vars) to check up on theme\_hook\_suggestions array for this field.

---
Tags: 7, theming, caching
---


title: Folderstructure for template files

text:
# Question
Title: Folderstructure for template files
Is there a restriction for template folders? Like for name or structure ?

# Answer
> 2 votes
No, Drupal doesn't place restrictions on the names of any template file or folder.

Restrictions for file naming are handled at the OS level.

# Answer
> 0 votes
No,there is no restriction for the file or folder naming structure. Drupal doesn't follow that name/structure restrictions.

---
Tags: 7, theming
---


# Question
Title: User being logged out of drupal when using form redirect
Looking at my logs I have an issue. I have not been able to recreate it myself.

I have a form which an anonymous user fills out. This form takes an email address. When submitting the form I take that email address and either log the user in or create an account and log the user in.

This code is working fine. As I have several `watchdog()` calls going in as the user who has been logged in.

The code then creates an order in Drupal commerce (with the user account above). I have a valid orderid created with the above user.

I then have:

```
watchdog('MyMod', t("Logged in as user));
drupal_goto('checkout/' . $orderid . '/review');

```

The `watchdog()` goes in as the user. When I hit `checkout/????/review` I then get an **access denied** for an Anonymous user.

This is only happening some of the time. As I said I have not been able to reproduce. What could be causing the `drupal_goto()` to log my user out.

**Update**

I now use

```
watchdog('MyMod', t("Insert in ref table complete"));
$formstate['redirect'] = 'checkout/' . $orderid . '/review';

```

To redirect my user however I am still getting the same issue.

**Update 2**

With some code.

Log out user

```
function _mymod_logout_user() {
  global $user;
  if ($user->uid > 1) {
    module_invoke_all('user_logout', $user);
    session_destroy();
  }
}

```

Create User

```
function _mymod_create_user($mail) {
  global $user;
  _mymod_logout_user();
  if ($user->uid != 0) {
    return $user;
  }

  $account = user_load_by_mail($mail);

  if ($account == FALSE) {

    $password = 'random12!££SsjsjaJAAJA3'; //made up

    //set up the user fields
    $fields = array(
      'name' => $mail,
      'mail' => $mail,
      'pass' => $password,
      'status' => 1,
      'init' => 'email address',
      'roles' => array(
        DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      ),
    );

    $account = user_save('', $fields);
  }

  // If the user is 1 then we want to return false as they will be logged in as admin
  if ($account->uid == 1) {
    return FALSE;
  }

  $form_state = array();
  $form_state['uid'] = $account->uid;
  user_login_submit(array(), $form_state);

  return $account;
}

```

Create Order

```
function _mymod_create_order($sku, $mail) {
  global $user;
  $user = _mymod_create_user($mail);

  // User is trying to create an account under user 1 so return nothing.
  // can only do this if logged in a user 1 not anon
  if ($user == FALSE) {
    return;
  }
  $uid = $user->uid;

  $order = commerce_order_new($uid, 'checkout_review');
  $product = commerce_product_load_by_sku($sku);
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id, array());
  commerce_line_item_save($line_item);

  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;
  commerce_order_save($order);
  return $order->order_id;
}

```

Insert into custom table

```
function _mymod_insert_ref_table($orderid, $ref) {
  db_insert('mymod_reference_table')
    ->fields(array(
      'orderid' => $orderid,
      'ref' => $ref,
    ))
    ->execute();
}

```

Form submit function

```
function mymod_form_submit($form, &$formstate) {
  global $conf;

  $sku = //Code that generates a SKU;

  $orderid = _mymod_create_order($sku, $form['email']['#value']); //email has all ready been validated by drupal

  $ref = // Call to WS that returns a reference number
  _mymod_insert_ref_table($orderid, $ref);
  watchdog('My Mod', t("Insert in ref table complete")); // This watchdog message goes in as the logged in user!
  $formstate['redirect'] = 'checkout/' . $orderid . '/review';  // When I reach this page I am logged out sometimes...

}

```

# Answer
> 2 votes
You should better use `$form['redirect']` within a form rather than `drupal_goto()`.

> If you use drupal\_goto() you will short cut the form processing skipping any other form\_submission functions that have attached themselves to the form. Thus, if you use path\_auto and do a drupal\_goto while processing a node form, a nice path will not be added to your node because the drupal\_goto() was executed before pathauto's node submission handler was called.

Source

This was before the original post was edited. Regarding the logout issue, let us review your procedure.

So essentially: when a form is submitted, `mymod_form_submit()` calls `_mymod_create_order()`, which calls `_mymod_create_user()`, which in turn calls `_mymod_logout_user()`. All of them unconditionally so far.

If not user 1, you will logout the user and then back in `_mymod_create_user()` you will attempt to create if necessary and then log the user in.

When you attempt to login the user via `user_login_submit()`, Drupal will call `drupal_session_regenerate()`. There, in an attempt to prevent several nasty security possibilities such as session fixation, will generate a new session ID. I suspect the trouble is somewhere there, depending on what exactly happens in the code that displays the redirection page "checkout/...".

In order to deal with this issue I would recommend you to adopt the procedure that other modules use to deal with the possibility that an anonymous user needs to login / be created. Ubercart and Drupal Commerce certainly deal with that. Personally I would suggest to take a look at Ubercart file "uc\_cart/uc\_cart.pages.inc", function `uc_cart_checkout()`

# Answer
> 0 votes
I've seen issues with user appearing to get logged out when the site can be accessed both through http://www.domain.com and http://domain.com: The drupal\_goto() call could send them from one version to the other, thus voiding the session cookie. Have you tried using .htaccess to redirect the www.domain.com to domain.com, or the other way around?

# Answer
> 0 votes
Check out if protocol changes. If you are being sent http to https, the http session won't continue into https.

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


# Question
Title: How to change an image field to a certain fid programatically?
Specifically, every time a comment is saved, I'd like to programatically change a comment field 'Picture' to an image field from the user who wrote the comment. I have the following custom module:

```
function MYMODULE_comment_presave($comment) {
    $user = user_load($comment->uid);
    $uid = $user->uid;

    $comment->field_picture['und'][0]['fid'] = $user->field_picture['und'][0]['fid'];
}

```

This doesn't work correctly, because the `field_picture_alt`, `field_picture_width`, `field_picture_title` and `field_picture_height` columns in my database don't get a value (they're `NULL`).

I've also tried

```
function MYMODULE_comment_presave($comment) {
    $user = user_load($comment->uid);
    $uid = $user->uid;

    $comment->field_picture['und'][0]['fid'] = $user->field_picture['und'][0]['fid'];
    $comment->field_picture['und'][0]['width'] = $user->field_picture['und'][0]['width'];
    $comment->field_picture['und'][0]['height'] = $user->field_picture['und'][0]['height'];
    $comment->field_picture['und'][0]['alt'] = $user->field_picture['und'][0]['alt'];
    $comment->field_picture['und'][0]['title'] = $user->field_picture['und'][0]['title'];
}

```

and that works perfectly.

However, I was wondering whether I always have to set the 'alt', 'title', 'width' and 'height' values manually as above.

Is there another faster way to inherit these caracteristics from the referred image? Can I for example inherit the 'height' and 'width' from an image style?

# Answer
> 2 votes
You can do this in the comment tpl file. Add something like this:

```
$img_array = array(
    'style_name' => 'thumbnail',
    'path' => $user->field_picture['und'][0]['uri'],
    'width' => '',
    'height' => '',
    'alt' => $user->field_picture['und'][0]['alt'],
    'title' => $user->field_picture['und'][0]['title'],
  );

$img = theme('image_style', $img_array);

```

You can then add `<?php print $img; ?>` where you want the image to appear.

---
Tags: 7, entities, media
---


# Question
Title: Media module: how to generate a pdf link?
I'm trying to use the media module to generate a link to a pdf that I uploaded using media module. The problem is that when I insert the pdf that is on my library and select the link format, it displays a missing image and does not generte my link. What should I do to make it generate the link to my pdf?

# Answer
Check out your file-types display settings in `admin/config/media/file-types` in combination with the field display settings you are using.
> 1 votes

---
Tags: wysiwyg, media, files
---


# Question
Title: How to link a view to the current language with a no results fallback to the default language?
I've already figured out how to link views to content language by the `Content: Language` filter. I know that I can create a second view to use as the No Results fallback and use the `Global: View area` to feed the other in. But to do this I have to:

* pollute my site's blocks with Localized and Unlocalized duplicates and hope the client understands that they should only enable the Localized block.
* make sure to maintain a duplicate of the original with only the `Content: Language` filter changed.
* tolerate a full second set of queries to generate the block? Some blocks are ordered by random, so they can't really be cached well.

Isn't there a better way to do this?

Also, I know I can use the rearrange feature on the languages to set up conditions like:

```
Content: Language (In user's current language) OR
Content: Language (In default site language)

```

But the issue is that then these languages are mixed. I need the default site language to appear only when there are no nodes in the current user's language.

# Answer
Check out http://www.webomelette.com/drupal-views-pre-render-alter-display, u should be able to use hook\_views\_pre\_render() in a custom module and check your result set before rendering.

In the case of no results, change language to sites default in the view object, although im not sure that this hook will trigger your new query to run and bring the default lang contents, but its a start!

http://drupalcontrib.org/api/drupal/contributions%21views%21views.api.php/7
> 0 votes

---
Tags: 7, views, i18n-l10n
---


title: D7 dynamic views by user input

text:
# Question
Title: D7 dynamic views by user input
First of all I want to let you know that I am a newbie with Drupal so maybe this question isn't good or even not possible to apply with Drupal.

I got a custom content type that includes in it a lot of fields and among them there are a date field and a list field.

My goal is that a pop window will flow when user enters my site, then he will submit a date and a value that the list contains, and he will get into a page that will display the nodes that include the same input he puts in.

Can someone explain me how to do it?

Thanks in advance :)

# Answer
> 1 votes
This is a broad question that it pretty much requires some proficiency with several aspects of Drupal.

In short, first I would recommend you that you find a ready theme which features some kind of pop-up as you require. Alternatively, you would need to theme a pop-up region by yourself.

Then, you need Views module with exposed filters in a block, which you would add to this specific region.

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


# Question
Title: How to set value in form validate for later validation functions
**Problem**

I'm adding the user register form onto the node create form with hook\_form\_alter.

The problem is the first step of account validation always fails because Drupal doesn't save Username to `form_state['values']['name']`. (I think because I'm combining two entity forms (user and node) and perhaps because it's not needed for the default entity node form?)

Either way I have 4 validation functions that run in $form\['validate'\];

```
0 (String, 18 characters ) node_form_validate | (Callback) node_form_validate();
1 (String, 39 characters ) commercecurrency_node_form_validate | (Callback) commercecurrency_job_advert_form_validate();
2 (String, 22 characters ) _editnode_validate | (Callback) editnode_validate();
3 (String, 26 characters ) user_account_form_validate | (Callback) user_account_form_validate();

```

I'm trying to set the value in `_editnode_validate` so `$form_state['values']['name']` is set when `user_account_form_validate` runs.

However the following code although it changes the value in `_editnode_validate`, doesn't save the value for the other validation functions. How can I get it to store the new value?

```
function _editnode_validate ($form, $form_state)

   $test_value = $form_state['input']['name'];
   $form_state['values']['name'] = $test_value;

```

(Both `_editnode_validate` and `user_account_form_validate` are added in `hook_form_alter`, and the code for `_editnode_validate` is in the `hook_form_alter` module.)

# Answer
> 2 votes
Is the problem just that your not passing $form\_state by reference in your \_editnode\_validate validation function?

```
// note the & before $form_state to pass by reference
function _editnode_validate ($form, &$form_state)

   $test_value = $form_state['input']['name'];
   $form_state['values']['name'] = $test_value;

```

---
Tags: 7, forms
---


title: Removing field from form

text:
# Question
Title: Removing field from form
I just came across a solution regarding media module. It suggested that:

replace all

```
unset($form[$id]);

```

to

```
$form[$id] = array('#language' => NULL);

```

in media\_gallery.module

This worked nicely for my problem, but I do not understand what it actually does. The unset is used when we want to remove a field from a form, fx when someone does not have access to the form. Is the 2nd equivalent of the 1st?

# Answer
> 2 votes
The first statement essentially removes a field from the form. The second statement sets the field's language to undefined (neutral). They are not the same, but they both help you to deal with this module's issue as they both prevent the form from passing invalid keys to `locale_field_node_form_submit()`.

---
Tags: users, forms, i18n-l10n
---


# Question
Title: Getting all revisions of an entity with EntityFieldQuery
I'm trying to get all revisions of an entity with EntityFieldQuery.

Here's my code:

```
function entity_hash_queue($entity_restrict = NULL) {
  if ($entity_restrict) {
    $entity_info = entity_get_info($entity_restrict);
    if ($entity_info['entity keys']['revision'] != NULL) {
      $query = new EntityFieldQuery;
      $query->entityCondition('entity_type', $entity_restrict);
      $results = $query->execute();
    }
  }
}

```

I'm trying to figure out what property of the EntityFieldQuery object I can use to ensure that it gets every revision of an entity (if that entity supports revisions).

I'm getting a list of all entity objects, but not each revision for each object. How do I go about getting that information? I can't find anything.

# Answer
> 1 votes
In this case, use db\_select instead EntityFieldQuery to get all revisions from the revision table:

```
$result = db_select('your_entity_revision_table', 'yert')
    ->fields('yert')
    ->condition('entity_id', {your Entity ID})
    ->execute()
    ->fetchAllAssoc('revision_id');

kpr($result);

```

---
Tags: 7, entities, nodes, database
---


# Question
Title: howto db_select and cross join on drupal?
a table:

```
CREATE TABLE `a` (`id` int(10));INSERT INTO `a` (`id`) VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

```

I need to make a cross join tables in drupal using db\_select:

```
$query = db_select('num', 'n1');
$query -> fields('n1', array('i'));
$query -> innerJoin('num', '10');
$query -> fields('n10', array('i'));
watchdog(__FUNCTION__, $query -> __toString(), $query -> getArguments());
$result = $query -> execute();
$records = $result -> fetchAllAssoc('i');

```

get as a result:

> Array ( \[0\] =\> stdClass token Object ( \[i\] =\> 0 \[n10\_i\] =\> 9 ) \[1\] =\> stdClass token Object ( \[i\] =\> 1 \[n10\_i\] =\> 9 ) \[2\] =\> stdClass token Object ( \[i\] =\> 2 \[n10\_i\] =\> 9 ) \[3\] =\> stdClass token Object ( \[i\] =\> 3 \[n10\_i\] =\> 9 ) \[4\] =\> stdClass token Object ( \[i\] =\> 4 \[n10\_i\] =\> 9 ) \[5\] =\> stdClass token Object ( \[i\] =\> 5 \[n10\_i\] =\> 9 ) \[6\] =\> stdClass token Object ( \[i\] =\> 6 \[n10\_i\] =\> 9 ) \[7\] =\> stdClass token Object ( \[i\] =\> 7 \[n10\_i\] =\> 9 ) \[8\] =\> stdClass token Object ( \[i\] =\> 8 \[n10\_i\] =\> 9 ) \[9\] =\> stdClass token Object ( \[i\] =\> 9 \[n10\_i\] =\> 9 ) )

watchdog: SELECT n1.i AS i, n10.i AS n10\_i FROM {num} n1 INNER JOIN {num} n10

this query in phpmyadmin gives the "multiplication" of tables: 100 rows that I deserve.

why not works through db\_select in drupal?

db\_select need to connect this query to a different sample already on tables Drupal, db\_query would not help me =/

# Answer
innerJoin takes 3 args: table, table\_alias, and condition. ex:

```
$query->innerjoin('node', 'n', 'c.entity_id=n.nid')

```

The above would produce "...INNER JOIN node n ON c.entity\_id = n.nid ..." You can add the fields form node by doing:

```
$query->fields('n', array(...));

```
> 0 votes

---
Tags: database
---


title: Per site htaccess with multisite

text:
# Question
Title: Per site htaccess with multisite
In short: Can I have a separate .htaccess file per site on a multi-site installation?

I've read quite a lot of conflicting stuff about this, including some which suggests you can put a .htaccess file in the site folder (i.e. /sites/www.site1.com/). However, some commenters seem to be saying this won't work.

As I am moving several non-Drupal sites over to a single multisite there will need to be lots of rewrites for old URLs, so this is pretty much essential for me.

Thanks, Chris

# Answer
Multisite logic (picking what site is what) works in Drupal itself, rather than the Apache level.

I do not think that putting a .htaccess in the sites folder would work, mainly because nothing is really fetched from there from Apache's perspective, except for files. Normal URLs would never see that file. There would also be some weirdness with the `RewriteBase`, and other complications because of the way .htaccess gets processed up the directory hierarchy.

My suggestion would be to use the Redirect module. This module essentially presents a UI for making and managing redirects for your Drupal site. You can enable this per site in your multisite setup. Therefore each domain could redirect its own URLs. I have found this module very useful for new site launches that use a new URL scheme.

Your other option would be to RewriteCond, eg

```
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule some/old/url.html the/new/url [L,R=301]

```

I would do this as an include from the main Apache configuration, rather than .htaccess, unless you a really careful about backing this up when you update core.

Of the two options, I would use the Redirect module. I would also think very carefully about committing to a multisite solution. They tend to create more problems than they solve.
> 3 votes

---
Tags: 7, multi-sites, .htaccess
---


title: THEME_preprocess_page_xxx?

text:
# Question
Title: THEME_preprocess_page_xxx?
I need to make changes to several admin pages, instead of conditionally tests for the page/node (ie: User, Appearance, Views admin pages right now) can I override each using more specific theme functions?

```
MYTHEME_preprocess_page_admin_user
MYTHEME_preprocess_page_admin_views
MYTHEME_preprocess_page_admin_appearance

```

Is this possible? It's the themeing function not the template TPL I need to execute as I am re-structuring some list items in each -- not really changing the markup per se.

Alex

# Answer
> 3 votes
Out of the box, Drupal won't do this. You can do something like this, though:

```
function MYTHEME_preprocess_page(&$variables) {
  $parts = explode('/', request_path());
  $subhook = __FUNCTION__;

  foreach ($parts as $part) {
    $subhook .= '__' . $part;

    if (function_exists($subhook)) {
      $subhook($variables);
    }
  }
}

```

This is untested (it may need some tweaking), but it will build up function names based on the `request_path()`. So, the idea is that if the URL is http://example.com/foo/bar/bar, it will check for

* `MYTHEHE_preprocess_page__foo()`
* `MYTHEHE_preprocess_page__foo__bar()`
* `MYTHEHE_preprocess_page__foo__bar__baz()`

and call each, in sucession, passing in the `$variables`.

As this will call functions based on user input, you will want to think about some logic to prevent malicious activity, such as only doing it for certain paths, etc.

Just note, that if you are doing this to the admin pages, then you need to do this in the admin theme you have defined for your site, and not the main theme.

I don't normally do this with the preprocess page hooks, but I use something similar for the node ones based on content type and view mode.

---
Tags: theming
---


# Question
Title: Can I make the Omega theme to either be or not to be responsive depending on the capability of the device to properly scale the site
I have a site which needs to be responsive to several devices (mobiles and tablets)

I will do this using the Omega theme. Then I have the option to make the theme **Responsive**. In this way the general layout of the site changes based in the size of the screen device.

So far so good.

I need to change this behavior in this way: if the device is capable of scaling and showing the site in an acceptable way (ex: like the iPhone(iOS) and Galaxy S2(Android) do) then the theme should no behave like responsive and show the site in its **normal** layout.

My question: Can I make the Omega theme to either be or not to be responsive depending on the capability of the device to properly scale the site?

# Answer
I don't really get your question.

Omega handles responsive changes by media queries. The default is to load a new stylesheet (narrow, normal, or wide) based on the rules you setup. If a browser doesn't support media queries, then just global and default get loaded. If you want to enable responsive layouts for older browsers, then you can enable the JS support.

Also, nothing prevents you from using media queries in the global and default stylesheets. This is how I handle retina and retina-like display graphics.
> 0 votes

# Answer
I'm pretty sure you can trigger contexts on specific devices using mobile tools, and you can probably turn Omega's responsiveness off with Delta.

I've never pulled such configuration, so please try out and give some feedback ;)
> 1 votes

# Answer
You can disable the 'ressponsiveness' of the Omega theme in it's settings, once you have created your subtheme. Just disable the responsive grid. You'll find the setting to do this at:

```
[your-domain]/admin/appearance/settings/[your-theme-name].

```
> 0 votes

---
Tags: theming
---


# Question
Title: Is it possible to query against the ldap server stored in drupal without reconnecting?
I have a drupal install that uses LDAP to authenticate users. I use that same LDAP to return user info such as roles, employee photo, email, role, and the center they work at.

```
    $ds=ldap_connect("ldap-example.com");
            if ($ds) {
                $r=ldap_bind($ds);
                $sr=ldap_search($ds, "DC=tpcontact,DC=co,DC=uk",$search);
                $info = ldap_get_entries($ds, $sr)or die('get info fail');
}

```

I need to make it so that the server is pulled from drupal. So, if it is possible to query ldap without reconnecting, I need to do that. Otherwise I need to query the drupal DB's ldap\_servers table, the only problem is that I dont have access to a MySql database that has LDAP enabled to see what the field is.

# Answer
So I assume that you are using the LDAP module?

I've not looked into the code they use however I would expect that they will close the connection before your module runs, and even if they don't the connection won't be a global variable so your module will not have access to it.

If you are writing a custom module then you *do* have access to the DB - just use db\_query and fetch the results, or look in your settings file for your connection details. Then you can connect directly to your DB using software like Navicat.

The table ldap\_servers has a field called **address**. This is where you will find the address to your ldap server.
> 2 votes

---
Tags: authentication-authorization
---


title: Rollover image swapping as a field

text:
# Question
Title: Rollover image swapping as a field
I'm learning Drupal and I'm trying to create a field where I can upload 2 images and let one face into the other while I mouse over/ hover / rollover it. Then I eventually plan to make it into a views like one in Zappos where the user can see alternate views on mouse over.

I've looked up the other thread and found the Rollover filter on Drupal but I still don't know how to make that work. I need it as a field of a node so that I can display a view of all the related nodes.

# Answer
> 0 votes
Got it to work! I added CSS code found here into the global.css of my theme:

http://css3.bradshawenterprises.com/cfimg/#cfimg7

```
#cf {
  position:relative;
  height:281px;
  width:450px;
  margin:0 auto;
}

#cf img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

#cf img.top:hover {
  opacity:0;
}

```

And later I used the Custom Formatter module as recommended by jpelan to add this html code from that same website.

```
<div id="cf">
  <img class="bottom" src="/images/Windows%20Logo.jpg" />
  <img class="top" src="/images/Turtle.jpg" />
</div>

```

# Answer
> 1 votes
I would set it up as a single image field with two values and then use https://drupal.org/project/custom\_formatters to create a custom formator for that field and do a display hide/show with css or jquery.

---
Tags: media
---


# Question
Title: Hide fields from "address_field Module" form
I have a site using **Profile2** with **address\_field** Module; and I would like to prevent users from filling out the follwing fields: Address 1 Address 2 ZIP Code Country

The goal is is only to be able to fill only CITY AND STATE; (e.g. Orlando, FLORIDA)

Thanks.

J.M.

# Answer
> 2 votes
in a hook\_form\_alter() add:

```
   hide($form['field_address']['und'][0]['street_block']);

```

you can use dpm($form\['field\_address'\]\['und'\]\[0\]) to get the name of the city, and country fields.

You could also use CSS to hide the fields but I ran into problems where browsers prefilled those fields. It's better to hide it with a hook.

# Answer
> 1 votes
Refer to the address-hide-country.inc file in the address module. It has given a good example of how to hide the country field.

Also there is an example module for how to create an address field plugin to create custom plugin to act on the address field.

# Answer
> 1 votes
You can hide the country by checking the "Hide the country when only one is available" box in the field settings for your address field. Then you can add the following code to custom module to hide the Address1, Address2, and ZIP (where "MYMODULE" is the name of your custom module, "MYPROFILETYPE" is the machine name of the profile type you are altering, and MYFIELD is the name of your address field):

```
/**
 * Implementation of hook_form_profile2_edit_PROFILE_NAME_form_alter()
 */
function MYMODULE_form_profile2_edit_MYPROFILETYPE_form_alter(&$form, &$form_state){
  //dsm($form['profile_MYPROFILETYPE']['field_MYFIELD']['und'][0]);
  hide($form['profile_MYPROFILETYPE']['field_MYFIELD']['und'][0]['street_block']['thoroughfare']);
  hide($form['profile_MYPROFILETYPE']['field_MYFIELD']['und'][0]['street_block']['premise']);
  hide($form['profile_MYPROFILETYPE']['field_MYFIELD']['und'][0]['locality_block']['postal_code']);
}

```

---
Tags: users, entities
---


# Question
Title: Definition join on field and where other field has value
I am building a views plugin and I need it to do this:

```
LEFT JOIN my_table mt ON (mt.nid = node.nid AND mt.value = 'some argument');

```

I have found documentation for creating a views plugin, but all of the documentation that I have found doesn't say anything about creating view joins like this.

Is it possible? If so, how do I go about doing something like this?

# Answer
> 0 votes
Drupal has an extra field in the join in which you can inject the extra where conditions, you can get to it by using a views\_query\_alter:

```
function my_module_views_query_alter(&$view, &$query) {
    if ($view->name === 'my_view' && $view->current_display === 'the_display') {
        $args = $view->args[0];
        $query->table_queue['my_joined_table']['join']->extra = array(
            array(
                'value' => $args, // pass the args through
                'numeric' => FALSE, // or true if it is
                'field' => 'the_field',
                'operator' => '='
            ),
        );
    }
}

```

---
Tags: views
---


# Question
Title: Boolean field: hide (in display) if unchecked
I have a content type with a boolean field (checkbox). Basically, what I'm trying to achieve is this:

* If this field is **checked**, only show the *label* (when viewing the page)
* If this field is **unchecked**, don't show the field *at all* (no label and no value)

Is there a simple way of doing this? (Without resorting to Views or custom code)

I've noticed that if I use "Check boxes/radio buttons" as widget type for this field, it comes close to what I want, since it offers three values to choose from (yes, no, and N/A), and if N/A is selected, the field isn't rendered on the display page.

However:

* I don't want 3 values to choose, but 2. (3 might be confusing for users, and having to explain *"Don't use the 'no' value"* really isn't a good solution.)
* I don't want the value to be displayed when "Yes" is selected (only the label).

# Answer
> 6 votes
OK, so it is possible and actually rather simple. Here's how I did it in the end:

Edit the field's settings:
"value if checked" -\> use the text you want to see displayed when checked
"value if unchecked" -\> leave empty

And then under Content type \> Manage Display, **hide** the label for this field.

This way, only the value of this field will be shown.
Since the value when *unchecked* is empty, nothing will be shown when the field is not checked.

# Answer
> 1 votes
If I understand you correctly, I think you just need to use a Boolean field and configure it as a **Single On/Off checkbox**. Then in the field settings, choose **Use field label instead of the "On value" as label**. I suspect the last part is the missing piece in your puzzle.

Otherwise, you may need the Conditional Fields module:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

# Answer
> 1 votes
I am trying to solve a very similar problem. While learning how to convert a legacy system to Drupal, I realized I had several tables in which a boolean field determines whether to hide or show several other fields. In addition to whether or not those other fields get shown, under no circumstances would I need to actually show either the label or the value of this actual boolean field.

After reading the other comments and suggestions and wrestling unsuccessfully with Conditional Fields, I found that the piece I was missing was Display Suite, which seems to give you a lot more control over the placement, hiding, and arrangement of labels and fields. Since my particular use case is a little bit different from yours, I am not sure this will help you -- did you already try Display Suite (in concert with Views, of course)?

---
Tags: 7, entities
---


# Question
Title: Drupal Feeds XPath Parser html parsing form IMDB
i have a movie site , i need import movie data from IMDB, for doing this i installed Feeds and Feeds XPath Parser for scrapping. i created a content type for movie wiht some field (poster,actors,...)

after that i create a feeds importer called "Movie importer" . i set Parser to "XPath HTML parser".

in the mapping i added xpathparser:0 ,xpathparser:1 and... for field i created for Movie content type.

in the XPath HTML parser settings i added Xpath like this

* context: //div\[@id='overview-top'\]
* title: /h1/span\[1\]
* poster: /div/a/img
* Genre: /div\[1\]/a/span
* Story: /p\[2\]
* stars: /div\[3\]/a/span
* movie rate: /div\[2\]/div\[3\]/strong/span

It's not working , and i don't know why.

one more thing i am newbie with XPath :(

Here Sample IMDB Page : http://www.imdb.com/title/tt0773262/

# Answer
> 1 votes
The `context` XPath expression is for finding a context of all other (variable) expressions. These queries do not have the context prepended, but evaluation starts with (one of the) results as context.

Thus, you may not start your query with `/`, otherwise search starts at the root again – and the root element is `<html/>`, not `<title/>` or any of the others.

For example, the query for the title has to be `h1/span[1]`. Anyway, I'd better go for the `@itemprop` attribute instead of a positional attribute: `h1/span[@itemprop='name']` or even decouple further from the underlying structure: `.//*[@itemprop='name']` and use the Movie schema properties whenever possible, as they are designed for scraping the data and will make it much more robust.

---
Tags: feeds
---


# Question
Title: Memcache Admin not showing up in Modules
I am updating a Drupal 6 installation to support memcached. After installing the memcache plugin, and configuring it with the following in settings.php, I cannot seem to access the Memcache admin page like I can on Drupal 7.

```
$conf['cache_inc'] ='sites/all/modules/memcache/memcache.inc';
$conf['memcache_servers'] = array(
  'ELASTICCACHE URL (Left out Intentionally)' => 'default'
  );
$conf['memcache_bins'] = array(
  'cache_page' => 'pages'
  );

```

I checked in modules to see if it was enabled but I do not see it there at all. All I can see is the memcache module without memcache admin.

Any suggestions?

# Answer
> 0 votes
The Drupal 6 version of memcache requires enabling the Memcache Admin module:

Once this module is enabled, there is an option at admin/settings/memcache to display memcache statistics on a page-by-page basis:

# Answer
> -1 votes
It looks like it had something to do with the version of Memcache I was using. The Development version reintroduced Memcache Admin (from Keithm's post).

---
Tags: 6, caching
---


# Question
Title: Caching results from an API via drupal_http_request
I need to frequently access a restful API via drupal\_http\_request. I am doing this in a custom View. Is there anyway to cache this data so that I don't need to as frequently query the servers?

# Answer
You could use the Drupal's cache API to store the response doing something like:

```
if (!cache_get('my_module_cache')) {
  $data = drupal_http_request($url, $options); // Add the param for the request to web service
  cache_set('my_module_cache', $data, 'cache',  REQUEST_TIME  + (3600 * 24 * 30 * 6)); // Stores in cache table and expires after 6 months
  return($data);
} else {
  $return = cache_get('my_module_cache');
  return($return->data);
}

```

Depending on how many times you need to get that cached value on same execution, you could also use drupal\_static().

On the example that I provided above, the expire policy is only based on time (6 months), in your case, you will need to analyse carefully the expire policy you are going to implement to expire/renew the cached value.

Lullabot has a great article about Drupal cache: A beginner's guide to caching data
> 2 votes

# Answer
If you are using it in a view, you can cache the view result itself as long as you are not doing the `drupal_http_request` in the a template file or a preprocess function at the theme layer. You can do so by accessing the view's configuration, then clicking on cache and set it to a desired duration Another way to do it is to use a wrapper function around your `drupal_http_request` and store the data using the drupal cache\_api as gerzenstl suggested.
> 0 votes

---
Tags: views
---


# Question
Title: drupal 7 template suggestions based on path alias
I am using this function on a D7 site to template based on url alias and everything works except when a page has a dash in it. For example mysite.com/test-page doesn't work. I tried `page--test-page.tpl.php` and no luck. If I change to testpage and use `page--testpage.tpl.php` it works. Any ideas?

Here is the function that works:

```
function mytheme_preprocess_page(&$variables) {
    // Get the alias for the page being viewed
    $alias = drupal_get_path_alias($_GET['q']);
    if ($alias != $_GET['q']) {
        $template_filename = 'page';

        //Break it down for each piece of the alias path
        foreach (explode('/', $alias) as $path_part) {
            $template_filename = $template_filename . '__' . $path_part;
            $variables['theme_hook_suggestions'][] = $template_filename;
        }
    }
}

```

# Answer
> 2 votes
Found solution here: http://cheekymonkeymedia.ca/blog/gene-bernier/how-create-page-tpl-suggestions-based-path-alias-drupal-7

Here is what I used to fix the dash in titles error. I also added no node-content-type solution:

```
function mytheme_preprocess_page(&$variables) {
  // Get the alias for the page being viewed
  $alias = drupal_get_path_alias($_GET['q']);
  if ($alias != $_GET['q']) {
    $template_filename = 'page';
    //Break it down for each piece of the alias path
    foreach (explode('/', $alias) as $path_part) {
      // Added the str_replace becayse path parts with - were not being picked up properly by the theme_hook_suggestions
      $template_filename = $template_filename . '__' . str_replace("-", "_", $path_part);
      $variables['theme_hook_suggestions'][] = $template_filename;
    }
  }

  if (isset($variables['node'])) {
    // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
  }
}

```

# Answer
> 0 votes
hyphens in template file names are important to Drupal. I can't think of a reason why your template doesn't work, because in my experience it probably should.

However, rather than trying to make that work, why not eliminate the hyphens?

```
$variables['theme_hook_suggestions'][] = str_replace(str_replace("-", "", $template_filename);

```

now you can use "page--testpage.tpl.php", which is a file name that Drupal can make sense of.

edit: if you're worried about collisions, replace "-" with something alphanumeric.

---
Tags: theming, path-aliases
---


title: Different customer types

text:
# Question
Title: Different customer types
Is it possible to have multiple customer types within Drupal commerce eg consumer and trade? These would then have different pricing stuctures

# Answer
> 0 votes
Yes, it's just up to you to add the fields or roles to your user accounts and then write product pricing rules to adjust prices through a calculation (10% off for role X) or price swapping from whatever price fields you've added to the product type (base price for normal customers, price 2 for role X, price 3 for role Y). This is just pretty standard Drupal stuff combined with Rules.

---
Tags: commerce
---


# Question
Title: Inserting "sponsored content" into a fixed position in a view
So this is an interesting scenario I'm faced with. Lets say I have a content type called Article. Within that content type there is a term that is tagged as "sponsored." The content type also holds other tags like Chicago, Seattle, San Fran, Etc.

The View I have built is simply time based and shows a feed based on time published of all articles. However I want some special functionality for any article that is tagged as "sponsored." At the moment the feed looks like this...

1) tag

2) tag

3) tag

4) tag

5) tag

6) tag

This means that if an article is tagged as sponsored is simply falls down the list as new articles are added. What I'd like to have happen instead is always FIX the 2 latest sponsored articles (maybe in a node queue) in the second and fifth position. All other articles without the sponsored tag would fall off as normal based on time while the sponsored articles would stay. So you'd get

1) tag

Sponsored

3) tag

4) tag

Sponsored

6)

Can this even be done in views? Should I just think about adding it to the view template file in a custom manor? Thanks

# Answer
I found a pretty great solution that i hope others can use. I simply made a new view with my list of sponsored content in a node queue. I then used the function views\_embed\_view inside my view template of content and displayed each block at a certain row ID whick looked a bit like this:

```
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>
 </div>
 <?php if ($id == 3): ?>
<?php print views_embed_view('sponsored_content','block_1'); ?>
 <?php endif; ?>
 <?php if ($id == 8): ?>
<?php print views_embed_view('sponsored_content','block_2'); ?>
 <?php endif; ?>

```
> 1 votes

# Answer
You can produce a block in a custom module, using hook\_block\_info() and hook\_block\_view() and a content callback for the block, like so:

```
/**
 * Implements hook_block_info().
 */
function YOUR_MODULE_block_info(){
  $blocks = array();
  $blocks['YOUR_BLOCK_DELTA'] = array(
    'info' => t('NICE NAME FOR YOUR BLOCK');
    'cache' => DRUPAL_CACHE_PER_PAGE,
  )
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch($delta){
    case 'YOUR_BLOCK_DELTA':
      $block['subject'] = 'YOUR BLOCK TITLE';
      $block['content']['markup'] = your_block_callback();
      break;
  }
  return $block;
}
function your_block_callback() {
      $position = 3;
      $sponsored = YOUR_SPONSORED_CONTENT;
      $query = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('n.status', 1)
        ->condition('n.type', 'YOUR_CONTENT_TYPE');
      $result = $query->execute();
      $return = '';
      $i = 1;
      foreach ($result as $r) {
         $node = node_load($r->nid);
          $teaser = node_view($node, 'teaser');
          if ($i == $position) {
            $return .= $sponsored;
          }
        $i++;
        $return .= render($teaser);
      }
      return $return;
    }

```

Replace all dummy text like YOUR\_BLOCK\_MACHINE\_NAME with your own names, and place this in your custom module's .module file. You'll have to add some code to fill in YOUR\_SPONSORED\_CONTENT. This will produce a list of teasers. You'll have to add conditions and other logic to the $query, of course.can
> 0 votes

# Answer
I think that you can solve this using the Views UI.

I would probably create a view for your content, containing one page display and two attachments like this:

* The main view display can hold the 2 sponsored items (appropriate filters needed)
* The first attachment display would filter out sponsored items and can hold the first 4 normal items.
* The second attachment display would also filter out sponsored items and can display the next number of normal items. For this you can use the offset setting in the pager options, see the screenshot

The first attachment display would be configured to appear *before* the main content (which are the sponsored items) and the second attachment display would be configured to appear *after* the main content.
> 0 votes

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


# Question
Title: Is there any way to alter the "field type" of a field?
I need to change the field type "file" to "image" in drupal 7. I just hack the database and found a table named "field\_config" and modified the "type" and "module" column, from "file" to "image". I found that it's works correctly.

My question is that, is this the correct way to change the "field type" of the field? Any better answer would be appreciated. Thanks in advance.

# Answer
Drupal itself does not support changing the field type, only the widget. This is because different types have different database structure. On the other hand, it is possible to change *some* types with custom code (e.g. see http://www.up2technology.com/blog/converting-drupal-fields) but in general, you would need to write migration to do this.

So in general, it is not possible to change the field type without loosing the data stored in it, especially not things like text -\> image etc.
> 3 votes

---
Tags: entities, media
---


# Question
Title: How to add <script type="text/template"> in drupal?
I'm using underscorejs function `_.template()` to render html on client side. I found that in many examples, the templates are placed in some `<script type="text/template" id="id">` on the page, and using `$('#id')` to get the templates. like this:

```
<script type="text/template" id="id">
  <div class="form-group row">
    <label for="nickname" class="col-sm-2 control-label text-right">nickname</label>
    <div class="col-sm-10"><span><%= data.subscriber.nickname %></span></div>
  </div>
  <div class="form-group row">
    <label for="sex" class="col-sm-2 control-label text-right">sex</label>
    <div class="col-sm-10"><span><%= data.subscriber.sex %></span></div>
  </div>
  <div class="form-group row">
    <label for="country" class="col-sm-2 control-label text-right">country</label>
    <div class="col-sm-10"><span><%= data.subscriber.country %></span></div>
  </div>
</script>

```

I try build a block to hold these tags, but drupal will break it, lost some tags eventually.

My solution right now drives me crazy: save the template as one line string or concat multiline strings with `\` in js.

I really need a better idea. Thanks.

UPDATE: I found a better idea, using coffee script raw string. From External template in Underscore

# Answer
> 1 votes
New solution:

Create a new format without any html filter at `admin/config/content/formats`. Then good to go :)

# Answer
> 1 votes
You really shouldn't be putting things like that in a drupal block via the UI anyway because someone with permissions could come along and mess it up and then everything breaks.

You can add/remove/change markup on the page by editing the templates in your theme.

For example you could add your template script tag into the page.tpl.php file of your theme.

Assuming you are using the same template on all pages (or a bunch of pages) or you just want a template on a specific page then this is really straight forward.

If you have more complex requirements you might need a large amount of template overrides or you may want to use some code in template preprocess functions in template.php to make things simpler.

For more information on this see Theming Drupal 6 and 7. There is a lot of info in there.

---
Tags: javascript, blocks
---


# Question
Title: IE8 is detecting the pages as mobile media
I am trying to workout why http://www.tradecarsspain.com/ is loading as a mobile page when viewed in IE8 ...

# Answer
> 2 votes
As you haven't provided any information this is a complete guess, based on the assumption that you're using the Omega 3 theme with respond.js.

There's a known issue with IE8, respond.js and CSS aggregation. To fix it, you can implement `hook_css_alter()` in your theme like so:

```
function MYTHEME_css_alter(&$css) {
  // Enable respond.js to work with Omega.
  foreach ($css as $key => $value) {
    if (preg_match('/^ie::(\S*)/', $key)) {
      unset($css[$key]);
    }
    else {
      $css[$key]['browsers']['IE'] = TRUE;
    }
  }
}

```

---
Tags: theming, media
---


# Question
Title: voting in all fields before submit results
I have a content type (computer) with multiple rate fields (performance, battery range, price, ...) type fivestars. By default, the module sends the results by ajax whenever you click on a star; what I need is that you vote in all fields, before the results are sent (with a button).

Is it possible to do this? And how?

# Answer
Actually Berliner was right. To achieve this functionality you need to override the rate module JavaScript.

Below is the code/steps to achieve the same.

1. Create you own module to override the rate module, never touch core/contrib. Let's take our custom module name as `rate_custom`. This is the info file (`rate_custom.info`):

```
name = Custom Rate module
description = Custom module to override Rate module
core = 7.x
package = Voting
dependencies[] = votingapi
dependencies[] = rate
files[] = rate_custom.module
version = "7.x-1.0"
core = "7.x"

```
2. Add the button to the rate widgets to submit their result using hook\_node\_view in our custom module (`rate_custom.module`) like this:

```
/**
 * Implements hook_node_view().
 */
function rate_custom_node_view($node, $view_mode, $langcode = '') {
  if ($view_mode != 'rss') {
    // Adding the button to the node view
    $widgets = rate_get_active_widgets('node', $node->type, $view_mode);
    if (!empty($widgets)) {
      $widget_code = array(
        '#weight' => 51,
        '#markup' => '<button class="rate-submit-button">'. t('Submit Rating') . '</button>',
        '#type' => 'item',
      );
      $node->content['rate_submit_button'] = $widget_code;
      drupal_add_js(drupal_get_path('module', 'rate_custom') . '/rate_custom.js');
      drupal_add_css(drupal_get_path('module', 'rate_custom') . '/rate_custom.css');
    }
  }
}

```
3. Now override rate module's rate submission calls JavaScript in separate JavaScript file (`rate_custom.js`) within our module. Below is the complete code.

```
(function ($) {
  Drupal.behaviors.rate_custom = {
    attach: function(context) {
      // Bind the click event to our submit button.
      Drupal.rateTrack = {};
      $('.rate-submit-button').die('click').live('click', function() {
        var $node = $(this).parents('div.node');
        // Prevent empy submission.
        if (typeof Drupal.rateTrack[$node.attr('id')] === 'undefined' || $.isEmptyObject(Drupal.rateTrack[$node.attr('id')])) {
          alert(Drupal.t('Please rate before submit.'));
          return false;
        }
        // Trigger the saved ratings one by one.
        for (var idx in Drupal.rateTrack[$node.attr('id')]) {
          var widget = Drupal.rateTrack[$node.attr('id')][idx].widget;
          var data = Drupal.rateTrack[$node.attr('id')][idx].data;
          var token = Drupal.rateTrack[$node.attr('id')][idx].token;
          Drupal.rateVote_old(widget, data, token);
        }
        // Empty the tracking variable.
        Drupal.rateTrack[$node.attr('id')] = {};
      });
      // Overriding the rate module's CSS to indicate currently rated result.
      $('.rate-button').die('mousedown').live('mousedown', function() {
        jQuery(this).parent('li').nextAll().find('.rate-button').removeClass('rate-fivestar-mark-filled rate-fivestar-btn-filled').addClass('rate-fivestar-mark-empty');
        jQuery(this).parent('li').prevAll().andSelf().find('.rate-button').removeClass('rate-fivestar-mark-empty').addClass('rate-fivestar-mark-filled rate-fivestar-btn-filled')
      });
    }
  };

  $(document).ready(function() {
    // Re-declare the rateVote function and assign the original function to another variable.
    Drupal.rateVote_old = Drupal.rateVote;
    Drupal.rateVote = function(widget, data, token) {
      var $node = $(widget).parents('div.node');
      // Fallback to original immediate ajax submission, if we're unable to find the rating
      // submit button for the current node.
      if ($node.find('.rate-submit-button').length) {
        if (typeof Drupal.rateTrack[$node.attr('id')] === 'undefined') {
          Drupal.rateTrack[$node.attr('id')] = {};
        }
        // Store the rating in the local variable by node and rate widget, so that user can
        // rate multiple nodes and modify their votes.
        Drupal.rateTrack[$node.attr('id')][$(widget).attr('id')] = {
          widget: widget,
          data: data,
          token: token
        };
        $(".rate-info", widget).text(Drupal.t('Please submit the rating to save it!'));
        return false;
      }
      else {
        return Drupal.rateVote_old(widget, data, token);
      }
    }
  });
})(jQuery);

```
4. Add the custom CSS (`rate_custom.css`) to override the rate module's CSS to indicate current result (Adjust the file paths as per your configuration).

```
.rate-fivestar-mark-filled {
  background: url("/sites/all/custom/modules/rate/templates/fivestar/fivestar.png") no-repeat 0 -16px !important;
}

.rate-fivestar-mark-empty {
  background: url("/sites/all/custom/modules/rate/templates/fivestar/fivestar.png") no-repeat 0 -32px !important;
}

```

Finally we're done with it, just go and enable your module. Now unless you click on "Submit Rating" your rating won't get submitted.

Note: I wrote this for the fivestar widget alone. Also check all the possible scenarios.
> 3 votes

# Answer
The only way I can think of to do this is to override the javascript function `Drupal.rateVote` which is declared in the file `rate.js`. It would require considerable work to achieve what you want.

You can have a look at this question where someone else had to override a javascript function from a contrib module.
> 5 votes

---
Tags: 7, entities, rating
---


# Question
Title: Assigning a badge to a user using Flag, Badges and Rules
I am interested in assigning to user a Badge after he favorites 3 nodes. I want to do this with Flag, User badges and Rules.

How can I do that?

# Answer
I would use the Goals module for this.

1. Create a 'Favorite node' task and a 'Favorited 3 nodes' goals.
2. Add an image to the goal. This is going to be your badge.
3. Create an 'Add to favourites' flag.
4. Create a rule that "records a task for goals" when a node is "flagged under 'Add to favourites'".
5. If you don't really need the User badges module, you can create an image field called 'Badge' for the users and use the following custom module (you can find more information here):

```
function MYMODULE_goals_completed_goal($goal_id, $uid) {
   $user = user_load($uid);
   $goal = goals_load($goal_id);
   $fid = $goal->goal_img['und'][0]['fid'];
   $img_title = $goal->goal_img['und'][0]['filename'];

   $edit = array();
   $edit['field_badge']['und']['0']['fid'] = $fid;

   user_save($user, $edit);
}

```
6. If you really need the User badges module, I think you can adapt the code a bit and everything should work fine.
> 0 votes

---
Tags: 7, users, rules, flags
---


title: Creating a page dynamically

text:
# Question
Title: Creating a page dynamically
Using Views in Drupal 7 I can consume the output of a restful API. I want to take some of the data and dynamically create pages. For example I get the following return json:

```
$data = {'title':'This is a page title','alias':'pages/page-alias-name','content':'This is some content'}

```

I would want to dynamically create a page located at http://www.example.com/pages/page-alias-name which would have a title of $data\['title'\] and the content would be $data\['content'\]. Is it possible to create pages dynamically like this. How can I go about doing this?

Additionally, if I had identical content stored in an external database that can be read by a custom Views module, can I do this and how would I go about it?

# Answer
> 1 votes
I'm not sure how you are using Views to do this, but with a custom module you could easily do this with a fairly simple hook\_menu(), eg, something along these lines:

```
function YOURMODULE_menu() {

  $items=array();

  $items['pages'] = array(
    'page callback' => 'YOURMODULE_get_some_rest',
    'access callback' => TRUE,
  );

  // any other menu items go here

  return $items;

}

```

and then:

```
function YOURMODULE_get_some_rest() {

  $args=func_get_args();

  if ($args) {

    $alias='pages/' . implode('/', $args); // so pages/foo works as does pages/foo/bar etc

    $data = /* get your data from your external service */ ;

    if ( /* $data was found */ ) {

      drupal_set_title( /* title in $data */ );

      return /* content in $data */ ;

    } else {

      return MENU_NOT_FOUND; // we don't have an alias of that name

    }

  } else {

    return MENU_NOT_FOUND;  // just called 'pages' so do something else here if need be, perhaps a list of all pages but for now, we just return not found

  }

}

```

so after a cache clear, users should now be able to go to `www.example.com/pages/alias` and Drupal will go out to your external service and grab the content and if found, populate the page with it, otherwise will return not found.

Now, if this data is going to be fairly static, I'd look into caching it so your users aren't delayed while Drupal fetches it. For that, I'd look into cache\_set() and cache\_get().

ADDITION:

Drupal's menu system works on a sort of best fit methodology. For example, if you define a menu item `foo`, it will obviously match `www.example.com/foo`, but, if no menu item has been defined for `foo/bar`, it will also match `www.example.com/foo/bar` or even `www.example.com/foo/bar/baz/bing` etc etc.

So, in my example above, I defined `pages`. This will match `www.example.com/pages` which is just an error condition above, but with some programming could list all of the potential pages you have available to you, but also will match `www.example.com/pages/alias-of-page` or `www.example.com/pages/alias/of/page`.

Inside the callback, I use PHP's built-in function func\_get\_args() to deal with the variable number of arguments that can be passed to this function. When you go to `www.example.com/pages`, no arguments will be passed to this callback and `func_get_args()` will return an empty array. But, when you go to `www.example.com/pages/alias-to-page`, Drupal will automatically pass `alias-to-page` to the callback, and `func_get_args()` will return an array containing it, and when you go to `www.example.com/pages/alias/to/page`, it will pass three arguments, `alias`, `to`, and `page` to the callback function and `func_get_args()` will return an array containing all three.

As to your commentary question regarding this inside Views, once again, I'm not sure how your are doing this inside Views, but yes, this would go inside YOURMODULE.module and would stand alone outside of Views (although Views might be a great place to generate the listing on `pages` by itself).

---
Tags: views, path-aliases
---


# Question
Title: How to get total of a field for all the nodes?
I've `payment` content type. One of the fields of this content-type is `Amount`. In a view (page display: table format) I'm listing all the payment nodes (subjected to some filtering). In the same view I want to calculate the total amount amount of all these filtered nodes & display. How?

# Answer
You should be able to use Views Calc or, if you need more flexibility, Views Aggregator Plus
> 3 votes

---
Tags: 7, views
---


# Question
Title: Drupal installation creates innoDB tables even though myIAM is set as default in my.ini
Drupal installation creates innoDB tables even though myIAM is set as default in my.ini

whenever i install a new Drupal 7.26 on my XAMPP (ApacheFriends XAMPP Version 1.8.2) running under Windows 7 I get innoDB tables in my database.

I put the following line in my my.ini file under \[mysqld\]

default-storage-engine=MyISAM

But still - after installing Drupal the tables are all innoDB?

What is is that i do wrong?

# Answer
> 1 votes
Drupal overrides the default to set it to innoDB because innoDB is a better choice for Drupal in many cases. Two main reasons for this:

1. InnoDB supports transactions; MyISAM doesn't.
2. When a row in a MyISAM table is being updated, the entire table is locked, so no other process can write to it. InnoDB locks rows in tables, rather than entire tables. For example, on this site, if many people are writing to the comments table at the same time, they would have to wait in a queue if the table were myISAM, but with innoDB, multiple writes can happen simultaneously, provided they're not to the same row in the table. This has obvious performance ramifications.

If you absolutely have to, you can edit the information schema table in mysql to set all the tables to MyISAM, but make sure you know what you're doing...

---
Tags: database
---