title: Instant Drupal documentation

text:
# Question
Title: Instant Drupal documentation
I am on Drupal 7. I would like to ask if you know of any Drupal modules or tools that will 'spit' (sorry for using this term) an instant documentation of a given Drupal install (Drupal version, installed modules list, installed modules versions and maybe some more information). Thank you!

# Answer
I'm not sure about one module to do it all, but Enabled Modules will show you the list of modules and their versions.

To view a sites status, and Drupal version, you can log in and visit admin/reports/status
> 1 votes

# Answer
Drush is your best tool for this..

> Drush is a command line shell and Unix scripting interface for Drupal.

For Example

```
drush status

```

Provides a birds-eye view of the current Drupal installation.

Drupal version : 7.22
Site URI :
Database driver : mysql
Database username : root
Database name : d7
Database : Connected
Drupal bootstrap : Successful
Drupal user : Anonymous
Default theme : bartik
Administration theme : seven
PHP configuration :
Drush version : 6.0-beta1
Drush configuration :
Drush alias files : /Users/Anilsagara/.drush/pantheon.aliases.d rushrc.php
Drupal root : /Applications/MAMP/htdocs/d7
Site path : sites/default
File directory path : sites/default/files
Private file directory path : sites/default/files/private
Temporary file directory path : /Applications/MAMP/tmp/php
> 1 votes

---
Tags: 7
---


# Question
Title: Rules - send email when users role changes to x
I need to send an email when an admin changes a users role to role x. The email should not be sent if the users role is already role x and 'save' is pressed on the user page.

I have set up a rule:

Event: After updating an existing user account

Actions: Send mail

This works fine. Then I add a condition of type 'data comparison' account(updated user):roles with the operator 'equals' and the data value 'role x'. But for some reason the email now never sends when I change the user role to 'role x' and resave. I'm confused about why this is not working.

Then once this is fixed I assume I'll need to negate the condition that the account(unchanged user):roles equals 'role x'

# Answer
Key according to me will be

Using condition as User has Roles choose "x" as user role and negate it.

An example export goes here.

```
{ "rules_update_user_role" : {
    "LABEL" : "Update User Role",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "account-unchanged" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Changed User!" } } ]
  }
}

```
> 2 votes

# Answer
Arpitr got me on to the correct solution for this. Here is the code that you can import:

```
{ "rules_update_user_role" : {
"LABEL" : "Update User Role",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_update" : [] },
"IF" : [
  { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "7" : "7" } } } },
  { "AND" : [
      { "NOT user_has_role" : {
          "account" : [ "account-unchanged" ],
          "roles" : { "value" : { "7" : "7" } }
        }
      }
    ]
  }
],
"DO" : [ { "drupal_message" : { "message" : "Changed User!" } } ]

```

} }

I like the way arpitr used a drupal message for testing if the rule had worked - i didn't realise you could do this.

It looks like the mistake I might have been making was to use the condition of type 'data comparison' and then try to drill into it to get to the user role rather than just using the 'user has role' condition. I think when i had tried previously to use the 'user has role' condition it failed because I made the used 'account:roles' rather than just account.

Hope this helps someone else.
> 5 votes

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


# Question
Title: Is there a way to set the styling for the "choose file" button for Webform module?
I've not been able to figure out how to isolate the "choose file" button that's set in file upload field for webform module. I can style the field, but I can't get the button. I've looked all of the place, but can't find anything on getting anything on that specific button. This is a D7 site using the 7.x-3.18 version of webform.

It would be great if I could add a class, but if I could just get ahold of it in some way that doesn't affect the entire field that would be ideal.

Here is the output:

```
<input type="file" id="edit-submitted-resume-upload" name="files[submitted_resume]" size="22" class="form-file">

```

The ID handles the entire field and I've been able to do a little with that, but can't use it to control that button.

Any ideas?

Thanks in advance.

# Answer
> 3 votes
Yes, actually styling a **FILE INPUT field** is hard because, just like you're seeing, it's a singular field that is hard to pick apart.

Here is a discussion of styling file input fields from stackoverflow.

As you can see - thought there are many solutions presented, they all require some jquery and essentially hide the input field and replace it with something else.

So in short - there is no easy way to do it.

# Answer
> 0 votes
There is no way to style the file upload button using CSS that is 100% cross platform. The only way is to replace the file upload button with another button and use javascript.

Something like http://blueimp.github.io/jQuery-File-Upload/ for an example.

# Answer
> 0 votes
```
(function ($) {
  Drupal.behaviors.autoUpload = {
    attach: function(context, settings) {
      var fakeFileUpload = document.createElement('div');
      fakeFileUpload.className = 'fakefile';
      fakeFileUpload.appendChild(document.createElement('input'));
      var image = document.createElement('img');
      image.src='/sites/all/themes/custom/helix/heliximages/upload.png';
      fakeFileUpload.appendChild(image);
      var x = document.getElementsByTagName('input');
      for (var i=0;i<x.length;i++) {
        if (x[i].type != 'file') continue;
        if (x[i].parentNode.className != 'image-widget-data') continue;
        x[i].className = 'file hidden';
        var clone = fakeFileUpload.cloneNode(true);
        x[i].parentNode.appendChild(clone);
        x[i].relatedElement = clone.getElementsByTagName('input')[0];
        x[i].onchange = x[i].onmouseout = function () {
          this.relatedElement.value = this.value;
        }
      }
    }
  };
})(jQuery);

#mycontenttype-node-form div.image-widget-data {
    position: relative;
}

#mycontenttype-node-form div.fakefile {
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 1;
}

#mycontenttype-node-form input.file {
    position: relative;
    text-align: right;
    -moz-opacity:0 ;
    filter:alpha(opacity: 0);
    opacity: 0;
    z-index: 2;
}

```

---
Tags: 7, webforms, theming
---


# Question
Title: A More Efficient Embedding Method for YouTube Videos
I have created a video gallery comprised of embedded YouTube videos using the Media: YouTube Module. Everything works as expected, but the page load is slow. This is a common issue when embedding many YouTube videos on a page.

Amit Agarwal proposed this solution on his blog which drastically reduces load time. Is there a way to do this with the current Module or custom scripting?

# Answer
> 0 votes
Yeah, you can essentially follow that approach in Drupal. I have used a variant on it.

In a `MYTHEME_preprocess_html()`, do a `drupal_add_js()` to load in the YouTube Javascript API.

Field out the video media type to add an image if you don't want to use the default YouTube thumbnail.

Create and edit media-youtube-video.tpl.php for your theme; the default is in the media\_youtube module folder. Make the markup match what you want.

Write a `MYTHEME_preprocess_media_youtube_video()` function to add in any addtional `$variables` that you may need in your template, like the image if you added one.

Then add a Javascript behavior to `.media-video-wrapper` so that when the user clicks on the thumbnail, the YouTube video is dynamically created. You probably also want to add some logic to destroy other videos on the page.

This is actually way easier than it sounds if you are comfortable with PHP for themes.

---
Tags: media, files
---


# Question
Title: Dynamic content generated via a PHP Filter field is not being indexed by Google
We just moved to Acquia Cloud hosting and we've realized that a few of our pages aren't being indexed by Google.

There is a distinct difference about these pages that is probably at least related to the cause and that is that these pages are generated by PHP encapsulated in the body field of a page node. Said PHP queries a non-acquia database and builds the page. The important piece of this is that the page looks at GET variables to build the query string, namely a variable called 'id'. The URL is then the page node's alias concatenated with ?id=XXX where XXX is the id of the element for which to query.

I know this is by no means best-practice for a page node and we are in the process of converting this functionality to module but, for now, we have what we have.

When I 'curl -IL' one of these pages with the ?id=XXX appended (i.e. http://www.domain.com/site/aliasPart1/aliasPart2?id=XXX), I find in the return:

Link: http://www.domain.com/site/node/24490; rel="shortlink",http://www.domain.com/site/aliasPart1/aliasPart2; rel="canonical"

the GET variable is getting truncated!

It looks like *that's* why Google isn't indexing these pages. My question for all of you is: is this why Google is not indexing these pages? If so, what can I do to fix it?

Thanks, Tim

# Answer
> 0 votes
Figured this one out.

In the Meta Tags \> Advanced section of the page node,

I've set Canonical ULR to: \[current-page:url:absolute\]?id=\[current-page:query:id\]

and Shortlink URLto: \[current-page:url:unaliased\]?id=\[current-page:query:id\].

---
Tags: uri
---


# Question
Title: How do i run node save in background process
I have created drupal website for ecommerce store.

Issue: After node save i will redirect to thankyou (destination) page for tracking but it takes long time to complete. Customer may skip if it takes long time to complete the process.

How do i run node save in background process and display thankyou page immediately after placed order.

I want to track order conversions and node save.

Please help me to resolve this issue.

Thanks, Yadavan

# Answer
You can instead of saving the node directly, modify the node object with attributes from the form and then add it to a queue so you can use the Drupal queue system to do the actual `node_save()` operation on it.
> 0 votes

---
Tags: nodes
---


# Question
Title: Creating quicktabs prorgammatically: code worked in D6 not in d7
I created a custom quicktabs module in drupal 6 that adds a block, and it is working just fine. Before moving it over to drupal 7, I edited the module and info files accordingly, but the module displays no block on `admin/structure/block` and the version of the module doesn't appear on `admin/modules`.

I have added the feeds and their blocks are displaying content and the bids are identical in both versions of the site.

I have read this and this and even tried this, but haven't found the solution. I have run cron and cleared cache when you would be expected to.

If I add a `print_r($tabs)` I get an array with all of the array pieces as designated below for the right days.

**quicktab\_custom.info file**

```
name = quicktab custom
description = custom quicktab block for event data
core = 7.x

```

**quicktab\_custom.module file**

```
/**
 * Implements hook_block().
 *
 * We want to define a quicktabs block.
 */
function quicktab_custom_block($op = 'list', $delta = 0, $edit = array()) {

switch($op) {
// 'list' shows the items in admin/build/block admin page
// we alsohave: configure, save, view
case 'list':
  $blocks['quicktab_custom_quicktabs'] = array(
    'info' => t('events this week'),
    'cache' => BLOCK_NO_CACHE,
  );
  return $blocks;
  break;
case 'view':

  switch ($delta) {
    case 'quicktab_custom_quicktabs':
     $today = date('D');

      //set tab content
      $tabs[] = array(
        'title' => t($today),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-14',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +1 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-15',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +2 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-16',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +3 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-17',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +4 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-18',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +5 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-19',

      );
      $tabs[] = array(
        'title' => t(date('D',strtotime($today . ' +6 day'))),
        'type' => 'block',
        'bid' => 'aggregator_delta_feed-20',

      );

      $quicktabs['qtid'] = 'quicktab_custom_quicktabs'; // machine readable name
      $quicktabs['hide_empty_tags'] = TRUE;     // hide tabs that are empty
      $quicktabs['default_tab'] = $today;   // set the default tab
      $quicktabs['tabs'] = $tabs;       // all tabs with content
      $quicktabs['style'] = 'Navlist';      // tabs theme -- originally set to Sky
      $quicktabs['ajax'] = FALSE;       // ajax or not
      $block = array('subject' => '', 'content' => theme('quicktabs', $quicktabs));

      return $block;
      break;
  }
 }
}

```

# Answer
According to this comment on the hook\_block() docs,

> Drupal 7 doesn't use anymore hook\_block(), but it uses a set of new hooks; see Converting 6.x modules to 7.x for more details.
> 1 votes

---
Tags: 7
---


# Question
Title: stream wrapper public /private not found Error
Configuration : WAMP on windows drupal 7

I have tried using

```
$image = file_get_contents('E:\Team_Install\wamp\www\rootfolder\sites\all\modules\my_module\errorwinmobilesdk.jpg');
$file = file_save_data($image, 'public://',FILE_EXISTS_REPLACE);

```

I can see the result after first line `file_get_contents` but on `file_save_data` I get that destination folder invalid error

Another method I had tried was `$file = file_copy($source, $dest);`

here also it says $dest does not exists Wrapper folder permission and path are check thorughly they are working when I add an image using media\_gallery module as it saves to public gallery or creates a new article with image, when I try to add from code it breaks and start showing message

> The data could not be saved because the destination public is invalid. This may be caused by improper use of file\_save\_data() or a missing stream wrapper.

Please help I am new to drupal and stuck at this.

Thanks in advance

# Answer
I had this problem too after some coding with file\_save\_data. And i solve it after clearing the cache and resaving the path in the file system configuration at admin/config/media/file-system.

My problem comes from an add field of file type, programmatically in an update.
> 0 votes

---
Tags: 7, stream-wrappers
---


# Question
Title: How can i maintain pagination with filter using tableselect?
I am creating listing of content using tableselect form type like as follow.

```
function partners_list($form,&$form_state){
        $header = array(
            'name'=>array('data' => t('Name'),'field' => 'ept.name'),
            'location'=>array('data' => t('Location'),'field' => 'ept.location'),
        );

        $form['search_ew_partner'] = array(
            '#type' => 'textfield',
            '#prefix' => '<div class="serachOuter "><div class="grayBg"><div class="searchInner clearfix"><div class="searchField pull-left">',
            '#suffix' => '</div>',
            '#default_value'=> $form_state['values']['search_ew_partner'],
            '#attributes' => array(
                'placeholder' => 'Search by name'
            )
        );

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

            '#prefix' => '<div class="btnOuter clearfix">',
            '#suffix' => '<a href="/partners/list" class="btn grayBtn">Reset</a></div></div></div></div>',

            '#attributes' => array(
                'class' => array('btn blueBtn')
            )
        );

        if(empty($form_state['input'])){
            $results = partners_list_submit($form,$form_state);
            $results=$results['filter_result'];
        }else{
            $results=$form_state['filter_result'];
        }

        $options = array();
        if(!empty($results)){
            foreach($results as $result){
                $options[$result->id] = array(
                    'name' => array('data' => array('#type' => 'link', '#title' => $result->name, '#href' => "partner/details/".$result->id)),
                    'location' => ucfirst($result->location),
                );
            }
        }

        $form['ew_partners'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $options,
            '#empty' => t('No partners.'),
            '#attributes' => array(
                'class' => array('table')
            )
        );

        $form['pager'] = array('#markup' => theme('pager'));
        return $form;
    }

    function partners_list_submit(&$form,&$form_state){
        $form_state['rebuild'] = true;
        $header = array(
            'name'=>array('data' => t('Name'),'field' => 'ept.name'),
            'location'=>array('data' => t('Location'),'field' => 'ept.location'),
        );

        $query = db_select('ew_partners', 'ept');
        if(!empty($form_state['values']['search_ew_partner'])){
            $query->condition('ept.name', '%' . $form_state['values']['search_ew_partner'] . '%', 'LIKE');
        }

        $query = $query->extend('PagerDefault')->extend('TableSort');
        $query->fields('ept',array('id','name','location'));
        $query->limit(2)
            ->orderByHeader($header);

        $results = $query->execute();
        $form_state['filter_result']=$results;
        $form_state['no_cache'] = true;
        return $form_state;
    }

```

Listing and pagination coming properly when there is no filtration on table. After filtration, pagination is not working. **I think due to form\_state values are reset when I clicked on next page.** The page count and the result for first page is coming properly.

**How can i maintain pagination with filter using tableselect?**

Thank you in advance Any help appreciated.

# Answer
> 5 votes
The search form method type is post thats why when you are submitting the search form the form values are sending as post therefore the form values are coming properly for first page. When your are clicking on second page the form state values are reseting with new form state values as form has default value.

So rather than using post method form I will suggest to use get method type form for search so that the search keyword will always persist in url.

So you have to add

```
$form['#method'] = 'get';

```

Access all filtered values using $\_GET like

```
$form['search_ew_partner'] = array(
            '#type' => 'textfield',
            '#prefix' => '<div class="serachOuter "><div class="grayBg"><div class="searchInner clearfix"><div class="searchField pull-left">',
            '#suffix' => '</div>',
            '#default_value'=> $_GET['search_ew_partner'],
            '#attributes' => array(
                'placeholder' => 'Search by name'
            )
        );

```

And change your code like

```
if(!empty($_GET['search_ew_partner'])){
            $query->condition('ept.name', '%' . $_GET['search_ew_partner'] . '%', 'LIKE');
        }

```

---
Tags: forms
---


# Question
Title: Problem with aggregated CSS/JS on flush cache
We are using Varnish and Pressflow (v6.30). Every time we flush cache in Drupal, we encounter problems where browsers can not get requested CCS/JS aggregate files as they do not exist. We have found that if we flush Drupal cache and then immediately flush varnish cache, problem is fixed.

Anybody else had this issue? And is there a module (purge or similar) which automatically handles Varnish flush cache with Drupal cache?

# Answer
> -1 votes
https://drupal.org/project/advagg might be the solution you're looking for.

If you want to flush both caches this will help https://drupal.org/project/expire

---
Tags: 6, css-js-aggregation, proxies
---


# Question
Title: How to conditionally render fields with a different formatter
I have a content type with two fields one called display which is a simple list and the other is an entityreference field.

I would like to change how the entity reference field is rendered depending on which option is selected in the first field.

I have custom formatters installed and I have created two custom formatters so I need a way of changing the #formatter based on the result in the first field.

I've tried a hook\_preprocess\_node() and also changing it in a custom tpl file but neither seem to render the field any differently to how it is set in the manage field UI.

# Answer
> 0 votes
In the end I did this in the tpl file for my content type using field\_view\_field(), I hide both fields the one that contains the option and the second that contains the data. I then use a case statement to set the correct formatter.

```
  hide($content['field_display_mode']);
  hide($content['field_link']);
  print render($content);
  $links_display_mode = $content['field_display_mode']['#items']['0']['value'];
  switch($links_display_mode) {
    case 1:
      $links_formatter = 'custom_formatters_entry_form_display_one';
      break;
    case 2:
      $links_formatter = 'custom_formatters_entry_form_display_two';
  }
  $field_link = field_view_field('node', $node, 'field_link', array('label' => 'hidden', 'type' => $links_formatter));
  print render($field_link);

```

# Answer
> 0 votes
I would try using the Context module API and adding a new reaction plugin.

---
Tags: entities, theming
---


# Question
Title: jQuery only effecting first node in slideshow
I have applied a jQuery plugin \[textfill\]\[1\] to certain elements within my a view and a view-slideshow. I have locally linked the relevant .js file via the .info file.

In the view-slideshow the first node is only effected However in my other view all nodes are.

Within the views-slideshow i have attached the jQuery targeted class '.textfill' class through the views 'global: custom text field' and have added a div to the corresponding replacement pattern. With the normal view i have attached the class to the desired field via the corresponding field tpl.php file.

Here's what it looks like: https://i.stack.imgur.com/nMOEw.jpg

This is the plugin:

```
; (function($) {
$.fn.textfill = function(options) {
var defaults = {
  debug: false,
  maxFontPixels: 40,
  minFontPixels: 4,
  innerTag: 'a',
  widthOnly: false,
  callback: null,
  complete: null,
  explicitWidth: null,
  explicitHeight: null
};
var Opts = jQuery.extend(defaults, options);

function _debug_sizing(prefix, ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels) {
  if (!Opts.debug) {
    return;
  }

  function _m(v1, v2) {
    var marker = ' / ';
    if (v1 > v2) {
      marker = ' > ';
    } else if (v1 == v2) {
      marker = ' = ';
    }
    return marker;
  }

  console.debug(
    prefix +
    'font: ' + ourText.css('font-size') +
    ', H: ' + ourText.height() + _m(ourText.height(), maxHeight) + maxHeight +
    ', W: ' + ourText.width()  + _m(ourText.width() , maxWidth)  + maxWidth +
    ', minFontPixels: ' + minFontPixels +
    ', maxFontPixels: ' + maxFontPixels
  );
}

function _sizing(prefix, ourText, func, max, maxHeight, maxWidth, minFontPixels, maxFontPixels) {
  _debug_sizing(prefix + ': ', ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  while (minFontPixels < maxFontPixels - 1) {
    var fontSize = Math.floor((minFontPixels + maxFontPixels) / 2)
    ourText.css('font-size', fontSize);
    if (func.call(ourText) <= max) {
      minFontPixels = fontSize;
      if (func.call(ourText) == max) {
        break;
      }
    } else {
      maxFontPixels = fontSize;
    }
    _debug_sizing(prefix + ': ', ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  }
  ourText.css('font-size', maxFontPixels);
  if (func.call(ourText) <= max) {
    minFontPixels = maxFontPixels;
    _debug_sizing(prefix + '* ', ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  }
  return minFontPixels;
}

this.each(function() {
  var ourText = $(Opts.innerTag + ':visible:first', this);
  // Use explicit dimensions when specified
  var maxHeight = Opts.explicitHeight || $(this).height();
  var maxWidth = Opts.explicitWidth || $(this).width();
  var oldFontSize = ourText.css('font-size');
  var fontSize;

  if (Opts.debug) {
    console.log('Opts: ', Opts);
    console.log('Vars:' +
      ' maxHeight: ' + maxHeight +
      ', maxWidth: ' + maxWidth
    );
  }

  var minFontPixels = Opts.minFontPixels;
  var maxFontPixels = Opts.maxFontPixels <= 0 ? maxHeight : Opts.maxFontPixels;
  var HfontSize = undefined;
  if (!Opts.widthOnly) {
    HfontSize = _sizing('H', ourText, $.fn.height, maxHeight, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  }
  var WfontSize = _sizing('W', ourText, $.fn.width, maxWidth, maxHeight, maxWidth, minFontPixels, maxFontPixels);

  if (Opts.widthOnly) {
    ourText.css('font-size', WfontSize);
  } else {
    ourText.css('font-size', Math.min(HfontSize, WfontSize));
  }
  if (Opts.debug) {
    console.debug('Final: ' + ourText.css('font-size'));
  }

  if (ourText.width() > maxWidth || ourText.height() > maxHeight) {
    ourText.css('font-size', oldFontSize);
  }
  // call callback on each result
  if (Opts.callback) Opts.callback(this);
});

// call complete when all is complete
if (Opts.complete) Opts.complete(this);

return this;
};

})(jQuery);

```

this is my other .js file

```
jQuery(function(){
   jQuery('.textfill').textfill({ maxFontPixels: 200 });
});

```

*i also should note that i am a relative beginner to drupal aswell as using stackerexchange*

# Answer
> 0 votes
If you are trying to affect all nodes within the view, why not iterate over all the nodes using jQuery to add your class? Ex.: `$('selectors for nodes inside view').addClass('textfill');` This is like calling `.each()`, except the iteration is implicit. Then, after you search the DOM and add the classes you want, call `$('.textfill').textfill();` .

# Answer
> 0 votes
I had the same problem using the Views Slideshow: jquery Cycle, I resolved it by adding : **"display:block !important"** in my css file. The problem was caused by textfill not able to evaluate the height and width of the divs that are hidden dynamically by the jquery plugin. Since the slides are displayed "position:absolute" in my design, that change did not affect the rendering of the slider, and now all the text in every slides are getting resized.

---
Tags: javascript, views
---


title: Identifying tags with no content tagged

text:
# Question
Title: Identifying tags with no content tagged
For my job site, jobs are tagged from terms of Tags vocabulary where new ones can be added. Sooner jobs expire and new arrive.

That has resulted in bloated taxonomy vocabulary with 2400 terms (or 2400 pages). I guess many remain empty for long periods.

Many tag pages simply show no classified content available which has attracted Google's Panda penalty.

What I want is removing those tags not used for any node, and automatically deleted those that have not been used in the past 3 months or so get.

Is there any simple way for doing this?

# Answer
> 1 votes
I have a similar script that I use, but I run it as a `drush scr`. You can adapt it for your needs, perhaps to do this in a `hook_cron()`:

```
$tags = taxonomy_vocabulary_machine_name_load('tags');

$tids = db_query('
  SELECT DISTINCT t.tid
  FROM {taxonomy_term_data} t
  LEFT JOIN {taxonomy_index} i ON i.tid = t.tid
  WHERE t.vid = :vid
    AND i.tid IS NULL
', array(':vid' => $tags->vid))->fetchCol();

if (!empty($tids)) {
  foreach ($tids as $tid) {
    taxonomy_term_delete($tid);
  }

  watchdog('foo', 'deleted @count orphaned tags', array(
    '@count' => count($tids),
  ), WATCHDOG_NOTICE);
}

```

**This exact version is untested and a hand-edit from a very specific use-case I have. Take backups and use at your own risk!**

The only problem is that `{taxonomy_term_data}` doesn't have a `created` column, so this will immediately delete orphaned terms. It also doesn't take into term hierarchy, or tags being on entities other than nodes.

---
Tags: taxonomy-terms
---


# Question
Title: How to alert views output using custom module
I am using hook\_views\_pre\_render() in order to calculate some values based on my $view-\>result and I can see how I can manipulate the arrays and I'm achieving some success with being able to drupal\_set\_message() my variables to the screen. However, I'm trying to actually alter the HTML output in the view - is this possible through the custom module?

I currently have a multi value field and in my Views table, I have a field for students which lists my students (nodes) in an unordered list - I'd actually like to only show the first student name and add "+ 8 more" (if there are 9 students altogether). While I can sort of drupal\_set\_message my variables - I'm unsure how you'd actually send this information to the view itself? Do you have to store the variables in the custom module and then send them to tpl.php files in Views?

I know this is possible using a pre made module but I'd rather know how it works myself. I'm just struggling to see how you output these things into the view itself using a custom module.

Here is an image:

Cheers, Garry.

# Answer
`hook_views_pre_render()` gets the `$view` object passed by reference. This means that if you change the `$view` object inside your `hook_views_pre_render()` function, it doesn't need to be `return`ed or saved or re-executed or anything. The view object itself, the same one that is rendered, is the one you're altering.
> 3 votes

---
Tags: views, 7
---


# Question
Title: Term order when saving a new taxonomy term
By default when you're saving a new taxonomy term it's placed by the alphabetical order, how to make newly added terms to appear below the existed terms? Or even highlight it? Because i have like 200 terms and it's hard to manage it when you're adding a new term.

# Answer
> 1 votes
while I am not aware of a solution that will get you this exactly behavior without spending a bunch of time on a unique setup, there maybe a simple workaround for you to quickly identify the new term and move it to whereever it belongs to.

but first of, the definition or new terms being sorted alphabetically is not entirely true. by default, newly added taxonomy terms have a Weight of '0'. this Weight value serves as the first sort criteria: terms with a higher Weight value will be further down, as will terms with a lower Weight value (can be negative too) appear further up in the list. only when multiple terms share the same Weight value, they further get sorted alphabetically.

you can see the exact Weight value for every term by clicking *Show row weights* just above the top right-hand corner of the table.

so if you have a taxonomy vocabulary where all terms have a Weight of -1 and below, newly added terms will be found at the very bottom of the list.

while this will put new terms to the very end of a list, setting up a list this way may be rather tedious, as you might run out of negative numbers or simply because managing 200+ entries this way can be a pain in the butt. instead, there is another approach I find myself using most of the time:

there are two View Modes managing Weights: one enables you to manually define a Weight value via a select list (the 'show row weights' mode mentioned above), and the other one lets you sort individual terms via dragging and dropping by clicking on the cross/drag cursor on the very left of each term. when you manually define a term order by dragging and dropping (dont forget to hit *Save*!), every term will be given a unite Weight value starting by 0.
this means only the very first term will have a Weight of 0. the second term will have a Weight of 1, the third gets a Weight of 2 and so forth.
when you now add a new term, it will be assigned the weight of 0 as well, placing it as either the very **first or second term** in the list. this will enable you to find it immediately and place it wherever you need it to be.
if you find yourself wanting to place that new term at the very bottom, dragging it all the way down can be tedious as well, so a quicker way now would be to enable *Show row weights* again, just pick the lowest value and hit Save.

again, maybe this is not exactly what you are looking for, depending on whether you actually care about the order they are listed, or just want to identify the newest entry.

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


# Question
Title: What can I do with content types that I can't with taxonomies?
I'm starting with Drupal and comparing `taxonomies` and `content types` and from what I see, they both:

* offer a URL via the `Name/Title` field
* have the same list of field types (`images`, `double-field`, `text`...)
* can refer each other (with `node/term` reference)
* have translation (with the proper translation modules enabled)

Therefore I seem able to create the same content via `taxonomies` as with `content types`.

However, `taxonomies` seem tightly integrated with views, offering categorization and filtering, unlike `content types`, which brings me to the following question:

**What's the point of using content types at all, is there anything we can do with content types that we can't do with taxonomies?**

# Answer
> 4 votes
Taxonomies allow hierarchical nesting of items in vocabularies, and each term can only be in one position and one vocabulary at a time.

Nodes, however, can be tagged with any number of terms from any number of vocabularies.

Tagging taxonomy terms with other terms from other taxonomies, or with other terms from within the same taxonomy could potentially have very different results than maintaining a separation between terms (descriptors) and nodes (content that can be described), especially when it comes to using something like Views to sort and separate content based on descriptors.

So it's not so much that content types can do things that terms can't, as it is that content types cannot do as many things that nodes ought not do.

---
Tags: taxonomy-terms, nodes
---


title: settings.php displays in browser

text:
# Question
Title: settings.php displays in browser
For all the Drupal sites I run except one, requesting /sites/default/settings.php in the browser results in a blank page, which seems right and proper.

But for one of my sites (on a different host), requesting /sites/default/settings.php actually results in the file's contents being served to the browser.

I have no idea where the trouble might be: is this a Drupal problem? Apache problem? Doesn't seem to be related to file permissions. How can I ensure that a request to settings.php doesn't serve the file?

As a stopgap measure I've added a line in .htaccess that generates a 410 error when settings.php is requested, but I'd really like to know how this is *supposed* to work...

# Answer
According to this Stackoverflow question you might need to add this to your server configuration:

```
AddType application/x-httpd-php .php

```

Another possibility is an encoding problem, according to this other Stackoverflow question.
> 2 votes

---
Tags: security, configuration
---


# Question
Title: Blank pages or wsod on a recently migrated site to a godaddy server only after logging in
Just recently I finished my friend's site on my local wamp server. Looks great on that server. Now I tried to migrate the site to a Godaddy shared hosting account. I was able to get it all setup with the database up to date and everything, but the second I log in the the backend of Drupal, it white screens. Again tried a different browser, the site came up fine until I logged into the admin again. At this point I can't get any page to load, not even the home page. I can delete my cookies in the browser to log myself out but that's about it. So stumped its not even funny...

# Answer
I solved it!

The PHP version on the live Godaddy server was incompatible with my specific build of Drupal. The PHP version was set to 5.2 and I was able to change it to 5.3. This fixed my WSOD problems when I logged in as admin to the live server.

Thank you everyone for the much appreciated help and support!
> 1 votes

# Answer
Check the official Drupal page for "white screen of death" (WSOD), you will useful guidance to help you to find the problem.

As my suggestion, enable temporaly the error report for php, adding on the index.php the following lines:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

Another thing that you could do is to go to admin page of your Godaddy shared hosting account and enable the option error.

A last thing, check if you have copied the .htaccess file too on the directory of the web hosting server.
> 2 votes

# Answer
This might probably be relevant to an issue with GoDaddy that requires you to uncomment the line:

```
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
   RewriteBase /

```

in the `.htaccess` file at the root of your installation.
> 1 votes

# Answer
Look in the PHP logs: http://support.godaddy.com/help/article/1197/working-with-error-logs and see what the error is. I would post it back here and someone may be able to give you a specific resolution.

You can try running update.php, which may fix the issue. You can update the setting update\_free\_access=TRUE in your settings.php file: https://drupal.org/upgrade/running-update-php

That being said, the correct way to move to a production site is to back up your /sites folder, and do a fresh install of drupal on the production server. Replace everything but the /sites/default/settings.php file with your backed up /sites folder.

More here on migrating a development instance of Drupal to a live development server: https://drupal.org/node/501724
> 0 votes

---
Tags: users, wsod
---


# Question
Title: How to embed javascript into content region
I am trying to embed javascript into the content page of my page. I decided to use php filter and the following is my code:

```
<?php
$scripty = "http://blah.com/plugins/embedvanilla/remote.js";
drupal_add_js($scripty, array(
'type' => 'external',
'scope' => 'content',
'group' => JS_LIBRARY,
'every_page' => FALSE,
'weight' => -1,
)
);
?>

```

The script shows on this page if scope is not set (which means it defaults to header).

How can I get it to display in the content region?

# Answer
Never use php filter, it's one of the worst inventions in Drupal.

You can create a region in your info theme. Then, use the preprocess hook like that:

```
function hook_preprocess_region(&$vars) {
  // Region names of (header|footer) collide with drupal_add_js()'s
  // (header|footer) labels.
  $scope_theme = 'your_region';
  if (!empty($scope_theme) && $scope_theme != 'footer' && $scope_theme != 'header'
    && $vars['region'] == $scope_theme) {

    // Inject javascript into page.
    $javascript = drupal_get_js($vars['region']);
    $vars['content'] = $javascript . $vars['content'];
  }

}

```

And finally, fire your drupal\_add\_js using the region you defined wherever you prefer... But never in php filter
> 1 votes

# Answer
Drupal has several ways to include javascript, but the most common is to define the script file in a module or theme .info file. Drupal will handle the inclusion and aggregation of your script file.

For more information on your options, have a look at the Developers Guide.
> 0 votes

# Answer
Using a scope other than `header` & `footer` is not supported with Drupal core's themes and most contrib themes. Using any scope is supported in all themes if you're using AdvAgg though. After installing AdvAgg you will need to add this to you're settings.php file to enable JS outside of normal scopes.

```
// Allow JavaScript insertion into any scope even if theme does not support it.
$conf['advagg_scripts_scope_anywhere'] = TRUE;

```

This is one of the hidden settings inside AdvAgg. You can read about the hidden settings inside of the AdvAgg readme.
> 0 votes

# Answer
If you're using php filter on your page, couldn't you just add the script tag into the node body?

```
<script type="text/javascript" src="http://blah.com/plugins/embedvanilla/remote.js"></script>

```
> -1 votes

---
Tags: javascript
---


title: File field fails to upload any files

text:
# Question
Title: File field fails to upload any files
I've been having an issue with a file field that is not accepting any file uploads -- it ends up returning a 500 ISE on the specific field call (see image of the returned upload error).

The actual field itself is left over from a Database import of the site on an Acquia Cloud install. I know that it may be possible to re-create the field, but we stand the risk of losing existing records. Server configuration wise, it looks like the file directory is writable by httpd, so I don't see any issues there.

It doesn't help that the Acquia logs don't give anything useful. Any ideas?

# Answer
> 1 votes
Check the size of the files, maybe they are to big. Check the max. file sizes on your server and in Drupal!.

PHP configuration check:

check the following parameters:

post\_max\_size

upload\_max\_filesize

If these values are to small, you have to change them on your server in your PHP configuration (for example php.ini)

---
Tags: 7, acquia-cloud
---


# Question
Title: The $string argument to t() should not begin or end with a space
I am using coder to review code of my module, and I am seeing this in .module file. I am not sure how to fix this up.

```
Line 49: The $string argument to t() should not begin or end with a space. (Drupal Docs) [i18n_11]

  '#title' => check_plain(t('Role Limit (' . $value . ')')),

```

# Answer
> 1 votes
It's a bug with coder module.. I can replicate using D7 version... See fix below..

```
'#title' => t('Role Limit (@value)', array('@value' => $value)),

```

Root cause analysis of above problem is

Coder works with pattern matching to report errors.. In above code you can see a space before single quote inside t function.. that's the reason it's throwing error...

I see same issue in D7 too... Changing your code as explained above will solve the issue..

# Answer
> 8 votes
The correct way of using variables in `t()` function is using placeholders.

Example of a correct usage:

```
$string = t('Role Limit @value', array('@value' => $value));

```

There are three types of placeholders for `t()` function.

* @variable : The variable will be checked through `check_plain()` function before it is inserted, so you don't need to check it in your script.
* !variable : The variable will be inserted as it is.
* %variable : The variable will be checked through `check_plain()` and highlighted with `drupal_placeholder()`

# Answer
> 0 votes
The message from the coder module is pretty much nonsense. The text of the error message doesn't really explain the problem.

You cannot pass variables into the t() function like that (check the docs in the link It specifically says that).

The reason is users submitting translations can't possibly know what is in that variable so it cannot be translated.

Also, you don't need to run through check\_plain() if you use t() correctly as it will do that for you (check out the different replacement patterns you can use and what they do in the drupal 6 version of the docs for the t() function).

You should do it like this:

```
'#title' => t('Role Limit (@value)', array('@value' => $value)),

```

---
Tags: 7
---


# Question
Title: How to set translated variables' values from settings.php (or similar)
When using the Variable translation module (part of the Internationalization suite), how can I set the value of a translated variable from the site's `settings.php` file ?

Using the `$conf` in the `settings.php` works, but off course it can only be used when the value of the variable is the same in all languages.

I'm looking for a solution that could be used to achieve the same goal of the `$conf` in the `settings.php` file: defining the values of variable at execution without the need store the values anywhere else. One use case is to assign different values to variables depending on the execution environment (as set in an environment variable).

# Answer
In settings.php

```
$conf['MODULE_i18n_variables'] = array('my_variable');
$conf['my_variable'] = 'default value';
$conf['my_variable__fr'] = 'french value';

```

And in a custom module

```
/**
 * Implements hook_init().
 */
function MODULE_init() {
  global $conf, $language;
  if (is_array($conf['MODULE_i18n_variables'])) {
    foreach ($conf['MODULE_i18n_variables'] as $variable) {
      if (isset($conf["{$variable}__{$language->language}"])) {
        $conf[$variable] = $conf["{$variable}__{$language->language}"];
      }
    }
  }
}

```

This work as long as other languages values are not used. For instance, a multi-language aware edit form for the variable will not reflect the enforced per language values.
> 2 votes

# Answer
Why don't you declare your variables inside a module with the variable module. Then you could use and translated them.

I suggest you read this: http://www.lullabot.com/blog/article/module-monday-variable

I don't think there is a way of having things translated in drupal without using the database, so i give you a simple option of using variable module as the only way.

you can add in your module.info file, so it will work as you enable your module.

```
/**
 * Implements hook_install().
 */
function mymo_install() {

  // save the translation of your variable
  variable_store_set('language', 'es', 'site_name', 'Este es mi Sitio', TRUE);

}

```

you could delete things with hook\_uninstall if you want.

hope i don't get extra -1, it could be useful to someone else...
> 2 votes

---
Tags: 7, i18n-l10n, configuration
---


# Question
Title: How can i export single content node (or) selected content nodes using drush command
I am using drupal 7. i created three basic pages name it as node1, node2, node3 when i export node using node-export-export command all pages(node1,node2,node3) as in one xml file. my intention is to export and import each node (or) selected nodes at a time. Please help me. Thanks for your help.

# Answer
> 2 votes
Drush command node-export-export accepts arguments ... You can see documentation of any drush command using below syntax..

```
drush help command-name

```

In your case

```
drush help node-export-export

```

Arguments: nids A list of space-separated node IDs to export.

For Example

```
drush node-export-export 45 46 47

```

export nodes with node IDs 45, 46, 47

---
Tags: 7, drush
---


# Question
Title: individual user profile on click of user name in view
I have a view of displaying uploaded image content by different users. The content is displaying in box in below manner.. i.uploaded image ii.title of the image iii.user name and profile picture iv.category

Now i want that 1. when the user clicks on either image or title one popup will open in a lightbox. in that popup the content should be the node content with all details. I have done successfully with the module lightbox2 only to popup image but i want that particular node content in that popup.

2.After click on user name or profile picture that page goes to the particular users page with their details and their upload content. Till now when i click on this link that particular user details opens in tab. but i want either all tabs merge in to one page or the things will display like i expained above.

please help me i am working it on since last 1 week but i am unable to find any solution..

please help/guide me ..

Thanks

# Answer
You can try Colorbox Node to open particular node content in popup. This module gives the user the ability to display ANY page inside a colorbox modal without the header and footer.

It can be integrated with views also.

Views Integration with node colorbox modal
> 0 votes

---
Tags: views, 7, theming, users, dashboard
---


title: search from modify html output

text:
# Question
Title: search from modify html output
im having problems to modify html of drupal search form. Currently it looks like this:

```
<form action="/" method="post" id="search-block-form--2" accept-charset="UTF-8">
<div>
    <div class="form-item form-type-textfield form-item-search-block-form">
        <label class="element-invisible" for="edit-search-block-form--4">Recipe Finder </label>
        <input title="Enter the terms you wish to search for." placeholder="Search" type="text"
               id="edit-search-block-form--4" name="search_block_form" value="Search" size="15" maxlength="128"
               class="form-text">
    </div>
    <div class="form-actions form-wrapper" id="edit-actions--3">
        <input type="submit" id="edit-submit--3" name="op" value="GO!" class="form-submit">
    </div>
    <input type="hidden" name="form_build_id" value="form-eHe5OqwUBJ_6iNuySpN1domgBeOYb4utKirLlh58QHY">
    <input type="hidden" name="form_token" value="ADv5U92njeULDgBszbJ6nDHTaGTxTEJMCCL2Qk3SAMk">
    <input type="hidden" name="form_id" value="search_block_form">
</div>

```

and i need something like this:

```
<form action="/" method="post">
            <div class="form-item">
                <label for="search">Recipe finder</label>
                <input type="text" name="search" class="search" id="search">
                <button type="submit">Search</button>
            </div>
        </form>

```

So i need to:

* Change input to a button
* Put that button in same div as input and label

I dont mind having this invisible elements and i know drupal needs them.

I know i need to use hook\_form\_alter for this but not rly sure how to do it.

# Answer
> 1 votes
I wanted to do the same thing and after struggling with all kind of hooks/theme functions, I finally found a solution directly inspired from bootstrap.

Here the 2 links of bootstrap implementation:

1. bootstrap\_form\_alter
2. bootstrap theme function

And for my purpose, I've created a custom module to implement a custom search block. So in `MYMODULE.module` file, I've put:

```
/**
 * Implements hook_theme()
 */
function MYMODULE_theme() {
  return array(
    'MYMODULE_search_form_wrapper' => array(
      'render element'  => 'element',
    ),
  );
}

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    //other implementations in themes/MY-THEME/template.php
    $form['actions']['submit']['#attributes']['class'][] = 'element-invisible';
    $form['search_block_form']['#theme_wrappers'] = array('MYMODULE_search_form_wrapper');
  }
}

function theme_MYMODULE_search_form_wrapper($variables) {

  $output = $variables['element']['#children'];
  $output .= '<button type="submit" class="btn-foldingsearch">';
  $output .= t('Search');
  $output .= '</button>';
  $output .= '<span class="icon-search icon-foldingsearch rotated"></span>';

  return $output;
}

```

Anyway, you'll have to adapt it to your configuration. Hope it helps.

---
Tags: 7, search
---


# Question
Title: How to delete a value from a multi-value entity reference field with EntityMetadataWrapper
I have multiple values in an entity reference field. I want to delete one of those values, but ::clear doesn't seem to work. I basically just want to do an unset, like:

```
$wrapper->field_entityrefs[3]->delete();

```

or something clean like that. What is the best way?

# Answer
> 0 votes
This seems to work:

```
$wrapper->field_entityrefs[3]->set();

```

Also, to test if the field is there in the first place:

```
$wrapper->__isset('field_entityrefs');

```

I'm now finding myself calling \__isset() on all wrapper fields.

---
Tags: 7, entities
---


title: Include selected language in a href

text:
# Question
Title: Include selected language in a href
I have a few hardcoded links in a block on my homepage.

```
<a href="/info">Info</a>

```

But I want them to include the selected language.

e.g. Wen french is selected I want it to link to

```
<a href="/fr/info">Info<a>

```

How can I do this?

# Answer
> 1 votes
You need to use  function to print links in Drupal... It has support for language

```
global $language;
print l("Info", "info",  array('language' => $language->language));

```

---
Tags: routes, navigation, i18n-l10n
---


# Question
Title: Extracting UID information from a URL and sending email to this user
As a beginner, I would be grateful if this community could help me out to solve the following problem, by giving me some pointers. This is the scenario I would like to implement in Drupal (I guess I need to create my own module):

A user (“U1”) enters a URL which looks like this: www.mywebsite/Foo/UID2 Note that U1 does not need to be registered on my web site ( = anonymous), although he / she may be, to access the page which will be invoked through this URL.

U1 is then automatically redirected to a web form page where he / she will enter text: “Hello my name is Bob…”, an email address: “u1@example.com, a phone number “123 345 67 89”.

An email containing this information will be sent to the user that has UID2 as his / her user ID. U1 will not see U2’s email address.

The information that U1 sent an email to U2 will be kept in a “from-to” table which manages the following information:

UID\_from (if it exists) U\_from First Name U\_from Last name Text\_from Email\_from Telephone\_from UID\_to (note: this UDI always belongs to a registered user) Date & time

Can someone give me some indications of the various functions invoked? If a ready-made module exists (which I did not find), the better.

I suspect hook\_menu will be used; but how to extract UI2 from the URL and send it to a web form, which later is handled by an email module?

Thanks so much,

Peter

# Answer
You can solve your problem using Out of the box Webform Module.

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

* You can read uid value from URL .. Webform has support for tokens. You need to create a field to collect UID and configure default value.

For Example: %get\[key\] - Tokens may be populated from the URL by creating URLs of the form http://example.com/my-form?foo=bar. Using the token %get\[foo\] would print "bar".

* Your URL should be http://example.com/my-form?uid=value .. You will configure default value as %get\[uid\]
* Webform has Email support out of the box.
* You can see user submitted results in webform you created.
* It automatically creates schema for you, and it has lot more features...
> 0 votes

---
Tags: uri
---


# Question
Title: Hide single menu item from users without a specific role (without 3rd party module)
I have a menu and would like to hide a specific item if the currently authenticated users doesn't have the "editor" role, which i created.

Since this is such a small thing, i would like to achieve that without the use of a 3rd party module.

update::

This is not about security, I just want to hide the item regardless of the linked node's permission. In my specific case I'm even linking to a public node and just want to hide the menu item as long as the user hasn't the "editor" role.

# Answer
Use hook\_menu\_item\_link to alter menu items. See below example:

```
function mytheme_menu_item_link( $link ) {
  if( $link[ 'title' ] == 'My Account') {
    return '';
  }
}

```
> 1 votes

# Answer
If security is not that important. This should kinda do the trick (untested code).

```
function YourTheme_menu_link(array $variables) {
  if ($variables['element']['#href'] == 'menu link to hide') {
    $variables['element']['#attributes']['class'][] = 'invisible';
  }

 return theme_menu_link($variables);
}

```
> 0 votes

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


title: URL encoding of en-dash

text:
# Question
Title: URL encoding of en-dash
I had a link:

```
www.example.com/issues/issue-week-2012–2013/poem1

```

But it is encoded as:

```
www.example.com/issues/issue-week-2012%25E2%2580%25932013/poem1

```

This is an URL alias, the en-dash (between "2012" and "2013") is encoded as `%25E2%2580%2593`, which shows a 404 error. But when I removed the "25" after each `%` in the URL manually it works.

Please tell me about the issue?

# Answer
Got the solution for the bug.

Actually the edit page (`node/*/edit`) is a secure page (HTTPS) and view page is not (HTTP). So while clicking any URL in the edit page, it will encode that URL in to HTTPS and then to HTTP (if the redirected page is not a secure page).

Here the URL gets encoded twice:

First:

```
https://example.com/issues/poems-week-2012%E2%80%932013/storyname

```

And then:

```
http://example.com/issues/poems-week-2012%25E2%2580%25932013/storyname

```

This bug can be fixed if the edit page is a normal page (not a secure page). And it seems that this will not make any security breach for the system.
> 0 votes

# Answer
I think there may be a solution using a RewriteRule in .htaccess.

Imagine I have the url `/some-page`

Now if I go to `/someTESTpage`

and I put this in .htacess:

```
RewriteEngine on
RewriteRule ^(.*)TEST(.*)$ /$1-$2 [L,R=301]

```

Then it redirects to:

```
/some‒test

```

Problems still to solve:

1) In the redirect URL that is an en-dash so is still the wrong url. Not sure how to get it to insert the correct character.

2) When I put a percentage sign in the string to be replace the whole thing stops working. Not sure how to escape a percentage sign in a RewriteRule.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: The node form will not submit,if the word 'exit' is put in the title field
I am using Drupal7, if the word 'exit' is entered into the text field, and the user submits/saves/previews the page, then the data is not submitted, saved, or previewed. The node edit page reloads and all changes are lost.

Is the word 'exit' a blacklisted word in node add/edit form?How can i over ride this prob?

Thanks in advance, Prem

# Answer
No, Drupal doesn't have any word blacklists.

That logic must be caused by a custom or contributed module that you have installed (or even a theme I suppose). Try methodically disabling modules/themes until you find the culprit.

Starting with modules that provide text filters or alter the content body in some way would be the obvious places to start.
> 0 votes

# Answer
Found the issue:

This was due to some server side scripting that some words will not be taken when a form is submitted. I cleared it by sending a support ticket to the server support team
> 0 votes

---
Tags: nodes
---


# Question
Title: Custom template file for taxonomy term in drupal 7
I need to create only one `tpl.php` file for all taxonomy terms in my website. I know `taxonomy_term_page.tpl.php` will do the required function in Drupal6.

For drupal 7 I had override the `taxonomy-term.tpl.php`. I see all the nodes associated to a term, is displayed at the last.

How can I hide those nodes?

# Answer
> 3 votes
taxonomy-term.tpl.php is used in Drupal 7. You can find it in ROOT\_DIRECTORY\modules\taxonomy\taxonomy-term.tpl.php. To override this template, copy it, place it in your theme template directory, and modify it. Don't forget to clear the cache to see the output from the modified template.

Do not modify any core files (including template files), in any case.

If you want to show only the details of taxonomy term then you can create a view of type 'Term referance' with suitable filter.

# Answer
> -1 votes
To override tpl you can find detailed information in "Drupal 7 Template (Theme Hook) Suggestions".

---
Tags: taxonomy-terms, theming, upgrading
---


# Question
Title: How to prevent users of particular role to access the content view (node view) of a particular content type?
I am using Content Access Module and have rebuild permissions after enabling the module.

After giving restricted access to users having role 'Data Entry Operator'. I have a content type delivery challan for which I have **ticked** on the following permissions for the role ABC.
**View own delivery\_challan content**(selected the particular permission for role 'Data Entry Operator' only ) and
**View any delivery\_challan content**(unselected the particular permission for role 'Data Entry Operator')
Here is the screenshot of the permissions set in the content access module.
When I login as user having role Data Entry Operator , I should not be able to view the contents of type 'delivery challan' But the issue is I am able to view the content How can I prevent user from viewing this content??

# Answer
> 0 votes
Ok there was a mistake from my side
the view 'any delivery\_challan content' permission was given to
authenticated user.
And by default any user has role authenticated user.
So User having role 'Data Admin Operator' was able to view any delivery challan content as user also has the role 'authenticated user'
**So the solution is to remove the authenticated role from the list of roles under the view any delivery challan content**

---
Tags: 7, users
---


title: Customize access denied page

text:
# Question
Title: Customize access denied page
I have many basic pages where I need the user to be logged-in in order to view them. How do I customize the site access denied page?

# Answer
> 7 votes
A custom access denied page can be defined under /admin/config/system/site-information. For example, one common 404 error page is provided by the Search404 module.

All you have to do is define your own page, perhaps with a teaser from the requested page and informing the user that access to the full content requires that they be logged in.

This will probably require tha you put some php code into the page body, or you might use the Search404 module as the basis for developing your own module to handle this.

Edit: The more I think about this the more interesting the question becomes. I think a case might be made for a 'View Teaser' permission in addition to 'View published content'. In other words, the page could be available for all users, but the teaser would display instead of the full content, and a message could be displayed indicating that the user had to be logged in to view the full content, much like is done for comments now. Perhaps an idea for a contributed model (could not find one on D.O.).

# Answer
> 7 votes
I think you can use page--403.tpl.php and page--404.tpl.php and code in template.php via

```
function THEMENAME_preprocess_page(&$variables) {
  $status = drupal_get_http_header("status");
  if($status == '403 Forbidden') {
    $variables['theme_hook_suggestions'][] = 'page__403';
  }
  if($status == '404 Not Found') {
    $variables['theme_hook_suggestions'][] = 'page__404';
  }
}

```

# Answer
> 2 votes
I am using the Custom error module for this.

To get redirect to originally requested page after a 403 to work, I've created this patch.

Here are two examples of my uses of the module:

---
Tags: 7
---


# Question
Title: Styling the autocomplete dropdown to work with the up/down arrow keys
The following custom styling for drupal core's autocomplete dropdown works when hovering, but it is ignored when using the up/down arrow keys. (Currently, pressing the arrow keys only turns the text white.)

Does anybody know the secret to getting styles and keypresses working together?

```
#autocomplete li:hover, #autocomplete li:focus{
background-color:#428bca;
color:green;
}

```

# Answer
This should work:

```
#autocomplete li.selected {
  background-color:#428bca;
  color:green;
}

```

The items from the autocomplete list are having the *.selected* class added on hover/key navigation.
> 0 votes

---
Tags: ajax
---


# Question
Title: Code for "All pages except those listed" in Show block on specific pages
While editing a block I want to use "Pages on which this PHP code returns TRUE (experts only)" at the same time support the URL's entered in "All pages except those listed" plus my own custom conditions.

Where can I get the **standard** code to match those URL using PHP code?

For example as in figure initially "All pages except those listed" is checked on but now I want to choose the Experts only(3rd one).

In this Experts only mode before adding my custom code I'd like to check for exclusion of those same URL's first then proceed.

# Answer
> 0 votes
I made this stuff copying from Core's block.module:

```
//This block will not show pages when these pattern match
$pages = <<< EOT
adsense/*
node/add/*
adsense/*
contact
privacy
tags/*
terms
about
check-for-expired-job
taxonomy/term/*
EOT;

$pages = drupal_strtolower($pages);
$path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
$hide_block = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
    $hide_block = $hide_block || drupal_match_path($_GET['q'], $pages);
}
if($hide_block)
{
return false;
}

//Now do other processing stuff

```

---
Tags: blocks
---


# Question
Title: Submit handler is not called from theme function
I am actualy trying to build up a dragable table, but for some reason after implementing the theme\_function, my submit handler is not longer getting called.

This is what my Code actualy looks like:

```
function he_ministerienschalter_theme($existing, $type, $theme, $path) {
  $themes = array(
    'he_ministerienschalter_admin_form' => array(
      'render element' => 'element',
    ),
  );
  return $themes;
}

/**
  * Implements the ministerschalter admin form
  */

function he_ministerienschalter_admin_form($form, &$form_state, $form_id, $item) {

  $domainnames = he_ministerienschalter_domainselect();

  $count = 0;
  $form['ressortswitch'] = array(
    '#prefix' => '<div id="curve-attributes">',
    '#suffix' => '</div>',
    '#tree' => TRUE,
    '#theme' => 'he_ministerienschalter_admin_form',
  );
  foreach ($domainnames as $key => $domainname) {
      $form['ressortswitch'][$key]['domainID-'.$key] = array(
        '#type' => 'value',
        '#value' => $domainname['domain_id'],
      );
      $form['ressortswitch'][$key]['domainname-'.$key] = array(
        '#type' => 'item',
        '#title' => $domainname['sitename'],
        '#size' => 60,
        '#maxlength' => 128,
      );
      $form['ressortswitch'][$key]['domainshort-'.$key] = array(
        '#type' => 'textfield',
        '#default_value' => $domainname['sitename'],
      );
      $form['ressortswitch'][$key]['weight-'.$key] = array(
        '#type' => 'textfield',
        '#default_value' => !empty($domainname['domain_weight']) ? $domainname['domain_weight'] : '0',
        '#size' => 3,
        '#attributes' => array('class' => array('item-row-weight')),
      );
      $count++;
    }

    $form['ressortswitch']['count'] = array(
      '#type' => 'hidden',
      '#value' => $count,
    );
    $form['ressortswitch']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save Settings'),
    );

  return $form;
}

/**
  * Theme callback for the he_ministerienschalter_admin_form
  */

function theme_he_ministerienschalter_admin_form($variables) {
  $element = $variables['form'];
  drupal_add_tabledrag('ressortswitch_table', 'order', 'sibling', 'item-row-weight');
  $header = array(
    t('Domainname'),
    t('Domainshort'),
    t('Weight')
  );

  $element_items = array();

  foreach($element['ressortswitch'] as $id => $record) {
    if(is_int($id)) {
      $element_items[] = $record;
    }
  }

  $rows = array();
  foreach ($element_items as $id => $item) {
      $domainNAME[$id] = $item['domainname-'.$id];
      $domainSHORT[$id] = $item['domainshort-'.$id];
      $domainWEIGHT[$id] = $item['weight-'.$id];

    $rows[] = array(
      'data' => array(
        drupal_render($domainNAME[$id]),
        drupal_render($domainSHORT[$id]),
        drupal_render($domainWEIGHT[$id]),
      ),
      'class' => array('draggable'),
    );
  }

  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => 'ressortswitch_table'),
  ));

  $output .= drupal_render($element['ressortswitch']['submit']);

  return $output;
}

/**
  * Implements hook_form_submit
  */

function he_ministerienschalter_admin_form_submit($form, &$form_state, $item) {
  db_delete('he_ministerienschalter')
  ->execute();
  $count_domains = $form_state['values']['ressortswitch']['count'];
  $count = 0;
  // dpm($form_state);
  dpm($form_state);
  while($count < $count_domains) {
    db_insert('he_ministerienschalter')
      ->fields(array(
        'domain_id' => $form_state['values']['ressortswitch'][$count]['domainID-'.$count],
        'domain_short' => $form_state['values']['ressortswitch'][$count]['domainshort-'.$count],
        'domain_weight' => $form_state['values']['ressortswitch'][$count]['weight-'.$count]
    ))
    ->execute();
    $count++;
  }
  drupal_set_message('Eingabe gespeichert');
}

```

Any idea how to solve that?

# Answer
> 1 votes
I Updated my theme function like this and now it works like a charm :-)

```
$output .= drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);

```

---
Tags: theming, forms
---


title: Drupal Multilingual Emails

text:
# Question
Title: Drupal Multilingual Emails
We have a multilingual website set up and functioning fine. The next step was to setup translations for the default Drupal account emails (e.g. Welcome, Account activation, Account blocked etc). This is also done - and our client can go in and add translations for each of these.

The issue is - the client is asking; seeing as these are default Drupal emails, have the translations already be done for each language?

We have the `l10n_update` module pulling down translate updates to core and each module - but the account emails are not receiving translates.

Does any one know if these emails have already been translated? Can anyone provide some insight? We've searched and haven't come across anything

thanks

# Answer
If you installed the Internationalization Module, you should have a sub-module called "Variable translation". If enabled, go to admin/config/regional/i18n/variable and choose the variables which you would like to translate.

In your case this would be the ones in the "User Emails" tab. Once checked and activated go to the user e-mail page (admin/config/people/accounts) and click on the different language links at the top of the page to translate.
> 4 votes

# Answer
I installed on my local computer a version of Drupal core in the language I needed. I then copied the emails in the right language into my multi-language website.
> 0 votes

---
Tags: emails, i18n-l10n
---


# Question
Title: UC Node Checkout for pay to publish user content?
Is there a way to use this module for a pay to publish set up, like in classifieds where user adds content and then pays to publish it in D7?

Generally speaking that is....I like many others having been paying for a module but the person who created it has disappeared now and it is first time ever I've paid for something re drupal. Normally I study up on anything open source- which just goes to show there are no shortcuts in this world.

# Answer
> 0 votes
Try Pay-per-node

This module allows creation of a number of nodes of chosen type for some users. It temporarily overrides the node creation permissions and keeps track of the number of nodes the user can create.

It can be used as standalone module or as an e-commerce plug-in. **In the second case paypernode can be integrated with Ubercart, providing a new "product feature" which will allow, upon product purchase, to create a number of nodes.**

# Answer
> 0 votes
I did this: eventually didn't need pay per node and managed to get uc\_node\_checkout to work for allowing anon to publish a node of type Job Advert which lands in the cart, requires checkout and is only published on payment complete by a rule using exec custom php

using the code from #19 here https://drupal.org/node/376384 and http://drupaleasy.com/blogs/ultimike/2009/03/event-registration-ubercart

set Create Job Advert to authenticated user role (not anon) to force login before purchase

---
Tags: ubercart
---


# Question
Title: Undefined variable: _SESSION in template.php
I use this code (not mine, I do not know how to code) to disable Maintenance mode message on front-page while developing a site, it's really annoying when it's flashing all the time in the middle of the page.

```
function theme_preprocess_page(&$vars) {
    if (variable_get('maintenance_mode', 0)) { //no maintenance mode message on front-end
      $message_count = count($_SESSION['messages']['status']);
      if($message_count > 1) {
        array_shift($_SESSION['messages']['status']);
      }
      else {
        unset($_SESSION['messages']['status']);
      }
}

```

So it works great while logged in and in maintenance mode, but when going to user/login page as anonymous, it gives this notice in red:

```
Notice: Undefined variable: _SESSION in theme_preprocess_page()
(line 141 of /sites/all/themes/mytheme/template.php).

```

So what is this? Is the code missing something?

# Answer
Apparently the $\_SESSION variable is not available on the login page (I don't know why, but probably to avoid conflicts with logged in users trying to log in again).

Try checking for it before you try to unset it:

```
function theme_preprocess_page(&$vars) {
    if (variable_get('maintenance_mode', 0) && isset($_SESSION['messages']['status'])) { //no maintenance mode message on front-end
      $message_count = count($_SESSION['messages']['status']);
      if($message_count > 1) {
        array_shift($_SESSION['messages']['status']);
      }
      else {
        unset($_SESSION['messages']['status']);
      }
    }
}

```
> 2 votes

---
Tags: 7, theming, maintenance-mode
---


# Question
Title: How can I collect data through a drupal form?
I want to allow users to contribute posts to my site. Should I set up a content type that can be created by the public or set up a new user role and get people to sign up first? I want to reduce the friction of adding a post to the absolute minimum.

# Answer
> 1 votes
I'd let users login first to prevent spam. However you could simplify the registration&login process by having users authenticate with OpenID (Google, facebook ect.) Similar as what stackexchange offers.

This should get you started: https://drupal.org/project/openid\_connect

---
Tags: database
---


# Question
Title: How to hide drupal error message - one or more problems were detected with your drupal installation
On logging on to Drupal administration page, I get an error message:

> One or more problems were detected with your drupal installation.

I've tried disabling modules.

Is there a way to hide this message?

# Answer
> 3 votes
The error you reported is caused by a module that implements `hook_requirements()` to check if some conditions are verified. Instead of hiding the message, you should check what caused the error message by visiting the "Status report" page, where the module that caused the error message to appear will explain the cause of the error.

Keep in mind that also Drupal core modules cause the error to appear, for example when you need to run the module updates to update the database tables used by a module.

# Answer
> 3 votes
You could check the status report and try to resolve the error but I guess you are happy to leave it that way.

Or you could hide the message by selecting the class and choosing not to display it using CSS. Create a file called style.css in your "Theme" folder (alongside the location of page.tpl.php) and place the class within it (you can check the class by using Firebug/Inspector "right click on it, then inspect element").

I think the class will be .warning or .alert, and an example CSS code would be:

```
div.warning, .alert, div.error, tr.error
{
display:none;
}

```

This would however hide all alerts and warnings for elements with the same class. So be careful because you could miss other critical notifications. You could have a style sheet for non-admin users that would turn this off and another for admin areas that would display these messages. Its your choice.

# Answer
> 1 votes
Instead of hiding these errors, you should configure properly corresponding modules...

Anyway, you can simply hide these errors in Site configuration \> Error reporting (no need to add css rule for this).

# Answer
> 0 votes
You can hide it temporarily: Go to admin/settings/error-reporting and change the *Error reporting* setting to *Write errors to log*.

The Disable Messages module shows the errors only to administrator users.

> Gives a site owner options to disable specific messages shown to end users. The core Drupal message system as offered by `drupal_set_message()` is an excellent way for modules to send out messages to the end users. However, not all Drupal site owners are keen to show all the messages sent out by Drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

I know you need to fix these errors. Meanwhile, all your site users see these red messages. They don't affect anyone except logged-in users, normally, and they may be completely minor.
I got many errors about the need of doing a security update, but the site worked normally. It's different when typical users are logged in, but in my case, I'm the only user and only administrator (except for the site designers who designed the site for me).
In a situation like this, the last thing you want is showing error messages to the visitors who are only interested to the content shown after the error messages. That could mean losing all your sales for one day or for several days if you happen to be on holiday.

---
Tags: 7
---


# Question
Title: How to prepare renderable array for images that are not stored in public or private filesystem, but are delivered statically with module?
I have a piece of code that prepares renderable array for my images:

```
if( !empty($row['image_file_id'])) {
  $row['thumbnail'] = array(
    '#theme' => 'image_style',
    '#path' => _mymodule_uri_by_id((integer)$row['image_file_id']),
    '#style_name' => 'product_thumbnail_small',
    '#attributes' => array(
      'alt' => $row['image_alt'],
      'title' => $row['image_title'],
    ),
  );
}

```

It works OK:

But I want to add `else` with image provided within a module. I still want this image to go thorough all image style processing etc. I want my theming colleagues to be able to simply not care if they'll ever decide to add some effects or change resolution. But of course this image is in module directory, not in `public://`. And it means this will not work:

```
else {
  $row['thumbnail'] = array(
    '#theme' => 'image_style',
    '#path' => drupal_get_path('module', 'mymodule') . '/frontend/noimage.png',
    '#style_name' => 'product_thumbnail_small',
    '#attributes' => array(
      'alt' => 'some universal stub',
      'title' => 'some universal stub',
    ),
  );
}

```

It gives:

And browser tries to read that image from http://example.com/sites/default/files/styles/product\_thumbnail\_small/public//sites/default/modules/mymodule/frontend/noimage.png?itok=-yYlM4ns

This gives nothing (status reports says "access denied"), unless I manually place image in `public://sites/default/modules/mymodule/frontend` \- but I don't want it to be in public file system, I want it to stay in module space. How can I make it work?

# Answer
Simply put...you can't, unfortunately (well not without changing some core stuff at least)

From the comments for `theme_image_style()`

> This function does not work with images outside the files directory nor with remotely hosted images.
> 4 votes

---
Tags: media, theming
---


# Question
Title: Need some advice on implementing a HDFS file storage solution for drupal
We are looking into using HDFS to store our files users upload through the drupal Site. I have not been able to find a module that claims to do this already so we thought we would build one. So my question is 2 folds.

1. Is anyone aware of a module that could do this?
2. Is there a specific API standard to build this out of drupal? Is it just a matter of implementing a HDFSStreamWrapper

Thanks

# Answer
I am not aware of any existing module for that, but you could start with storage\_api and extend it by your custom implementation for HDFS.
> 1 votes

---
Tags: files
---


title: Views gives wrong path

text:
# Question
Title: Views gives wrong path
I use Drupal Commerce module and Views Slideshow. In Fields I have this `(Products referenced by field_product) Commerce Product: Product Image` field and in Relationships `Content: Product`, it is an image field and selecting Link image to: Content it links it to admin/commerce/products/4 when the product display for user is node/5

What I do wrong?

# Answer
> 0 votes
The answer is only a google search away..

https://drupal.org/node/1108180

---
Tags: 7, views, commerce
---


# Question
Title: Which hook can I use for a Drupal webform Post to a Google Spreadsheet?
I have a webform with some options and fields. When user submit the form i receive an email.

I want to hook right before(or after) drupal send the email and populate my Google Spreadsheet so i can review from my Google Drive account.(And send the email as normal)

I have make the connection with a custom php file. I don't know what hook i can use.

# Answer
The hook you need is `hook_webform_submission_presave($node, $submission)` that, according to the documentation allows to modify a Webform submission, prior to saving it in the database.

So all values should be available there.
> 1 votes

---
Tags: 7, hooks, webforms
---


title: Trigger AJAX from a Google Maps Marker

text:
# Question
Title: Trigger AJAX from a Google Maps Marker
I have a Google map loaded through the Google Maps API with markers generated from node locations.

How can I cause content to be loaded via AJAX when one of the markers is clicked.

For example, if the marker is clicked, it would replace another div on the page with information from that node gathered via a db query.

Currently I have the following js which will fire the alert when the marker is clicked

```
google.maps.event.addListener(marker, 'click', function() {
    //alert(marker.nid);
    $.post('search-map/ajax/marker.nid',{
        nid:marker.nid
    });
});

```

The "search-map/ajax/marker.nid" URL corresponds to a URL added through hook\_menu

```
$items['search-map/%/%'] = array(
    'page callback' => 'mymodule_map_marker_click',
    'page arguments' => array(1,2),
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM
);

```

And then I'm trying to get this callback function to run, which as a test, just should replace the contents of a div with some test output:

```
    function mymodule_map_marker_click($ajax, $building_nid) {
        if ($ajax == 'ajax') {
            $commands = array();
            $output = 'test';

            $commands[] = ajax_command_invoke('.search-listings__listings', 'html', array($output));

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

        } else {
            // if ajax disabled
            return array(
            );
        }
    }

```

I get this response visible in Firebug, but no action happens on the page:

```
    [{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"mytheme","theme_token":"-CJtCsEvk1Nlzi_mfwSlDTCUoeOv7yyIBHLItpFSIC4"}},"merge":true},{"command":"settings","merge":false},{"command":"invoke","selector":".search-listings__listings","method":"html","arguments":["test"]}]

```

# Answer
In my case, I was able to solve this by taking the response from Drupal.ajax and just parsing it myself into the command I needed to run:

```
                google.maps.event.addListener(marker, 'click', function() {
                    console.log(this.nid + this.title); //#DEBUG
                    $.ajax({
                        url: 'search-map/ajax/' + this.nid,
                        success: function(data,status){
                            for (var key in data) {
                                if (data[key].command == 'invoke') {
                                    console.log(data[key].arguments[0]); //#DEBUG
                                    $(data[key].selector).html(data[key].arguments[0]);
                                }
                            }
                        },
                    });
                });

```
> 0 votes

---
Tags: ajax, google-maps
---


# Question
Title: Custom Content- Predefined image selection
I am trying to create a custom content type that allows the user to select PREDEFINED images. This means the user WILL NOT have the option to upload image. I have seen people use the media module, but one I don't want the user to upload image and two I want to provide a selection option.

# Answer
You can use Select with Style module. More info go through the documentation of this module.

Or if it not suits as your requirement try jQuery Image Select with customization.
> 1 votes

---
Tags: media, files
---


title: Why isn't jcarousel.on() executed?

text:
# Question
Title: Why isn't jcarousel.on() executed?
I am using the following JavaScript code.

```
(function ($) {
  Drupal.behaviors.gsdOmega4ExampleBehavior = {
    attach: function (context, settings) {
      var jcarousel = $('.home-jcarousel');
      console.log('executed');
      jcarousel.on('jcarousel:create jcarousel:reload', function() {
        console.log('never executed');
      })
      console.log('executed');
  };
})(jQuery);

```

`jcarousel` is correctly referenced. I don't understand why `jcarousel.on()` is not executed.

# Answer
> 0 votes
Most likely because `on()` didn't exist before jQuery 1.7, and Drupal ships with...well, not 1.7.

The standard solution is to install jQuery Update and select 1.7 as the version for the site.

For future reference, check for JS errors in the browser console - there will be something very similar to this in there:

> Object \[object Object\] has no method 'on'

---
Tags: javascript
---


# Question
Title: Get node ID for all results for current view including its filters, disregarding the pager
I have a view that produces say 70 results with certain exposed filters applied (this is a view that uses Apache Solr indexed content) and I want to get the NID of every result, so I can then send it through to another page in a simple array of NID's.

I've found that all the results NIDS are within the $results array produced by views, but this only has the results that are shown on the current page, is there a way to get all the results disregarding the pager, without removing it entirely. Is this impossible to do without generating a new query based on the active filters? this is what I'm trying to avoid because there are quite a few filters.

# Answer
> 1 votes
You will have to run another query. There is no way around it. However you don't have to use Views for the second query. If you only need a list of nids, an `EntityFieldQuery` is perfect.

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
 // Add whatever filters your user has set. For example...
  ->entityCondition('bundle', 'mynodetype') // Filter by type
  ->propertyCondition('status', 1) // filter by published/unpublished status
  ->fieldCondition('field_foo', 'value', 'bar', '=') // filter by the value of a field
// Order however you want, for example...
  ->fieldOrderBy('field_foo', 'fid', 'DESC') // Order by a field value
// Set the range to get the number you want to see.
  ->range(0, 70)

$result = $query->execute();
$nids = array_keys($result['node']);

```

That will get you just a list of nids, more quickly and performantly than running a whole separate query such as that generated by a View.

# Answer
> 3 votes
I ran into this problem on a recent project. I decided against a `EntityFieldQuery` or `db_query()/db_select()` solution for four reasons.

1. Views can do some really weird things when it builds a query. For example, in some instances when you add a sort, the sort key will be added to the returned field list. This can alter what gets returned when you enable aggregation, reduce duplicates, etc.
2. Views tends to use `LEFT JOIN` instead of `INNER JOIN`. You can do this with `db_query()` and `db_select()`, but not `EntityFieldQuery`.
3. SQL can be unpredictable with the undefined ordering between having a `LIMIT` or not. For example, if you are sorting by titles and have duplicates, I have seen different results orders. This mans you may need to be really explicit with sorts, if order is important (I was implementing prev/next through a result set, so it was).
4. I really don't like implementing things in code when I know a non-coder may want to adjust the View.

So, I ended up using this:

```
$all = views_get_view('my_view');

$all->display['default']->display_options['pager'] = array(
  'type' => 'none',
  'options' => array(
    'offset' => 0,
  ),
);

$all->set_display('my_display');

$all->display[$all->current_display]->display_options['pager'] = array(
  'type' => 'none',
  'options' => array(
    'offset' => 0,
  ),
);

$all->pre_execute();
$all->execute();

$nids = array();

foreach ($all->result as $result) {
  $nids[] = (int) $result->nid;
}

```

This will

* Manually instantiate the view.
* Reset the pager on the master to show all results starting from 0.
* Set the display to whatever I am using.
* Reset that pager, too.
* Execute the view
* Loop through the results for what I need.

---
Tags: views
---


# Question
Title: How to create similar to multi-image field struture in drupal using form api
How can I make a structure like adding new textfield with a button and removing that field with remove button. The structure generated should be similar to when we upload a image in multi-image field and it generates image and remove by the side of it. What I want is similar to this instead of image I want is textfield and remove by the side of it using form Api. I have tried with examples module on drupal, ajax add more, but it is not giving what I exactly want. Thanks in advance. Please help me on this.

```
<?php
// this is inside the form callback
$form['#tree'] = TRUE;
   $form['replace_div'] = array(
     '#markup' => '<div id="info-replace-div"></div>',
   );
   $form['info_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    '#prefix' => '',
    '#suffix' => '',
    );
 if(empty($form_state['num_info'])){
     $form_state['num_info'] = 1;
   }

if($form_state['values']['op'] == 'Add one more' || empty($form_state['values'])){
    for ($i = $form_state['num_info']; $i > $form_state['num_info']-1; $i--) {
      $form['info_fieldset'][$i]['add_name'] = array(
        '#type' => 'submit',
        '#value' => t('Add one more'),
        '#submit' => array('add_more_add_one_info'),
        '#limit_validation_errors' => array(),
        '#ajax' => array(
          'method' => 'before',
          'callback' => 'ajax_add_more_info',
          'wrapper' => 'info-replace-div',
        ),
      );
     $form['info_fieldset'][$i]['remove_name'] = array(
        '#type' => 'submit',
        '#value' => t('Remove').$i,
        '#limit_validation_errors' => array(),
        '#submit' => array('remove_more_add_one_info'),
        '#ajax' => array(
          'method' => 'before',
          'callback' => 'ajax_remove_one_info',
          'wrapper' => 'info-replace-div',
        ),
      );
      $form['info_fieldset'][$i]['module_markup_name1'] = array(
        '#type' => 'item',
        '#markup' => '<div class="module-title info">' . t('Information') . '</div>',
      );
      $form['info_fieldset'][$i]['module_element1'] = array(
        /*'#type' => 'text_format',*/
        '#type' => 'textarea',
        '#title' => '',
        /*'#format' => 'full_html',*/
        '#rows' => 5,
        '#cols' => 50,
        '#default_value' => (!empty($node) && isset($node) && isset($node->body[$node->language][0]['value']) ? $node->body[$node->language][0]['value'] : ''),
      );
      $form['info_fieldset'][$i]['module_desc_markup1'] = array(
        '#type' => 'item',
        '#markup' => '<span class="qtip-link">
                            <span class="qtip-tooltip">' . $module->description . '</span>
                          </span>',
      );
      $form['info_fieldset'][$i]['module_position1'] = array(
        '#type' => 'textfield',
        '#default_value' => (!empty($position_values_arr)) ? $position_values_arr[1] : 6,
        '#size' => 20,
        '#attributes' => array('class' => array('my-weight-for-element')),
      );
      $form['info_fieldset'][$i]['module1'] = array(
        '#type' => 'hidden',
        '#default_value' => in_array($module->mid, $actModule) ? 1 : 0,
      );
    }
      }

function add_more_add_one_info($form, &$form_state){
  $form_state['num_info']++;
  $form_state['rebuild'] = TRUE;
  //add more is working fine
}
function ajax_add_more_info($form, &$form_state){
  return $form['info_fieldset'];
}
function ajax_remove_one_info($form, &$form_state){
  return $form['info_fieldset'];
}
function remove_more_add_one_info($form, &$form_state){

//  unset($form_state['info_fieldset'][$form_state['num_info']]);
//   $form_state['rebuild'] = TRUE;
// need to find the logic for this one
}![enter image description here][1]

```

As  shown in the image I can manage add button below the all generated field but I need remove button by the side of the field. So, that only that field is removed.

The functionality in the end I need to create is there should be a form and multiple element can be added to the form as in google form. Refer the link and image for example.

# Answer
Not sure why you want this feature. But This module has similar features you need, you can try it.

After installing module just try this in your form,

```
$form['your_form_id'] = array(
'#type' => 'options',

);

```

Regardless of other features this module provides, simply you can use it as the text field also, the value are passed to

```
$form_state['values']['your_form_id']

```

You can hide those unnecessary elements as per your needs, just add these css to your theme,

```
.form-option-add
{visibility:hidden;}

.form-options-manual
{visibility:hidden;}

.remove-default
{visibility:hidden;}
.form-radio
{visibility:hidden;}

.tabledrag-handle
{visibility:hidden;}

.tabledrag-processed thead
{visibility:hidden;}

```
> 1 votes

# Answer
In D7, Example module contains a submodule form\_example. Use form\_example module, Go through form tutorial #9 by accessing a url like abc.com/examples/form\_example/tutorial/9. This tutorial implement same work that you want to do.
> 0 votes

---
Tags: forms, media
---


# Question
Title: How to sort a view on a Drupal Commerce product image field?
I have several Drupal Commerce views. I want to sort on whether the image is "interesting", which means not equal to `no-image-available.png`.

I have added "Indexed Commerce Product: Image » The image file." as a relationship but it's still not showing up in the sortable fields.

I remember there was something like "enforce" relationship but this is not showing up where I was expecting it:

# Answer
One way to solve this is to store a sortable value in an extra field.

Computed field can be a good choice. There is a quite lengthy article here. See "Additional Values for Sorting".

I also want to quote the "Downsides" mentioned in this article:

> Since the stored value computed field is only computed when the node is saved, your nodes need to be re-saved to allow for code changes. If you change the content type’s field, you may need to re-save all nodes of that type. If you have thousands of nodes, this can be troublesome. However, several modules (which are outside the scope of this post) can help, as can simple one-off scripts.
> 0 votes

---
Tags: commerce, views
---


# Question
Title: Is hook_init the right hook I should use in my case?
If I want to override a certain page with drupal\_set\_title() is hook\_init the right hook to use?

Same thing with adding a js script on a certain page with drupal\_add\_js() is hook\_init the right hook as well?

# Answer
> 0 votes
It really depends on what you want to achieve... If you want to alter several pages the page title module might be better suited. Using a combination of this module and your own could lead to your code in hook\_init() being overwritten. But it does not have to happen.

The more modules you have, the later you want to interfere with everything as more modules might try altering your outputs. So in those cases hook\_init might not be the right place.

If you want to add JavaScript to your own custom module you might also add it in the module.info file. This usually works better with aggregations.

Update:

You could use any page hook, for instance hook\_view() like this:

```
mymodule_view($node, $view_mode) {
  if($node->nid == 1) { // Act only if this node id (nid) is requested
     drupal_set_title("title");
     ...
  }
}

```

# Answer
> 0 votes
Using a hook or a module for altering the page title of a single page is IMHO overkill.

When I want to override the title or some other feature on a specific page, I usually use the override feature of the Drupal template system.

For instance, to override the node template for `node/42`, I create `node--42.tpl.php` by copying the default `node.tpl.php` (this is the D7 naming convention), place the copy in my theme's `templates/` directory, and then edit it to hold any modifications (including `$title`) that I want to make to that particular page.

Remember to flush caches to see the effect when you're overriding a template!

---
Tags: hooks
---