title: Getting date_popup new value with JS

text:
# Question
Title: Getting date_popup new value with JS
I'm currently working on a module with a form where people enter information about their order and select products, where the product selection is handled by JavaScript.

The handling of the form will happen with AJAX.

But my current problem is that when outputting my form with the date\_popup type, my JavaScript can't get it's value. This is the form element.

```
$form['date'] = array(
        '#type' => 'date_popup',
        '#title' => t('Datum'),
        '#id' => 'new-order-date',
        '#date_label_position' => '',
        '#default_value' => $today,
        '#date_type' => DATE_DATETIME,
        '#date_timezone' => date_default_timezone(),
        '#date_format' => 'd/m/Y',
        '#date_increment' => 1,
        '#date_year_range' => '0:+3',
        '#datepicker_options' => array('minDate' => 'today'),
    );

```

So, when processing the JS request, the value of the input text box is never changed. This is what I'm using for getting the selected date.

```
var dateField = document.getElementById("new-order-date-datepicker-popup-0");
var selectedDate = dateField.value;

```

However, this always returns the default date, not the date I picked.

My form is generated with this function.

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

    if (func_num_args() > 2) {
        $client = func_get_arg(2);
    } else {
        $client = 0;
    }

    $clientoptions = array();
    $query = db_query("SELECT * FROM {expoline_clients}");
  foreach ($query as $currentclient) {
        $clientoptions[$currentclient->cid] = $currentclient->name;
    };

    $form['client'] = array(
        '#type' => 'select',
        '#title' => t('Klant'),
        '#default_value' => $client,
        '#required' => TRUE,
        '#options' => $clientoptions,
        '#multiple' => FALSE,
    );
    $today = date("Y-m-d H:i:s");
    $form['date'] = array(
        '#type' => 'date_popup',
        '#title' => t('Datum'),
        '#id' => 'new-order-date',
        '#date_label_position' => '',
        //'#default_value' => $today,
        '#date_type' => DATE_DATETIME,
        '#date_timezone' => date_default_timezone(),
        '#date_format' => 'd/m/Y',
        '#date_increment' => 1,
        '#date_year_range' => '0:+3',
        '#datepicker_options' => array('minDate' => 'today'),
    );

    $form['save-order'] = array(
        '#type' => 'submit',
        '#value' => t('value'),
    );
    $form['#prefix'] = '<div class="my-form-class">';
    $form['#suffix'] = '</div>';

    return $form;

}

```

And this is my JavaScript

```
$(document).ready(function() {

      var oTable = $('#datatable-1').dataTable();
      var pTable = $('#datatable-2').dataTable();

      var currentOrder = {};

      var selectDropdown = document.getElementById("edit-client");
      var currentClient = selectDropdown.options[selectDropdown.selectedIndex].value;

      var dateField = document.getElementById("new-order-date-datepicker-popup-0");
      var selectedDate = dateField.value;

      currentOrder.client = currentClient;
      currentOrder.date = selectedDate;
      currentOrder.products = [];

      $('.product-row').dblclick(function() {

        var clickedProduct = {};

        clickedProduct.ID = $(this).children().eq(0).text();

        if (currentOrder.products[clickedProduct.ID]) {
          currentOrder.products[clickedProduct.ID].amount++;
          var elementID = 'product-' + clickedProduct.ID;
          document.getElementById(elementID).value = currentOrder.products[clickedProduct.ID].amount;
        }
        else {
          var newOrderLine = {};
          newOrderLine.productName = $(this).children().eq(2).text();
          newOrderLine.amount = 1;
          currentOrder.products[clickedProduct.ID] = (newOrderLine);
          //currentOrder.products[clickedProduct.ID].productName = $(this).children().eq(2).text()
          //currentOrder.products[clickedProduct.ID].amount = 1;
          oTable.fnAddData( [
            $(this).children().eq(1).text(),
            '<input id="product-' + clickedProduct.ID + '" type="text" value="1" size="3">',]
          );
        }

        console.log(currentOrder);
      });

      $('#products-paint').click(function() {
        pTable.fnFilter('paint');
      });
      $('#products-linemarkings').click(function() {
        //pTable.fnFilter('linemarkeringen');

        var saveData = {};
        saveData.client = currentClient;
        saveData.products = [];
        var product = {};
        product.name = 'Fruitsap';
        product.amount = 1;
        saveData.products.push(product);
        $.post( "http://localhost/expoline/test", currentOrder, function( data ) {
          //$( ".result" ).html( data );
          alert("succes");
        });
      });

```

Any help?

Thanks!

# Answer
> 0 votes
Ok, I feel slightly embarrassed now, but the solution was actually quite simple.

As you can see from my JS, the 'selectedDate' gets set AS THE PAGE LOADS, not when the button is clicked. So of course, altering the date won't have an effect on the selectedDate variable.

Case closed.

---
Tags: javascript, datetime
---


title: drush cannot update commerce kickstart

text:
# Question
Title: drush cannot update commerce kickstart
I just installed Commerce Kickstart and got a prompt to upgrade from 7.x-2.20 to 7.x-2.21. drush cannot update throws error: `The commerce_kickstart directory could not be found within the modules directory at [error]
/var/www/planetwigs.com/profiles/commerce_kickstart, perhaps the project is enabled but has been deleted from
disk.` Now, the directory exists and the modules are there. In the GUI I am offered the option to download module, which I did and replaced all modules with new version, just overwrote since I did not modify anything yet and the old sftp method worked, but drush did not. BTW it is impossible to use the dropdown to selected version 2.20

# Answer
> 0 votes
Drush update for commerce kickstart is not just update drush pm-update, but rather:

drush dl commerce\_kickstart drush updatedb

Check here

---
Tags: drush, commerce
---


# Question
Title: What is the warning I get after moving to a new server?
This is the warning that I've received:

```
Warning: file_put_contents(temporary://devel_themer/cs6782ec6bb66b8a6ebfd11530a1ce0d9d1ce55eba): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in devel_themer_store_krumo() (line 348 of /home/u894021300/public_html/sites/all/modules/devel_themer/devel_themer.module).

```

What is it?

# Answer
Check for file permission where this module is trying to write , especially the temporary folder: admin/config/media/file-system
> 1 votes

# Answer
Whenever you move files/folders from one server to another then sometime permissions on those files/folders don't move as expected. So give required permissions to 'files' folder. For example,

chmod -R 777 sites/default/files/

As suggested by @4life, if you will go to 'admin/config/media/file-system' and try to save the settings, it will throw an error if the files folder don't have enough permissions.
> 0 votes

# Answer
In my case, the sites/default/files/ folder was set to 775 ( not a good idea to have it set to 777 )
I had to delete the following folder :

```
rm -rf /tmp/devel_themer/

```

Then it worked !
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Call to undefined function menu_load() in .../public_html/includes/menu.inc on line 579
I really need your help. Actually, my journey begin with the installation Drupal and some modules. After a couple of days I suddenly get an issue "500 Internal Server Error".

I asked my hosting provider why this happened, they said "That because of the file .htaccess and you should add to this file php display error". So i did this and I get a new issue :

> Fatal error: Call to undefined function menu\_load() in public\_html/includes/menu.inc on line 579.

By the way that's line 579 `else {$return = $function($value);}`. P.S I am a beginner in PHP. I really want to study Drupal more and create cool sites, but this problem...

# Answer
Here are few tips:

* Make sure your Drupal core has all the files in the right place (especially menu module).
* Make sure your imported database is in UTF-8 format.
* Upgrade your Drupal core to the latest version (`drush fr && drush up drupal`).
* Clear all your caches (`drush -y cc all`), including your memcached (`killall memcached`).
* Rebuild your registry by using Registry Rebuild.
* Ff you're using modules which are implementing `drupal_bootstrap()` (such as Secure Site), disable them.
* Try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem.
* Test it on different environment/machine.
* Check your database collation (it should be case insensitive, e.g.: `general_ci`).
* Eventually restore your database from the point where it was working before.
> 0 votes

---
Tags: .htaccess
---


# Question
Title: After DB backup and restore: Call to undefined function user_access() in ...includes/menu.inc
This question pertains to a Drupal 7 multi-site install. As a test for some future backup/migrate bash scripting that I am doing for work, I made a backup/dump of my test site postgres DB. I then dropped the DB and recreated it with the same (old) name. I then restored the DB from my backup. I did not touch any files. I thought everything had worked out well, except I have an error that I cannot figure out:

> Call to undefined function `user_access()` in .../includes/menu.inc on line 634.

Things I've tried:

* As a sanity check, I made sure that User module was in my core files and that user\_access was defined in user.module
* Checked out the restored database in pgAdmin, made sure that user 0 (anonymous user) was still there
* Truncated any table starting with '\_cache':

```
Truncate table prefix_cache;
Truncate table prefix_cache_block;
Truncate table prefix_cache_bootstrap;
Truncate table prefix_sessions;
Truncate table prefix_cache_field;
Truncate table prefix_cache_filter;
Truncate table prefix_cache_form;
Truncate table prefix_cache_image;
Truncate table prefix_cache_menu;
Truncate table prefix_cache_page;
Truncate table prefix_cache_path;

```
* Checked the system table and disabled, checked and re-enabled various modules including user module via the 'status integer' value/col. (I'm not sure if this is the way to enable and re-enable modules in the DB).
* Tried to install Drush on my server but file permissions are very restrictive. It seems that Drush has limited abilities. Drush can only clear its own cache even after I setup an alias for the site in question.
* Created a 'modules' directory inside of the site's multi-site directory and copied the user module out of core and put it there.
* Tried the export using utf8 as the encoding of the DB and re-importing (no change in error)

# Answer
> 1 votes
Here are few tips:

* make sure your Drupal core has all the files in the right place (especially user module),
* upgrade your Drupal core to the latest version (`drush fr && drush up drupal`)
* clear all your caches (`drush -y cc all`), including your memcached (`killall memcached`),
* rebuild your registry by using Registry Rebuild,
* if you're using modules which are implementing `drupal_bootstrap()` (such as Secure Site), disable them,
* try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem,
* use XDebug and generate a trace file to analyse the code execution,
* or use IDE debugger, breakpoint on the failing line and check why the function doesn't exist,
* test it on different environment/machine,
* eventually restore your database from the point where it was working before.

---
Tags: 7, backups
---


title: After drush arr - cannot login

text:
# Question
Title: After drush arr - cannot login
php 5.5.x, mysql 5.5, drush 5.x, drupal 7.33,

1. backed up drupal: 'drush ard default --destination=/manual\_backup/backup\_site\_2014\_11\_15.tar'
2. switched to new 14.04 Ubuntu server, installed drush, import tar file:

drush arr ./backup\_site\_2014\_11\_15.tar --destination=/var/www
3. edited /etc/hosts:

127.0.0.1 mysite.local

4. edited /etc/apache2/sites-available/default.conf

`ServerName mysite.local
 Root /var/www

 AllowOverride …`

5. Restarted apache

While 'drush cc all' I got the message:

> > PHP Fatal error: Call to undefined function node\_load() in /data/www/fdb/includes/menu.inc on line 593 \<\<
> >
> > Drush command terminated abnormally due to an unrecoverable error \<\<
> >
> > Error: Call to undefined function node\_load() in /data/www/fdb/includes/menu.inc on line 593 \<\<

Then I did 'drush dl registry\_rebuild' and 'drush rr'.

Unfortunately I couldn't login. So I created a one time login which works.

I see all nodes, users, views, rules etc.

But after logging out I cannot login regularly.

Then I created a new password for user admin\_ip via '/scripts/.create-new-pwd newpwd' and put the hash into the users database.

Finally I tried to login again but it didn't work.

How would you start to see what's wrong?

# Answer
Here are few tips:

* make sure your Drupal core has all the files in the right place (especially node module),
* make sure your imported database is in UTF-8 format,
* upgrade your Drupal core to the latest version (`drush fr && drush up drupal`)
* clear all your caches (`drush -y cc all`), including your memcached (`killall memcached`),
* rebuild your registry by using Registry Rebuild (which you already did),
* if you're using modules which are implementing `drupal_bootstrap()` (such as Secure Site), disable them,
* try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem,
* test it on different environment/machine,
* eventually restore your database from the point where it was working before
> 1 votes

---
Tags: drush
---


# Question
Title: How to display form submitted values without storing in database
I am new to Drupal. I couldn't figure out how to display the values submitted in a form on a new page without storing in a database. I found a video on how to retrieve data submitted through a form and stored in a database, but, for my site I wouldn't need to store data. The data will get some simple mathematical processing and then the result will be displayed on another page. Here is the code I have.

```
<?php
/**
 * Implements hook_permission().
*/
function form_price_permission() {
return array(
'submit form_price' => array(
  'title' => t('Submit form_price'),
  'description' => t('Submit the form_price form'),
  ),
);
}
/**
* Implements hook_menu().
*/
function form_price_menu() {
$items = array();
$items['form-price'] = array(
  'title' => 'Form to calculate price',
      'page callback' => 'drupal_get_form',
  'page arguments' => array('form_price_form'),
  'access arguments' => array('submit form_price'),
);
return $items;
}
/**
 * form implementation
*/
function form_price_form($form,&$form_state){
$form = array();
$form['numberb'] = array(
    '#required' => '1',
    '#field_prefix' => 'Number B',
    '#weight' => '1',
    '#title' => t('B'),
    '#type' => 'textfield',
);
$form['numbera'] = array(
    '#required' => '1',
    '#field_prefix' => 'Number A',
    '#weight' => '2',
    '#title' => t('A'),
    '#type' => 'textfield',
    );
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
    '#weight' => '3',
);
 return $form;
 }
/**
  * how to display A + B
 */
function form_price_form_submit($form, &$form_state) {
$a = $form_state['values']['numbera'];
$b = $form_state['values']['numberb'];
$c = $a + $b;
}

```

# Answer
> 1 votes
I suggest:

* deleting all the default submit handlers in the submit array in the $form variable - to stop the data being stored in the database
* add your own submit handler to do the calculation and store the result in the standard PHP \_SESSION variable
* add a #redirect property in the (correct place) $form array variable to redirect the to URL of the result page
* write code for the result page output the result in the \_SESSION variable. To do this determine what type of page will display the result so that you can implement appropriate code to display the result - there are several ways to do it: e.g. code in a template file, or a custom programmatically created block

# Answer
> 1 votes
The "quick and dirty" way to display the result of the addition is to add the following line at the end of your submit handler:

```
drupal_set_message($c);

```

That will display a status message above the form with the result.

But if you want to display a new page with the result, I suggest redirecting the form to a new menu item. Thus your submit handler will look like this:

```
function form_price_form_submit($form, &$form_state) {
$a = $form_state['values']['numbera'];
$b = $form_state['values']['numberb'];
$c = $a + $b;
$form_state['redirect'] = 'form-price-result/' . $c;
}

```

And you will need to add the following menu item for function form\_price\_menu:

```
$items['form-price-result/%'] = array(
'title' => 'Result of price calculation',
'page callback' => 'show_result',
'page arguments' => array(1),
'type' => MENU_CALLBACK,
'access arguments' => array('submit form_price'),
);

```

And the following callback function to display the result:

```
function show_result($result){
   return t($result); }

```

---
Tags: forms
---


# Question
Title: Can I use hook form alter to add an attribute to a webform field?
I am trying to use hook form alter to add an onchange attribute to a select field but it is not working. Is it possible or is there something wrong with my module code?

```

function addonchange_form_alter(&$form, &$form_state, $form_id){
  // target a single form
  if($form_id == "webform_client_form_22"){
    $form['submitted']['company']['#onchange'] = 'changevalue';
  }
}

```

Thanks for any help.

# Answer
> 3 votes
You have to do something like this:

```
function addonchange_form_alter(&$form, &$form_state, $form_id){
  // target a single form
  if($form_id == "webform_client_form_22"){
    $form['submitted']['company']['#attributes']['onchange'] = 'changevalue';
  }
}

```

---
Tags: forms
---


# Question
Title: Node access, Cron, and DANGEROUS_ACCESS_CHECK_OPT_OUT'
Observations:

1. Anonymous users can view nodes of a certain type
2. Cron runs as an anonymous user
3. Cron cannot access nodes of this type when using EntityFieldQuery
4. Cron can access nodes of this type when the tag 'DANGEROUS\_ACCESS\_CHECK\_OPT\_OUT' is added to the query.

It seems to me that DANGEROUS\_ACCESS\_CHECK\_OPT\_OUT is a misnomer and should actually be DANGEROUS\_ACCESS\_CHECK\_OPT\_IN. If access was checked, Cron would know that anonymous users have access to this type of node, or am I missing something?

Based on the initial comments I think my question is not clear, so I am going to rephrase it. What I am seeing is that I allow the anonymous user to see this type of node, but Cron cannot query it. The references to this issue are ambiguous about the reason. If Cron runs as an anonymous user, then Cron should not get different access than an anonymous site user. Or Cron does not run with any user profile at all. That would actually make sense, but that is not how people explain this. So what is really going on? Is the flag a misnomer, or do people not make a clear distinction between "anonymous user" and "no user"?

# Answer
> 1 votes
I read it more as "Dangerous, Access Check Opt Out"

# Answer
> 1 votes
It is used to by-pass the access control Drupal implements for entities and their fields. It is normally used for querying entities that are not shown to the user, for example user accounts that have never been used to access the site and that needs to be removed basing on the content of some fields, the nodes assigned to the currently logged-in user who requested the cancellation of their account and which needs to be deleted.
The `EntityFieldQuery` class assumes the data is being showed to the user currently logged-in (and verifies the user has access to the entity being queried), but that is not always the case, as in the case of functions automatically running as cron tasks.

So, Alex Laughnan correctly reads it as "Dangerous: Access check is being opted out."

---
Tags: 7, users, cron
---


# Question
Title: How to use hook_menu to create wildcard aliases to a normal node page
I have a node template where I check the url for the existance of some parts and play with that, eg, if the node is called `your/recipies`, I catch urls like

```
/your/recepies/bananas
/your/recepies/apples
/your/recepies/oranges

```

and check the url for bananes,apples,oranges in the template.

I used aliases to point those urls to the original node, but they keep on dissapearing. It's probably be a breeze to set up a module router, like

```
function kitchen_menu() {
        $items = array();

        $items['your/recipies/%'] = array(
            'title'  => t('Recipies'),
            'page callback' => 'drupal_magic',
            'page arguments' => array('your/recipies')

        );
 }

```

to make drupal just render the node (and not redirect somewhere). however, i cant find out what to write instead of `drupal_magic`.

(recipies, if you must know, is a webform; not something i can easily generate myself)

# Answer
> 0 votes
fwiw, I now did this different. I won't accept this as an answer, because it isnt. But this works as well in my case

```
function kitchen_url_inbound_alter(&$path, $original_path, $path_language) {
    if (preg_match('|^your/recepies(/\w+)?|', $path, $matches)) {
        $path = 'your/recepies';
    }
}

```

---
Tags: 7, redirection, routes
---


# Question
Title: How to create a select list that contains url links
This is probably a very noob question but here it is none the less. I want to create a select list that contains the names of places around the world. When the user clicks on a name, it uses a hidden url to go to that place. So what the user sees is a normal select list of place names (not links), when they select an item then they are taken to that page.

On the manage field tab of the node that this is implemented on, I tried creating a select element with the following options:

```
 http://www.australia.com|Australia
 http://www.germany.com|Germany

```

But this doesn't work. What do I need to do to accomplish what I want?

# Answer
> 1 votes
With views you van create jump menu's: http://nodeone.se/en/learn-views-with-nodeone-part-18-jump-menu

You can use that view as a block on your page.

If you want to use it between your other fields, you can use the module https://www.drupal.org/project/viewfield. Add a field of type viewfield on your content type, choose the view you created earlier and pass the nid as parameter.

---
Tags: 7, nodes
---


title: Default language not working properly

text:
# Question
Title: Default language not working properly
I have a site with 2 languages: **English** and **Spanish** and Path prefix: **en** and **es** respectively. Then Spanish language is set to default (see image 1)

And the Language negotiation is set to: **Path prefix with language fallback** (see image 2)

Everything works as expected but there is one problem: when the site is loaded it takes the English as default language. Then if I change language (with the Language Switcher) everything works fine.

To be clear, it the url is:

www.mysite.com (landing page is loaded in english) **I need this to be in spanish**

www.mysite.com/en/home (landing page is loaded in english)

www.mysite.com/es/home (landing page is loaded in spanish)

I can't fix this..Any help please?

# Answer
> 2 votes
The description given in the settings page reports what exactly the option you selected means:

> **Path prefix with language fallback.** The presentation language is determined by examining the path for a language code or other custom string that matches the path prefix (if any) specified for each language. If a suitable prefix is not identified, the display language is determined by the user's language preferences from the My Account page, or by the browser's language settings. If a presentation language cannot be determined, the default language is used.

You are accessing the page without any page prefix (the URL is just www.mysite.com); in that case, the language is set basing on what the logged in users have selected in their user profiles, or what the settings for their browsers are.

I would try setting the front page to www.mysite.com/es/home, but in that case, the front page would always be in Spanish. As alternative, one of the modules of the Internationalization project should correctly set the language for the front page.

# Answer
> 5 votes
1. goto: Home » Administration » Configuration » Regional and language » Languages.
2. select the 'DETECTION AND SELECTION' tab.
3. Un-check all except 'URL' and 'default'. Keep 'URL' on top of 'default'

# Answer
> 0 votes
You can try the Language Selection Page module. (The module is a sandbox project: use it at your own risk.)

# Answer
> 0 votes
If you want to stick to the "Path prefix with language fallback" mechanism, you cannot use the "Path prefix and default language" mechanism proposed by @user392795, which otherwise is great.

However, there are also solutions for this:

**First case: You don't need Drupal's default feed on the front page**

This is the simpler case, as we can exploit the shortcoming that Drupal will not do language negotiation when setting the "Default front page" field at `/admin/config/system/site-information`. So just set it to a URL of a node or view etc. that is in Spanish. This solution is also dealt with in this question.

Just make sure the "Default front page" does *not* say "This is a multilingual variable." below it, because that adds language dependent front pages which are not available in Drupal out of the box. If this is the case, you can get rid of it by following this process in reverse.

**Second case: You also want to keep the Drupal default feed on the front page**

In this case, Drupal's language selection mechanisms govern the front page, so you have to make sure that users arrive at the frontpage always with the path prefix for Spanish. Else, the language fallback mechanism would kick in and determine the language from the profile preference or browser language, as explained by @kiamlaluno already..

So, set up a URL forwarder that will do this redirect. For example with the Apache mod\_alias mechanism in `.htaccess`:

```
Redirect 301 / /es/home

```

This one should also work, bit nicer:

```
Redirect 301 / /es

```

(If this does not work in your case, see some details.)

---
Tags: i18n-l10n
---


title: How can I fix the pages pager returns?

text:
# Question
Title: How can I fix the pages pager returns?
I have a number of "product nodes" that I'd like to return and display in a paged table.

The original query is generated as follows:

```
    $productNodeQuery = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('type', 'product', '=')
    ->extend('TableSort')
    ->extend('PagerDefault')
    ->limit($page_limit);

    $productNodes = $productNodeQuery->execute();

```

This returns all the products I want, however the pages are all messed up. Some pages have 3 items, some pages have 10, others have the full $page\_limit (50) items per page.

I have a loop

```
foreach($productNodes as $productNode) {
....
}

```

to iterate over the results and add each product to the $rows\[\] array with this:

```
 $rows[] = array(
            'data' => array(
            'autoupdate' => $part['autoupdate'] == "1" ? 'ENABLED' : 'DISABLED',       // Display Checkbox?
            'part_number' => $part['part_number'],
            'title' => l($this_node->title, url($base_url . '/node/' . $this_node->nid)),
            'category' => l($this_category_name, url($base_url . '/catalog/' . str_replace(' ', '-', $this_category_name ))) . "<br />(Markup: " . $this_markup_percent['suggested_markup']*100 . "%)",
            'supplier_price' => $supplier_prices_string != "" ? $supplier_prices_string : "N/A",
            'suggested_price' => isset($suggested_prices_string) ? $suggested_prices_string : "N/A",
            'sell_price' => '$' . number_format($this_node->sell_price, 2),
            'competitors_price' => isset($competitor_prices_string) ? $competitor_prices_string : "N/A",
           'edit_node' => l('Edit Node', $edit_node_link, array('attributes' => array('target' => '_blank'))),
           'message' => "<em>" . $row_message . "</em>",
                ),
           'class' => array($row_class),
  );

```

Finally, after the $rows array has been defined with all the data I need I am building the table with this:

```
$form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => 'There are no product nodes found',
);
$form['pager'] = array(
    '#markup' => theme('pager')
);

```

Does anyone have an ideas as to where I'm going wrong with the pager?

(Full Form Code is available here: http://pastebin.com/bna1g1iV)

Thanks,

# Answer
> 0 votes
I would add this as a comment if I could. Looking at your code, it looks like you're only adding rows to $rows is $part\['wtcr\_sku'\] is an empty string (line 258). It's possible you could be filtering out rows because of that.

---
Tags: paging, theming
---


title: How to locate page template in use?

text:
# Question
Title: How to locate page template in use?
I have a strange situation where my Drupal 7 Omega 4 site appears to not be using a page.tpl.php template. The page renders and content appears but when I alter all of my page templates to indicate which one is in use (By adding a "\<h1\>TEMPLATE NAME.tpl.php\</h1\> above the "print render($page\['content'\]);") I see nothing in the rendered output on screen.

I have cleared the caches. Many times.

Is it possible for Drupal to somehow not use a page template and still render a page's content? I would have thought not but can't figure out how this could be happening. I'm guessing I'm completely forgetting something quite basic here.

Any help greatly appreciated.

# Answer
You can use the https://www.drupal.org/project/devel\_themer module to see what tpl file is in use. You should see the path to your subtheme. If you see the path to the base theme, then your tpl file is not found.
> 3 votes

# Answer
There are quite a few variables that determine which template/function is used for any specific theme hook. There is a hierarchy of suggestions involved, where different patterns may take precedence. That general concept is outlined in the main theme documentation.

It's also important to note that if you are using a sub-theme (as is likely the case with a framework like Omega) your sub-theme's "page" template will take precedence over Omega's "page" template, which will also have precedence over core's own "page" template.

Because of all these precedence rules, you may have a case where there is a page template defined in your setup, which you have not "tagged" with your test `<h1>TEMPLATE NAME.tpl.php</h1>` text, that is being selected by specificity (perhaps it's targeting a content type, or path, or something more specific than the generic page templates you have already checked).

To see exactly which templates are used at any given time, you may want to check out the Theme Develper module, as it will provide a nice visual explanation of how Drupal's various theme hooks are related to DOM elements. Here's an example of the kind of output it can produce for the page-level container:
> 1 votes

# Answer
Check out Theme Developer. It will show you what templates are used on each renderable part of the page (page, block, node, etc.).

You could probably also implement hook\_preprocess\_page in your custom theme, and look at either $vars\['theme\_hook\_suggestions'\] or $vars\['theme\_hook\_suggestion'\]. See this page about template suggestions.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How not render a region on specific page programmatically on Drupal 8
I put a custom block (develop for me) on sidebar first region for every page, every fine, but I want that this block not render on the home page.

On my module, I made this:

```
funtion mymodule_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    unset($variables['page']['sidebar_first']);
  }
}

```

The sidebar not show, but the block already was rendered (I debug this code and the build function of my block was called before of mymodule\_preprocess\_page function). Then how I programmatically avoid that this block not render.

# Answer
> 1 votes
Got to /admin/structure/block on your domain. Click the configure button beside your block. In the lower part of the configuration form you have a section called visibility. One of the tabs in this section is labelled pages. This is where you configure where the block is permitted or forbidden to be rendered. In your case one would write `<front>` and choose the radio button labelled "Hide for the listed pages".

# Answer
> 0 votes
Maybe `hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)` ?

---
Tags: blocks, 8
---


# Question
Title: How to force homepage to non-default language
I'm working on a bilingual website (French and English). The homepage currently shows up as per language detection settings, but I need it to show in French *first*, with the English version available via language switcher.

Info: Both languages use prefixes, and the language detection settings are ordered as URL\>User\>Browser\>Default (English). The homepage is built with Panels and Views.

I've tried playing with redirects (has no effect) and i18n Variables (results in the page content not being found).

# Answer
> 1 votes
At admin/config/system/site-information add your system path (node/1, node/2 or whatever) to Default front page field. (Don't ask why the "prompt" sometimes displays the language prefix, sometimes doesn't, I don't know.)

Language detection settings have no effect here, I think. At least when you have URL first.

# Answer
> 0 votes
You *can* use redirects, but you might have to set them up on the web server level. Setting a front page redirect up in Drupal might be too late in the process. So:

1. **Give the path prefix highest priority** in the language negotiation settings. Else, URLs would not reliably select a language version. Already done in your case.
2. **Find a URL that loads your French front page content.** Options:

* Something like `http://example.com/fr/node/1`. For example, if you use Panelizer to panelize a node and to add views to it. Simplest option, but does not look good.
    * Something like `http://example.com/fr/home`. Uses the node alias instead of the node ID.
    * `http://example.com/fr`. Nicest URL. If it does not work for you, then possibly because you use Drupal's default front page config field, with which the language switcher does not work. You can make it work by enabling multilingual front page configuration \[see here, or here for more details).
3. **Set up a redirect in the web server.** For example if you use Apache and the "nicest URL" from above, you can use the mod\_alias mechanism in `.htaccess`:

```
Redirect 301 / /fr

```

(If this does not work for your case, see some details.)

---
Tags: i18n-l10n
---


# Question
Title: Pass custom query strings across website
I want to use some custom query strings for tracking purposes and for visibility rules. The goal is, to provide a link such as www.example.com#affiliateid=1 and the string is preserved through the whole web session. Ideally, # should be used instead of ?, as it is ignored by google and prevents duplicate content.

However, each time I click a link on my site, the parameters are lost.

I don't really know where to start - are they usually passed and is this a problem with url rewrite or would I have to learn drupal that it should append the strings to each link?

Thank you!

# Answer
> 0 votes
I found a working jQuery-based Solution on the Internet:

```
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

jQuery(document).ready(function ($) {
var persistedQueryParam = getParameterByName('PARAMETER1');

if (persistedQueryParam && persistedQueryParam.length > 0) {
$('a[href]').each(function () {
  var elem = $(this);
  var href = elem.attr('href');
  elem.attr('href', href + (href.indexOf('?') != -1 ? '&' : '?') + 'PARAMETER1=' + persistedQueryParam);
});
}
});

```

This seems to work good SEO wise as the links seem to stay the same until click. So I suppose google should be ale to use the original rel=canonical link, right? Or would I have to write an exception for it?

# Answer
> 0 votes
That's probably a bit messy. Have you considered using cookies or even the session variable?

**Edit:** Turns out it might actually be possible and without much fuss! Thanks OP for raising the question and making us question (and research) this a bit.

Drupal has a hook to rewrite all URLs (hook\_url\_outbound\_alter), which coming to think about it makes total sense.

Basically you can use this hook to grab a session variable or a cookie - you still want to store it somewhere just so that in case you lose it at some point you can easily retrieve it and recover the navigation - and rewrite the URLs according to whatever rules you need.

Here's a sample for future reference, not mine just adding it here so we don't lose it if the link breaks:

```
<?php
/* Helper function for using strpos with an array of strings.
 */

function strposa ($haystack, $needles) {
    $bool = false;
    foreach ($needles as $needle) {
        if (strpos($haystack, $needle) !== false) {
            $bool = true;
        }
    }
    return $bool;
}

/* Implements hook_url_outbound_alter
 */

function rl_int_url_url_outbound_alter(&$path, &$options, $original_path) {
    //Break path into an array
    $arr = explode('/',$path);
    //Get country list and exclude paths
    $c_list = array('us','ca');
    $system_paths = array('admin', 'user', 'sites', 'system');
    $exclude_paths = array('node/add', 'sitemap');
    //If the path contains a system path in the first argument, or has an exclude path in the full path string, do not set a prefix.
    if (in_array($arr[0], $system_paths) || strposa($path, $exclude_paths)) {
        $options['prefix'] = '' ;
    //OK, it's not an excluded path. If the path doesn't have the prefix already, add a prefix.
    } else if (in_array($arr[0], $c_list) == false) {
        $c = $_COOKIE('Drupal_visitor_country');
        $l = $_COOKIE('Drupal_visitor_language');
        $options['prefix'] = $c . '/' . $l . '/';
        //Special case: remove "home" from the path if it's the home page, so that it's example.com/us/en instead of example.com/us/en/home.
        if (drupal_lookup_path('alias', $path) === 'home') {
            $path = '';
        }
    }
}
?>

```

Hope this helps!

---
Tags: uri
---


# Question
Title: Drupal 7 "Page not found. The requested page "/" could not be found" after enabling module
While enabling a module (Imagecache External), Drupal showed an error related to memory limit, then the site crashed. I'm unable to login anymore, since any page shows now:

> Page not found. The requested page "/" could not be found.

I get the same result when I try to go http://www.example.com/index.php?q=user.

`phpinfo()` says mod\_rewrite is enabled.

# Answer
After extensive research I managed to solve this issue. The following info was helpful: https://www.drupal.org/node/262892

What I did:

1. Disabled the problem module in the system table in SQL, by setting the status field of the suspect module to 0 in the {system} table.
2. Rebuilded Database menu system to get access again, by running update.php. The update.php by default don't allow to access, so I need to edit **settings.php** (located in /sites/default/) and change `$update_free_access = FALSE;` to `TRUE`. After rebuilding menu remember to change this back to `FALSE`.
> 3 votes

---
Tags: 7
---


title: Default language wrong on front page

text:
# Question
Title: Default language wrong on front page
I've got two langagues enabled on a Drupal 7 test site, English (set to default in admin/config/regional/language) and Finnish. Under 'Detection and Selection' URL and Default are checked, and URL is set to look for a path prefix.

I've 'translated' (i.e. run through Google Translate) one content item and can switch between the two versions by adding or omitting 'fi' to the path. However, on the front page list of content items the Finnish version is displaying, when I'm expecting to see the English one.

Does anyone know what I'm likely to have messed up or overlooked?

Toby

# Answer
*You say this happens with "the default Drupal front page" (that content feed). Realizing it now. The below is for those who have this problem with the front page set to display a specific node instead (at `/admin/config/system/site-information`).*

**Possible cause: using a multilingual variable** for setting the front page content, and forgetting to update it. In that case, when visiting `example.com/en`, the Finnish version of the front page's node is displaying. However, when accessing that same node via (say) `example.com/en/node/1`, the English version would show.

**Explanation.** Normally, one URL is configured as alias for the frontpage at `/admin/config/system/site-information`. If this points to a content item with translations, they are shown as selected by the path prefix. With the multilingual variables however, one URL is configured per language version of the front page, completely overriding Drupal's normal language negotiation mechanism. The path prefix then selects the node given in the corresponding language version of the configuration option, *even if that node is in a language not matching the path prefix*. (Which leads to the funny effect that in the code rendering that front page node, `$language` is "wrong": it is that node's language, here and only here potentially different from the language selected by the path prefix.)

**Fix.** To fix this condition and preventing it from recurring:

1. Go through all translations of your frontpage node and set them to the same alias, let's say, `home` \[source\]. This should work, as each has a different language path prefix.
2. Go through the language versions of `/admin/config/system/site-information` and update all "Default front page" fields to contain `home`.
3. You probably have to repeat the last step for a new language after adding it. But I did not confirm this.

This whole multilingual variable thing is only to allow the front page being shown in different languages even when language is not selected by path prefix.

Or disable the multilingual versions of this variable altogether, by following this process in reverse.
> 0 votes

# Answer
The default Drupal front page that you use "does not filter by language in any way" \[source\]. When using content translation (aka "node translation": one node per language version), Drupal would list all language versions of all your nodes in the default Drupal front page's feed.

So perhaps you are simply not seeing the English nodes listed as they are omitted or paged to a second page?

If you want your single content item on the front page, shown in your English default language by default, you can simply put your content item's path into the "Default front page" field at `/admin/config/system/site-information`.

However, that will mean that the language switcher does not work for this content on the front page (except *maybe* when using entity translation). So instead, I recommend to follow this answer, which will make the language switcher work on the front page even with node translation.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: how to add posting options to content types?
I'm porting a Drupal 6 module to Drupal 7. In Drupal 5 & Drupal 6, there was a Workflow section in the Content Types area and the additional fields went there. This is gone in Drupal 7. I tried to add a custom section, but it's not working at all.

Here is my code:

```
/**
* Implements hook_form_alter() - adds fields to Content Type forms.
*/
function phpfreechat_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $type = (isset($form['type']) && isset($form['type']['#value'])) ? $form['type']['#value'] : NULL;
  $node = isset($form['#node']) ? $form['#node'] : NULL;

  if ($form_id == 'node_type_form' && isset($form['identity']['type'])) {
    // Content-type edit form
    // Define field set in additional settings group
    $form['phpfreechat'] = array(
      '#type' => 'fieldset',
      '#title' => t('phpFreeChat settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#weight' => 10,
      '#group' => 'additional_settings',
    );
    $form['phpfreechat']['phpfreechat_nodeapi'] = array(
      '#type' => 'radios',
      '#title' => t('Show chat room'),
      '#default_value' => variable_get('phpfreechat_nodeapi_' . $form['#node_type']->type, 'never'),
      '#options' => array(
        'never' => t('Never'),
        'always' => t('Always'),
        'pernode' => t('Per Node'),
      ),
      '#description' => t('None: Nodes of this content type can never have a chat room.
' . 'Always: Nodes of this content type will always have a chat room.
' . 'Per Node: Nodes of this content type can choose to have a chat room if desired.'),
    );
    $form['phpfreechat']['phpfreechat_nodeapi_custom'] = array(
      '#type' => 'checkbox',
      '#title' => t('Allow node to set title & channels'),
      '#return_value' => 1,
      '#default_value' => variable_get('phpfreechat_nodeapi_custom_' . $form['#node_type']->type, ''),
      '#description' => t('If this is checked then node editors will be able to set the chat ' . 'title and select what channels to join.'),
    );
    $form['phpfreechat']['phpfreechat_nodeapi_title'] = array(
      '#type' => 'textfield',
      '#title' => t('Default Chat Channel Title'),
      '#default_value' => variable_get('phpfreechat_nodeapi_title_' . $form['#node_type']->type, ''),
      '#size' => 70,
      '#maxlength' => 128,
      '#description' => t('This is the default channel title for this content type. ' . 'Leaving this blank will use the global or node chat ' . 'title, or the node title if these are also blank.'),
    );
    $form['phpfreechat']['phpfreechat_nodeapi_channels'] = array(
      '#type' => 'textfield',
      '#title' => t('Default Chat Channels'),
      '#default_value' => variable_get('phpfreechat_nodeapi_channels_' . $form['#node_type']->type, ''),
      '#size' => 70,
      '#maxlength' => 128,
      '#description' => t('Enter the default channel or channels to be joined for this content type. Separate multiple channels by commas (e.g. *Channel1, Channel2*). If you leave this blank, it will default to the global node channel(s), or the node title if this is also blank.'),
    );
  }
  elseif (isset($form['type'])) {
    // Node edit form
    // Define field set in additional settings group
    if (phpfreechat_nodedata($type) && user_access($permission_create_chatboxes)) {
      $form['phpfreechat'] = array(
        '#type' => 'fieldset',
        '#title' => t('phpFreeChat Settings'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => 10,
        '#group' => 'additional_settings',
      );
      if (variable_get('phpfreechat_nodeapi_' . $form['type']['#value'], 'never') == 'pernode') {
        $form['phpfreechat']['phpfreechat_enabled'] = array(
          '#type' => 'checkbox',
          '#title' => t('Show Chat Room'),
          '#return_value' => 1,
          '#default_value' => ($node->phpfreechat_enabled == 1 ? TRUE : FALSE),
          '#description' => 'If this is selected a chat room will be displayed below the content',
        );
      }
      if (variable_get('phpfreechat_nodeapi_custom_' . $form['type']['#value'], '') == TRUE) {
        $form['phpfreechat']['phpfreechat_title'] = array(
          '#type' => 'textfield',
          '#title' => t('Chat Channel Title'),
          '#default_value' => $node->phpfreechat_title,
          '#size' => 70,
          '#maxlength' => 128,
          '#description' => t('This is the chat title. You can leave this blank to use the default.'),
        );
        $form['phpfreechat']['phpfreechat_channels'] = array(
          '#type' => 'textfield',
          '#title' => t('Chat Channel'),
          '#default_value' => $node->phpfreechat_channels,
          '#size' => 70,
          '#maxlength' => 128,
          '#description' => t('Enter the channel or channels to be joined for this chat. Separate multiple channels with commas (e.g. *Channel1, Channel2*). You can leave this blank to use the default.'),
        );
      }
    }
  }
}

```

I posted it on the Drupal forum, but they're too arrogant to answer questions over there. They ignore everything I post.

https://www.drupal.org/node/2431113#comment-9648927

# Answer
Looking at the code you posted:

```
if ($form_id == 'node_type_form' && isset($form['identity']['type'])) {

```

I don't think there's a $form\['identity'\] defined in node\_type\_form, so your form fields would not be added at all. If you're checking for a valid content type, you can look for $form\['#node\_type'\].
> 0 votes

# Answer
Thanks very much. That turned out to be it. I found the answer in this response to another question:

https://drupal.stackexchange.com/a/5891/44501

I changed the "if" statement to:

```
if ($form_id == 'node_type_form')

```

and it worked. :)
> 0 votes

---
Tags: nodes
---


# Question
Title: Best practice: content types with unique machine names
We have a module install script that auto-generates content types.

The content type machine names are based on text field data inputted by a user using a custom form. For example:

User title = 'Technical' =\> Auto-generated machine name = technical\_comp

User title = 'Specialist Claims' =\> Auto-generated machine name = specialist\_claims\_comp

… and so on.

For the module to be robust, it needs to create unique 32 character machine names where there are two text fields with the same data.

Is there best practice around this?

I was thinking something along the lines of:

User title = Technical =\> Auto-generated machine name = a1\_comp

User title = Specialist Claims =\> Auto-generated machine name = a2\_comp

… which would give us plenty of scope but would require some kind of content type count.

# Answer
Counting content types should be as easy as:

```
$result = db_select('node_type')
        ->fields('node_type')
        ->execute();
$num_of_results = $result->rowCount();

```

https://www.drupal.org/node/1226410
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Select an image from a list to an image field
I'd like to achieve the following:

When the user creates new content, instead of uploading an image to an image field every time, I would like to make an opportunity for the user to select from 8 pre-uploaded images and if none of those are appropriate, allow her/him to upload a custom image as well.

Is there any way I can achieve this with contrib modules?

Thank you.

# Answer
> 1 votes
You can try "IMCE for File Field" module for this: https://www.drupal.org/project/imce\_filefield

It depends on IMCE module. Gives the option to select a file from the predefined location instead of uploading.

# Answer
> 0 votes
Have you tried Avatar Selection module?

> When a user edits their account details they can choose to upload an image or photo of themselves, also known as an avatar.

**Another Hint:** Using the Media module you can allow users to select images from a library or upload there own which sounds like what you want.

# Answer
> 0 votes
A very simple approach would be to use the "List" option for selecting text as a field, and in the "allowed options" put in the image tags you want. These may or may not appear as images in the drop-down or button selector, but you can fix that in the help file or in a side block.

---
Tags: 7, media
---


# Question
Title: how to identify first element in array of node objects?
hook\_node\_load($nodes, $types) in Drupal 7 takes two arrays as parameters. In the module I'm working on (Drupal 7 port from Drupal 6), just one node of one type is being loaded. I tried $node\[0\] to specify the first node in the array, but no joy. How do I get at the first node and the first type? There is only one object in each array.

# Answer
> 1 votes
$nodes is keyed by the node ID, which you probably won't know in advance. Instead of directly trying to access the first node in the array, iterate over them with a foreach loop.

```
function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $nid => $node) {
    if ($node->type == 'basic_page') {
      ...
    }
  }
}

```

---
Tags: nodes
---


# Question
Title: What Drupal tables to export from broken site
I'm on localhost with Acquia Dev Desktop , Drupal 7.34. Php 5.3.29.

I was just playing in the Views when suddenly the site crashed. After few `drush cc` and restart of Acquia Dev Desktop and trying to access the site again showed me:

> Fatal error: Allowed memory size of X bytes exhausted (tried to allocate X bytes) in c:\sites\*\database.inc on line 2171.

I tried to increase memory limit to 1024M in `php.ini` and `settings.php`. Then I check the PhpMyadmin and I found that the watchdog table has ~6,000,000 records and its 6.4GB so I deleted it. `drush cc`, disable statistics and `dblog` modules. But still can't access the site. it just don't open. I copy watchdog table from another Drupal install (actually it was a previous backup) but still doesn't work and now it shows:

> Fatal error: Maximum execution time of 300 seconds ...

and the watchdog db increased from 0mb to 350mb with ~777,034 rows. Can I export certain tables with my views, taxonomy and settings and import them in another Drupal clean install? the Content is not important.

Edit:

> Watchdog Message:`%type: !message in %function (line %line of %file).`
>
> Variables: \[BLOB - 294 B\]
>
> location: http://nina2.dd:8083/
>
> the file watchdog\_variables.bin says:

```
a:6:{s:5:"%type";s:14:"Strict warning";s:8:"!message";s:40:"Creating default object from empty value";s:9:"%function";s:43:"views_many_to_one_helper->ensure_my_table()";s:5:"%file";s:60:"C:\Sites\nina2\sites\all\modules\views\includes\handlers.inc";s:5:"%line";i:940;s:14:"severity_level";i:7;}

```

# Answer
Not at the database table level, no. There's a contributed module in Drupal called "Features" that lets you export content types, fields, views and some other configuration into a custom created module, but you would need a functioning site to begin using it.
> 0 votes

---
Tags: 7, database, importing-exporting, log-messages
---


# Question
Title: Is it possible to use search api indexs together?
I'm trying to create a search page for forum topics. Forum topics however are both posts and the comments attached to them, unlike other content the comments and actually posts are just as important to search.

I have an index of all forum posts and one of all forum comments. I'd like to be able to have both searchable from one page. Maybe even if it's possible then I'd like to have one index that handles all of them. But if that is not possible then is it possible to combine two index's in search api into one page search?

I'm not finding anything on this so far, but will keep looking. If I find something before I get an answer I'll post it here.

# Answer
Yes, you need to used the **Search API multi-index searches** module.

> This module is an addition to the Search API module which allows users to search on several indexes at once.
>
> When the module is enabled, you'll get a new Views base table where you can search all enabled Search API indexes at once. Performance might suffer, though, if not all indexes lie on the same Solr server (or other backend server that supports this feature).
>
> Please note that, since multi-index searches aren't supported explicitly by the Search API, most other Search API add-on functionality (facets, autocomplete, saved searches, search pages, etc.) won't work with searches created with this module.

There is also a sanbox project that allows you to combine Search Multi Index and Facets.
> 0 votes

---
Tags: search
---


title: Delete only referenced Nodes

text:
# Question
Title: Delete only referenced Nodes
I have created a report of each students with their paid fee invoices.

Now I would like to delete the invoices only.

Please help me out from this.

# Answer
> 0 votes
This could be solved by creating a simple view with VBO. Try this steps:

1. Create a view of content, without any filter criteria.
2. Add a relationship to the view of the reference field in the 'student' content type. Say 'field\_invoice'.
3. Add a filter to the view of "content type", select 'invoice'. **Use** the relationship in the filter that was created in step 2.
4. Add a filter of "content title". Expose this filter. **Use** the relationship in this filter too.
5. Add a VBO field of type "Bulk operations: Content (Content)". Select 'delete' from the operations.

From this view, you should be able to filter by name of any student. It will list the invoices. And using VBO, you should be able to delete them.

---
Tags: views
---


# Question
Title: Secure Way of sending argument from one page to another
In my Drupal Page I have one l() function as follows:-

```
l('View Comments','admin/comments', array('query' => array('commentid' => $rinap_comm['record_id'])

```

So in this case I am passing the argument to new page 'admin/comments' using 'commentid'. The url will look like this:-

```
http://XXXX/someURL?commentid=15

```

In new page I will retrieve the value using

```
$commentId= $_GET['addUser'];

```

This is all fine to get and set argument using GET function. But I didn't find it secure way to transfer confidential information from one page to another as the value will get appended in URL which can be visible to everyone.

Can anyone please suggest if there is more secure way of passing the information without visible to end user? If possible please brief me the steps.

# Answer
You can symmetrically encrypt the data into a cipher before sending it, and decrypt it at the receiving page. This will not stop anyone from seeing the encrypted data, but they will not have access to the encryption key and will therefore not be able to understand the data.

If the data to passed is short, the encrypted data can be passed in the URL. To use an URL, just base-64 encode the resulting cipher so it can be represented by a string (and base-64 decode it at the receiving end to get back the cipher). Remember to decrypt to convert from the cipher to the original cleartext.

If the data is too bulky to fit in an URL, you may use a session variable to transfer the cipher. Then you can skip the base-64 encode/decode step. A session variable is not secure. However, just as with the URL, encryption will keep the data confidential.

Or, you can simply use pass the data using the database. This requires you to create a very small custom module that associates the data with a token that does not give away any information (e.g. an integer). You then pass the token by means of the URL, e.g.:

```
http://XXXX/someURL?tokenid=15

```

The receiving page then use this token to look up the data in the database.
> 3 votes

---
Tags: 7, routes
---


# Question
Title: How to have on-page comments in Drupal 7?
Currently, if you enable threaded comments on Drupal, the user has the ability to click on "reply". This takes the user to another page where they can write the comment. I want this functionality to happen on-page. In other words, if they click "Reply", a comment box must drop open using JavaScript or Jquery.

First prize is if there is already a module available or some setting that does this that I am missing. Alternatively, I would assume the best way is to just include the code in the Template File of the comments being generated?

# Answer
It seems you're looking for the AJAX Comments module

**Features:**

> Provides ajax comments to Drupal sites. Features:
>
> * Makes AJAX submits
> * Allows replies to comments on the actual thread page
> * AJAX comments deleting
> * Works with CAPTCHA
> * Cool jQuery sliding
> * views integration
> 3 votes

---
Tags: 7, comments
---


# Question
Title: HTML comment based tokens in hook_views_post_render()
I am trying to figure out why my HTML comment based tokens are not getting replaced in hook\_views\_post\_render(). I have a view where I've got a couple of fields, let's say, nid and the content title. I want to replace the title with something else.

So, I've edited the content title and checked the box to rewrite the output of the field and added something like this:

```
<!--something-->

```

Now, in hook\_views\_post\_render() I am doing this:

```
strtr($output, array('<!--something-->' => 'my changed output');

```

But the problem is, nothing happens. For some reason, $output doesn't have the HTML comment, it's like it is being stripped out. I have specifically looked at the options for the field in my view and I don't have any of the checkboxes checked that strips out the HTML. I can add other html in $output and they all work fine, so there is no problem with the html going through. So, I am wondering what the issue is. Would appreciate any help on this.

# Answer
It is being stripped -- rewritten views field output still gets run through filter\_xss\_admin(), which strips out any HTML tag-like construct that isn't in the default allowed\_tags list.

Instead of using a `<!--something-->` format, try using `[SOMETHING]` instead.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Drupal and mobile - integration across multiple applications
I have Drupal installed to Amazon EC. I was wondering is it possible to make another database so that mobile users can upload pictures with location there and users from the Drupal website can see these pictures? What would I need to do?

# Answer
> 2 votes
You need something like next, right?

* User upload image from mobile application
* User can see it in site

If it's right - it's not need new database, all can be maked with one. As one method - you can create special node type and one of next things:

* Create custom module, that create new nodes (in my opinion - it's better)
* Submit node creation form from application

# Answer
> 0 votes
I am not sure if you are approaching this from the right angle.

First, to answer the question you're asking: Yes, it is trivial to make Drupal show data hosted elsewehere. Just link to it using the URL, (with some secret key that is authentcated on the receiving end if the data shall not be exposed outside of Drupal's access control). A custom module with about 15 lines of PHP should do this bare bones with pictures. You shall of course need some extra code to handle transfer of other data types (location, title, byline, license, access level, etc.) However, I am not sure this is the best solution.

Here is my suggestion for an alternative approach:

The Drupal login dialogue is not the *only* way a user can authenticate with Drupal. For instance, if you want to use a native app to interact with Drupal, you may use the *deviceID* for authentication, or the user may register the app once. To do this, you just need to let the programmer write a custom authentication module for your Drupal site, to exchange authentication credentials with the mobile app. It is not hard to make this authentication handshake (between the app and Drupal) invisible to the user.

Or, if the user is using a browser on their smartphone, he/she may authenticate by logging in on the site using Drupal's standard login dialogue before uploading the image using Drupal's build-in file upload.

Whether you implement the client end as a native app, or you just use the smartphone's browser, interacting with Drupal directly instead of interacting by means of a secondary DB seems to me like a better approach.

---
Tags: views, theming
---


# Question
Title: Override menu name shown by Superfish in mobile view mode?
I've installed Superfish and set a new menu. All works fine but when I dive into mobile-view I see the **machine-name** of my menu printed on a rectangle. This could be nice sometimes but I really want to override it to something else rather than *"Main Menu"*.

How will you change that?

# Answer
> 2 votes
You can change this in superfish settings. If you have accordion menu it can be set under "Accordion Menu title".

If you have select menu, there is also an option to change that at "Select settings".

---
Tags: navigation, routes
---


# Question
Title: The requested page "/http://.. could not be found. (puts slash in front of URL)
All of a sudden I cannot login because it says The requested page "/http://testsite.com/user/login" could not be found. It puts a slash before the URL

I have no idea where that comes from.

# Answer
> 0 votes
Check whether you have changed the $base\_url variable in settings.php file in sites/default folder.

---
Tags: uri
---


# Question
Title: Display HTML code in a Drupal field as plain text
I am using Drupal as a blog for posts about programming. Naturally, I have to post code samples.

When I post the code samples, Drupal renders them as actual HTML. How can I stop this from happening?

Example,

```
<h1 style="font-style: italic; font-variant: small-caps; font-weight: normal; font-size: 13px; line-height: 150%; font-family:Arial, Helvetica, sans-serif; color: #000;">Thank You</h1>

```

^ This gets displayed as the words "Thank You" with the listed formatting in the inline style.

```
 <!--[if gte mso 9]>
    <style type="text/css">
   .contact {
display:none;
}
    </style>
<![endif]-->

```

^ This doesn't get displayed at all.

**Steps I have taken**

I have created a new input format and turned off all the filters. I wrap the code in both `<code>` and `<pre>` tags.

I know Drupal has a filter called " Display any HTML as plain text". If I use this, then it works. But then all my formatting for the test of the post (e.g. paragraphs, links) get displayed as text making the post unreadable.

# Answer
> 1 votes
Try the Syntax Highlighter module

> This module integrates the SyntaxHighlighter Javascript Library into Drupal for source code list syntax highlighting within any Drupal contents.

Image from project page

# Answer
> 1 votes
Looks like you're looking for Code Filter.

> This module provides a simple text format (input filter) that handles `<?php ?>` and `<code></code>` tags so that users can post code without having to worry about manually escaping `<` and `>` characters with `<` and `>`.

It is the module used on Drupal.org for escaping markup.

---
Tags: input-formats, entities
---


# Question
Title: Asserting a failed login attempt on Simpletest
I want to test a module that adds an additional login validation clause. Only users whitelisted somewhere else are allowed to log in to the system.

In order to test this behaviour with Simpletest, I would like to assert that a random user has no access to the system.

I have tried to create this random user and then to call `drupalLogin()`. Unfortunately, my test fails because `drupalLogin()` is checking whether the log in succeeded, by calling `assertLink()` internally.

This is what I have tried:

```
    $user = $this->drupalCreateUser(array());
    $user->roles[] = 'authenticated user';
    user_save($user);

    // Try to login with it
    // It fails, because of the additional validation performed by my custom module
    $this->drupalLogin($user);

    // I would like to assert it here instead:
    $this->assertFalse(isset($this->loggedInUser->uid));

```

What should I do in order to avoid the assertion to fail at `drupalLogin()`, so that I can assert it myself?

Any help will be appreciated.

# Answer
> 1 votes
In case someone else wonders about this... It wasn't difficult, but I didn't realise at first that it can be done by copying part of the DrupalWebTestCase::drupalLogin() source code:

```
$edit = array(
  'name' => $user->name,
  'pass' => $user->pass_raw,
);
$this->drupalPost('user', $edit, t('Log in'));

```

And then asserting that the user could not log in:

```
// Assert that the user is not logged in
$this->assertNoLink(t('Log out'), 0, t('User not logged in.'), t('User login'));

```

---
Tags: 7, testing
---


title: Views autorefresh

text:
# Question
Title: Views autorefresh
I've setup views autorefresh which works fine. But one thing I would like to achieve is instead of automatically loading the new articles if it would just create a notification say there is "1 new post" or "5 new posts", then when you click it, it then loads in the new posts.

# Answer
> 0 votes
I just stumbled upon this. Can you use it and let me know whether it has worked for you or not?

---
Tags: views, nodes
---


title: Taxonomy Access module with role

text:
# Question
Title: Taxonomy Access module with role
After install Taxonomy Access and access the basic admin content page "admin/content" with an admin role called "publisher" which has the authority to administer the content the page does not show any content at all as in the attached image even i created admin views to show specific content and it works well with the "publisher" role, any reason why the basic admin page is empty !?

# Answer
> 0 votes
It was from the custom relation i made to the Administration: Nodes (Content), now it works after removing the unneeded relations.

---
Tags: users, taxonomy-terms
---


title: Dreadful Google CSE error

text:
# Question
Title: Dreadful Google CSE error
We have several sites on a multisite structure, and almost all of them use Google CSE. However, some of these websites display the error "Refused to display 'http://www.google.com/cse?cx=...' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. This behaviour happens only for a couple of sites. I have compared Google CSE settings, and they are identical. How can I fix this issue?

UPDATE: I've compared directory sizes from both sites and they were different, so I've tried removing the module from the site that doesn't work, and copying one from a site that does work; but no dice :S

# Answer
> -1 votes
Doing a quick search on Google I found this answer to a similar question: https://stackoverflow.com/questions/7905169/when-did-google-search-start-sending-x-frame-options-sameorigin

I hope it helps.

Best regards, David.

---
Tags: search
---


# Question
Title: How to return JSONP from a menu callback
I can create JSON output using a menu hook using the `drupal_json_output` callback.

Example:

```
$items['page/%/json'] = array(
  'access callback'   => TRUE,
  'page callback'     => '_modulename_json',
  'delivery callback' => 'drupal_json_output'
);

function _modulename_json() {
  return array(
    'item1' => $field_item1[0]['safe_value'],
    'item2' => $field_item2[0]['safe_value'],
    'item3' => $item3,
    );
}

```

Output:

```
{"item1":"Field item1 content","item2":"Field item2 content","item3":"Item3 content"}

```

But I need to have JSONP, and am struggling to find an elegant solution... I have tried the code from the bottom of the API page, it does the padding, but makes a mess of the content.

```
$response = array(1,2,3);
$callback = check_plain($_REQUEST['callback']);
// If its a jsonp callback request
if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}
else {
  drupal_json_output($response);
}

```

Output this way:

```
callbackName({\u0022item1\u0022:\u0022Field item1 content\u0022,\u0022item2\u0022:\u0022Field item2 content\u0022,\u0022item3\u0022:\u0022Item3 content\u0022});"

```

# Answer
> 2 votes
The array was being double encoded. First by the `$json_response = drupal_json_encode($response);` and then again by the menu delivery callback `'delivery callback' => 'drupal_json_output'`.

To fix this, remove the delivery callback, and use just `'type' => MENU_CALLBACK,`.

In the function change this:

```
if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}

```

to this:

```
if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  drupal_add_http_header('Content-Type', 'application/javascript');
  echo $callback . "(" . $json_response . ");";
  drupal_exit();
}

```

---
Tags: 7
---


title: Insert query using ajax drupal

text:
# Question
Title: Insert query using ajax drupal
I am totally new to Drupal Ajax. In my projects one simple form with submit button only there for insert "yes" value to Database. so it should be done with Drupal Ajax. So When that button submit the value should be store in Db with out page load and after submit display text " successfully selected" instead of button.

So please anyone can help me for this task

# Answer
First of all I want to point you to the AJAX Example module. This has some neat examples on how to use it.

For your task what you basically need is the following:

1. Replace normal submit handler by custom submit handler
2. Add an AJAX callback and wrapper to your submit button
3. Do your database queries in the submit handler, force rebuilding the form and define the message.
4. Replace the submit button of your form with a new one and show the message.

I cannot test the following code right now but it should basically give you the idea:

```
<?php

function MY_MODULE_form($form, &$form_state) {
  // some form elements

  $form['submit'] = array(
    '#type' => 'submit',
    '#submit' => array('MY_MODULE_form_custom_submit'), // define custom submit handler
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'MY_MODULE_form_callback', // define ajax callback to show the message
      'wrapper' => 'my-submit-button', // define what div should be replaced
    ),
    '#prefix' => '<div id ="my-submit-button">', // wrap this button in the div that is replaced
    '#suffix' => '</div>',
  );
}

function MY_MODULE_form_custom_submit($form, &$form_state) {
  // do your db query
  drupal_set_message(t('Something has been done!')); // your message

  $form_state['rebuild'] = true; // rebuild the form. not sure if this is required now.
}

function MY_MODULE_form_callback($form, &$form_state) {
  return $form['submit'];
}

?>

```

Hope this helps. If the code does not work as it should let me know and I will test it asap.

cheers, j
> 1 votes

# Answer
If you have Rules module installed, then the Rules Link module has the ability to create an ajax button and you can configure in the attached rule where the data will be stored.

Another option is the Flag module, which allows more configuration.
> 0 votes

---
Tags: database, ajax
---


# Question
Title: How to set static field on Display Suite
i would like to set a static field using Display Suite in Drupal 7 but don´t know how. It´s a text snippet that won´t change so i want to place it using a field.

Can somebody help me how to do it?

Thank you very much.

Kind Regards

# Answer
> 0 votes
You can create custom fields at admin/structure/ds/fields. You can maybe add a code field for entity Nodes with your text snippet and then place it in your custom DS layout for a content type.

# Answer
> 1 votes
Add a code field to Display Suite. In that code field you add your html (with token support if token is installed). Then just place the code field in the display tab for the content type.

Tutorial here.

---
Tags: 7, display-suite
---


# Question
Title: How can I get an absolute path to a theme?
Is there a Drupal function that returns the absolute theme path? Or is there a canonical / base practice way of doing this correctly returning the theme path?

What I've found so far is this:

```
<?php
// @file template.php
$template_path = DRUPAL_ROOT . drupal_get_path('theme', 'foo');

```

I'm looking to require\_once the template path in a template.php file like so:

```
<?php
$template_path = DRUPAL_ROOT . drupal_get_path('theme', 'coo');
// ...
// Check file exists etc
require_once $template_path;

```

# Answer
The `base_path()` function would return the base bath of the Drupal installation

> Returns the base URL path of the Drupal installation. At the very least, this will always default to /.

and `path_to_theme()` will return the path to the current theme.

> Return the path to the current themed element.
>
> It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.
> 18 votes

# Answer
Mohammed Shameem's answer is correct, but if you're really looking for the correct way (the Drupal way) to render a custom template, do not use `include()` or `require_once()`. Instead, use the Drupal theme system. Changing the output of something that already has a template is easy, see Overriding themable output to learn how to override a template. If there is no template yet, you would have to learn about hook\_theme, registering your own templates, and render arrays.
> 2 votes

# Answer
You can try this module: System stream wrapper

It provides wrappers(examples from module's site) :

* module://file/icons/text-plain.png
* theme://bartik/screenshot.png
* theme://default/screenshot.png
* profile://minimal/minimal.info
* profile://current/standard.info (profile://current expands to the active profile for the site)
* library://ckeditor/images/spacer.gif (works only if the Libraries module is enabled)
> 0 votes

---
Tags: 7, theming, uri
---


# Question
Title: How to display block with term image field when viewing term node
I'm using the default Taxonomy term view in drupal 7. I have Vocabulary: Portfolio with terms: Wedding Photos, Kids Photos, Other Photos. And I want to show a block of the term image field when a specific term is visited.

similar to this ( Add taxonomy term image to a view )

But because there are many content types in the same category the block is showing many term image fields instead of just one. I try different Contextual filters and Relationships and Query settings: Distinct. But no result so far.

# Answer
> 0 votes
I found my error: In the Format: Settings I had Grouping field N1 selected with the category term image field, which caused the duplication of the image.

**Contextual Filters**: Content has taxonomy term ID (with depth), Depth:0, Provide Default Value: Taxonomy term ID from URL \> Load default filter from term page **Relationships**: Entity Reference: VocabularyName - Require this relationship **Fields**: Taxonomy Term - the term image field - using Views Distinct I select Filter Repeats

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


# Question
Title: How to fix SalesForce authentication errors on localhost?
I am fairly new to developing with Drupal, and new to this forum, so any help would be greatly appreciated.

While trying to authorize SalesForce with a local install I get the following two errors with when going to the oauth\_callback.

Note: I have not included the entire path to save space but the reference points are accurate for the doc and line the error references.

> Notice: Undefined property: stdClass::$data in Salesforce-\>requestToken() (line 338 of salesforce.inc)
>
> SalesforceException: Error opening socket ssl://login.salesforce.com:443 in Salesforce-\>requestToken() (line 342 of salesforce.inc)

Local Environment: Mac OS Mavericks with XAMPP 5.6.3, SSL enabled on port 443 in `httpd-vhosts.conf` with certs created using OpenSSL.

Extension: `php_openssl.dll` uncommented in php.ini

Also to note the Drupal install was pulled from a live site that has SF module enabled and working.

I created a new connected app with the proper `oauth_callback` to the local site which is `https://secure.localhost/salesforce/oauth_callback`

I have both HTTPS and HTTP enabled, I have noticed that in the *Status Report* when using HTTPS I do get a HTTP Failure error in the status report.

The request url from salesforce is passing a code EX: `https://secure.localhost/salesforce/oauth_callback?code=aPrxMZkm7lCkgfR3...`

With a Status code of `500 Service unavailable`.

I have looked all over online and on this site, and can't seem to find anything that works. I have tried a few patches to the `common.inc` file, but none of them seemed to work.

Like I said any help would be greatly appreciated, I am just not sure if it is Drupal, Salesforce, or my local setup.

# Answer
> 3 votes
In general, to make SalesForce authentication to work on localhost, you need to:

* Create an app in Salesforce with URL Callback to your local (`https://localhost/salesforce/oauth_callback`) with appropriate permissions.

> In Salesforce go to Your Name \> Setup \> Create \> Apps then create a new Connected App. (Depending on your Salesforce instance, you may need to go to Your Name \> Setup \> Develop \> Remote Access.)
* Your site needs to be SSL enabled to authorize the remote application using OAUTH.
* If using the SOAP API, PHP must be compiled with SOAP web services and OpenSSL support.
* Use the right auth *key* and *secret* to Authorize your app (Configuration » Salesforce).
* Make sure you're connecting to the right endpoints (live or sandbox).
* For more help, check *Help » Salesforce API* in Drupal, or SalesForce documentation.
* Add `$conf['https'] = TRUE;` to your setting file.

The error in `Salesforce->requestToken()` indicates that there is a problem exchanging an authorization code for an access token.

Further more, the error:

> Error opening socket ssl://login.salesforce.com:443 in Salesforce-\>requestToken()

indicates the problem connecting to Salesforce endpoint it-self (check `requestToken()` in `includes/salesforce.inc` for more details).

To diagnose the problem, please check *Reports » Status report* if you've got *HTTP Failure error* and that your localhost can connect to Salesforce end point via curl:

```
$ curl login.salesforce.com:443

```

If your `curl` is connecting fine and you've still *HTTP Failure error* in your *Status report*, then try to:

* Temporary disable Secure Site or Secure Pages modules if present.
* Make sure you've firewall (e.g. `iptables`) and antivirus is switched off (for testing purposes).
* Make sure you're not behind the proxy.
* Make sure you're not running LAMP in a chroot/jail/VM environment.
* Make sure you some network functions aren't disabled PHP functions (e.g. `stream_socket_client`).
* Make sure your PHP is not in Safe mode (`safe_mode = On`) by:

```
php -r "var_dump(ini_get('safe_mode'));"

```
* Double check your `/etc/hosts` or `~/.curlrc` doesn't have anything suspicious (you can add `insecure` to your `.curlrc` for testing purposes).
* Check is there is no any problem with certificates (e.g. your system date is incorrect, you added the certificate and your PHP openssl sees your certificates correctly).

In PHP 5.6 you can specify *openssl.cafile* and *openssl.capath*,

e.g. `openssl.cafile=/usr/local/etc/openssl/cert.pem`

If none of above work, please check below simple PHP script which can check if your PHP can connect to external host:

```
<?php
fsockopen('ssl://login.salesforce.com',443,$errno,$errstr) ? print("UP") : print("DOWN:".$errstr);
?>

```

Save it to the file (`test.php`) and place it inside your web root and open via web browser.

If it fails, it's either problem with your PHP configuration or your network. You can debug it further more by using system call tracer (debugger) as below (install it if required):

```
$ strace -f -e network php test.php # For Linux
$ truss -f php test.php # For BSD
$ sudo dtruss php test.php # For OSX
# For Windows, you may look for StraceNT.

```

Then you've to analyse the log for any issues.

Or the following perl script:

```
use strict;
use warnings;

use LWP::UserAgent;
use Mozilla::CA;
my $ua = LWP::UserAgent->new(
        ssl_opts => {
                verify_hostname => 1,
                SSL_ca_file => Mozilla::CA::SSL_ca_file()
        }) or die;
my $url = $ARGV[0] || 'https://login.salesforce.com/';
my $res = $ua->get($url);
print $res->code . "\n";

exit;

```

See also:

---
Tags: crm
---


# Question
Title: Populate a multivalue image field when importing xml data with Feeds
I created an importer to fetch data from an http xml file. To create the importer I'm using Feeds and Feeds XPath Parser

So far so good. Thing is that the xml file has several images to import in a single multivalue image field of my nodes.

Then I guess I have to concatenate these images into one value and then after populate my field. To do this I'm using Feeds Tamper. This one allowed me to REWRITE the multivalue image field using tokens where I set one token for each image. It seems simple but it doesn't work. What am I missing here?

Is there any other way to do this?

Image capture of the xml: https://drive.google.com/file/d/0B71-gfIvQWAUU3ZpWVpVZzJjTFk/view

# Answer
> 0 votes
* For Multi-Valued field you could use `Explode` Plugin in feeds Tamper
* Also Use `Trim` Plugin to Remove white spaces if any in Image URL.
* Reference: Feeds Example

---
Tags: feeds
---


# Question
Title: How can I call 3 tpl.php files in hook_theme function?
I have 3 tpl/php files and i want to call those .tpl files on the request of user. where i have given user a dropdown list to select the .tpl files. I have created dropdown list but i don't know how to call them on the request of user.

```
/*
 *implements hook_menu().
 */

function dropdown_page_menu(){
  $items = array();
  $items['page/layout/%'] = array(
    'title' => 'Select Layout',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('dropdown_page_select_form'),
    'access arguments' => array('access content'),
    );

  return $items;
}

/**
 * Implements hook_theme().
 */

function dropdown_page_theme(){
    return array(
      'dropdown_page_select_form' => array('render element' => 'form',),
      );
}

function dropdown_page_page(){
  $content[] = l(t('select layout'),'page/layout/%');

  return $content;
}

function dropdown_page_select_form($form, &$form_state){
  $options = array(
    'layout_1' => t('Layout 1'),
    'layout_2' => t('Layout 2'),
    'layout_3' => t('Layout 3'),
    );

  $form['choice'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Select your layout'),
    );

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

function dropdown_page_select_form_submit($form, &$form_state){
  drupal_set_message(t('Your layout %input', array('%input' => $form_state['value']['choice'])));
}

```

The detail description is i want to create a page which render list of nodes in a page but i like to give option to user that weather he wants all the node in single column layout or 2 column layout or 3 column layout. For these layout i'm creating 3 different .tpl files so now i want to call them on the request of dropdown list.

```
function dropdown_page_menu(){
  $items = array();
  $items['page/layout/%'] = array(
    'title' => 'Select Layout',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('dropdown_page_select_form'),
    'access arguments' => array('access content'),
    );

  return $items;
}

/**
 * Implements hook_theme().
 */

/*function dropdown_page_theme(){
    return array(
      'dropdown_page_select_form' => array('render element' => 'form',),
      );
}*/

function dropdown_page_theme($existing, $type, $theme, $path) {
      $theme = array();
      $theme['node__blog_post'] = array(
        'render element' => 'content',
        'base hook' => 'node',
        'template' => 'views-view-unformatted--layout-1--page',
        'path' => drupal_get_path('themes', 'views-view-unformatted--layout-1--page.tpl.php') . '/templates',
       );
      return $theme;

}

function dropdown_page_page(){
  $content[] = l(t('select layout'),'page/layout/%');

  return $content;
}

function dropdown_page_select_form($form, &$form_state){
  $options = array(
    'layout_1' => t('Layout 1'),
    'layout_2' => t('Layout 2'),
    'layout_3' => t('Layout 3'),
    );

  $form['choice'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Select your layout'),
    );

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

function dropdown_page_select_form_submit($form, &$form_state){
  drupal_set_message(t('Your layout %input', array('%input' => $form_state['value']['choice'])));
}

```

I'm still not able to call the .tpl.php files

# Answer
> 0 votes
Set a cookie with user prefs on form submit.

In the preprocess function for your templates (ie template\_preprocess\_page), read the cookie value, and depending on the value, prepend the appropriate template to $variables\['theme\_hook\_suggestions'\].

# Answer
> 0 votes
You could try `hook_theme` to create template suggestion in module based on user selection

```
<?php
    /**
     * Implements hook_theme().
     */
    function mymodule_theme($existing, $type, $theme, $path) {
      $theme = array();
      $theme['node__blog_post'] = array(
        'render element' => 'content',
        'base hook' => 'node',
        'template' => 'node--blog_post',
        'path' => drupal_get_path('module', 'mymodule') . '/templates',
       );
      return $theme;
    }
?>

```

---
Tags: 7, theming
---


# Question
Title: Personal Contact Form granular permissions
I want to be able to set specific permissions by role for the use of the Personal Contact Form.

Searching drupal.org shows a few modules to work with Contact forms, but none do what I am looking to do, so I'm wondering if I'm overlooking something simple.

What I would like to do:

**Role A**

* Can have own Personal Contact form **BUT** it is *only* available to other Authenticated Users
* Can access and use Personal Contact form for any other user (Role A or Role B)

**Role B**

* Can have own Personal Contact form available to Anonymous **AND** Authenticated Users
* Can access and use Personal Contact form for any other user (Role A or Role B)

**Anonymous Users**

* Can only access Personal Contact Form for Role B Users, **NOT** Role A Users.

The idea is that **Role B** Users have the *privilege* of allowing the public / anonymous users to contact them via the Personal Contact Form, but all Authenticated Users should be able to contact each other using the form.

Should I do this with the Webform module? Or is there some permission setting for the Personal Contact Form I am missing?

I don't want it to be binary (either you have a Personal Contact Form or you don't), but I want some types of users to be able to access some other users Personal Contact Form.

# Answer
> 0 votes
I would do this using hook\_form\_alter.

Set up your roles, then create a function using hook\_form\_alter that checks if it's building the contact form or not. If building the contact form, check the current user's role, and either redirect to a 403 or allow it to go through.

---
Tags: users, emails
---


# Question
Title: How to make a webform block specific template?
i would to make a custom tpl for a webform in a block.I get is ID but actually i can't it to works.what the way to do this ? what si the folder / files structure to do this ? i'm on drupal 6 and webform 3.x

thanks

EDIT: this my code for node-webform.tpl

```
<!-- NODE-WEBFORM.TPL GENERIK -->
<div class="node<?php if ($sticky) { print " sticky"; } ?><?php if (!$status) { print " node-unpublished"; } ?>">

     <!--______________COLONNE GAUCHE 1________________ -->

<div id="col_G1" class="colG1_webform">
     <?php if ($title): /*insertion du titre de la page et style differencié*/?>
     <h1 class="titre_pl"><?php print $title; ?></h1>

    <?php endif; ?>
      <br clear="all"/>
       <!-- Deco page-->

    <?php  print $node->field_image_deco_lycee[0]['view'] /*Image deco page lycee*/ ?>
</div>
<!--______________COLONNE GAUCHE 2________________ -->
<div id="col_G2" class="colG2_webform">
     <?php if ($submitted) { ?>
    <span class="submitted"><?php print $submitted?></span>
  <?php }; ?>

  <div class="content">
    <table>
    <tr>
    <td><?php print $node->content['body']['#value']; ?></td>
    </tr>
    <tr>
    <td><?php print $node->content['webform']['#value']; ?></td>
    </tr>
    </table>
  </div>

    <?php if ($links): ?>
    <div class="links"> <?php print $links; ?></div>
  <?php endif; ?>

     <?php if ($terms) { ?>
    <span class="taxonomy"><?php print $terms?></span>
  <?php }; ?>

</div>
<!--______________COLONNE GAUCHE 3________________ -->

<div id="col_G3" class="colG3_webform">
     <?php print $picture; ?>

    <div class="content">

        <br clear="all"/>
           <?php if ($node->field_vue_actus_lycee[0]['view']): ?>
        <div id="bloc-actu-lycee">
           <?php  print $node->field_vue_actus_lycee[0]['view'] /*Vue actus du lycée*/ ?>
        </div>
           <?php endif;?>
    </div>

    <?php if ($terms): ?>
      <div class="taxonomy"><?php //print $terms; ?></div>
    <?php endif;?>

</div>

  <?php if ($picture) { print $picture; }?>

  <?php if ($page == 0) { ?>
    <?php if ($title) { ?>
      <h2 class="title"><a href="<?php print $node_url?>"><?php print $title?></a></h2>
    <?php }; ?>
  <?php }; ?>

<div class="clear-block clear"></div>

</div><!-- /node -->

```

# Answer
You need to copy (not move) sites/all/modules/webform/templates/webform-form.tpl.php to sites/all/themes/yourTheme/templates/webform-form-nid.tpl.php (obviously replace yourTheme and nid) and clear caches.
> 1 votes

---
Tags: theming, webforms
---


# Question
Title: Calculate time between start and end time
I'm building a website where I need to know the time (in hours) between the start and end time from a date field. So I want to know how long it took. It's usually from one day to another, sometimes just on one day (don't know if that matters).

I made a field Date (Unix timestamp) with month, day, hour and minute. Users need to choose both start and end time. I also made a Computed field. The first part is the Computed code and the second part is de display code:

```
<?php
$field_tijden = array_pop(field_get_items($entity_type, $entity, 'field_date'));

$start = $field_tijden['value'];
$end = $field_tijden['value2'];
$timezone = $field_tijden['timezone'];

$date_start = new DateTime($start, $timezone);
$date_end = new DateTime($end, $timezone);

$interval = $date_start->diff($date_end);

$entity_field[0]['value'] = $interval->format('%h');
?>

<?php
$display_output = $entity_field_item['value'] . " hours";
?>

```

I checked "Store value in the database", checked "Float", data length "3,2" and the other settings I kept on default. This is what I copied from another website and all I tweaked was changing it to $field\_tijden which is the name of the field. I know almost nothing about PHP, so I have no idea what to change to get this to work. Right now when I save a node the field is not being displayed.

Is there anyone who can help me getting this to work? Thanks in advance!

Edit: These are the settings I put in a Rule, but it's not working yet. Does anyone see what I'm doing wrong?

Events: \- After saving node

* After updating existing node

Conditions: nothing

Actions:

* Convert data type. Value: Integer. Selector: node:field-tijden:value (this is the start time). Label: conversion-result-start.
* Convert data type. Value: Integer. Selector: node:field-tijden:value2 (this is the end time). Label: conversion-result-end.
* Calculate a value. Selector: conversion-result-end. Operator value: (-). Selector 2: conversion-result-start. Label: result-calculation.
* Calculate a value. Selector: conversion-result-calculation. Operator value: (\*). Selector 2: 60. Label: result-in-minutes.
* Calculate a value. Selector: conversion-result-in-minutes. Operator value: (\*). Selector 2: 60. Label: result-in-hours.
* Convert data type. Value: Integer. Selector: result-in-hours. Label: conversion-result-in-hours-converted.
* Set a data value. Selector: node:field-tijden:duration (I'm not sure where the :duration is coming from)

# Answer
There is a way to accomplish this without writing any code. You can use the Rules module to calculate the difference between dates and to update a field in any entity or node.

There isn't a Rules action that will calculate the difference between dates, but there is still a way to do it in Rules. It involves four simple steps:

1. Use the "Convert data type" action to convert both date objects to Integer types. This will create variables that use a Unix int timestamp (number of seconds since 1/1/1970)
2. Calculate the difference between the two integers and store in a variable
3. Divide the result by x number of seconds, depending on what you want to calculate. To calculate days, divide by 86400 (60 * 60 * 24)
4. Use "Convert data type" to round the subtraction to an integer (and store in a new variable)

Then you can simply use the Rules action "Set a data value" to store this value in a node (or entity) field

You can trigger this Rule whenever the user saves or edits content of specific type.
> 3 votes

---
Tags: datetime
---


# Question
Title: FROM_UNIXTIME(o.created,'%d-%m-%Y') in where clause gives error
I am working on Drupal 6. while executing query when I add
`and FROM_UNIXTIME(o.created,'%d-%m-%Y') < '".arg(3)."'";`
to WHERE clause it doesn't return result. i have tried by using same query in MySQL Query Browser it returns result. so I am confused how to pass above condition in WHERE clause,
as I am passing 31-10-2012 in arg(3).

# Answer
> 4 votes
You just need to escape the percent sign with another, i.e.,

```
FROM_UNIXTIME(o.created,'%%d-%%m-%%Y')

```

Also make sure you use parameter replacement rather than injecting strings directly into the query; you're not protected from SQL injection at the moment.

That would be something like

```
$sql = "SELECT * FROM {table} WHERE FROM_UNIXTIME(o.created,'%%d-%%m-%%Y') < '%s'";
$result = db_query($sql, arg(3));

```

# Answer
> 1 votes
In this question https://drupal.stackexchange.com/questions/149472/addexpression-and-from-unixtime-format, I asked the same question but in relation to Drupal 7 and the addExpression method of the SelectQuery object.

Problem Code:

```
$query->addExpression('FROM_UNIXTIME(w.submitted, "%Y-%m")', 'Date');

```

Solution (reverse the quotes):

```
$query->addExpression("FROM_UNIXTIME(w.submitted, '%Y-%m')", 'Date');

```

---
Tags: datetime
---