# Question
Title: db_query() not compatible with IN operator?
I ran into a snag setting placeholders for the IN operator, and then I ran into a webpage that basically says, if I'm reading it correctly, that they are not compatible. I also found a forum post on this subject in which the questioner gave up and expanded his IN into a series of ORs.

Apparently, I have the choice of either expanding the IN into ORs or learning to do dynamic queries. Since db\_select() apparently comes with a lot of overhead, I suppose the ORs will run faster.

Is this correct, or is there a way to use IN with db\_query?

# Answer
You can use placeholders in IN conditions, but you need to set them up correctly first. Using the example in your first link, this should work:

```
$replacement_values = array();
foreach(array_values($your_values) as $i => $val) {
  $replacement_values['@val' . $i] = $val;
}
// Should look something like:
// $replacement_values = array(
//   '@val1' => 'your first value',
//   '@val2' => 'your second value',
// );

$placeholders = array_keys($replacement_values);
$placeholders = implode(', ', $placeholders);
// Should look something like:
// $placeholders = '@val1, @val2';

$res = db_query('SELECT field FROM {table} WHERE cond_field in(' . $placeholders . ')', $replacement_values);

```

n.b. I haven't tested this so it might need some tweaking.

That said, I'd urge you to look into dynamic queries. They're not that hard to get your head around and if you wan't to right modules that might ever be used on another Drupal site that uses an alternative database to MySQL then they are a must.
> 1 votes

# Answer
You can easily use placeholders inside db\_query() with IN condition. Just pass array as a value for placeholder and don't do implode()!

Here is working example:

```
$types = array('article', 'poll');
$res = db_query('SELECT * FROM {node} WHERE type IN (:types)', array(':types' => $types));
$nodes = $res->fetchAllAssoc('nid')

```
> 1 votes

# Answer
I got this from the Static Queries page on d.o where they used `db_query` for their example:

> Drupal's database layer includes an extra feature of placeholders. If the value passed in for a placeholder is an array, it will be automatically expanded into a comma separated list as will the corresponding placeholder. That means developers do not need to worry about counting how many placeholders they will need.
>
> An example should make this behavior clearer:

```
<?php
// This code:
db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => array(13, 42, 144)));

// Will get turned into this prepared statement equivalent automatically:
db_query("SELECT * FROM {node} WHERE nid IN (:nids_1, :nids_2, :nids_3)", array(
  ':nids_1' => 13,
  ':nids_2' => 42,
  ':nids_3' => 144,
));

// Which is equivalent to the following literal query:
db_query("SELECT * FROM {node} WHERE nid IN (13, 42, 144)");
?>

```

I don't know what exactly you're doing since you haven't provided any code, but this is essentially what Eugene Fidelin and Paul Querol have said in their answers. (Although Paul Querol's answer is the 'expanded' second part of the code above)
> 1 votes

---
Tags: database
---


# Question
Title: Page Categorisation and Multi-level Paths
I want to categorise my pages and see the category names in path.

For example: instead of http://localhost/a-funny-story, http://localhost/stories/funny/a-funny-story.

What is the best practice? I tried to do it with Pathauto module. I created a content type with a term reference of a category taxonomy.

I use this pattern `[node:field_my_page_category]/[node:title]` in "CONTENT PATHS". But this doesn't work for multi-level categories. I tried to use "join" `[node:field_my_page_categories:parents:join:/]/[node:title]` as mentioned here.

But I get this error: `The Pattern for all Sayfa paths is using the following invalid tokens: [node:field_my_page_category:parents:join:/]`.

# Answer
If it is a node, you need to use Pathauto and also `Replacement Patterns`, in the `Replacement Patterns` select the taxonomy term and put it in the url.

But if you need to list set of contents based on the url you need to use Views and add the terms as contextual filters.
> 1 votes

# Answer
Enabling **Entity Tokens** module and changing the pattern to `[node:field_my_page_categories:parents:join:/]/[node:field_my_page_categories:name]/[node:title]` solved my problem.
> 0 votes

---
Tags: taxonomy-terms, path-aliases, uri
---


# Question
Title: How do I remove the site name from the page title on a particular page?
I have unchecked the sitename in *admin/build/themes/settings* but all of the titles of pages are still showing the site name.

I am not sure why this happens. Is there any other way to remove it?

I have installed the Page Title module, and in *admin/settings/page-title* I have the page title set as `[page-title]` for that particular page, not as `[page-title] | [site-name]`.

# Answer
> 1 votes
Try the Page Title module. Here is a quote about it (from the module's project page):

> The word "title" is a bit overloaded. Every piece of content in Drupal has a title, and so does every page. The page title is the one found in the HTML head inside the tag. It is also used on SERPs (Search Engine Result Pages) and can greatly enhance your websites SEO (Search Engine Optimization).
>
> This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.

# Answer
> 0 votes
You could create a Panel (or a mini-panel) that includes the **page element** "Site name" and place it wherever you want in that Panel, and than Toggle off the Site's name in the Themes' settings (only after you have created that panel, or mini-panel).

---
Tags: 7
---


# Question
Title: JSON format for creating users with custom fields using services
I am using Services module to register new users. My registration form has some custom fields like text field, radio buttons and select list. The following is the data I am sending:

```
{
"name" : "testapi",
"mail" : "test@test.com",
"pass" : "testapi",
"field_name" : {
"und" : [ { "value" : "Prashant TestAPI" } ]
},
"field_contact_no" : {
"und" : [{ "value" : "9898989898" }]
},
"field_user_sex " : {
"und" : [ { "value" : "male" } ]
},
"field_role_s_ " : {
"und" : [ {"value" : "developer"}, { "value" : "tester" } ]
}
}

```

The other fields like username, password, email and name(textfield) goes through fine but the sex is a radio button and role is a checkbox, those are not getting populated.

If there a specific way of handling those form types?

Update: I was able to get it to work with the following code.

```
{
"name" : "apiuser",
"mail" : “apiuser@example.com",
"pass" : "testapi",
"field_name" : {
"und" : [ { "value" : "Prashant TestAPI" } ]
},
"field_contact_no" : {
"und" : [{ "value" : "9898989898" }]
},
"field_user_sex" : {
"und" : "male"
},
"field_role_s_" : {
"und" : ["developer","other"]
}
}

```

# Answer
> 0 votes
The views datasource module is more handy. Try this module and create a view of the data you need to send.

---
Tags: services, 8
---


title: Unable to render menu in theme

text:
# Question
Title: Unable to render menu in theme
I'm creating a custom theme in Drupal 7 but I'm having trouble getting it to render the menu

I'm using the following code in page-front.tpl.php

```
<?php if ($page['main_menu']): ?>
    <div id="main-menu"><div class="section clearfix">
<?php print render($page['main_menu']); ?>
    </div></div>

```

But it does not render anything. I have double checked that a menu exists.

# Answer
$page\['main\_menu'\] is not menu. It's the region with name main\_menu. You can put there any block what you want. You can configure blocks on this page admin/structure/block

But in the basic drupal themes the main menu can be available in this variable $main\_menu in the template page.tpl.php
> 1 votes

---
Tags: routes, theming
---


title: Run a drush script from php system()

text:
# Question
Title: Run a drush script from php system()
I have a Drupal module with a function that runs a system(“myscript.drush”);

```
function _deploy_monitor_stream($submission_id) {
  header("Content-type: text/plain");
  disable_ob(); // Outputs to browser

  $command = 'whoami'; // Debug : Returns my local user since i'm using MAMP
  system($command, $return);

  $command = 'pwd'; // Debug : Returns my drupal root so it's fine
  system($command, $return);

  $PATH = getenv('PATH'); // Debug : I tried to force my path to have all bins i need
  putenv('PATH=' . $PATH . ':[FULL_PATH_TO/drush:/Applications/MAMP/Library/bin/mysql');

  $command = 'drush myscript.drush --option1 --option 2 | tee mytest.log;
  system($command);
}

```

`myscript.drush` runs different `drush_shell_exec()` including a site-install function.

```
$si = DRUSH_PATH . " -y si my_profile --db-url=mysql://root:root@localhost/$DATABASE_NAME ";
$si .= "-l $SITE_URL --sites-subdir=$SITE_URL --account-name=$DRUPAL_ADMIN_NAME --account-pass=$DRUPAL_ADMIN_PWD ";
$si .= "--site-mail=$SITE_CONTACT_MAIL";
drush_print("Installing site ... " . $site_code); // ---- INSTALL INSTALLATION PROFILE
if (drush_shell_exec($si)) {
  drush_log("Site succesfully installed", 'ok');
}
else {
  //If install failed, we abort
  foreach (drush_shell_exec_output() as $m) {
    drush_print($m);
  }
  drush_die("Command // $si //  failed");
}

```

While it works fine if I run it from the command line, it doesn't work when my PHP calls the script.

Here is the script output :

```
Installing site ... /Users/me/.composer/vendor/drush/drush/drush --root=/Users/me/Documents/workspace/proto -y si my_profile --db-url=mysql://root:root@localhost/test_site.test.com -l test_site.test.com --sites-subdir=test_site.test.com --account-name=admin --account-pass=admin --site-mail=system_contact@example.com
Directory /Users/me/.drush/cache/default exists, but is not       [error]
writable. Please check directory permissions.
You are about to CREATE  the 'test_site.test.com' database. Do you want to continue? (y/n): y
sh: mysql: command not found
Starting Drupal installation. This takes a few seconds ...                  [ok]
WD php: Exception: To start over, you must empty your existing           [error]
database.To install to a different database, edit the appropriate
settings.php file in the sites folder.To upgrade an existing
installation, proceed to the update script.View your existing site.
in install_begin_request() (line 301 of
/Users/me/Documents/workspace/proto/includes/install.core.inc).
WD php: Warning: Cannot modify header information - headers already    [warning]
sent by (output started at
/Users/me/.composer/vendor/drush/drush/includes/output.inc:38)
in drupal_send_headers() (line 1233 of
/Users/me/Documents/workspace/proto/includes/bootstrap.inc).
Exception: <ul><li>To start over, you must empty your existing database.</li><li>To install to a different database, edit the appropriate <em>settings.php</em> file in the <em>sites</em> folder.</li><li>To upgrade an existing installation, proceed to the <a href="http://test_site.test.com/update.php">update script</a>.</li><li>View your <a href="http://test_site.test.com">existing site</a>.</li></ul> in install_begin_request() (line 301 of /Users/me/Documents/workspace/proto/includes/install.core.inc).
Drush command terminated abnormally due to an unrecoverable error.       [error]
drush: Command // /Users/me/.composer/vendor/drush/drush/drush --root=/Users/me/Documents/workspace/proto -y si my_profile --db-url=mysql://root:root@localhost/test_site.test.com -l test_site.test.com --sites-subdir=test_site.test.com --account-name=admin --account-pass=admin --site-mail=system_contact@example.com //  failed

```

As you can see, it cannot find the mysql command `sh: mysql: command not found` I tried to add the path to mysql to all and even force it to the PATH var before running the script in case it would only live for the current run - but it doesn't solve the problem.

If i do an

```
drush_shell_exec('echo $PATH');
foreach (drush_shell_exec_output() as $m) {
    drush_print($m);
}

```

At the beginning of my drush script, it confirms mysql is in the PATH var. So Drush should be able to find it as well !

Anybody can help ?

Thanks !

# UPDATE 1

Here is a log with a `si --debug` option. It doesn't give more information - We still see that the "script" failes to call mysql `Installing site ... /Users/me/.composer/vendor/drush/drush/drush --root=/Users/me/Documents/workspace/proto -y si --debug my_profile --db-url=mysql://root:root@localhost/test_site.test.com -l test_site.test.com --sites-subdir=test_site.test.com --account-name=admin --account-pass=admin --site-mail=system_contact@example.fr
Bootstrap to phase 0. [0 sec, 1.88 MB] [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 2 MB] [bootstrap]
Directory /Users/me/.drush/cache/default exists, but is not [error]
writable. Please check directory permissions. [0.01 sec, 2.01 MB]
Cache MISS cid: 6.5.0-alias-path--e51a01eaadbedd8992f93f4b1e37a340 [debug]
[0.01 sec, 2.01 MB]
Cache MISS cid: 6.5.0-commandfiles-0-9f983fb1e5cd5a06f3cad18503b4c204 [debug]
[0.01 sec, 2.02 MB]
Cache SET cid: 6.5.0-commandfiles-0-9f983fb1e5cd5a06f3cad18503b4c204 [debug]
[0.02 sec, 2.03 MB]
Bootstrap to phase 0. [0.06 sec, 5.59 MB] [bootstrap]
Bootstrap to phase 1. [0.08 sec, 5.6 MB] [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.09 sec, [bootstrap]
6.49 MB]
Initialized Drupal 7.35 root directory at [notice]
/Users/me/Documents/workspace/proto [0.09 sec, 6.49 MB]
Found command: site-install (commandfile=core) [0.09 sec, 6.49 MB] [bootstrap]
Calling hook drush_core_site_install_validate [0.15 sec, 6.52 MB] [debug]
Returned from hook drush_core_site_install_validate [0.15 sec, 6.52 [debug]
MB]
Calling hook drush_core_pre_site_install [0.15 sec, 6.53 MB] [debug]
Executing: mysql --database=test_site.test.com --host=localhost --user=root --password=root -e "SELECT 1;" 2> /dev/null > /dev/null
You are about to CREATE the 'test_site.test.com' database. Do you want to continue? (y/n): y
Sites directory sites/test_site.test.com already exists - [notice]
proceeding. [0.15 sec, 6.53 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.15 sec, [bootstrap]
6.54 MB]
Initialized Drupal site test_site.test.com at [notice]
sites/test_site.test.com [0.15 sec, 6.54 MB]
Cache MISS cid: [debug]
6.5.0-install_profile-fbfb0256099ded6086bc55133257a1bc [0.16 sec,
6.55 MB]
Cache MISS cid: 6.5.0-commandfiles-2-5ea45eaeffdc711df5631f275d26edd1 [debug]
[0.16 sec, 6.55 MB]
Cache SET cid: 6.5.0-commandfiles-2-5ea45eaeffdc711df5631f275d26edd1 [debug]
[0.23 sec, 6.57 MB]
Executing: mysql --database=test_site.test.com --host=localhost --user=root --password=root -e "SELECT 1;" 2> /dev/null > /dev/null
Calling system(mysql --database=information_schema --host=localhost --user=root --password=root < /private/tmp/drush_QDZllv);
sh: mysql: command not found
Returned from hook drush_core_pre_site_install [0.26 sec, 7.74 MB] [debug]
Calling hook drush_core_site_install [0.26 sec, 7.75 MB] [debug]
Starting Drupal installation. This takes a few seconds ... [0.26 sec, [ok]
8.03 MB]
Calling install_drupal(Array) [0.26 sec, 8.03 MB] [debug]
WD php: Exception: To start over, you must empty your existing [error]
database.To install to a different database, edit the appropriate
settings.php file in the sites folder.To upgrade an existing
installation, proceed to the update script.View your existing site.
in install_begin_request() (line 301 of
/Users/me/Documents/workspace/proto/includes/install.core.inc).
[0.32 sec, 12.26 MB]
WD php: Warning: Cannot modify header information - headers already [warning]
sent by (output started at
/Users/me/.composer/vendor/drush/drush/includes/output.inc:38)
in drupal_send_headers() (line 1233 of
/Users/me/Documents/workspace/proto/includes/bootstrap.inc).
[0.32 sec, 12.29 MB]
Exception:

To start over, you must empty your existing database.

To install to a different database, edit the appropriate settings.php file in the sites folder.

To upgrade an existing installation, proceed to the update script.

View your existing site.

 in install_begin_request() (line 301 of /Users/me/Documents/workspace/proto/includes/install.core.inc).
Drush command terminated abnormally due to an unrecoverable error. [error]
[0.32 sec, 12.27 MB]
drush: Command // /Users/me/.composer/vendor/drush/drush/drush --root=/Users/me/Documents/workspace/proto -y si --debug my_profile --db-url=mysql://root:root@localhost/test_site.test.com -l test_site.test.com --sites-subdir=test_site.test.com --account-name=admin --account-pass=admin --site-mail=system_contact@example.fr // failed`

# Answer
Ok so I managed to make my script work by adding a `PATH=MYPATH.... &&` before calling my drush site-install command.

This way I make sure my PATH contains all the necessary bins when running the command.

I'm sure there is a "cleaner" way to do it, but adding the path "inline" do the trick
> 0 votes

---
Tags: drush
---


title: Action on module enable?

text:
# Question
Title: Action on module enable?
I want to show a message when a module is being enabled. I used `hook_modules_enabled` and it shows me the message while enabling a new module.

Now I need the currently enabled module machine name in the hooks argument. But `hook_modules_enabled($modules)` returns an **array of modules** in the argument.

*Eg:*

When **views** is enabled, I need to set a message as:

> "**Views** Module is enabled"

Here I need "views" (i.e. the module name) as argument in `hook_modules_enabled` in order to print it in message but it returns me an array.

How can I achieve this. Is there any other hook for this?

# Answer
The argument `$modules` in `hook_modules_enabled($modules)` returns an array of modules enabled. You should loop through the array to print the message.

Note: But only machine name of the module will be in the array.

For eg:

```
function MY_MODULE_modules_enabled($modules) {
  foreach ($modules as $module) {
    // To get Module Name
    $module_info = system_get_info('module', $module);
    $module_name = $module_info['name'];
    //Loop through the modules and set the message.
    $msg= "$module_name is enabled";
    drupal_set_message(t($msg), 'status', FALSE);
  }
}

```
> 0 votes

# Answer
`hook_module_enable()` should do the job unless I'm missing something from your question.

> Perform necessary actions after module is enabled.
>
> The hook is called every time the module is enabled. It should be implemented in the module's .install file. The implementation can rely on the .module file being loaded.
> 0 votes

# Answer
I don't see any other hooks that you could invoke; you could keep track of modules yourself, compare it with what you get in `hook_modules_enabled()` and then do whatever you want for each of the enabled/installed modules.

Here are general steps:

1. Upon installation of your custom module (or in update hook), save the snapshot of what is installed in the system at the moment. This would go into `.install` file and you could use part of the code from this answer. Querying directly the `{system}` table might even work. Store everything as an array using `variable_set()`.
2. Use `hook_modules_enabled` (or `hook_modules_installed`) to compare the new list with the old one. Store differences in a separate array (e.g. `array_diff()`).
3. For each of the newly installed/enabled modules perform your action.
4. Update the custom variable for storing the list of modules using `variable_set()`.

Let me know if I misunderstood the question.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: How to fix the unresolved dependency in the Flag module about Flag Friend?
I am trying to update my modules and I am getting this error line:

> Fatal error: Class 'RulesEventHandlerEntityBundle' not found in /home1/kctd/public\_html/community/sites/all/modules/rules/modules/node.rules.inc on line 147.

I am in the Update.PHP screen (see photo near the bottom) and I have a few unresolved dependencies. I would normally retro install some of those modules, but when I try to check manually, or even go to my modules screen, I get the error listed above. I am locked out.

What should I do?

# Answer
> 2 votes
According to your "unresolved dependency" error messages, you are currently using the 2.2 version of the Flag module. While the Flag Friend module requires the 2.1 version of it.

It's worth trying to replacing the entire flag folder in your modules directory as follows:

* backup your flag module folder (to somewhere outside your Drupal root).
* delete the flag module folder and its entire content.
* download the 7.x-2.1 release of the flag module and unpack that version in the very same "flag" module folder.

Then try again and see if that helps. If not restore your backup directory (to try some other approach).

---
Tags: 7, updating, flags
---


# Question
Title: Immediately check if field content already exists in a node form
I am struggling with a problem which I thought might be answered simply... Any help would be appreciated!

I have a content type called 'review'. Each review has a field called 'location'. As a user creates a new review, once they have filled in the location field, I would like a small message to appear in case that same user has already created a review for the same location.

Doing it when the user is about to save the node is not too complicated. But I actually want it to happen as soon as the relevant field is not empty.

Thanks

# Answer
> 0 votes
You can write little custom jQuery snippet using 'blur' event in order to do this. More information you may find on this page http://www.w3schools.com/jquery/event\_blur.asp

---
Tags: forms, ajax, nodes
---


# Question
Title: Field rendered invisible when code block enabled
I have this weird issue when altering a webform. Below are two versions of my code:

```
function tubitekuz_form_webform_client_form_97_alter(&$form, &$form_state, $form_id) {
  $form['submitted']['kullanici_adi'] = array(
    '#type' => 'textfield',
    '#ajax' => array(
      'event' => 'blur',
      'callback' => '_tubitekuz_do_stuff',
    ),
  );
}

```

The above code renders my field invisible, while

```
function tubitekuz_form_webform_client_form_97_alter(&$form, &$form_state, $form_id) {
 $form['submitted']['kullanici_adi']['#ajax'] = array(
    'event' => 'blur',
    'callback' => '_tubitekuz_do_stuff',
  );
}

```

gives me .

What might I be doing wrong?

# Answer
> 0 votes
I found out why. It seems our designer chose to add `display:none` to `ajax-processed` class, which is added to `#ajax` calls.

---
Tags: 7, webforms, forms
---


# Question
Title: is there a way to know witch module is responsible to programmatically alter a view's query?
I have a view that diplays some orders with a filter by current user if he is owner of the order or not ..

If the current user is admin, i can see my orders with no problems. If im logged in with another role the view is always empty althought im ordering products with that user.

I doubt about the view access, or some modules permission (for example if this role has the permission to view his own orders or if he has permission to view his own product ...) I checked these permissions carefully, but the view result still empty.

when I debug the query I get inside where clause an additional condition that's applyed only for non admin users :

> (AND 1 = 0)

as you know this condition returns always false, so that's why the result of the query is empty.

Is there a way to know from where is coming this condition when im logged in with a non admin role ?

Thanks in advance.

# Answer
> 0 votes
Interesting question / challenge, not obvious to debug ...

Here is what I would do, in the order specified:

* Scan the entire modules directory for a string containing '`1 = 0`'.
* Scan the Drupal database (all tables) for a string containing '`1 = 0`'.

If none of both scans lead to any results, I'd consider using the X-ray module, to check if that would help me any further. Some details about this module (from its project page):

> X-ray module gives a look at the skeletal structure of a site to help developers and site builders see how things work.
>
> X-ray Features:
>
> * A technical summary is added to the help above the main administrative sections. For example, blocks, content types, and menus are summarized on Structure; themes on Appearance; etc.
> * A table of permission titles matched to their permission machine names.
> * A table of most\* hooks which Drupal invokes (and when they are invoked) and that are available to be implemented.
> * The function and arguments producing each page you visit, displayed on that page.
> * The form ID of every form you see, displayed on the form.

# Answer
> 0 votes
Please check, that all line items in order related to this order (order\_id field in line item entity). Also, please check the following issue: https://www.drupal.org/node/1541206

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


title: Count flags on user's content

text:
# Question
Title: Count flags on user's content
In my Drupal 7 site I want to display how many times user's content was flagged. As option I want to set a global variable `counts` and display it in different parts of `*.tpl.php` files. The value can be calculated with `flag_get_counts($entity_type, $entity_id)` for each user's `node_id`. Function that calculates `counts` should be called in `template_page_preprocess()` to update value each time page is reloaded.

What is more efficient approach to implement this?

# Answer
> 1 votes
The right way is using `template_preprocess_node()`.

Place the following code in `template.php` of your front end theme:

```
function YOUR_THEME_preprocess_node(&$vars) {
  // I suppose you don't want to do this for every content type on the site.
  switch ($vars['node']->type) {
    case 'YOUR_CONTENT_TYPE':
      $vars['count'] = flag_get_counts('node', $vars['node']->nid);
      break;
  }
}

```

This will make the `$count` variable available in `.tpl.php` files that are used for displaying nodes of your content type.

---
Tags: theming, flags
---


# Question
Title: Multililingual views displaying wrong content
I have created a view which lists a bunch of nodes. This works fine when the site is in the default language of English. I have cloned that view and made sure it only displays the French version of those nodes and changed the path where it should be displayed. This all works as it should in the view's preview area. However when I go the French url for that page, I only see the English version of the listed nodes and not the French ones as defined in the view.

I am confused as to why this would be. Different urls should display different content but it is not. What could be causing this issue? I am completely stumped and this is an urgent issue for a client.

# Answer
> 1 votes
To make the view results correspond to the language switcher, add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

**If** no option for the '*User's Current Language*' is available in the filter criteria form, **then** verify your configuration at *Configuration -\> Languages -\> detection and selection*: the order should be 'URL, Default, User', and not something like 'Default, URL, User' (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Note: filtering Views results in a multi language site can sometimes be challenging, as illustrated also in discussions such as in https://groups.drupal.org/node/47478 ...

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


# Question
Title: How to resize automatically when users upload images by CCK image field
I would like to make the size of images smaller automatically when users upload them using CCK image field.

For example, I would like to let users upload big sized images like 5MB but resize them smaller automatically like 0.5MB before saved on the server.

The reason is that the capacity I can use on the shared server is very limited. Of course I can set "Maximum upload size per file" to a small size but then users who have big sized images but don't know how to resize them before upload will not be able to upload them. I have tried also "image cache" a bit but it doesn't seem to save the files with the name, attributes and in the directory specified by CCK image field.

I don't know if this kind of thing is possible to achieve or not.. Any Idea?

# Answer
> 3 votes
Imagecache is great, but since it keeps the original file around, it won't save space. In fact, if you have multiple presets, it will increase your disk usage as it creates its caches of images of those sizes.

What you may want to investigate is putting some logic into `nodeapi()` (or, if on Drupal7, its equivalent function) when saving your node that looks at the filepath of whatever image field you are concerned with and does some image manipulation on it if it is over a certain size and then saving it in place.

# Answer
> 2 votes
The module you want is: Max Image Size

> This module will resize uploaded images to be below the set dimensions. It is not an image style or other presentation layer module. If you want to maintain the original image you should use Image Resize Filter or an image style. The use case for this module is sites where users may upload very large images, but you do not want/need to keep the original.
>
> This is different from the core image field size restrictions in that it will work on already uploaded files and imported content.

# Answer
> 1 votes
The imagefield cck field (which depends on filefield) provides this capability out of the box. You add a filefield to your content type, set the display widget to "image", and then when you edit the settings for the field one of the settings is called "Maximum dimensions for images". Here you can set this to something like 600x400, or whatever you like. If a larger image is uploaded, it will automatically be resized.

# Answer
> -1 votes
Not really what you're asking for but anyway: You already discovered the Drupal way of handling big images: image cache. If you can, switch to a hoster with a lot of storage (some offer unlimited space).

---
Tags: files, media
---


# Question
Title: fetching records from webform_submitted_data table through following source code but showing error
How to display the records from the table by using the following source code?

> Notice: Undefined offset: 0 in eval() (line 20 of /var/www/module(80) : eval()'d code).

```
<?php
include_once(drupal_get_path('module', 'webform').'/includes/webform.submissions.inc');
$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid','data'));
$query->condition('nid','159','=');
$results =$query->execute();

echo "<table>";
echo "<tr>";
echo "<th>  Profile Photo </th>";
echo "<th> Faculty  Name and Department  </th>";
echo  "</tr>";

if ($record = $results->fetchAssoc())
{
$sid = $record['sid'];
$nid = $record['nid'];
$submission = webform_get_submission($nid,$sid);
echo "<tr>";
echo $val = $submission->data[15][0];
}
?>

```

# Answer
Try below code,

You can retrieve node webform all submissions using webform\_get\_submissions which accepts an array of filters.. As per the error you mentioned in the question seems like below code is causing problem

```
echo $val = $submission->data[15][0];

```

I would suggest printing the information that you got before you try to fetch the data so that you know you are correclty accessing the array results.. print\_r will assist you to see the results..

```
module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> 159));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '<pre>';print_r($row);print '</pre>';
        print '<pre>';print_r($data);print '</pre>';
    }
}

```

Extract the information you want from $row and $data ...
> 1 votes

# Answer
On a sidenote, you should consider using `theme_table` to print a table, preferably using a renderable array ( as opposed to `theme('table',.. )` ).

If you print everything manually, it's easy to forgot a tag, which might then completely screw up your layout :)

You can read more about `theme_table` here and renderable arrays here
> 0 votes

# Answer
Alternatively if you are planning on generating your own HMTL then use the following to view the data.

```
module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(1111);
krumo($submissions);

```
> 0 votes

---
Tags: webforms
---


# Question
Title: Language switcher to non-source language not working
I have a `Branch` content type, which also happens to be an Organic Group. I use the Pathauto module to set the URL to:

```
branch/[node:menu-link]

```

I have created a content, and a `Menu` with a menu item which linked to said content. Everything works well up until now.

Next I enabled Entity translation and translated it into two different languages (French and German). Since, with entity translation, the node ID will be the same, I don't need to change the link in the menu item.

When I go to the English (the default and source language) page, I see that in the 'Language Switcher (Content)' block, the other two languages are not linking. However, manually changing the language prefix in the URL worked. So, the page actually exists.

```
/en/branch/my-branch ----> /fr/branch/my-branch

```

When I am on the French page, the language switcher shows 'English' as clickable, but German is disabled. The same for the German page.

So it appears that the language switcher doesn't link to non-source languages. Is this a bug? Any pointer are appreciated!

# Answer
> 0 votes
This looks really similar to what is described in Language switcher (content) does not work, which is an issue on D.O that is not yet resolved (status = active).

---
Tags: i18n-l10n, path-aliases
---


# Question
Title: How to render a DS fieldgroup programmatically in a node template?
I am overriding a Display Suite view mode of a node using the template suggestion *myLayout-node-myNode-full.tpl.php*.

I am getting the $node-\>content using the *node\_build\_content* function. Then I have access and I am rendering all the node display fields using:

```
drupal_render($node->content['field_myField'])

```

But I **cannot render fieldgroups** using the drupal\_render function, as it requires array parameter, but my fieldgroups are **stdClass** objects that can be accessed as:

```
$node->content['#groups']['group_myGroup']

```

Printing the $node variable, I do not get any other reference to fieldgroups, eg. $node-\>content\['group\_myGroup'\] does not exist.

Any suggestions on how I could render fieldgroups in my template file in Drupal 7?

# Answer
`node_build_content` is probably not suitable for your use case. However you should use `node_view` instead which calls `node_build_content` anyway but returns you the actual renderable array after it processes it and sends it through an alter as well.

For example:

```
function mytheme_preprocess_node(&$vars) {
  if (!empty($vars['node'])) {
    $node = $vars['node'];

    if ($node->type == 'my_content_type') {
      $vars['content'] = node_view($node); //optionally supply view_mode as a second argument
    }
  }
}

```

Now you can just `drupal_render($content)` from your node template.
> 0 votes

---
Tags: 7, nodes, theming, display-suite, entities
---


title: Applying a patch doesn't work

text:
# Question
Title: Applying a patch doesn't work
I'm having trouble with applying a patch for a Drupal module. I thought it was as simple as using "git apply thepatch.patch," but when I do this in the main directory that holds the .git directory, I get the following error message:

> Checking patch entity\_translation.admin.inc…
> error: entity\_translation.admin.inc: No such file or directory

When I do this in the directory where the files are located, nothing happens; no error is shown, but no file is changed.

It's not a problem I have with this particular patch, but I never seem to be able to apply a patch, and I just end up manually editing the files.

I would like to know the solution once and for all.

# Answer
> 17 votes
It is possible that the patch was rolled before the days of Git on drupal.org.

For old patches:

```
patch -p0 < thepatch.patch

```

For new patches that mysteriously fail with `git apply`:

```
patch -p1 < thepatch.patch

```

# Answer
> 3 votes
Follow below steps:

1. Download the patch file and place it to the module folder ie. `sites/all/modules/varnish`
2. Make sure you are at the same module directory ie. `sites/all/modules/varnish`
3. Use `git init` command to start git on that repository, even if you have git initialized at drupal root.
4. Run command `git apply -v filename.patch`

# Answer
> 2 votes
The command `git apply -v thepatch.patch` should work.

You will need to run in in the module directory which you are patching (eg. `sites/all/modules/module_name/`) and the `.patch` file should be in that directory as well. The `-v` option is for verbose and should tell you whether the patch application was successful.

# Answer
> 2 votes
The instructions given for each project hosted on Drupal.org are the following (you can find them on this page, for example):

> Applying a patch
>
> Download the patch to your working directory. Apply the patch with the following command:
>
> ```
> git apply -v [patchname.patch]
>
> ```
>
> To avoid accidentally including the patch file in future commits, remove it:
>
> ```
> rm  [patchname.patch]
>
> ```

The working directory is the directory containing the module files; in the case of the Views module, it's the directory containing the views.module, views.info, and views.install files you need to patch.

# Answer
> 2 votes
I had the same issue, in my case, the following worked for me.

patch -p1 \< thepatch.patch

---
Tags: version-control
---


# Question
Title: Which module should I use to manage translations in D7?
I want to develop a multilingual site with support for which I followed this site. But after doing the initial steps I am not getting the translation management.

I downloaded the Hindi translation package, internationalization, locale modules have been installed. Unable to install the internationalization views as it's not compatible with Drupal 7.x

Translation management is also not supported

So how can I translate my site to any other language?

I'm using Drupal v7.34.

# Answer
> 0 votes
Excerpt from the Translation Management project page:

> ... provides complete workflow management for multilingual Drupal sites.
>
> Content managers can manage all translations from one central page. The module shows which contents need translation and notifies translators about what they need to do.

Be aware however that this is a D6-only module, not at all suited for a D7 site.

For D7 there are basically 2 alternatives available:

> ... provides a table listing the site's nodes and showing what's been translated into each language. It also lets you assign priorities for translating nodes into the various languages.

* Translation Management Tool, considered as the successor of the previous module, and "the" module to move forward with in D8 also. From its project page:

> ... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.
>
> This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.

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


# Question
Title: Modify Userpoints List FormTo Show Entity ID?
How does one modify the List used to display userpoints?

eg.

http://example.com/user/123/points

I'd like to be able to modify that (table) to display the Entity ID (the source transaction id).

Apparently, it is generated as a form/table in the Userpoints module, right? I think that SQL field is already part of the query. But is there a way to hook into that form and add columns without hacking the module? How is that done?

The form ID is userpoints-list-transactions

I see a hook in userpoints.api.php

function hook\_userpoints\_list\_alter

so I created a function in my own module (which I know is loading and working for other functions)

```
 function jch_utilities_userpoints_list_alter(&$output) {
    dpm($output);
    }

```

...and it never fires. What am I doing wrong?

# Answer
> 0 votes
Do you have the Devel module installed? dpm() won't work without that.

---
Tags: forms, userpoints
---


# Question
Title: How can I allow non admin users to edit the menu settings for a node?
How can I set a "Menu settings" field to be available to non admin roles in the permissions page?

Here's an image to clarify what I am trying to allow select roles to edit when creating a new node of a specific content type.

I need to allow editors etc to adjust the menu settings but can't find the appropriate permission.

Can anyone point me in the right direction for how to do this?

# Answer
> 0 votes
I would not advise using the first answer since that is a **very** heavy-handed approach, and the permissions page item 'Bypass content access control' gives a clear warning right below it:

> View, edit and delete all content regardless of permission restrictions. Warning: Give to trusted roles only; this permission has security implications.

The better way to go about this is to use the menu\_admin\_per\_menu module. Note that to use this your users would need access to the Management menu. You can also tame that menu's options by using the config\_perms module. The two work well together. This way, certain roles can be set to have access only to particular menus so they can create new menu items, or move them, etc.

# Answer
> 0 votes
Goto to the Permission tab & provide the below permissions :

> 1. Bypass content access control
> 2. Administer menus and menu items

---
Tags: 6, routes, users
---


title: Google Analytics Module: Sub Domains

text:
# Question
Title: Google Analytics Module: Sub Domains
I am using a Drupal Multiple Site (several sites running on 1 Drupal installation). Each site is part of a subdomain.

For example:

* mysite.com
* store.mysite.com
* blog.mysite.com

Each site has its own separate database. Do I set up Google Analytics on just the main site or on all the sites?

In this post, it says you need to set it up on all the sites. However, it also says you need to "show the ".domain setting" in footer". I can't find this setting anywhere in the UI.

# Answer
> 4 votes
You will need to install the module on each site using the same UA# (assuming these should all be tracked under the same account).

All you need to do is select `One domain with multiple subdomains` for everything to track properly.

# Answer
> 2 votes
The answer of the question depending on how you want to track each website in GA.

First off, since you have multiple configurations/databases, you'll need to setup GA (@ **/admin/config/system/googleanalytics**) on each the site if you're wanting to track each one, regardless how you track the sites in GA.

Next, if you're wanting to track **each site separately in a different GA property** (each with its own independent tracking metrics/dimensions/etc), you want to use the `A single domain (default)` option with each site having a different `Web Property ID` (e.g. UA-xxxxxxx-yy).

If you're wanting to track all these interrelated ***sites on one GA property***, you'll need to use the `One domain with multiple subdomains` option. You'll be using the `Web Property ID` across all sites, but you'll have to make additional configurations to accommodate GA:

* If you're not using Universal Analytics, this means that the `$cookie_domain` (in **settings.php**) needs to tweaked so that it reports to GA the same .mysite.com domain (this is what your linked d.o. is addressing).
* If you are using Universal Analytics, then just setting the `One domain with multiple subdomains` option is fine.

Note, if you go with the `One domain with multiple subdomains` option, you'll need to make some additional changes on the GA side so that filters show the domain. Otherwise, you're going to see various domain URLs mixed into the GA property.

---
Tags: google-analytics
---


# Question
Title: How to calculate number of submitted webforms?
I want to show the number of submitted webforms in a block in the front page of my website.

I searched and found (( function webform\_get\_submission\_count )) . But I'm absolute beginner: I know it is inside webform.submission.inc, but then where shall I call it? How to place it in a block like in the following image:

Any help would be greatly appreciated.

# Answer
> 3 votes
Another option would be to use **Views** to create a view of webform submissions, and display the count from that.

# Answer
> 1 votes
Since you wrote you're *an absolute beginner*, you might want to consider using contributed modules to do so. Be aware however that reporting about webform submissions can be a bit challenging, especially if you try to do so with the Views module. Below are a few alternatives to consider.

## Webform add-on modules

There are many Webform related modules which extend Webform, including integrations with third-party software.

As a sample, if you'd want to create charts from the submitted webform results, there seem to be even 2 alternatives to pick from (with extremely similar module names ...):

* Webform Charts, to display Webform results in a graphical manner using a charting library.
* Webform Chart, which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

Another possible module to consider, is the Views Aggregator Plus module. Here is an excerpt from its project page:

> Works great with Webform 7.x-4.x (aggregate your webform submission results tables).

## Module Forena

Display Webform Submission Data using Views is a bit challenging. As an alternative to installing Webform MySQL Views (which depends on Data and Schema), consider the Forena module. Here is a quote about it:

> ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

So in this case you'd use Forena to report about the Webform data stored in the Webform tables, which are contained in your Drupal database.

Disclosure: I'm a (co-)maintainer of the Forena module,
I hope this does not violate the site's policy on self-promotion.

---
Tags: 7, webforms
---


# Question
Title: Create view with parent taxonomy terms only
I have a view of nodes, which are associated with a vocabulary, and it contains both child and their respective parent terms. What I want is in this view, only the parent categories will be coming. I have already tried the parent relationship but it gives me repetitive rows with each parents. I have described the problem and what i want to achieve here :

https://www.drupal.org/node/652234#comment-9422885

Help appreciated...

# Answer
Create contextual filter with parent taxonomy term id as fixed value 0
> 0 votes

# Answer
In views add filter:

Taxonomy term: Parent term and it is equal to NULL, leave blank.
> 0 votes

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


# Question
Title: How to create form on users account page?
I used `hook_user_view_aler()` to add some info to user's page.

```
 $account['summary']['member_five'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('I do'),
    '#markup' => 'Real magic',
  );

  $account['summary']['member_six'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => '',
    '#size' => 30,
    '#maxlength' => 60,
    '#required' => TRUE,
  );

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

```

Also I added form elements and they do appear but I couldn't submit it. `hook_user_view_aler_submit()` obviously is too much and it doesn't work. Is there any way to create form on user's page?

# Answer
You'll have to define a form function using the drupal form API See this tutorial for more info on how to make your own forms.

So the actual form function would look something like this

```
MY_FORM_FUNCTION($form, &$form_state){
  // Build form array here
  return $form;
}

MY_FORM_FUNCTION_validate($form, &$form_state){
  // Validate function here
}

MY_FORM_FUNCTION_submit($form, &$form_state){
  // Submit function here
}

```

Now in the tutorial they use `HOOK_menu` to display the form on a page. But you can call `drupal_get_form('MY_FORM_FUNCTION')` from everywhere and generate a render array for the form.

So this would show your form on the user page via HOOK\_user\_view\_alter

```
 $account['form'] = drupal_get_form('MY_FORM_FUNCTION');

```
> 0 votes

---
Tags: forms, users
---


# Question
Title: References module doesn't specify/read a pager limit when field is using a view to generate potential references
Discovered an oddity that seems inherent in the `node_reference.module 7.x-2.1`. It is a rather specific use-case, so I can see why it might not have come up frequently before. Just wondering if anyone has any work around ideas, either that or I'll document my findings if I reach a solution.

How to reproduce the issue:

1. Create a reference list view, and use it to power an autocomplete field.
2. Create another view and attempt to use the created field as a filter.
3. Everything will work fine, unless that field has a large number of values. The field I'm using has upwards of 90,000 items.
4. This is because the views filter UI attempts to render all possible values as a checkbox list.

The reason it trips up is because:

```
function _node_reference_options($field, $flat = TRUE) {

```

Goes on to call:

```
$references = node_reference_potential_references($field);

```

Without any options. Which leads to:

```
references_potential_references_view(
  $entity_type, $view_name, $display_name, $args, $options);

```

Being called without any options, and it seems this code does not read the pager settings to get its `limit` value. Instead it relies on `$options['limit']`.

```
$limit = !empty($options['limit']) ? $options['limit'] : 0;
$view->display_handler->set_option('pager', array(
  'type' => 'some', 'options' => array('items_per_page' => $limit)));

```

I'm not sure which bit of the code is at fault — i.e. who should definite a limit, or read the pager settings — but there definitely needs to be a defined limit and not `0`. Especially when dealing with so many possible values. Setting a limit specifically for the pager in Views UI does not work as it is circumvented.

Currently I can't even get to edit my view with the filter specified, unless I hack the references module to pass:

```
$references = node_reference_potential_references($field, array('limit' => 10));

```

I'm only adding this as a filter so I can state that the field isn't empty. I could just leave the hack in until I've set the filter to a state that doesn't read the values. However this feels rather unsafe — especially if someone else was to take over the code at a future point.

# Answer
> 0 votes
I haven't found a neat general solution to this issue, but in terms of a specific solution you can use `hook_query_alter`. Basically in one of my bespoke modules I added the following:

```
/**
 * Implements hook_query_alter().
 */
function bespoke_module_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('views_autocomplete_for_ref_files')) {
    $view = $query->getMetaData('view');
    if ( !empty($view) && $view->current_display == 'references_lead_image_by_default' ) {
      $query->range(0, 10);
    }
  }
}

```

> **NOTE:** Awkwardly there doesn't seem to be an ability of `SelectQuery` to get back the current range settings. The code could be more general if it could detect that no limit was set.

Out of the above `views_autocomplete_for_ref_files` is the machine name of the reference list view, and `references_lead_image_by_default` is the name of the display. I can focus on the default display because I have code elsewhere that switches the view in use depending on certain contexts. The default display is never actually used by the site, except when it is requested by the Views UI (because the widget hook below is not used for the Views UI display).

```
/**
 * Implements hook_field_widget_form_alter()
 *
 * Modifies the autocomplete path for autocomplete widgets
 */
function bespoke_module_field_widget_node_reference_autocomplete_form_alter (&$element,
    &$form_state, $context) {
  $instance = &$context['instance'];
  $field = &$context['field'];
  /// only step in if the field uses a view to populate
  if ( $field['settings']['view']['view_name'] == 'autocomplete_for_ref_files' ) {
    /// switch the view display depending on content type
    if ( (arg(0) == 'node') && ($node=node_load(arg(1))) && ($node->type) ) {
      $field['settings']['view']['display_name'] =
        'references_lead_image_for_' . $node->type;
    }
    /// hijack the current autocomplete path to point to our own callback
    $element['nid']['#autocomplete_path'] =
      $instance['widget']['settings']['autocomplete_path'] . '/' .
      $instance['entity_type'] . '/' . $instance['bundle'] . '/' . $field['field_name'];
    /// hijack the autocomplete validate function, to validate with our own criteria
    $element['nid']['#element_validate'] =
      array('bespoke_module_node_reference_autocomplete_validate');
  }
}

```

I'll keep looking to see if I can find a more general solution.

---
Tags: views, nodes
---


# Question
Title: How to add multi nodes on a single page without using an iFrame?
I came up with the Multi Node Add module to add multiple nodes to single page. But the nodes are shown on iframe.

Is there another way with which we can add multiple node on single page without iframe?

# Answer
Consider using the Rules module, to insert a message with a clickable link in the Drupal Message area, whereas that link points to "/node/add" each time a node is saved.

Here is a summary of the rule to implement this:

**Events**: After saving new content

**Actions**: Show a message on the site, whereas the "value" of the message to be displayed should be something like so: `<a href="[site:url]/node/add">Click</a> to add another node.`

This assumes you want to do this for all possible content types. If you'd want to limit it to specific types only, you'd have to add appropriate **Conditions** (for the desired content types) also.
> 0 votes

# Answer
I would recommend the Advanced Form Block:

> Welcome to Advanced Form Block Module. With this module you can do the following:
>
> 1) Create any number of blocks with a particular node edit form. 2) create any number of blocks with a particular node add form of a content type. 3) Create as many blocks as you like of each kind. 4) From the content type choose which fields to display on a per block basis.However required fields will be automatically displayed. 5) All forms will be saved through ajax. So multiple node forms can be independently placed on a single page and worked with simultaneously.

With this, you can add any number of node add/edit forms (each with their own submit controls)
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Creating Custom Drupal 7 Registration Form
I am trying to create a custom registration form on D7. According to this article

The steps should be (theme name is icompany)

1. Modify `template.php` to override the registration form

```
function icompany_theme(&$existing, $type, $theme, $path){
  $hooks = array();
  // Make user-register.tpl.php available
  $hooks['user_register_form'] = array (
    'render element' => 'form',
    'path' => drupal_get_path('theme','icompany'),
    'template' => 'user-register',
    'preprocess functions' => array('icompany_preprocess_user_register_form'),
  );
  return $hooks;
}

```
2. Create a second function which builds the form

```
function icompany_preprocess_user_register_form(&$vars) {
  $args = func_get_args();
  array_shift($args);
  $form_state['build_info']['args'] = $args;
  $vars['form'] = drupal_build_form('user_register_form', $form_state['build_info']['args']);
}

```
3. Create `user-register.tpl.php` with the newly styled form

My problem is this does not work. My custom form does not seem to be called.

The alternative approach is to create page--user--register.tpl.php. This sort of works, any text I put on the page appears but the form fields do not using the syntax

```
<?php
print render($form['account']['name']);
print render($form['account']['mail']);

?>

```

# Answer
> 1 votes
I have tested the code and it's almost working as it's intended to be. One thing to note is when you placed the template file inside of the templates folder then the following should work.

On the **icompany\_theme()** function, change the *path* value from `'path' => drupal_get_path('theme','icompany'),` to `'path' => drupal_get_path('theme','icompany') . '/templates',` which specifies to look for the file inside the templates folder.

Then flush your caches.

---
Tags: theming
---


# Question
Title: How can I remove "please wait..." from a form?
I saw this Remove the "Please wait" text on Ajax Call but I can't find the form element. `<?php dsm($form);?>` and `<?php dpm($form);?>` return errors. This is what I found in $node:

I may have missed it. I tried using the ID path in the unset form function but it didn't work. This is what I'm putting in template.php:

```
function fivestar_form_fivestar_custom_widget_alter($form, &$form_state) {
  unset($form['field_funny']['#ajax']['progress']['message']);
}

```

I also tried theme\_fivestar\_form . . .

# Answer
this can be done in css:

```
.fivestar-widget .ajax-progress
{
    display:none;
}

```
> -1 votes

---
Tags: 7, forms, rating
---


title: Add ellipsis replacement to Pathauto

text:
# Question
Title: Add ellipsis replacement to Pathauto
To handle users who like to occasionally use the custom ellipsis character from MS Word in titles, I would like to add replacement options for the character in the Punctuation settings for Pathauto using hook\_pathauto\_punctuation\_chars\_alter(). The problem is determining what value to put in the value setting in the hook. I found the T\_ELLIPSIS constant in tokenizer.php, and tried using it like so:

```
function my_module_pathauto_punctuation_chars_alter(array &$punctuation) {
  $punctuation['ellipsis'] = array(
    'value' => T_ELLIPSIS,
    'name' => t('')
  );
}

```

and the value shows as `Ellipsis (389)` for the field label in the settings. However, when the alias is generated with the ellipsis character in the node title, it doesn't get replaced.

Is there a better/easier way to handle this? Also, should I use something like the UTF-8 code instead of the constant?

# Answer
> 0 votes
My prefered solution to scrub out extraneous characters in Pathauto URLs is this option under **Configuration » Search and metadata » URL aliases » Settings**.

It will scrub out all the extraneous characters that can mess up browsers/crawlers. This is assuming you're on an English language website.

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


# Question
Title: How to access replacement tokens present in views field rewrite output in its .tpl file of that field
I've created a view and I want to manipulate the field output to show bar graph instead of field value.

I'm using bootstrap 3's progress bar as the bar graph, but I'm unable to set width of the progress bar to show progress as drupal doesn't allows style attribute inside "Rewrite the output of this field" in views.

So, I decided to create that field's tpl file now the problem is how can I access the Replacement tokens in the tpl file that are available in "Rewrite the output of this field"

$data = $row-\>{$field-\>field\_alias} this prints numbers 1 2 3 4 5 ....

# Answer
> 0 votes
Under the Field settings, you can add a class to the field:

this can accept replacement tokens, so for example you could:

* create 5 classes each with a different length
* add a field prior to this field that will calculate the correct length
* use the replacement token of the calculated field to include the proper class: barsize1, barsize2, barsize3, etc

---
Tags: views, theming
---


# Question
Title: Add static text on flag confirmation form?
The flag confirmation page works fine with standard fields, but I would like to add a basic description/help text/guidelines text field that is admin-controlled and doesn't show up on the flag form as an editable field per each flagging.

Basically: Are you sure you want to flag x? {Flagging Guidelines} \<- add Fields from manage fields show here

flag confirm / cancel

# Answer
> 0 votes
It can be done in the hook\_form\_alter. You can just add markup element to this form with flagging guidelines

---
Tags: 7, flags
---


# Question
Title: How to add a menu to Drupal with all external links from module code?
I am writing a module that gets data from a couple sources, mostly XML, and then creates a nested array of values, such as "Title" and "URL"/link.

I'd like to create a new menu and then loop through my nested array and for each entry create a new menu item or child menu item, passing the title and URL to Drupal's menu system. I know that I can create menus with menu\_save and items with hook\_menu but how to create a new menu that has all external URLs?

Here is a part of the data:

```
Array
(
    [8CB0A2C5DC3B19401323F1A3F22D5769] => Array
        (
            [id] => 8CB0A2C5DC3B19401323F1A3F22D5769
            [parentId] => CA4CBBBB070F043ACF7FB35FE3FD1081
            [level] => 1
            [link] => http://externallink.com/fjdsklafjdkl
            [title] => Foo
            [orderWeight] => 1
            [children] => Array
                (
                    [259D3A1F1BCB8D601B13742603415970] => Array
                        (
                            [id] => 259D3A1F1BCB8D601B13742603415970
                            [parentId] => 8CB0A2C5DC3B19401323F1A3F22D5769
                            [level] => 2
                            [link] => http://externallink.com/hi
                            [title] => FooFooFoo
                            [orderWeight] => -3
                            [children] => Array
                                (
                                    [23C7938348994922AB879B87A85567DF] => Array
                                        (
                                            [id] => 23C7938348994922AB879B87A85567DF
                                            [parentId] => 259D3A1F1BCB8D601B13742603415970
                                            [level] => 3
                                            [link] => http://externallink.com?jfsdk
                                            [title] => FooFooFooFooFooFoo
                                            [orderWeight] => -1
                                        )

                                    [993EC027EC1342E39F48A30E754621AA] => Array
                                        (
                                            [id] => 993EC027EC1342E39F48A30E754621AA
                                            [parentId] => 259D3A1F1BCB8D601B13742603415970
                                            [level] => 3
                                            [link] => http://externallink.com
                                            [title] => FooFooFooFooFoo
                                            [orderWeight] => 1
                                        )
                                  )
                            )
                      )
                )
          [B7D67ECD8DD382E2A9F6E8F8149011E4] => Array
              (
                  [id] => B7D67ECD8DD382E2A9F6E8F8149011E4
                  [parentId] => CA4CBBBB070F043ACF7FB35FE3FD1081
                  [level] => 1
                  [link] => http://externallink.com
                  [title] => FooFooFoo
                  [orderWeight] => 3
                  [children] => Array
                      (
                          [B18FA5C86281B72BB9914EC541216F21] => Array
                              (
                                  [id] => B18FA5C86281B72BB9914EC541216F21
                                  [parentId] => B7D67ECD8DD382E2A9F6E8F8149011E4
                                  [level] => 2
                                  [link] => http://externallink.com
                                  [title] => Foo Foo Foo
                                  [orderWeight] => 8
                                  [children] => Array
                                      (
                                          [C20086F4FDF627499800D60391C384E3] => Array
                                              (
                                                  [id] => C20086F4FDF627499800D60391C384E3
                                                  [parentId] => B18FA5C86281B72BB9914EC541216F21
                                                  [level] => 3
                                                  [link] => http://externallink.com60391C384E3
                                                  [title] => Foo Foo
                                                  [orderWeight] => 9
                                              )

                                          [E5F00486FC054E78B68A996B30DAC89C] => Array
                                              (
                                                  [id] => E5F00486FC054E78B68A996B30DAC89C
                                                  [parentId] => B18FA5C86281B72BB9914EC541216F21
                                                  [level] => 3
                                                  [link] => http://externallink.commmm
                                                  [title] => Foo
                                                  [orderWeight] => 26
                                              )
                                        )
                                  )
                            )
                      )
)

```

# Answer
You can create menu programmatically, using menu\_save function and after that add links to this menu using menu\_link\_save function.
> 2 votes

---
Tags: routes
---


# Question
Title: How to add custom field to content view?
I would like to add to my main content view in drupal 7 (the one with the path /admin/content) a custom field called "mobile friendly". This field should tell the user if the current node is mobile friendly. The values should be "yes" or "no".

The values theme selves are in special dedicated table which has 2 columns: the first is "nid" and the second is "mobile\_friendly" (which is either "1" or "0")

I would like this field to be sortable and and i would like to filter by it also.

i have looked in the Drupal docs but didn't understood how to do it.

Can someone give me please an example in code or refer me to some close example?

Thanks in Advance

# Answer
View module doesn't have access to the custom tables by default, but you can fix it using hook\_views\_data function. More information you may find here http://www.sitepoint.com/exposing-tables-views-drupal-7/
> 0 votes

---
Tags: views
---


# Question
Title: How do I change the position of "sidebar first" for the Arabic version of website?
Can I change the position of the "sidebar first" if I change the website language?

More Details: My default website language is now English, and my "sidebar first" is in left position. This is what I want: to change the position of the "sidebar first" if I make the website in the Arabic language.

# Answer
Install the Context module.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.

Make sure that Multilingual select which is part of the Internationalization module is also installed (this will provide the proper condition).

You can now create a new context that has a condition of 'Language' and a reaction of 'Blocks'.

You will create a condition-reaction pair for two cases. First for all the LTR languages, second for all the RTL languages.

Allthough this does not directly answer your question as to regions, you can play around with the reactions, such as template suggestions etc to achieve your objective.
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: Why cant I configure or remove this module?
I was trying to figure out Google Analytics and installing it broke my site so I uninstalled it. Now I have reinstalled it, There is no link to configure it and the configuration page isn't even accessible from the URL.

So I tried to uninstall the module again and when I try to uninstall it goes to white screen and when I refresh I get back to the modules list and the module is still there. I cannot configure or uninstall or get the module to work. It seems to be stuck there.

I have even tried to WinSCP into the server and straight up delete the module. This removes the file from the list but when I reinstall the module I am back to square 1 where I cannot do anything with it.

I checked the error log and when I try to uninstall I get the following error PHP Fatal error: "Call to undefined function google\_analytics\_clear\_js\_cache()"

Is there anything I can do?

# Answer
> I checked the error log and when I try to uninstall I get the following error PHP Fatal error: Call to undefined function google\_analytics\_clear\_js\_cache()

This means that there is a bug in this module (and off-topic here).

But this is a general problem, and this anser provides is a general solution to this problem, that can also be used with other modules.

Whenever you get a WSOD upon *uninstall* and the log tell you it is because a "Call to an undefined function" - locate that call in the module's source code, and just *delete* the statement with the call. Then try to uninstall again.

After doing this, make sure you *report* the problem to the module's issue queue on Drupal.org to make the maintainer fix it (and alert others about it).
> 4 votes

# Answer
No guarantee it will help, but I think it's worth trying: increase your php memory limit and try again.

Since you're experiencing problems because of "adding" modules, it could well be that you've reached a memory limit that causes these kinds of related problems ...
> 0 votes

# Answer
Just uninstall the module and clear the cache.May be it will work.
> -1 votes

---
Tags: 8, google-analytics
---


title: Find current location of logged in user

text:
# Question
Title: Find current location of logged in user
How can I find out the current location of the logged in user? When a user is logged in I just want to search the current location of user and save the lat and long in the database . How can I do that? Please help.

# Answer
> 1 votes
You a use a geo IP database/service to lookup a lat/long based on the user's IP address. There are many PHP API's out there to do this. The most popular Drupal module based solution is Smart IP.

> Smart IP identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored at session variable ($\_SESSION) with array key 'smart\_ip' and Drupal $user-\>data object with array key 'geoip\_location' of the user but optionally it can be disabled (by role) at Smart IP admin page. Other modules can use the function smart\_ip\_get\_location($ip\_address) that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.

---
Tags: users, location
---


# Question
Title: Display a field only when dependee image field has more than three images
I have a content type "Product", and on its view node, I want to display a field(which is a select list), only when my other field, which is dependee for this field and is an image field, contains more than three images.

Any suggestion will be appreciated.

# Answer
> 1 votes
You can do this by using Conditional Fields module.

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

How to use ?

---
Tags: media
---


# Question
Title: Ubercart- free shipping through pay per click
Can anyone think of a way to offer free shipping for people who arrive at the site through Pay-per-click advertising (without a coupon code).

drupal 7.

thanks!

# Answer
> 0 votes
You need to use Commerce Free Shipping module.

> This module provide a solution to add Free shipping rate on top of commerce\_shipping services.
>
> This module change the price of the service to 0 and can display a message to the user saying the free shipping are applyed or the amount left to obtain free shipping.
>
> You can use this module to have a free shipping rate by:
>
> * Shipping service
> * Total amount of the line items in the cart (don't take in account the shipping line items)

How to setup free shipping

---
Tags: ubercart
---


title: Same taxonomy in two content type

text:
# Question
Title: Same taxonomy in two content type
I have two content types *Blog* and *Stay* which use the same taxonomy *Location*. I have two or more posts use same term *Cyclades*.

Is it possible when a user clicks on a *Cyclades* term link in a *Blog* post to only show posts from *Blog* content on the taxonomy page? Likewise, when a user clicks on *Cyclades* in a *Stay* post, to show only *Stay* content on the page?

I know i can create two different taxonomy for each content type, but I dont want this solution.

# Answer
> 1 votes
You can have same taxonomy being used by multiple content types.

You can achieve this by using 2 options 1. Overriding node.tpl.php for the taxonomy page. Here you can create two separate tpl files specific two different content types. 2. Create PAGE display of VIEWs and pass "type" as an argument. Based on this argument you can always display the teasers belonging only to the desited "Content Type."

Option # 2 is little easier from implementation point of view whereing Option # 1 though could little time consuming but will be better from performance perspective.

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


title: Change URL on ajax link

text:
# Question
Title: Change URL on ajax link
I've got a custom AJAX link on my site, which does it's current job fine, but what I'd like to do is make it change the href attribute of an element on the page as well. I'm not brilliant at jQuery, so I'm not sure how I'd use the Drupal AJAX commands to do something like this, if it can even be done.

Basic info of my existing setup

HTML

```
<a href="path/to/my/site/ajax/mymodule/slide/15" class="use-ajax ajax-processed">Add</a>

```

Module

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    // Creates a page to listen for a new slide being added
    $items['ajax/mymodule/slide/%node'] = array(
        'page callback' => 'mymodule_append_slide_to_deck',
        'page arguments' => array(3),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

  return $items;
}

function mymodule_append_slide_to_deck($node) {
    if (!empty($node)) {
        if ($node->field_image) {
            // CODE TO GET HTML OF THUMBNAIL FROM THE NODE REFERENCED, ADDED TO VAR $thumbnail

            // Prepare an ajax command to insert the node html into our ajax wrapper.
            $commands = array();
            $commands[] = ajax_command_append('#deck .deck-creator', $thumbnail);

            // Render the commands into JSON and print them.
            print ajax_render($commands);
            exit;
        }
    }
}

```

All this part works fine, does it's job. However I have another button on the page, and I'd like to pass this Node ID of the node I've referenced (in this case 15) to the end of the href property. Can this be done? or is the simplest thing to replace the HTML entirely using `ajax_command_replace();`?

# Answer
Found the best way of doing this was using `ajax_command_invoke()` instead.

By using this you can make a call to a custom jQuery function, in which you can then do what you want.

```
    ...
    // Prepare an ajax command to insert the node html into our ajax wrapper.
    $commands = array();
    $commands[] = ajax_command_html('#deck .deck-creator', $thumbnails);
    $commands[] = ajax_command_invoke(NULL, array('customAction'));

```

in a jQuery file

```
(function($) {
    $.fn.customAction = function() {
        // do my code
    }
})(jQuery);

```
> 2 votes

---
Tags: 7, ajax
---


# Question
Title: Is there a best form for security surrounding updating an entity of an unspecified type?
In Drupal 7, I have a field on both nodes and users that I'd like to update from a single function. What's the most efficient and what is best practice for updating by entity id?

I want the client to hit my Services REST API endpoint with an entity id and value. So far I've got:

```
function json_field_resource_update($entity_id = NULL, $data = array()) {
  global $user;

  $entity_type = 'user';
  $entity = entity_load_single($entity_type, $entity_id);
  if (!$entity) {
    $entity_type = 'node';
    $entity = entity_load_single($entity_type, $entity_id);
  }
  if (!$entity) {
    return services_error(t('No user or node entity found by entity_id !entity_id', array('!entity_id' => $entity_id)), 406);
  }
  if (!entity_access('update', $entity_type, $entity)) {
    return services_error(t('Permission denied for !user to update entity !entity_id', array('!user' => $user->name, '!entity_id' => $entity_id)), 403);
  }
...

```

The purpose of the above is to first check whether this entity Id refers to a user or a node then perform the appropriate access check. This works ok, but am I missing some magical all-in-one Entity API function or something?

# Answer
> 1 votes
I think the entity metadata wrapper is semi indiscriminate aslong as the field is the exactly the same on both entities. So you can just wrap it and then use the default set/get methods

```
// All your code (it looks fine)
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->FIELD_TO_SET->set(VALUE);
$wrapper->save();

```

More info on the metadata wrapper

# Answer
> 0 votes
> am I missing some magical all-in-one Entity API function or something?

You're not. Think of an entity as a database table, and imagine trying to query it. This is what you'd have with your current workflow:

```
SELECT * FROM WHERE id = ?

```

Notice the table name is missing, because no one has provided it.

Same thing for entities; you need to provide the type of entity you're trying to load, otherwise Drupal can't know which type to look for.

You need to get that entity type into the request. Best practice would be to properly separate your concerns, e.g. have a separate resource for updating nodes and users respectively. Remember, conceptually speaking, you're updating an **entity** here, not a field, so the layout of your resource should really reflect that.

The services modules actually has node and user update resources included by default, so you don't even need to do any extra work.

If you're hell-bent on having a separate resource just for updating this field, then you need to pass the entity type along when you consume the resource, or provide a different parameter that you can use to distinguish the type of entity you're trying to update. Drupal can't help you to make the decision, it simply doesn't know what you mean when you give it nothing but a number to work with.

---
Tags: entities
---


title: how to get correct user id on page

text:
# Question
Title: how to get correct user id on page
I've added two custom fields to my user form - `field_license` and `field_download_date`. In my `preprocess_page` function, I'm doing this:

```
if(isset($vars['user'])) {
   $user_data = user_load($vars['user']->uid);
   error_log("userdata");
   error_log(print_r($user_data, 1));
}

```

I'm not trying to get the current user info, but a specific user. When I look at the error log, though, `$user_data` is printing out the info of the user I'm logged in as, not the user that's displaying on the page based on the URL (mysite.com/user/2). How do I get the data for the user based on the url?

# Answer
> 0 votes
You can use

```
user_load(arg(1));

```

# Answer
> 3 votes
For getting user based on current page, you can try to use `$account = menu_get_object('user')` code. Var $account will contain user object. Read more about this function here: https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu\_get\_object/7

# Answer
> -2 votes
you can use global $user; $user\_id = $ser-\>uid;

---
Tags: 7, users, theming
---


title: Template vs hook for views filed output

text:
# Question
Title: Template vs hook for views filed output
There are two possible solutions ( php field and view field are not recommended as I know ) to override output of a view field

1. Create template (tpl) file for field and code for desired output
2. Use hook `hook_views_pre_render`

as per the various articles, its not good to have too much templates in drupal.

which approach is good and loads fast ?

# Answer
> as per the various articles, its not good to have too much templates in drupal.

With respect, and depending on exactly what you mean by "too much", that's pretty much nonsense. If we're talking about 10,000 template files on an uncached site, then yeah, you would probably have problems. But those problems would be with your application's design; in the real world, with a normal application, that statement is just untrue.

> which approach is good and loads fast ?

Both are 'good' (or 'bad'), depending on your point of view, and how well you write the code for them; differences in load times will be negligible, especially with caching. If you're really worried about micro-optimising, then you need to benchmark your site, while it's under load and sitting on production hardware; that's the only way you'll know which method is faster for your use case.

It's not possible to give a blanket "this way is quicker" statement, because it depends on what the rest of the site is doing, how you have it and the server configured, and how good your code is. Always test in the real world rather than ask for others' experiences - you have no way to know if their experiences actually apply to your scenario.
> 1 votes

# Answer
It depends on what you you need to alter if you need to add new layout to set html tags surely .tpl would be the best solution.

If you need to do some checks on fields and do some logic before display fields you could user the pre render hook.

And you could use the two solutions on your needs.

About loading I see tpl file may be loading fast as the theme registry cached form my point of view.
> 0 votes

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


title: Block user after 6 month of inactivity

text:
# Question
Title: Block user after 6 month of inactivity
I want to block the user who does not logged in the application since six month.

# Answer
Looks like you're looking for Inactive User.

> The inactive\_user module provides Drupal administrators with a way to automatically manage inactive user accounts. This module has two goals: to help keep users coming back to your site by reminding them when they've been away for a configurable period of time, and to cleanup unused accounts.

(It is marked as "Unsupported" - but it does the job.)

A more stable module is User expire.

> This module allows an administrator to define a date on which to expire a specific user account. Use cases for this include anytime a user (such as contractors or short-term employee) are only active for a set period of time until their Drupal account should be disabled. This best fits when different users have unique expiration timeframes.

But it is not an exact match for your use case, since I understand that you want to have an automatic default six month expiry period.
> 3 votes

---
Tags: users
---


# Question
Title: How to list nodes that share one or more of the same entity references as the current node
I have three content types Projects, Campaigns and Blog Posts. Campaigns and Blog Posts share an entity reference field that allows for selection of one or more related Projects.

I currently have a View with block that is displayed on the individual Project nodes and lists Blog Posts that are related to that Project. There is a contextual filter to compare the array of related (Project) nodes within the Blog Posts with the ID of the current Project node. I want to add the same type of list to the individual Campaign nodes.

The Campaign nodes will have one or more referenced Projects and the Blog Posts must be compared to see if they share any of the referenced Projects in common.

For example Campaign 1 with references to:

* (Project 1, Project 2, Project 3)

should show related Blog Posts with either:

* (Project 1)
* (Project 2)
* (Project 3)
* (Project 2, Project 3)
* (Project 1, Project 3)
* (Project 1, Project 2)
* (Project 1, Project 2, Project 3)

I have read and tried a couple of possible solutions to configure the contextual filters and relationships, but nothing is working; the results are blank. I know for a fact that there is a Blog Post and a Campaign that share at least one common Project reference. So the results should show at least that one Blog Post.

Any ideas? Clearly defined configuration options would be appreciated.

# Answer
> 0 votes
You could get the blog posts related to projects refernced by the campaign displayed through:

1- create a view to get project id for projects have relation with that campaign.

2- create a new view listing blog posts that have relationships with projects taking project id as a contexctual filter.

3- create a .tpl file displaying the output of the view that gets projects from theme information

In that file embed blog posts view using views\_embed\_view() function giving the projects ids as a parameter for the view but you will need to

Configure views to accept multiple parameters you should set this option: View → Advanced → Your Contextual Filter → More → Allow Multiple Values

you will loop through fields to extract and form the ids array and pass it as the code sample below

```
$array = array('32+50+32');
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();

```

By that you will be able to get blog posts from another separated view

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


title: Variables in template files

text:
# Question
Title: Variables in template files
In my `.tpl.php` template files, I have several links and names of external websites. I would like to print these as variables, which are defined in `template.php`. That way, if I have to change a link, I can just change it in `template.php` and have them updated in all my `tpl.php` files.

How can I do this?

## Steps I have tried

In this tutorial, it says you can define your variables in `themename_preprocess_page(&$variables)`. You can then call them with `<?php print render($page['your_variable_name']); ?>`

However, when I try this, I just get a message stating `Notice: Undefined variable: page in include()`. The variable also doesn't print.

Also, if I use this method, can I use my variable in all tpl.php files or just the page.tpl.php file?

# Answer
> 3 votes
If you create a variable in `themename_preprocess_page(&$variables)`, it should could be accessed using the variable name itself. Example

```
function themename_preprocess_page(&$variables) {
  $variables['my_new_variable'] = "String value";
  $variables['my_new_variable_array'] = array(); // Some renderable array.
}

```

And then in your template you could simply print the first variable directly

```
<?php print $my_new_variable; ?>

```

And render the renderable array using the `render()` function:

```
<?php print render($my_new_variable_array); ?>

```

**Note:** The array keys become the name of the variable, so please make sure to use a unique name to the keys.

---
Tags: theming
---


title: How to Split Regions

text:
# Question
Title: How to Split Regions
Is there any way I can split a region into 2 different regions. For example, in Garland theme I want to split the HIGHLIGHT block region horizontally into two regions.. is it possible ?

Any help would be so much appreciate.

# Answer
> 1 votes
You should build your own theme and edit the tpl file to apply the layout you need

the easiest way is to build child theme and edit what you need in tpl files

create child theme

---
Tags: 7, blocks, theming
---


title: Pass Fields Via URL to a View?

text:
# Question
Title: Pass Fields Via URL to a View?
Use case #1: Display the Demonstration Title and Demonstration ID on the Deliverables view.

Use Case #2: The Deliverables view displays all Deliverables associated with a state specific State Demonstration.

So it seems like I need to pass two fields via URL to the Deliverables view page?

**Content Type:** Demonstration **Fields:** field\_demonstration\_title, field\_demonstration\_id

**Content Type:** Deliverables

Screen Capture of Workflow

# Answer
contextual filters takes arguments from entities whether in the url or not

you could build the url and match arguments with url parts
> 0 votes

---
Tags: views
---


# Question
Title: Find user profile page link from database
I know the link structure of a user page . Like For admin,it is example.com/users/admin But I want to know from database how can I find the link? or which table contains the link?

# Answer
The path "/users/admin" is actually an "alias" for something like "user/1", where 1 is the user id. In Drupal 7, these aliases are stored in the {url\_alias} table along with the real path that they point to.

So if you want to figure out what user the alias "users/admin" points to, look in the {url\_alias} table and you will see a column called "source", which should have something like "user/1". "1" in this example is the user id.
> 2 votes

---
Tags: users, database
---


# Question
Title: How to change the value of site_name to "My site name" in multilingual sites using Drush?
I'm trying to use this Drush command:

```
drush variable-set site_name "My site name"

```

I have no problem at all to use this command when the site has only 1 language. But it doesn't seem to work (have any effect) in a multilingual site when the "site name" is to be translated to additional languages.

Is there a way to use this Drush command to set the site-name in every of those additional languages? Either at once or in every language (in several steps)?

# Answer
> 4 votes
I understand your question as trying to use Drush for setting the site name, using Drush command like so:

```
drush variable-set site_name "Some name here"

```

And this for a multilingual site.

The equivalent of doing this via Drupal admin screens (instead of Drush), would require to first declare your site name as a "*multilingual varialable*". For more details on these kind of variables, and how to get this to work, refer to my answer at How to make content translation available for front page?.

In this case however, in "step 4" the variable to be selected is "Site name" (not "Default front frontpage"), within "Site information". While you're at it, you probably want to double check other similar variables like Site Slogan, etc.

If you try to do this using Drush, it won't work however, as explained in the issue about set i18n variables with drush? However, if you have the Variable module enabled, then according to Comment #3 in that issue, it should be possible to use Drush to achieve the equivalent result via Drush command like so (to set the Spanish language (es) to 'Spanish site'):

```
variable-realm-set language es site_name "Spanish Site"

```

Curious to some hear if in this case this Drush command resolved the issue here.

---
Tags: drush, i18n-l10n
---


# Question
Title: URL alias, tokens is replacing 0s and 1s with node and entity
Has anyone seen a case that url aliases or tokens end up replacing certain numbers in a url with the words node and entity. A UTC Timestamp in my url ended up replaced like this:

```
node4328522entityentity

```

I cannot find any errors in the watchdog table. It seems like it's trying to "encode" numbers, but those are numbers that shouldn't be encoded. Or another possiblitiy I've thought of is maybe it is trying to grab something out of a non-existent array at index 0 and 1?

# Answer
> 4 votes
This seems pretty similar to what is asked in the question about Tokens causing incorrect text substitutions .

Refer to my answer in that question for various options to further debug what might be going on. If you can, please enhance your question (by editing it) to indicate which of the possible reasons in your case do apply, or don't apply at all.

Also note the brand new comment there (from "diego"), here is what that comment says:

> I was able to find a work around at east for the Webform submissions. If I use a Rule to send the email (using \[data:{field-name}-display\] tokens) instead of the Webforms built in email function it doesn't seem to substitute any of the tokens.

# Answer
> 3 votes
I have been having a similar problem as shown in the question Pierre links to. Unfortunately we haven't been able to find the source of the problem yet to find a fix, but I have found a work around that has been working for me temporarily.

What I have been doing is going into the database and running the following query:

```
UPDATE url_alias SET alias = REPLACE(alias, 'node', '1') WHERE pid <> 0;

```

This replaces all instances of the word 'node' with the number '1' in the 'alias' column of the 'url\_alias' table. You can fairly easily edit it to be 'entity' and '0'.

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


title: file_usage_add issue for compound field

text:
# Question
Title: file_usage_add issue for compound field
I have created a custom compound field which contains a managed\_file element in the field widget form.

The issue I am having is not with saving the file, but with adding the file usage information.

I picked hook\_field\_presave based on some research, but this is not working for new content or translating the node.

```
function MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

```

The issue here is that when I save a newly created node, at this point, `$entity->nid` has not been defined. This number is required by `file_usage_add`.

Is there another hook that I can use to do what I'm trying to do?

# Answer
> 0 votes
Since I'm dealing with fields, `hook_node_insert` was overkill, but it got me on the right track.

The answer is to remove the `file_usage_add` logic from `hook_field_presave` and put it in hook\_field\_insert and hook\_field\_update.

Remove from `hook_field_presave`:

```
function MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      // no file logic here
      break;
  }
}

```

Add to `hook_field_insert`:

```
function MODULE_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

```

Duplicate for `hook_field_update`:

```
function MODULE_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

```

# Answer
> 1 votes
You could add the file usage by implementing hook\_node\_insert which gives you all node fields besides what you are looking for nid and the fid using file\_load in that case you could add file usage

---
Tags: 7, entities, files
---


# Question
Title: How to organize a lot of related blocks for facet search programatically?
I am experimenting with Solr search and the Facet API, and I've created a search page that now has about a dozen facet blocks on it.

Right now it just looks like Block 1, Block 2, Block 3, Block 4, etc.

I would like to group these into categories, such as Category A (Blocks 1-3), Category B (Blocks 4-9), and Category C (Blocks 10-12). Ideally these categories would be collapsible.

I already have way too many modules on my site so I want to avoid adding a new module (such as Block Group) to do this.

In this case, is CSS the way to go, or is there some aspect of Drupal that can help with this?

# Answer
I ended up doing this with Panels. I took the facet blocks and grouped them using mini panels, and then I used Panels Style Collapsible to allow them to be expanded or contracted as necessary.
> 0 votes

---
Tags: blocks, search
---