title: Search Nodes by Username

text:
# Question
Title: Search Nodes by Username
Is there any way to find node content (e.g., articles, pages, etc.) by username using Drupal's (version 7.x) core site search (i.e., the search end users can use)?

The installation that I'm working on currently indexes usernames only if they occur within the body of the node content; however, the users' respective articles will not show up.

I've attempted to write a small module to update the index to use the username (modifying this example for 7.x). I had no luck with this.

I've also attempted to write a small module that hooks into the search; however, it seems to be only accessible to the core node and user modules, which implement the hooks already.

For the time being, I have edited the core search module (in `search.pages.inc`) to call my small module. Then I grab the search keywords and see if they resembles an author name. If so, I grab some recent articles.

It works for now, but it's obviously not a good idea to edit the core.

Anyway, thanks for any help!

# Answer
Here's my Core Drupal search based solution for the same. The code below would be responsible for indexing the node author in a custom module badly named My custom module ('my\_module.module'). Most of the code is heavily inspired by the core search module's `search.api.php`.

Once the module is in place ensure that its name (again My custom module) is checked in **Active search modules**.

```
/**
 * Implements hook_search_info().
 * This ensures that the Search Content by author tab is present in your Search result
 * and available in the path site/byauthor/<searchterm>
 */
function my_module_search_info() {
  return array(
    'title' => 'Search Content by author',
    'path' => 'byauthor',
    'conditions callback' => 'callback_search_conditions',
  );
}

```

Following this click and confirm re-index content and run cron for the actual indexing The `hook_update_index` is written such that for each node the author name is retrieved and stored in the search index as a type *'nodebyauthor'*.

```
/**
 * Implements hook_update_index().
 *
 * To actually index the nodes based on the uid
 * "Inspired" by search.api.php from drupal core search
 */
function my_module_update_index() {
  watchdog('my_module', 'entered my module update index');
  $limit = (int)variable_get('search_cron_limit', 100);
  $result = db_query_range("SELECT n.nid FROM {node} n
            LEFT JOIN {search_dataset} d ON d.type = 'nodebyauthor'
            AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0
            ORDER BY d.reindex ASC, n.nid ASC", 0, $limit);
  foreach ($result as $node) {
    // simple query seemed a better option than loading the node and author object
    $author = db_query("SELECT `uid` FROM {node} WHERE `nid` = :nid",
              array(':nid' => $node->nid))->fetchField();
    watchdog("my_moduleupdateidx", "Node is {$node->nid} and uid is {$author}");
    if ($author !== FALSE) {
      $author_name = db_query("SELECT `name` FROM {users}
                     WHERE `uid` = :uid",
                     array(':uid' => $author))->fetchField();
      search_index($node->nid, 'nodebyauthor', $author_name);
    }
  }
}

```

A helper hook `hook_search_reset` to mark content for reindexing when re-index option is triggered

```
/**
 * Implements hook_search_reset().
 *
 * Reset the indexed item timestamp for being reindexed on subsequent cron runs.
 */
function my_module_search_reset() {
  db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    ->condition('type', 'nodebyauthor')
    ->execute();
}

```

The `hook_search_execute` is where the actual newly indexed content (after enabling our custom module and running cron) will provide results based on the user when a search is triggered:

```
/**
 * Implements hook_search_execute().
 *
 * To provide matching node results based on the node author when searched, again blatantly copied from search.api.php
 */
function my_module_search_execute($keys = NULL, $conditions = NULL) {
  $query = db_select('search_index', 'i',
           array('target' => 'slave'))
           ->extend('SearchQuery')
           ->extend('PagerDefault');
  $query->join('node', 'n', 'n.nid = i.sid');
  $query
    ->condition('n.status', 1)
    ->addTag('node_access')
    ->searchExpression($keys, 'nodebyauthor');

  // Insert special keywords.
  $query->setOption('type', 'n.type');
  $query->setOption('language', 'n.language');
  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }
  // Only continue if the first pass query matches.
  if (!$query->executeFirstPass()) {
    return array();
  }

  // Add the ranking expressions.
  _node_rankings($query);
  /*drupal_set_message((string) $query);
  drupal_set_message(var_dump($query->arguments()));
  drupal_set_message((string)$query->countQuery());*/
  // Load results.
  $find = $query
    ->limit(10)
    ->execute();
  $results = array();

  foreach ($find as $item) {
    // Build the node body.
    $node = node_load($item->sid);
    node_build_content($node, 'search_result');
    $node->body = drupal_render($node->content);

    // Fetch comments for snippet.
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
    // Fetch terms for snippet.
    $node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);

    $extra = module_invoke_all('node_search_result', $node);

    $results[] = array(
      'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
      'type' => check_plain(node_type_get_name($node)),
      'title' => $node->title,
      'user' => theme('username', array('account' => $node)),
      'date' => $node->changed,
      'node' => $node,
      'extra' => $extra,
      'score' => $item->calculated_score,
      'snippet' => search_excerpt($keys, $node->body),
    );
  }
  return $results;
}

```

Despite being huge even with some additional search hooks missing I believe anything is better an option than hacking core. Hope this helps.
> 4 votes

# Answer
I always just created a views search (using the Views module) with an exposed filter for the user search field. It was also nice because I could output the exact fields that I wanted to show without having to edit any TPL files.
> 2 votes

---
Tags: 7, search
---


title: Adding contents to custom blocks

text:
# Question
Title: Adding contents to custom blocks
I have created a custom region `regions['my_region']` in `mytheme.info` file. I have added a block `myblock` to the region. Now how can I add contents to this block? Currently I have created a template file `region--my_region.tpl.php` and added contents there. Is this the right way? How can a normal user will be able to edit these contents?

# Answer
There is simple method to add content in block.

* Go to Administration -\> Structure -\> Block
* click on 'Add Block' link in top of page.
* Add content in 'body' section and assign the region for your theme in 'region settings' section in page and save the form.

Kindly see that only administrator or user which has access to edit block, can edit the block content.

As we can add multiple block in a region, so its not good solution to add content in `region--my_region.tpl.php` file. If you will add content in your `region--my_region.tpl.php` file, then you can set 'page visibility' condition for the block.
> 1 votes

# Answer
Blocks are considered configuration, not a content. Thus, there is no separate privilege you can give your "normal users" to allow them to edit blocks.

There is another way round. You can make some of content to be a blocks with Nodeblock or one of it's competitors:

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

That way you can create content type Block, and apply node permissions to it. All of them, including "edit own block" or "edit any block".

Just be sure no one have "delete" permissions on them, as it would remove block you placed from your page, and that should be admin-only task.

---

Other way is to use Views module. With Views, you can define a block and make it to show user's content, using various filters and orders. You could, for example, make a Views block that displays content of type news from users with role reporter, unless it's Friday in Iceland, and when it is, display content of type joke. Order by random, by date, by user's reputation, by anything you want :)
> 2 votes

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


# Question
Title: Using SQL functions in conditionals in Drupal 7 db_select()
I am trying to write a condition into a SQL WHERE clause that forces the column comparison to a variable to be compared in lowercase. However the addExpression function isn't accomplishing this (since that is putting the expression in the field selection, not the where clause.

Here is what I have tried:

```
$category = 'mobile wifi';
$query = db_select('taxonomy_term_data', 'ttd')
    ->fields('ttd', array('tid'));
$query->innerJoin('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid');
$query->addExpression("LOWER(ttd.name) = $category");
$result = $query->condition('machine_name', 'images_cat', '=')
    ->execute()
    ->fetchAssoc();

```

And this:

```
$category = 'mobile wifi';
$query = db_select('taxonomy_term_data', 'ttd')
    ->fields('ttd', array('tid'));
$query->innerJoin('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid');
$result = $query->condition('machine_name', 'images_cat', '=')
    ->condition('LOWER(ttd.name)', $category, '=')
    ->execute()
    ->fetchAssoc();

```

The second one becomes invalid and the first one causes the problem I mentioned above. Any thoughts or suggestions?

Thanks, Patrick

# Answer
change

```
$query->addExpression("LOWER(ttd.name) = $category");

```

to

```
$query->where('LOWER(ttd.name) = :category', array(':category' => $category));

```
> 15 votes

# Answer
Using `LOWER()` is considered slow in MySQL. It isn't necessary too because `LIKE` in Drupal's Database API (DBTNG) is case insensitive, at least when your MySQL table is configured to use one of the \*_ci collations. A standard MySQL installation uses \*utf8\_general\_ci\* and so is Drupal.

So you just need to use a LIKE condition:

```
$query->condition('name', $category, 'LIKE');

```

See Conditional Clauses for a comprehensive explaination.

BTW: A DBTNG based database driver is responsible for implementing a case insensitive LIKE. PostgreSQL for instance uses ILIKE instead of LIKE which is handled in *includes/database/pgsql/database.inc*.
> 3 votes

# Answer
You can still use addExpression.

```
// Functions - You can use sql functions using addExpression ($expression, $alias = NULL, $arguments = array()).
$query->addExpression('MIN(o.tid)', 'min_term_id');

```

Resource: SQL query examples in Drupal 7
> 1 votes

---
Tags: 7, database
---


# Question
Title: How do i check the duplicate entry in the table?
I have created a custom form as below. And the user has to fill all the fields for the submission(I am storing all the fields after submission).

Question is how do i check if the email address has already been entered ?

# Answer
> 2 votes
One way of doing that is using the `hook_form_alter` and add the custom validation function, and in that custom validation you can check if the enterd email already exists in the database than set error, somewhat like below:

```
/**
 * Implements hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form id of your form.
  if ($form_id === 'YOUR_FORM_ID_WHICH_YOU_WANT_TO_EDIT') {
    $form['#validate'][] = 'check_email_address_exists';
  }
}

function check_email_address_exists(&$form, &$form_state) {
  // Get the value of email field. if you are under than use: "dpm($form_state['values'])"
  $email_entered = $form_state['values']['EMAIL_FIELD_NAME'];

  // Generate the query somewhat like below, For Example I am using users table's "uid".
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'));
  $query->condition('u.mail', $email_entered);

  // This will return the count of the fields found.
  $row_count = $query->countQuery()->execute()->fetchField();

  if (isset($row_count) && ($row_count > 0)) {
    form_set_error('EMAIL_ADDRESS_FIELD_NAME', t('This email already exists, please try with another email  address!'));
  }
}

```

In order it to work you have to change the values as per you requirement, and don't forget to modify the `db_select query` as per your requirement, and last **CLEAR THE CACHE** after implementing the same.

---
Tags: forms, emails, database
---


# Question
Title: Get node url alias/path when loading the node using node_load()
Does the `node_load()` does not return the node url alias in the node object or am I missing something.

I know one way of getting the url alias/path is using the `drupal_get_path_alias("node/NODE_ID")`, however I was hoping the object return by node\_load should contain node url alias as well.

# Answer
No, the URL alias is not a field nor entity property, and it doesn't get added to the node object when it's loaded.

It would be trivial to add that data though, using `hook_node_load()`

```
function MYMODULE_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->url_alias = url("node/$node->nid");
  }
}

```
> 4 votes

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


# Question
Title: how to hide articles page from home page in drupal
I have added article page in my project and made Views for that, but articles page also display on the front page. How to hide article from home page?

# Answer
> 0 votes
you have to untick "Promoted to front page " on structure / content types / your content types / publishing options, for every content type you have.

---
Tags: views, nodes
---


# Question
Title: Better exposed fiters with Views: how to show quantity of nodes tagged with certain term?
I use better exposed filters with views. I chose to show field "term reference" as hierarchical checkboxes on my exposed filter. It works great.

But now I need to add quantity of nodes having certain term near each checkbox inside filter. What is the best way to do it? Thank you!

# Answer
I ended up with editing \sites\all\modules\better\_exposed\_filters\better\_exposed\_filters.theme

Inside it I made a query to field\_data\_, got all terms with nodes count:

function theme\_select\_as\_checkboxes:

$res = db\_query('SELECT field\_dance\_styleee\_tid, COUNT(\*) as count FROM field\_data\_field\_dance\_styleee GROUP BY field\_dance\_styleee\_tid'); $allNodes = array(); while($record = $res-\>fetchAssoc()){ $allNodes\[$record\['field\_dance\_styleee\_tid'\]\] = $record; }

Then passed $allNodes to

```
  $output .= bef_checkbox($element, $key, $value, array_search($key, $selected_options) !== FALSE, $allNodes);

```

function bef\_checkbox($element, $value, $label, $selected, $allNodes=array()) {

$value = check\_plain($value); $label = check\_plain($label); $id = drupal\_html\_id($element\['#id'\] . '-' . $value); // Custom ID for each checkbox based on the 's original ID $properties = array( '#required' =\> FALSE, '#id' =\> $id, '#type' =\> 'bef-checkbox', '#name' =\> $id, );

// Prevent the select-all-none class from cascading to all checkboxes if (!empty($element\['#attributes'\]\['class'\]) && FALSE !== ($key = array\_search('bef-select-all-none', $element\['#attributes'\]\['class'\]))) { unset($element\['#attributes'\]\['class'\]\[$key\]); }

// Unset the name attribute as we are setting it manually. unset($element\['#attributes'\]\['name'\]);

$checkbox = '';

$properties\['#children'\] = "$checkbox $label". (( $element\['#name'\] == 'field\_dance\_styleee\_tid' && isset($allNodes\[$value\]) )? "(".$allNodes\[$value\]\['count'\].")" : '')."";

$output = theme('form\_element', array('element' =\> $properties)); return $output; }
> 0 votes

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


# Question
Title: How to display Articles on another page ? not in home page
I had Crated some articles for my project how to display that all articles on another page ? not on home page.

# Answer
> 0 votes
You are looking for Views module:

> You need Views if
>
> * You like the default front page view, but you find you want to sort it differently.
> * You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
> * You use /tracker, but you want to restrict it to posts of a certain type.
> * You like the idea of the 'article' module, but it doesn't display articles the way you like.
> * You want a way to display a block with the 5 most recent posts of some particular type.
> * You want to provide 'unread forum posts'.
> * You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

---
Tags: taxonomy-terms
---


title: Sub-theme of a sub-theme

text:
# Question
Title: Sub-theme of a sub-theme
If you have a sub-theme of a sub-theme...

* Sub-theme a
* Sub-theme b (base theme = Sub-theme a)

Ideally, what I want to do is have the default theme as 'Sub theme a' and just introduce some minor theming and processing in 'Sub theme b'. Reason being, there are lots of versions of this site being deployed and some minor fixes are required that can be thrown away at the click of a button i.e. remove Sub-theme b.

Google has not been helpful in this instance ;-)

**If both themes are enabled and sub-theme a is the default, how do I get sub-theme b to work? (because its not working i.e. I have added a stylesheet in the .info file and its not being added. If I make sub-theme b default then Sub-theme a doesnt work)**

# Answer
You *always* start with a base-theme. Let us call this **Theme A**. If you introduce a sub-theme (e.g. **Theme B** as a sub-theme of **Theme A**), it inherits everything from **Theme A**. You can introduce minor (or major) tweaks in **Theme B**.

If you set **Theme B** as the default, then you get **Theme A** \+ **Theme B**.

If you set **Theme A** as the default, then you get **Theme A** (with nothing from **Theme B**).

In other words, if you've set **Theme A** as the default, then **Theme B** is not *supposed* to work. To get **Theme B** to "work", you *must* set **Theme B** as the default.

This also works if you cascade with more sub-themes.

For instance, if you introduce another sub-theme (e.g. **Theme C** as a sub-theme of **Theme B**), it inherits everything from **Theme A** and **Theme B**. You can then introduce minor (or major) tweaks in **Theme C**.

If you set **Theme C** as the default, then you get **Theme A** \+ **Theme B** \+ **Theme C**.

A theme need to be enabled to be set as default, but works fine as an inherited theme even when it is not enabled.
> 2 votes

---
Tags: theming
---


# Question
Title: add a field to registeration to subscribe to newsletter module
I want something like the enewsletter module (it is for Drupal 6) for Drupal 7.

I used `simplenews` module, it add a subscribing field to user registration and it is well, but my problem is that in registration user select with category(from favourites taxonomy) want to be subscribe, and in creating simplenews content type select the term that this email send to them,( send simplenews content type according to taxonomy terms ).

I found simplenews terms module but it is for Drupal 6.

I try `newsletters` module but it is very complex and doesn't provide something I want.

# Answer
in `/admin/config/services/simplenews/add` add multiple category you want, by adding any category here, add term to newsletter category and you can do any thing with its taxonomy
> 0 votes

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


# Question
Title: SQL left join query using Drupal DB Layer
The following (my)?sql query performs a left joins of `node` table with `url_alias` table by matching a node with its url alias, and returns rows with the node's title, date created, type, and url-alias:

```
SELECT n.title, n.created, n.type, ua.alias
FROM node AS n LEFT JOIN url_alias AS ua
ON ua.source = CONCAT('node/', n.nid);

```

I would like to use the drupal DB Interface to accomplish the same thing. Ideally, I would like to write:

```
$query = db_select( 'node', 'n' )
  ->fields( 'n', Array('created', 'title', 'type' );
$query->leftJoin( 'url_alias', 'ua', 'ua.source = CONCAT("node/", n.nid)');
$query->addField('ua', 'alias');
$results = $query->execute();

```

which fails with a PDO exception: "node/" is not a valid column (which is true, but I didn't mean it to be a column, hence the `CONCAT`):

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'node/' in 'on clause': SELECT n.title AS title, n.type AS type, n.created AS created, ua.alias AS alias FROM {node} n LEFT OUTER JOIN {url_alias} ua ON ua.source = CONCAT("node/", n.nid); Array ( ) in _long_and_obscure_named_function() (line 680192318389 of narp.module (it's a large file; I went nuts).)
```

Rather than feeding the `left join` query raw into a `db_query`, is there some way that I can implement the query with `db_select` and `::leftJoin`, etc?

Any help would be much appreciated. (I should add that I am running Drupal 7.x).

# Answer
> 4 votes
I've seen this before, I can't remember *why* it's this way but you can fix it by swapping out which types of quote you use.

Changing your code to this will fix the problem:

```
$query = db_select( 'node', 'n' )
  ->fields( 'n', array('created', 'title', 'type'));

// Change wrapping quotes to "" and internal to '' for 3rd arg here
$query->leftJoin( 'url_alias', 'ua', "ua.source = CONCAT('node/', n.nid)");

$query->addField('ua', 'alias');
$results = $query->execute();

```

It's either a Drupal or PDO issue, as either type of quote works fine when executing directly against the MySQL server.

---
Tags: database
---


title: My site language is undetected?

text:
# Question
Title: My site language is undetected?
My D7 site uses Hebrew as it's default language, and though, an application such as SEOquake told me that the language is undetected. now, that's not an SEO question and it has really nothing to do with SEOquake, i just use it as an example for the given situation of an external device not detecting the language.

I have been told to add the following input, but i have no clue how to do it on Drupal, not even at the TPL files (if it's even a starting point), the input:

```
<html dir="rtl" lang="he-IL">

```

How could i apply this to all pages of the site?

Thank you very much.

# Answer
I have this in my html.tpl.php file:

```
<html
    xmlns="http://www.w3.org/1999/xhtml"
    xml:lang="<?php print $language->language; ?>"
    version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"
>

```

where $language is a global object, it prints, in my case:

```
<html
    xmlns="http://www.w3.org/1999/xhtml"
    xml:lang="en"
    version="XHTML+RDFa 1.0" dir="ltr"
>

```

Check out the variables available to you in html.tpl.php.

Make sure to clear your cache after you change the template.

**EDIT**: Full contents of html.tpl.php:

```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"
    <?php print $rdf_namespaces; ?>>
    <head profile="<?php print $grddl_profile; ?>">
        <?php print $head; ?>
        <title><?php print $head_title; ?></title>
        <?php print $styles; ?>
        <?php print $scripts; ?>
    </head>
    <body class="<?php print $classes; ?>" <?php print $attributes;?>>
        <?php print $page_top; ?>
        <?php print $page; ?>
        <?php print $page_bottom; ?>
    </body>
</html>

```
> 1 votes

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


# Question
Title: How to see recently inserted terms in the site?
I've many of my people tagging content in my site. I'd like to review all those newly entered terms of any vocabulary. Is there any easy way to do so? I understand there no author/date time entry when a new term is added.

I know one crude method. I can remember the tid from yesterday and display all terms greater than it if I want to see today's entry.

# Answer
> 4 votes
You could add a field to the term which saves the current date when saved. Use the hook\_taxonomy\_term\_insert() for this.

I think there is no other information on the term itself than the tid.

# Answer
> 0 votes
What about creating this field (that saves the current date) like Lance suggested, and creating a View that displays taxonomy terms, + your field and Sort them.

Regards

# Answer
> 0 votes
If you want something quick and dirty with MySQL and don't need complex access control to this information (no one but yourself needs to access the data):

* Add a new column of type `TIMESTAMP` with default of `CURRENT_TIMESTAMP` to the table (in D6, its `term_data`). I don't know what the PostgreSQL equivalent. It will then automatically get the timestamp for when the new record is created.
* Browse the table in a GUI SQL browser (example: Toad or Sequel Pro).

# Answer
> 0 votes
I think Lance's answer is a good approach. However, you could also use the message module (https://drupal.org/project/message). Messages are fieldable entities. You would:

1. Create a message type for tracking new tags (i.e. tag\_added, or similar)
2. Add a field to store the tag created.
3. Use hook\_taxonomy\_term\_insert() to catch the event and create a new message (you could probably use a rule instead if you prefer)
4. Build a view to show tag\_added messages (or use the built-in, generic view that message ships with)

This is a more generic approach that would make sense if you also want to track other events or activities on your site (new users, new content, modified content, etc). One advantage is that you'd also collect the user info for each new tag.

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


# Question
Title: how to retrieve field collection data associated with a node
I have an event node which contains a reference to a gallery field collection. If I do a dump of the $variables variable, I can find this

```
$variables -> field_gallery_image['und'][0]['value']

```

but I don't know where to use that value to do a table look up to actually find the data in the field collection. I was able to find that id number in the field\_collection\_item table, and then was able to find that id in the field\_data\_field\_image table (I have an image field), but I'm not sure where to go from here.

# Answer
I believe you are looking for field\_collection\_item\_load or field\_collection\_item\_load\_multiple function both are in field\_collection.module
> 1 votes

---
Tags: entities
---


# Question
Title: What is the template name for www.mysite.com/user/login
I have literally tried every combination possible, what am I missing?

page--user--login.tpl.php page--user.tpl.php page--login.tpl.php user--login.tpl.php page-user-login.tpl.php

# Answer
page--user--login.tpl.php ... if you create one, make sure you flush your cache!

Also, check out this module: https://drupal.org/project/devel\_themer

It'll help you determine these sorts of things, just don't leave it running after you're done development!
> 1 votes

# Answer
As per the template suggestion following will be the template file for `user/login` page:

> page--user--login.tpl.php

However to use tme above template you may require the following template:

> page--user.tpl.php

Also make sure you **CLEAR THE CACHE** after applying the changes.

Reference:
https://drupal.org/node/1195754

---

Alternatively if you want to define the custom suggestion for the `user/login` page than you can do it with the `phptemplate_preprocess_page` as following:

```
function phptemplate_preprocess_page(&$vars, $hook) {
  // Check to see that the user is not logged in and its correct page.
  if ($vars['user']->uid == 0 && arg(0) == 'user' && (arg(1) == '' || arg(1) == 'login')) {
    // Add suggestion for template-file "page--login.tpl.php" for user login page
    $vars['theme_hook_suggestions'][] = 'page__login';
  }
}

```

Now you can use **page--login.tpl.php** for the `user/login` page.
> 0 votes

---
Tags: theming
---


title: Displaying menu in theme

text:
# Question
Title: Displaying menu in theme
How do I render a menu in a theme? Is there an easy way to do this?

I would prefer just a line of code that calls all the menu items in for a custom menu.

Say for example I had a menu named "brands"

How would I put that on my page--front.tpl.php?

# Answer
I pulled this out of one my themes:

```
<div class="menu">
    <?php
        print theme(
            "links",
            array(
                "links" => menu_navigation_links("MENU-NAME"),
                "attributes" => array(
                    "class" => array(
                        "links",
                        "menu-links"
                    )
                )
            )
        );
    ?>
</div>

```

Alternatively, you can use Menu Block module and assign a menu block to a region, thus removing all of the ugly code from above from your theme file.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Opening user session programmatically using headers information
I'm developing a website with an external user authentication provider. The whole login process is external, that I don't need to worry about. Once a user is logged in, the external provider adds extra data in the request headers (i.e. customer id), that I can use to map an external customer id with a user from the Drupal users table.

Which hook suits the best to open a session and login the user programmatically on each page request? (`hook_boot()` ?)

# Answer
> 2 votes
As the `hook_init()` doesn't works for the cached pages so the alternate option that seems to me is the `hook_boot()` (This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request),

**However** the discussion here on using the session during hook\_boot make me feel that **hook\_boot() is invoked too early to use the session, as Drupal has not yet initialised the session**.

> There is a trick to avoid the page is cached: Call drupal\_page\_is\_cacheable(FALSE) in hook\_init().

Check more here: using drupal sessions during hook\_boot

---
Tags: 7, users, hooks
---


title: Language comparison in template file

text:
# Question
Title: Language comparison in template file
My site has 3 languages. In my `node--service.tpl.php`, I've put the following:

```
<?php if ($language = 'es'): ?>
  <div class="more"><a href="<?php print $base_url . $node_url ?>">Leer más</a></div>
<?php elseif ($language = 'en'): ?>
  <div class="more"><a href="<?php print $base_url . $node_url ?>">Read more</a></div>
<?php else: ?>
  <div class="more"><a href="<?php print $base_url . $node_url ?>">Leere más</a></div>
<?php endif; ?>

```

However, it only shows me the language `es` even a page `en`, i.e. it only shows me the first div. Any idea?

# Answer
> 1 votes
`node--TYPE.tpl.php` doesn't include the global `$language` variable as you can see in this document but you can still use it by bringing the variable into scope, using `global`.

I've updated your code below to show you how to get this working.

```
<?php global $language; ?>
<?php if ($language->language == 'es'): ?>
  <div class="more"><a href="<?php print $base_url . $node_url ?>">Leer más</a></div>
<?php elseif ($language->language == 'en'): ?>
  <div class="more"><a href="<?php print $base_url . $node_url ?>">Read more</a></div>
<?php else: ?>
  <div class="more"><a href="<?php print $base_url . $node_url ?>">Leere más</a></div>
<?php endif; ?>

```

---
Tags: theming, i18n-l10n
---


# Question
Title: Changing the default "View" page when user logs in?
In Drupal 6 when a user logs in, they are presented with a completely useless page that has no information other than how long the user account has existed.

How do you edit this? Can you embed a view or something there? How would I make a Homebox the default tab? (I've tried using Tab Tamer to hide and disable the tab, but no effect -- still has the lousy "History" info.).

Thanks!

# Answer
I think the Login Destination module may help you.
> 3 votes

# Answer
If you are using Panels/Pages you can enable the user\_view page (admin/build/pages/edit/user\_view) and add views or whatever else you want there.
> 1 votes

# Answer
The Login Tobogan module will let you direct users to something else when they log in. It has lots and lots of configuration options.

Or you could use a Panel to override the display of the user profile and put the other views you want there.
> 0 votes

---
Tags: 6, users
---


# Question
Title: How do I use the Print Module with a Custom Form Module?
I have searched and searched but have not found a definitive answer or direction. I've installed the Print module (Printer, email and PDF) and have it successfully working when associated with content types.

My problem however, is making it work with custom forms. I have tried placing `print_insert_link()` in the form and it doesn't show up. I think all I'm missing is an example of `print_insert_link()` pointing to a custom form module. The path for the custom module I'm working with now is `glatfelter_forms/form_scorecard`. How do I properly use `print_insert_link()`? I'm using Drupal 7.23. This is my first post so please let me know if I can provide any additional detail. Thanks!

# Answer
In the configuration page of the Print module at `admin/config/user-interface/print`, there is a section **'Show link in system (non-content) pages'**.

If you select **Show on only the listed pages.** and enter the path of your form (`glatfelter_forms/form_scorecard`) in the textarea below, there will be a print link on that page.
> 0 votes

---
Tags: 7
---


# Question
Title: How to grant Userpoints after adding a comment once?
I created a Rule that grants Userpoints to users when they comment on a node. However, I would like to grant these points only once per node per user. That means future comments from the same user on that node should not result in extra points.

How can I do that?

# Answer
> 1 votes
I solved my problem with the Flags module: I created the flags called 'Commented on this node' & 'First reaction'\* and rule called 'Commented on a node'. These are my rule's settings:

*EVENTS:* After saving a new comment

*CONDITIONS:*

* Content is of type Parameter: Content: `[comment:node]`, Content types: Article
* NOT Node is flagged Parameter: Flag: Commented on this node, node: `[comment:node]`, User on whose behalf to check: `[comment:author]`

*ACTIONS:*

* Grant points to a user Parameter: User: `[comment:author]`, Points: 2, Points category: Reaction, Entity: `[comment:node]`, Description: New reaction, Operation: Add, Display: false, Moderate: Automatically approved
* Flag a Node Parameter: Flag: Commented on a node, Node: `[comment:node]`, User on whose behalf to flag: `[comment:author]`, Skip permission check: false
* Flag a Comment: Parameter: Flag: First reaction, Comment: `[comment]`, User on whose behalf to flag: `[comment:author]`, Skip permission check: false

So, every time a user adds a comment to a certain node for the first time, the node is flagged as 'Commented on a node', the reaction is flagged as 'First reaction' and the user who added the comment is rewarded 2 points.

\**I use the 'First comment' flag in a related question.\*

# Answer
> -1 votes
I would create a new role and use rule module to grant points. Point will be granted only (along with the role) if the user doesnt have the role assigned to him already.

---
Tags: 7, rules, comments, flags, userpoints
---


title: User field image deleted next day

text:
# Question
Title: User field image deleted next day
I have a strange issue with my drupal website. I created a image field to let users upload their own user galleries (like favorite images), this is not the profile image. The field works fine, users can upload their photos without limits, i can show it on each user profile (ex, if uid = 10 upload 3 photos, that 3 photos will appear on user profile with uid = 10, not on all profiles).

Now the issue is, in the next day (after the user upload the user photos), the photos disappear, i checked the file\_managed table, and they no longer exist, but the entries on field\_data\_field\_user\_gallery exists. I tried to reproduce the error and this is what i do:

* I log as user, upload some photos to my profile;
* I visit my user profile page and everything work;
* I change my computer date to next day;
* I check table file\_managed and files still exists;
* I visit my user profile again, and no images;
* I check again file\_managed and the previous entries disappear;

Anyone has any suggestion for fixing this? I already tried to create a new image field, tried to put in different directory, but always end with the same :/ .

Thanks everyone for your help.

**UPDATE**

I did some tests with @arpitr and found new data. The error (image deleted from file\_managed) only happens if i am logged in as VIP user (a role that i have on my site), so if i am logged and admin or "normal user" or even without login, the behaviour is correct, i can visit the (vip) user profile without any problems. Only VIP users can add and edit user gallery.

I temporarily found a solution using file\_lock module, but i want to know and fix if possible why is this happening only with vip user role logged in.

Any ideas?

Thanks a lot.

# Answer
> 0 votes
Are you sure the files are not temporary? It does sound like the files are being deleted because they are not yet permanent as Jayendra suggests.

Are you handling the file uploads yourself? Like through a custom form, because I've forgotten to save files permanently before, and I remember wasting a lot of time on it figuring it out :)

The temp files are cleaned with cron I believe, so I find it weird that altering your computer date would trigger the issue. They might however also be automatically cleaned up when you try to render an image that's not yet permanent, and that has passed it's 'lifetime'.

---
Tags: entities, media, users
---


# Question
Title: How to parse mysql query output as variable into another command in linux via Drush?
Currently I'm doing a mysql query via the command line using Drush and I want to parse the query output and grab the Node ID #, then put that ID # into a `drush php-cli 'node_delete(X)'` command. How can I do this? Currently I have the command:

drush sql-query 'select * from node where type="feed\_item" AND status=0 limit 1 \G'

then

```
drush php-eval 'node_delete(X)'

```

I think I'm suppose to use the command xargs?

From there how can I make this as a loop and delete everything that get's outputted? Yes I know I can just do it via the site, but i want to know how to do it via the command line using only Drush. Eventually I just want to make an interactive bash script where I can just put in the node ID range numbers and it will just delete it at once.

# Answer
Based on the query that you've provided, you're just getting one unpublished feed\_item, then deleting it. This can be done in one line, without an intermediate bash step.

```
drush ev "node_delete(
  db_select('node')
    ->fields('node', array('nid'))
    ->condition('status', '0', '=')
    ->condition('type', 'feed_item', '=')
    ->range(0, 1)
    ->execute()
    ->fetchField()
);"

```

If you wanted to delete multiple nodes at once - or all nodes returned with your conditions, then use https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_delete\_multiple/7 , remove the range and use fetchCol() to return an array of NIDs.

```
drush ev "node_delete_multiple(
  db_select('node')
    ->fields('node', array('nid'))
    ->condition('status', '0', '=')
    ->condition('type', 'feed_item', '=')
    ->execute()
    ->fetchCol()
);"

```
> 1 votes

---
Tags: drush, batch-operations
---


# Question
Title: Send e-mail when webform submission changes
Well, I want to send an e-mail when the web form is submitted, and when it is edited, so how can I do this? The employee fills a form, and submit it, an email have to be sent to the boss, then, the boss approved or denied the form, and e mail is sent to the employee.

# Answer
If you look here : http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/group/webform\_hooks/7 , you'll see that Webform provides some hooks on which you can act.

There's a hook called 'hook\_webform\_submission\_update', which triggers on the update of a submission. Using that one, you can check if the boss approved/denied it, and send out an email.

The plain 'send email on submission' can be configured through Webform itself, so you won't need to use a Webform hook for that. Although you could if you want to.
> 1 votes

# Answer
There is "Webform Rules" which does exactly what you are looking for (Rules integration on Webforms). Here is a quote about it (from the module's project page):

> ... adds rules integration on webforms.
>
> Did you ever want to react on webform submission using rules but couldn't find the proper event? Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).
> 1 votes

# Answer
While it is possible to edit webform submissions, it doesn't seem convenient and I'm not sure if it can trigger actions such as sending email.

Another way would be creating a new content type for your questions, allow users to create new content of that type, and define some rules (with Rules module) for sending email.
> 0 votes

---
Tags: webforms, emails
---


# Question
Title: How to debug queries and exports sent to Salesforce?
I'm using Salesforce Suite module.

My initial investigation says that the connection is encrypted via HTTPS.

Is there any easy way of debugging what is exactly sent to Salesforce?

I ended up by tracing the code via XDebug, but it's useless on environment which doesn't have it.

The module uses SalesforceSoapClient.

# Answer
If you're using Ubercart / Salesforce Integration, you can use the following patch:

**Drupal 6**

```
--- a/uc_salesforce/uc_sf_order/uc_sf_order.module
+++ b/uc_salesforce/uc_sf_order/uc_sf_order.module
@@ -635,6 +635,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
     // Export the object to Salesforce.
     try {
       $response = $sf->client->create(array($object), $map->salesforce);
+      drupal_alter('uc_sf_order', $response, $sf);
     }
     catch (Exception $e) {
       drupal_set_message(t('Error exporting order to Salesforce.'), 'error');
@@ -681,6 +682,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
         }
         try {
           $product_responses = $sf->client->create($product_objects, $uc_order_products_fieldmap->salesforce);
+          drupal_alter('uc_sf_order', $product_responses, $sf);
         }
         catch (Exception $e) {
           sf_dpm($e->faultstring, 'Ubercart order line item exception');
@@ -718,6 +720,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
       else {
         $user_object_export = salesforce_api_fieldmap_export_create($user_map_id, $account);
         $user_response = $sf->client->create(array($user_object_export), $user_map->salesforce);
+        drupal_alter('uc_sf_order', $user_response, $sf);
         $account_sfid = $user_response->id;
       }
     }

```

and then you can define the following function:

```
<?php
/**
 * Define debug constant
 * To activate, run: drush -y vset foo_debug 1
 */
define('FOO_DEBUG', variable_get('foo_debug', FALSE));

/**
 * Implements hook_TYPE_alter().
 */
function foo_uc_sf_order_alter($response, $sf) {
  $xml_request = $sf->client->getLastRequest();
  $xml_response = $sf->client->getLastResponse();
  FOO_DEBUG ? watchdog('foo', "UC Salesforce XML request/response:\n<br>Request:\n@req\n<br>Response:\n@res", array('@req' => $xml_request, '@res' => $xml_response), WATCHDOG_NOTICE) : NULL;
}
?>

```

To activate debug messages, run the following drush command:

```
drush -y vset foo_debug 1

```

And run watchdog messages in foreground before your test:

```
drush watchdog-show --tail --full

```

Read more:

Add hook\_alter for catching and debugging the requests and responses.
> 0 votes

---
Tags: debugging
---


# Question
Title: Programmatically save file into profile2 entity
I'm trying to save a file into my Profile2 entity, I've taken the user through a multi-step form, I've saved all the data and at the point I want to input my data into my profile object, I have a variable which 'holds' the file object which has already been uploaded before this point.

However, I can't find out what code I need to run to tell my profile2 entity (in pseudo terms)

field\_cover\_letter = $file

I've tried opening up a profile object of an existing account to see what it saves it as, which it seems to just be an array of the file object as well, but I tried typecasting my object to an array and using those values, but it throws a PDO. There must be a simple command to add a file to the profile2 object?

Cheers

# Answer
> 0 votes
If you are working with an unmanaged file, the following three-step process should do the trick:

1. Move the file (if necessary) to its final home defined by the file field on the entity.
2. Create a file object (see file\_save\_data() for some hints on how to do this) and then save it using file\_save(). This will turn the file from unmanaged to managed.
3. Add the file reference to the file field. You may also want to add an entry in the file usage table by calling file\_usage\_add(). Here is a code snippet for adding a file object to a file field on a node.

$node-\>file\_field\_name\[LANGUAGE\_NONE\]\[0\] = array( 'fid' =\> $saved\_file\_object-\>fid, 'display' =\> 1, 'description' =\> '', );

This assumes the file field accepts only one entry (index 0).

---
Tags: forms, entities, files, users
---


title: node_save causing duplicates

text:
# Question
Title: node_save causing duplicates
I've seen a few other issues where people were causing this by calling node\_submit followed by node\_save, but I'm not - any ideas why this is creating a duplicate of every piece of content?

```
$art = node_load($node->nid);
$field_language = field_language('node', $art, 'field_intro');
$art->field['field_intro'][$field_language][0]['value'] = $record->intro;
node_submit($art);
print $art->title . ' saved <br />';

```

I've tried both node\_save and node\_submit, both with the same results

EDIT: sorry guys, it was a conflict with a bit of code from another custom module - nothing to see here!

# Answer
> 1 votes
If you want to update the content of existing entity than you may use field\_attach\_update($entity\_type, $entity): this saves field data for an existing entity.

Example:

```
$art = node_load($node->nid);
$field_language = field_language('node', $art, 'field_intro');
$art->field_intro[$field_language][0]['value'] = $record->intro;
field_attach_presave('node', $art);
field_attach_update('node', $art);

```

**Note:** `field_attach_update()` always expects all fields (like we are \[passing the complete node object as `$art`), but If you just pass it the fields you actually want to update it will drop others like image or file fields.

# Answer
> 0 votes
According to the node\_save() documentation:

> If $node-\>nid is omitted (or $node-\>is\_new is TRUE), a new node will be added.

So, check the loaded node to make sure there's an `->nid` set on it, and `->is_new` is not set to `TRUE`. And I'd definitely use `node_save()` here.

Additionally, the syntax for changing an existing field should be: `$art->field_intro[$field_language][0]['value']`. And, if your fields always use the same language as the node, you can just use `$node->language` instead of loading the field language implicitly.

---
Tags: 7, nodes
---


# Question
Title: Any twitter boostrap(ish) theme for Drupal 6?
I'd like to make a legacy D6 site's theme more responsive. I love to be able to use the omni-present twitter bootstrap theme or something that comes close to it in responsiveness. I know that there is a quite a few for drupal 7+ but could not fine any for D6 on Drupal site.

So I'm wondering if there is any mature D6 Bootstrap theme? And if not, how hard is it to convert a D7 theme to D6?

# Answer
> 2 votes
Either you may start creating your own theme (you can use any light weight theme as base theme) from scratch using Twitter Bootstrap, or you may check the couple of options present on the sandbox project, which contains experimental code for developer use, as below:

If any of the above suits your requirement, then you can use them and modify it as per your need, instead of creating it from the scratch.

---
Tags: theming
---


# Question
Title: How to avoid writing to database in form submit?
I have a webform and I need to validate a condition before you type in the database.

Use the hook\_form\_alter, this is my code:

```
function validate_entry_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'webform_client_form_1'){
    $form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";
  }
}

/* function HOOK_FORM_SUBMIT */

function _validate_entry_webform_client_form_submit_handler($form, &$form_state){
  $option = $form['submitted']['eventos']['#value'];
  $data_total = db_query("SELECT count(data) FROM webform_submitted_data WHERE data = $option")->fetchField();

  print_r('<pre>');
  print_r($data_total);
  print_r('</pre>');
  exit();
}

```

I've noticed that my function to handle the submit is handled when it wrote in database.

I need a "hook" where you can get all the results before they are written to database. Validate the data and if everything is correct, follow the workflow in database insert.

# Answer
Form validation is called in the the first part af your code not in the submit function. Add another parameter to your form\_alter:

```
$form['#validate'][] = 'nameOfMyModule_functionName_validate';
$form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";

```

When validation passes, the submit function will be called. if not form\_set\_error can be called displaying a message like so:

```
function nameOfMyModule_functionName_validate($form, &$form_state) {
// Check for the color 'blue'.
    if ($form_state['values']['color'] == 'blue') {
    form_set_error('color', 'Sorry, your favorite color is actually yellow.');
    }
}

```
> 0 votes

---
Tags: 7, forms, hooks, webforms, database
---


# Question
Title: How to add delete link to recent comments block?
I'd like to add a delete link to the 'recent comments' block on my dashboard. How can I do that? Is it possible to edit the view aswell?

# Answer
> 0 votes
You can override the theme\_comment\_block(): You can find a good tutorial here: http://www.webomelette.com/theming-comment-block-drupal-7

I instead liked to just replicate the functionality in a Views block, and then styled the block to look the same way. I felt it gave me more control, and I try to avoid hacking up core blocks.

---
Tags: 7, views, blocks, comments, dashboard
---


# Question
Title: How to avoid appending incremental number to filename
I don't want Drupal to add incremental numbers to my file names to make them unique. I want to always have files stored with the same name they had when I uploaded them.

If the file with given name already exist, "Replace already existing file?" prompt should appear instead of default behaviour.

# Answer
> 1 votes
The Upload File Replace module should do the trick:

> Module Page Description
>
> This is a small utility module that automatically stops Drupal from renaming new files upload via filefield CCK. When 2 files with the same name exist, the older files will be renamed.

Edit: Sorry, I missed the part where you are expecting a prompt. According to the comment below, it is not possible.

---
Tags: 7, files
---


# Question
Title: How to open User registration in a pop up?
I'm using Fancybox to open user registration page in a pop up window. Here is the code

```
$('.fan_popup').fancybox({
  type: 'iframe',
  href: '/user/registration',
  width: 800,
  padding: 5,
  height: 600
});

```

The pop up window is shown but the page gives message like "You are not authorized to access this page.". How to overcome this.

# Answer
> 1 votes
Probably your server's settings prevent opening registration pages within frames. This prevents embedding your registration form in 3rd party webpage to create spam users et cetera. That is usually a good thing, even if what happens to you is over-restrictive.

Now, why to reinvent the wheel? There is a Modal forms module ready.

> Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window. Supported forms
>
> * Log in (modal\_forms/nojs/login)
> * Request new password (modal\_forms/nojs/password)
> * **Create new account** (modal\_forms/nojs/register)
> * Contact (modal\_forms/nojs/contact)
> * Comment (modal\_forms/nojs/comment/reply/%node)
> * Webform (modal\_forms/nojs/webform/%node)

*Emphasis mine.*

It has some bugs, but for first 3 it works pretty well. Or at least it used to.

---
Tags: users, status-messages
---


# Question
Title: Syntax highlighting for admin-side text areas (during node or block editing)
I'm trying to find a module that will highlight HTML (and preferably CSS/JavaScript inside of style/script tags, but that's an added bonus) **when I'm editing** a node or block in the administrative side of Drupal.

While I've searched on drupal.org for syntax highlighting modules and come across options like GeSHi and Syntax Highlighter, both of those seem to be for the public-facing end content and not the administrative side. Am I wrong and would one be suitable for me? I've also seen a few projects that highlight PHP code blocks, but that's less important to me than HTML/CSS/JavaScript.

I never use a WYSIWYG editor for my own HTML but some highlighting would be very helpful in editing my content.

# Answer
I use the BUEditor module, for which you can add syntax highlighting with some additional configuration. You can specify to only allow administrators access to this interface via the module's options page.

**Step-by-step instructions**

1. Install the BUEditor module (I used 1.6).
2. Download bue.highlight.min.css and bue.highlight.min.js from this page. I placed these files in a `bueditor` directory inside the directory for my custom theme.
3. Go to the BUEditor config page: `/admin/config/content/bueditor`. Edit the settings for the relevant version(s) of BUEditor (probably default, but it depends on which you assign to each role-- if you want, you can configure different BUEditor options per role, but then you will need to set up syntax highlighting for each.)
4. On the Editor settings screen, click the **Editor paths** tab and then add the following **Editor specific library files** (*My example assumes that you put the JS in your theme directory.*):
> %THEME/bueditor/bue.highlight.min.css
> %THEME/bueditor/bue.highlight.min.js
5. Then, scroll down to the bottom of that page (under **Buttons**) and add `tpl:syntax` along with this code:

js: BUE.postprocess.\_turnOnHlight = function(E, $) { setTimeout(function(){E.highlight('html')}); };

Then save the configuration and you should be good to go.
> 4 votes

# Answer
Wysiwyg CodeMagic module have the option, see the Demo

> CodeMagic is an advanced source code editor plugin for Tinymce. It integrates the CodeMirror library for syntax coloring, and the JSBeautifier library for code formating and indentation.

As I mentioned already Ace Code Editor, You can try this patch with the combination of wysiwyg editor. You can find the patch here
> 4 votes

---
Tags: input-formats
---


# Question
Title: Bots still register on website even though CAPTCHA is activated
I have activated CAPTCHA but bots still register on the site. If someone can advise how this can be prevented.

# Answer
> 6 votes
This kind of captcha is easily recognised by OCR software within bots. You can use:

* reCAPTCHA \- it was good not so long ago and it still stops significant part of bots that would solve regular CAPTCHAs
* Are You A Human PlayThru \- a bit more time consuming for users, at least if normal CAPTCHA was readable, but at the moment most solid way I know, as it can't be replaced by software very well.
* Confident CAPTCHA \- bases on human ability to recognize and name things we see. CPU power needed to do that is significantly higher than one needed for OCR (you can OCR on mobile phone, and Google's cat recognition was using 64'000 of CPU as far as I remember), so until computers are much more faster, and CPU power cheaper, this is a pretty good way to provide robot detection.
* Mollom could probably be used to detect attempt to post spam content, and then auto-delete users. Would require pretty complicated setup, but it would work on user's actual behaviour, so it has a potential to be a most honest way (and also auto-ban human spammers who by the very nature can solve CAPTCHAs).

# Answer
> 7 votes
To specifically block bogus registrations, I've found the project MotherMayI to be a great help.

> Mother May I provides a simple to use extra hurdle to reduce the bother of spamming account requests. It's primarily useful to sites with a limited target audience (at least for authenticated accounts) where valid users have some side information about the group. The site administrator can define a site-specific "secret word." Anyone requesting an account must enter the secret word before even a temporary account is created.

As the quoted text says, it is best suited for sites with a limited target audience. However, the module lets you give a "hint" that is supposed to make it simple for humans to find the secret word, and I've found that even ridiculous easy task where where the hint is "Please type in cartoon character Fred Flint's last name" (and the secret is "Flint") works great.

MotherMayI allow you to have a long "hint" text and use a RegExp for the answer, but only allow one "secret" word.

There is an alternative in the CAPTCHA family called Captcha Riddler that works similarly. It allow multiple riddles to be defined to separate humans from robots, but only allow short texts for riddles and have no RegExp function.

Since *you* define the "secret" word (MotherMayI), or "riddle" (Captcha Riddler), these methods are more immune to the "training" feature of *Xrumer* and other pests. This means the 'bot need to be trained *specifically* for your site. Unless your site is really huge, you'll be able to fly under the radar for a long time. *And* it is trivial to replace the secret word or riddle if the robot is trained to recognize your site.

Are You A Human playthru (also mentioned by Mołot) is in the same genre as the previous two, but IMHO slightly more cumbersome for humans to "solve".

# Answer
> 5 votes
Another option is to use the Honeypot module.

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site (read more here). These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user \[YouTube\].

# Answer
> 4 votes
If you are familiar with programming, add one hidden checkbox. Bots try to fill in everything, so they won't see its hidden. In the validation procedure-\>if this checkbox is filled in-\>filter

You will need `hook_form_alter()`

# Answer
> 4 votes
Have you considered the possibility that humans (paid a miserable pittance per form) are filling in the forms and not bots? My site gets dozens of spam registrations a day and it used to be hundreds. We tried Riddler and similar techniques but they get past every CAPTCHA.

The best solution we have found is using Views Bulk Operations to monitor new registrations. During business hours we block spammers a few times a day, after hours they are blocked by default and we approve them the next day.

# Answer
> 4 votes
I tried many configurations of captchas, with deceiving results most of the time. But I found the graal to forget definitively bots : botcha.

This module is amazing for 2 reasons :

* I've never had any spam submission of my forms anymore.
* It's user friendly, as it is completely transparent and non-intrusive.

As says the project : spambots learned to bypass CAPTCHA really well, and real users are frustrated with increasing complexity and burden of CAPTCHA. Instead, BOTCHA lets spambots to prove they are bots, and let real users zip by.

# Answer
> 2 votes
I have had great success with reducing spam registration with the Spambot module. It connects to the StopForumSpam API and will prevent IPs and email addresses matching entries in their database.

In addition, the module allows you to retroactively review your userbase for bogus user accounts and will unblock / delete them as you see fit. You can also report new bogus accounts to the SFS database if you generate an API key.

Another great tool in the kit to help solve this problem.

---
Tags: captcha, 7
---


# Question
Title: What functionality is available from Drupal.theme()
I have some complex data in javascript I need to render, mostly as tables.

This page explains how to add new theme functions, but I just want to create basic vanilla html. This apparently is the "official documentation."

I can't for the life of me find a list of the functions/functionality available in Drupal.theme()

I note this list of functions available from php - but I'm assuming the javascript version is a subset?

# Answer
These are the JS theme functions defined by core:

**Tabledrag**

* `Drupal.theme.prototype.tableDragChangedMarker`
* `Drupal.theme.prototype.tableDragIndentation`
* `Drupal.theme.prototype.tableDragChangedWarning`

**Vertical Tabs**

* Drupal.theme.prototype.verticalTab

**Overlay Module**

* `Drupal.theme.prototype.overlayContainer`
* `Drupal.theme.prototype.overlayElement`

Many contrib modules also define their own theme functions, it's not possible to list all of those here so your best best is to run a `grep -nr "Drupal.theme.prototype" /path/to/drupal` and see what's available in your own installation.

It's also worth bearing in mind that individual theme functions will only be available in the page if the file that contains them has been included. So if the Overlay module is disabled, for example, the related theme functions won't be available. If the vertical tabs JS hasn't been added that won't be available, and so on.
> 4 votes

---
Tags: 7, javascript, theming
---


# Question
Title: Is it a good idea to split a Drupal site into multi-site one for editors/admins and another for front end users?
To illustrate:
I have a multisites with a shared db edit.example.com and site.example.com. They share many tables but do not share all (a work in progress to determine what exactly need to be share). For example, the system table is not shared in order to be able to control what modules need to be enabled across all, on edit.example.com only and on site.example.com only. Does this can help performance? Is this a good idea or is it just adding an extra level of unnecessary complexity?For example I see caching becoming a problem because cache\_page is not shared, or even if it is shared.

If there are any references out there please refer me to it.

# Answer
> Is this a good idea or is it just adding an extra level of unnecessary complexity?

There is no functional advantage of creating a multi-site for the purposes of separating content administration, as that will add an unnecessary level of complexity.

Some of the issues include determining what tables to share (which you've identified). Another common scenario is that content will be rendered differently depending on the site, leading to troubleshooting nightmares. An unscrupulous developer can have multiple versions of the same module in the site code, which creates head-scratching differences.

A single site is significantly easier to manage and ensure that administrative roles and permissions are logically set given your needs.

It can be helpful to have a distinct administration theme to visually enforce the difference between a normal and administrative roles. It's possible to specify a role per theme - https://drupal.org/project/role\_theme\_switcher for example.
> 1 votes

# Answer
On a *large* site, I feel there are multiple problems can that be addressed by splitting a site into a "frontend", and a "backend" site. Different use-cases might find it beneficial to split along some other axis.

1. Security: When the administrative users and roles are mixed with the non-administrative ones, the risk of privilege escalation is massively increased. Forcing a separation between the two adds a strong layer of protection.
2. Performance: A Drupal bootstrap is heavy. When `select count(name) from system where status = 1;` returns some high 3 digit number, it can be *very* expensive. There's multiple sections across which one could split the modules, but a "admin"/"non-admin" should be a fairly common way that's useful. This makes the bootstrap cheaper, invokes fewer hooks with each invocation and generally performs better.
3. Stability:

1. When a large number of modules are enabled, interesting side-effects slowly start to pop up. Module X invoking hook Y was completely unanticipated, simply because the number of interactions between modules grows exponentially. Most of the time this will be what you want, and other times it will be innocent at best. Sometimes, it will bring your site down and you have no idea why.
    2. A large site will often be performing more than one tasks. Does it really make sense to disable all of that functionality because you need to put the site in maintenance mode, or worse because the site went down unintentionally. If large and important pieces of functionality are split up, they can fail gracefully independently from each other.

> Is this a good idea or is it just adding an extra level of unnecessary complexity?

Of course, running two sites, and keeping their content in sync, say with services, is also a lot of work. So I don't see this as relevant for the average site, it's to much work for to little benefit. Whether or not it's "unnecessary" is a decision that varies from site to site.
> 1 votes

---
Tags: performance, multi-sites
---


# Question
Title: Display only last item in multifileld (files by media)
I added one multifield - files with media widget. Drupal rendered all items, but I need only last. I can fix this by code below in template.php, but i don't know, it is good?

```
$i = 0;
while($i < $items_count - 1) {
  unset($variables['content']['field_files'][$i]);
  unset($variables['content']['field_files']['$items'][$i]);
  $i++;
}

```

What is the best way?

# Answer
You shouldn't unset array elements in tpl files. Instead, use `hide()` function:

> Hides an element from later rendering.
>
> The first time render() or drupal\_render() is called on an element tree, as each element in the tree is rendered, it is marked with a #printed flag and the rendered children of the element are cached. Subsequent calls to render() or drupal\_render() will not traverse the child tree of this element again: they will just use the cached children. So if you want to hide an element, be sure to call hide() on the element before its parent tree is rendered for the first time, as it will have no effect on subsequent renderings of the parent tree.
> 0 votes

---
Tags: theming, files, media
---


# Question
Title: How do I get the menu title via the menu name, Drupal 7 API
I'd like to get the title of the menu.

if I do:

```
menu_navigation_links('menu-name');

```

I get only the links without the title, which is good but I still need the title.

Any ideas ?

Cheers

# Answer
```
menu_load('menu-name');

```

Returns title, description and menu\_name for this menu.
https://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu\_load/7
> 2 votes

---
Tags: routes
---


# Question
Title: date_popup element not working when the form is rendered with ajax
How to attach javascripts to form rendered with ajax?

In particular, I have problem with popup calendars in my form. They are not showing, when my form is rendered with ajax.

I am rendering form with javascript as follows:

```
$.get('/event-form', {}, function(data) {
$('#event-popup-container').html(data);

```

This code calls ajax callback "/event-form". returned variable 'data' containes my form. This form is displayed on web page in HTML element $('#event-popup-container'). It works OK, just date\_popup elements in form don't show popup calendars. Propably I have to attach some javascripts somehow, when the form is not loaded with page load, but with ajax call. But I have no clue how.

I have such a code in my menu callback of path '/event-form':

```
<?php
  //...
  $event_form = drupal_get_form('ef_event__form', $event_id, NULL);
  $output .= drupal_render($event_form);
  drupal_json_output($output);
?>

```

Can anybody help, how to make work all needed javascripts, when the form is loaded with ajax?

# Answer
The problem is that you are not using any of AJAX helpers provided by Drupal. When you are using Form API AJAX, for example, all behaviors are re-initialised and functionalities like calendar added to new elements.

If you are not using Drupal-provided AJAX functionality, you need to manually call all behaviors with a proper context after your request is finished and DOM tree updated, probably by calling

```
Drupal.attachBehaviors(element)

```

on added DOM element.
> 2 votes

---
Tags: 7, ajax, datetime
---


# Question
Title: Hide the content while the current user has no access on
I written a module to filter the access for country\_admin,country\_admin can only view and edit the content that have the same country with the country\_admin.(Both the country\_admin and content have a country field.) Now I want to hide the content that current country\_admin have no access on. Is there a function can hide the content in drupal 7 ? Will be very appreciate if anyone can help.

```
if(!isset($target_user->field_role_country) || !$target_user->field_role_country['und'][0]['value']) {
  // The value is false (checkbox not checked) so we refuse access:
  return FALSE;
}
elseif ($node->type == 'clinic'
    && strtolower($target_user->field_role_country['und'][0]['value']) != strtolower($node->field_country['und'][0]['value'])) {
  drupal_set_message('This clinic does not associated with :country, You have no permission to view.', array(':country' => $target_user->field_role_country['und'][0]['value']));
  return FALSE;
}

```

# Answer
> 0 votes
`hook_query_alter()` serves this purpose.

The exact query alter you want looks like this:

```
function modulename_query_node_access_alter(QueryAlterableInterface $query) {
  // Obtain node, if needed
  $node = $query->getMetaData('node');

  // Do some calculations

  // Add condition
  $query->condition( /* your custom conditions here */ );
}

```

More details on Query alteration documentation page.

---
Tags: entities, nodes
---


# Question
Title: Show specific articles when clicking on tag
I'm working with a page view that contains articles and a block view that contains tags. I would like to display all the articles tagged with the tag I click.

So when clicking on the CITY tag I only want to display the articles tagged with CITY, does anyone know how I can achieve this?

Thanks

# Answer
Give the page view a contextual filter for the taxonomy term field in question and click "Specify validation criteria", then choose the "Taxonomy term" validator, select your vocab, and select "Term name converted to Term ID" for the "Filter value type" setting, like this:

Then in your tags view, for your term name field, select "Output this field as a link" and set the "Link path" to be the path of your page view, with the term name on the end for the contextual filter, like so (\[name\] is the term name field in my case):

\- Note that if this is a content view instead of a taxonomy term view you will have to add a relationship for your taxonomy term field before you can use the term name field. In your case the relationship should be "Content: Tags".

This would be the same for other entities, for example if your view was a user view and the user had the tags field on it.

Alternatively you could use the term ID contextual filter and term id field instead of using term name and the convert term name to term id option.

I prefer the term name as it looks nicer than term id in the url, but if you have really long term names or they have strange characters in them or anything the term id might be preferable.
> 1 votes

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


# Question
Title: there any field in view that display Display author and date information
I have created a view for my project, is there any field in view that displays "Display author and date information" ?

# Answer
Assuming you mean the date posted and making assumptions also on entity types.

**For nodes:**
Author: Add the "Content: Author" relationship and then the "User: Name" field.
Date: Add the "Content: Post date" field.

**For comments:**
Author: Add the "Comment: Author" field.
Date: Add the "Comment: Post date" field.
> 1 votes

# Answer
I have created similar views which display node author and node post date.

Code Snippets:

```
$view = new view();
$view->name = 'news';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'News';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'News';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = '';
$handler->display->display_options['fields']['body']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['body']['type'] = 'text_summary_or_trimmed';
$handler->display->display_options['fields']['body']['settings'] = array(
  'trim_length' => '600',
);
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = '';
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'custom';
$handler->display->display_options['fields']['created']['custom_date_format'] = 'd m Y';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'news';

```
> 0 votes

---
Tags: views
---


# Question
Title: Why are routing files filled with underscores?
What is the deal with all the parameters with, and without, a prefixed **underscore** character?

Where does Drupal decide how to process these parameters?

Was this concept introduced from Symfony, or is it new to Drupal?

**Example** (*node.routing.yml*):

```
node.overview_types:
  path: '/admin/structure/types'
  defaults:
    _controller: '\Drupal\Core\Entity\Controller\EntityListController::listing'
    entity_type: 'node_type'
    _title: 'Content types'
  requirements:
    _permission: 'administer content types'

```

# Answer
Here comes a hopefully good explanation behind the idea of the routing system as well as the drupal specific additions to it.

## General overview

The Symfony components have two important concepts here. The http kernel is a system which gets the request, somehow ask other systems to produce to define the piece of code which produces the requested output (a response object) and send the response back to the client. This piece of code is called controller, so this can be either a pure php4 like function, a method on an object or even a anonymous function.

The system that knows which controller is responsible for the current request is the routing system.

## Basic routing file

As module developer you define the list of routes and the corresponding controllers.

Here is an example for a json response:

```
taxonomy.autocomplete_vid:
  path: '/taxonomy/autocomplete_vid/{taxonomy_vocabulary}'
  defaults:
    _controller: '\Drupal\taxonomy\Controller\TermAutocompleteController::autocompletePerVid'
  requirements:
    taxonomy_vocabulary: \d+

```

Most symfony documentation mention pattern, but drupal decided to just allow the non-deprecated "path" key in its routing file.

The key concept is the controller which gets some parameters from the system and converts them to the response. In this example you have the parameter 'taxonomy\_vocabulary'. So everything without an underscore is considered to be a parameter to the controller. If you want to specify a default value, you put it into the defaults array. In the same yml array you specify the class and method connected with '::' to tell the system where to look up stuff. Every other property has nothing to do with the controller parameters and so are considered to be internal and so have an underscore as prefix.

Symfony itself also allows you to define regular expressions to validate that the incoming parameter is valid (using 'requirements'). Here it would match to only numbers.

## Controller resolver

Once symfony found out which controller is active on the current request, it asks the so called controller resolver to create an instance of the controller, that can be executed via call\_user\_func\_array. The controller resolver has one method to get the controller callable (object + method, anonymous function) and one method to get the parameters passed to the controller, see Controller resolver

## Drupal extensions

This is basically what symfony gives you.

Drupal though is slightly more complicated:

* You can check access to the route. For example calling user\_access() was very common in Drupal 7 and below.
* You don't want to convert the taxonomy\_vocabulary to its actual entity object
* You don't want to generate the full page response, but just the "main content".

## Access check

Drupal has introduced a system on top of the symfony parts that checks whether the user has access to the current route and alternative throw a 403 (access denied) exception. Access manager

In the routing file you specify this in the requirements part. The most common bits are listed in the example:

```
  path: '/user/{user}'
  options:
    _access_mode: 'ANY'
  requirements:
    _permission: 'access user profiles'
    _entity_access: 'user.view'
    _role: 'administrator'

```

\_permission defines a call to user\_access(), \_role ensures that the user has a certain role (you can specify multiple ones via , for OR and + for AND logic). \_entity\_access asks the entity system whether you have access to view the user entity. Per default drupal ensures that you add access checkers allow you to proceed, but you can switch it in the options via the \_access\_mode.

## Upcasting

As mentioned in the listing you don't want to take care about loading an entity, see /user/{user} as example. For entities you basically just use the name of the entity type and it will execute a entity\_load with the ID passed in the URL. Param converter manager

## Page response

As written before the controller is responsible to generate the response object. This would be horrible in Drupal as a page consists of so much more like all the blocks appearing in its regions, the html and page templates etc. Therefore drupal specified a different key to specify a controller which returns the content of a page:

```
user.page:
  path: '/user'
  defaults:
    _content: '\Drupal\user\Controller\UserController::userPage'
  requirements:
    _access: 'TRUE'

```

The string defined is the controller used to generate the render array for the main content region of your page.

Another addition is also the way how to deal with forms, as returning a page with a form is slightly more complex than just a render array, so you can define \_form with the FormInterface responsible for the current form.

```
user.pass:
  path: '/user/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
  requirements:
    _access: 'TRUE'

```

Note: This covers the most important points from my perspective, though there are for sure many more points to talk about.

## TL;DR

* Underscores are specified for everything which are not parameters to the controller. This is coming as a sort of "standard" from symfony.
* These parameters are upcasted via the param converter and passed to the controller using the controller resolver
* Drupal has some additions to make it easier for people to interact with the symfony routing system.
> 42 votes

---
Tags: 8, routes
---


# Question
Title: How to increase weight range avaliable when using Tabledrag?
I have a tabledrag with more than 20 entries. Much more. Default weight range is from -10 to +10, so it can only order first 20 entries. Every additional one have weight of 10 and is ordered by secondary means like ID, name or whatever, and not the way user set it to. How can I expand that range? I can't see anything like that in drupal\_add\_tabledrag documentation.

My form definition is pretty much copy-paste from Examples for Developers.

# Answer
> 5 votes
If you are using a field of type "weight" like in the examples module you need to use the #delta attribute.

---
Tags: forms, javascript
---


title: How do I pass parameters to the URL?

text:
# Question
Title: How do I pass parameters to the URL?
I want to pass parameters to the URL. With node/1/param1/param2, it works. If node/1 has the contenu/accueil path alias, contenu/accueil/param1/param2 returns a 404 error.

How do I pass parameters to the URL even when there is a path alias defined for the URL?

The Pathauto module is disabled.

# Answer
> 3 votes
You need the Sub-pathauto (Sub-path URL Aliases) module for that. Here is a quote about it (from the module's project page):

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
>
> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.

---
Tags: path-aliases
---


# Question
Title: how to create all dynamic ubercart product images for CDN module to sync
I have enable CDN module to handle image/css and js requests from a static server. As drupal creates product images for different styles dynamically there are many products whose images are not present at the time to CDN and my domains syncing of images. How can i handle the request to new product images in this scenario \> Right now the missing images are coming blank

# Answer
> 0 votes
This worked with the following setting in default/settings.php file

$conf\['image\_allow\_insecure\_derivatives'\] = TRUE;

---
Tags: ubercart, cdn
---


title: states multiple triggers

text:
# Question
Title: states multiple triggers
I have looked at previous posts but can't seem to get the following to work. It just displays the form line all the time, I can get it to work when checking for just a single option.

```
$form['type'] = array(
  '#type' => 'radios',
  '#options' => array(
    '10' => '10',
    '29' => '29',
    '30' => '30',
  ),
  '#title' => '',
);

$form['line'] = array(
  '#type' => 'radios',
  '#options' => array(
    '1' => '1',
    '2' => '2',
    '3' => '3',
  ),
  '#title' => '',
  '#states' => array(
    'visible' => array(
      ':input[name="type"]' => array(
        array('value' => '29'),
        array('value' => '30'),
      )
    ),
  ),
);

```

# Answer
> 3 votes
The problem is that this will work as OR, not as AND, so one or the other will make it pass:

```
'#states' => array(
  'visible' => array(
    ':input[name="type"]' => array(
      array('value' => '29'),
      array('value' => '30'),
    ),
  ),
),

```

This will do AND, however because you cannot have 2 array keys the same, you run into trouble:

```
'#states' => array(
  'visible' => array(
    ':input[name="type1"]' => array(
      array('value' => '29'),
    ),
    ':input[name="type2"]' => array(
      array('value' => '30'),
    ),
  ),
),

```

Since the array keys you see there are just jQuery selectors the key is to use 2 different selectors that apply to the same field. For example, something like this might work:

```
'#states' => array(
  'visible' => array(
    ':input[name="type"]' => array(
      array('value' => '29'),
    ),
    '.form-item :input[name="type"]' => array(
      array('value' => '30'),
    ),
  ),
),

```

This assumes your type field is in a .form-item div. There would be a number of possibilities here depending on your markup.

However, making something show when 2 different radio buttons are checked at the same time is impossible because you can only check one at a time.

If you were using checkboxes you could make it so that line only showed if type was 29 AND 30 by doing this:

```
$form['type'] = array(
  '#type' => 'checkboxes',
  '#options' => array(
    '10' => '10',
    '29' => '29',
    '30' => '30',
  ),
  '#title' => '',
);

$form['line'] = array(
  '#type' => 'radios',
  '#options' => array(
    '1' => '1',
    '2' => '2',
    '3' => '3',
  ),
  '#title' => '',
  '#states' => array(
    'visible' => array(
      ':input[name="type[29]"]' => array(
        array('checked' => TRUE),
      ),
      ':input[name="type[30]"]' => array(
        array('checked' => TRUE),
      ),
    ),
  ),
);

```

---
Tags: javascript
---


title: Line breaks on seperated Tags

text:
# Question
Title: Line breaks on seperated Tags
When I comma seperate my tags to make individual tags, drupal tend to put a linebreak behind every individual tag.

What happens:

That means that I need to make 1 huge tag, which is not factual.

I am Pretty newbie when it comes to drupal but this is kinda annoying.

Thanks in advance.

# Answer
> 0 votes
This is just how out of the box drupal styles the tags fields.

You can fix it by overriding the themeing of your tags in your theme, but the easiest way I have seen to fix it is by using the Text list formatter module.

Install that then go to the display settings for your content type and there will be a new option "List", which then has further configuration options that can give you the output you desire.

---
Tags: 7
---


title: Context within context?

text:
# Question
Title: Context within context?
I need 2 context that are identical expect that a single block will not be shown for one. Do I have to create 2 completely separate context (which will be more work to maintain)? Or is there someway to not show a single block within a context based on a new criteria?

For instance my context is page = front page. Im using mobile detect and I need to hide a certain block in this context for mobile devices.

# Answer
I dont think this can be done but its not too hard to have an elegant solution anyway. This is probably pretty obvious to anyone whos used Context for a while but here it is:

Create a front page context that has every block except for the one thats hidden on mobiles. Then add another context that is front page and not mobile devices, and add the block.
> 0 votes

---
Tags: 7
---


# Question
Title: Organic Groups (7.23) and D7 | drush or cmdline integration?
Just wondering how to manage OG in D7 from command line oder drush. OG seems frequently used so I'm surprised not to see any method to manage OG from shell, e.g. like create, modify Ogroups... As far as I know there were some former OG-DRUSH integrations in D6 but not in D7. Someone pointed out that the 'feature' module might be a solution (as part of the installation?). Anybody there who's willing to share his knowledge or give some information?

# Answer
I started, but never had time to finish Drush commands for og-6.x-1.x. Please see https://drupal.org/node/1090438 for the preliminary implementation. I don't know why no one else has picked this up; I agree it would be useful.

For og-7.x-2.x, I do some programmatic operations in my sandbox project https://drupal.org/sandbox/greg1anderson/2049677. These are not broken out into direct og operations, but it might serve as a starting point for someone who wanted to pick up the task of adding Drush commands to organic groups.

Finally, for anyone who wants to quickly make a Drush command from a template, see https://drupal.org/project/drushify.
> 2 votes

---
Tags: drush, organic-groups
---


# Question
Title: How to set context by url argument for node preprocess
I have a View of nodes, rendered using a Display Suite view mode. I need for users to either view the page with or without an argument in the path. If they don't enter an argument, I want the nodes in the View to render normally, but if they do, like someview/10, I simply want to add a CSS class for that node in preprocess. I have the Context module installed, so I'd like to be able to use that, but it doesn't seem like I can specify path arguments that I maybe set a context for that I can check for in the node preprocess. Or if I can do it in Views somehow, that would be great, but I can't seem to figure that out.

This functionality is for a nojs user. For js users, I just send the ajax commands back and set the CSS, but for nojs, I need to route them (I guess with drupal\_goto()) to the View with the nid as an argument.

# Answer
Here's a sketch of what you could do, using a custom module:

1. Define a menu entry for someview/%node.
2. Define a callback function for the menu entry with a node argument.
3. Store the node ID for later use. This could be done using drupal\_static or the context API.
4. In your preprocess function, retrieve the node ID and add a CSS class if required.

You could also use Panels to achieve a similar end, I think, but this is a fairly lightweight, if specific solution.

Let me know if you need a fuller explanation. I realise not everyone is familiar with Drupal APIs.

```
So your menu callback might look like:
function mymodule_callback($node) {
 context_set("mymodule", "active_nid", $node->nid);
 return views_embed_view((... ...);
}

```

and in the preprocess:

```
$active_nid= context_get("mymodule", "active_nid");
 if($active_nid==$node->nid) {
 ...
}

```
> 1 votes

---
Tags: views, 7
---


# Question
Title: Notice: Undefined index: field_brand_image in include() in views field template
I've got another question about undefined index that I can use help with.

The error message I get is: Notice: Undefined index: field\_brand\_image in include() on line 15

I'm pretty sure that this is the same lnaguage and "und" portion of the field array issue I had in my other question here: Notice: Undefined index: und in include()

And only displays when the field is empty

Except this time the error is coming from a views template, the line throwing the error looks like:

```
php print $fields['field_brand_image']->content;

```

I "think" the answer involves an isset conditional, but I don't know what the syntax should be. I'm using D7.23 and views 7.x-2.3

I'd appreciate some help. Thanks.

# Answer
One way of doing that is using a empty to check the field as following:

```
<?php print (!empty($fields['field_brand_image'])) ?
  $fields['field_brand_image']->content : ''; ?>

```
> 1 votes

---
Tags: theming
---


# Question
Title: Can the Devel page generation times be placed at the top of the page?
Can the Devel page generation times be placed at the top of the page?.

Devel places the page timer and memory usage figures at the bottom of the page making it necessary to scroll down to view them.

Is there some setting to place it below at the top, either above or below the page header?

# Answer
The **devel\_timer()** function present in the `devel.module` file returns the page execution time for every page which is as below:

```
/**
 * Displays page execution time at the bottom of the page.
 */
function devel_timer() {
  $time = timer_read('page');
  return t_safe(' Page execution time was @time ms.', array('@time' => $time));
}

```

as the function is present in the module file(which is available on all pages) therefore you can call the function anywhere you want something like below:

```
$page_execution_time = devel_timer();
print $page_execution_time;

```

---

**UPDATE:** another way of doing it with the **JS** is to get the value of page execution time from the default wrapper and display it in the custom wrapper as below:

```
<div id="page-execution-time-custom"></div>
<script>
(function ($) {
  // Jquery onload function.
  $(document).ready(function(){
    // Display the page execution time in the custom wrapper as below.
    var page_execution_time = $('.dev-query').text();
    $('#page-execution-time-custom').text(page_execution_time);
  });
})(jQuery);
</script>

```

I have tried it in the custom block(whose format was FULL HTML) that I placed in the header and it was giving the correct result (as the page execution displayed in block was same as displayed at the bottom of page), however it would be good to move the JS code to JS file (for testing I have tried this).
> 1 votes

---
Tags: debugging
---