# Question
Title: Use title instead of nid for node reference contextual filter
I have a view with a node reference field as contextual filter. Instead of using pagename/\[nid\] I would like to use /pagename/\[title\] or the pathauto url.

For uid fields there is an option to either use the uid or the name (or even both). I don't see such an option for nodes.

Is it possible?

# Answer
> 3 votes
The reason Views' user reference field allows both the user uid and name is most probably because they are both unique, while the title of a node isn't guaranteed to be so, but of course the nid is.

If, however, your content titles are unique, you might try using it as the contextual filter, hooking it up with a relationship (or rather whatever the D7 term is for it :) to the node reference field, and using all of the lower case transforms and spaces to dashes stuff.

That only leaves a problem if the title has funky characters in it, eg, if the title is `This & That` your path has to be `pagename/this-&-that` for the view to work which is ugly to say the least.

Now, how I've dealt with this is to create another text field in my content types that I want to search for by title and I store a url safe title in there. I auto fill them here in D6 land like this:

```
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {

  if (isset($node->field_url_safe_title) && $op == 'presave') {
    module_load_include('inc', 'pathauto');
    $node->field_url_safe_title[0]['value']=pathauto_cleanstring($node->title);
  }

  // all the other nodeapi stuff here

}

```

and now I can use `pagename/this-that` by filtering on this field instead of the title.

I use the nodeformcols module to hide this field on the node edit/add forms and don't display it in the node itself, but I am sure there are D7 ways of doing that. Obviously, in D7, I'd also assume you'd use `hook_node_presave()` instead of `hook_nodeapi()` and add in a language array field when setting the field, but the logic would remain the same.

# Answer
> 0 votes
I had a similar problem and after solving it, I have shared my detailed solution (the drupal way) on a similar question here - How to use node title or path alias instead of node id in node reference contextual filter in views?

---
Tags: 7, views
---


title: Drupal 7 Contextual Filter on URL Alias

text:
# Question
Title: Drupal 7 Contextual Filter on URL Alias
I have a view which shows a list of articles, located at:

> mypage.com/articles

Each article is linked to its main sub page view, like this:

> mypage.com/articles/name-of-my-artile-yay

The URL path is created with autopath & URL aliases.

In views, how do I create a contextual filter to show only the selected sub page view?

I have this as my path in views:

> articles/%

but don't know where to go from here. I tried title and making it lowercase and replacing spaces with a hyphen, but that won't always work and the URL aliases change the URL such that it removes words like:

> a, an, as, at, before, but, by

And if a page title is:

> This is my page title - with this

The URL alias becomes:

> my-page-title

Therefore it won't be able to match in my contextual filter using the page title.

What am I missing?

# Answer
> 8 votes
I think the simpliest way is to use Panels, and override the Node page. Add a variant and put your view in it, and send the node's nid argument to it, using node:nid contextual argument.

1. *(install page manager)*
2. Enable **node view** page *(node/%node)*
3. Add a variant, set a validation criteria selecting your concerned node type
4. Use simple one-column display
5. Add your view in your column
6. It asks for an argument, **send the node:nid**, (or entity\_id, or whatever)
7. In your view, **use node:nid** contextual filter

All is done.

# Answer
> 3 votes
Set path alias for the content type to something like `articles/[node:title]`

**Option 1: using views to run detail pages**

In views:

1. Create a `Page` view with the path set to the `/articles/%`
2. Add Contextual filters *Content: Nid* and set it to the following:

* *When the filter value is NOT in the URL* =\> Provide default value
    * *Type* =\> Raw value from URL
    * *Path* =\> Component 1 (Check "use path alias")

This does a path lookup on the last url segment (something like "my-article-title-path-alias") and returns the correct node ID.

**Option 2: By-pass views to run detail pages**

Instead of setting the path as `/articles/%` simply set it as `/articles` and let the all the path aliased `/articles/%` nodes resolve normally.

# Answer
> 1 votes
Add a contextual filter for the node ID and provide the default using PHP:

```
if (isset($this->view['args'][0])) {
  $path = db_query("SELECT source FROM {url_alias} WHERE alias = :alias LIMIT 1", array(':alias' => 'article/' . $this->view['args'][0]))->fetchColumn();
  if ($path) {
    $parts = explode("/", $path);
    if (isset($parts[1]) && is_numeric($parts[1])) {
      return $parts[1];
    }
  }
}

return FALSE;

```

This will return, for example, `node/123` if node 123's title was *My the Page and Title* and you accessed the View at `example.com/the_view/my-page-title`.

# Answer
> 0 votes
```
**Contextual filters**

```

1) Global: Null 2) (article) content/node: nid When the filter value is NOT available Provide default value : Raw value from url

# Answer
> 0 votes
Try this approach...

you first grab the normal drupal path "node/nid" then, you take the nid to load the full load and then use the node title as contextual filter.

1) Get the normal path of the current node being viewed...

```
<?php
$ogpath = drupal_lookup_path("source",$_GET['q']);

```

2) This may be expensive but try it ... get the current nid

```
$ogarray = explode('/', $ogpath);
$node = node_load($ogarry[1]);
return $node->title;

```

Tell me if it works.

Your pathauto is stripping words in a way I haven't come across yet, are you sure it is configured correctly?

# Answer
> 0 votes
I had a very similar problem and I not just found the solution to it, but also learned new things about how view works. Let me share what I learned and the solution to your problem too.

When you are creating a view with one or more contextual filters, the view must receive values of those filters from somewhere. This can be done by -

1. Picking the context filter value(s) **from the URL**
    * Typically you would have a *page view* for such purposes one that has URL of the form `foo/%/bar` or `foo/bar/%` for single contextual filter OR of the form `foo/%/bar/%` or `foo/bar/%/%` for multiple filters
    * In case you have multiple filters, the url value that appears first is mapped to the first filter, next to the second filter and so on.
2. Views allows you to tell **what to do if** the filter values are **not available in the URL**. This is typically used for *block views*.
    * You can choose from different actions and then configure the choice too. asdfj kajsdf
3. Another thing views allows you is to tell **what to do with** the filter values **if they are found in the URL** as described in #1 above. Typical use cases are - Making dynamic titles based on filter values, Validating filter values etc.
    * When validating filter values, you can change the values too! (That is where our solution lies btw). This is very akin to the way we can change $form values in the drupal form validation callbacks.

**Solution to your specific problem** lies in using a very similar code in the sections pointed to by the arrows in the above image.

Here is the link that proved out to be great help to me - http://www.drupalfoo.com/drupal-7-views-contextual-filter-argument-node-reference-using-url-alias

---
Tags: 7, views
---


# Question
Title: How to migrate a book from Drupal 6 to a menu in Drupal 7
Recently I came across a situation where I had to migrate a book with lots of links into a menu (since the customer wanted a simple navigational menu).

I came up with some code that worked pretty fine, so I decided to share it as an answer.

If you believe it could have been done in a better way, please feel free to comment and propose your ideas and methods. This code requires you to be somewhat familiar with the Migration process and the Migrate module.

# Answer
To begin with we define a class derived from Migration.

```
<?php

/**
 * To define a migration process from a set of source data to a particular
 * kind of Drupal object (for example, a specific node type), you define
 * a class derived from Migration. You must define a constructor to initialize
 * your migration object. By default, your class name will be the "machine name"
 * of the migration, by which you refer to it. Note that the machine name is
 * case-sensitive.
 *
 * In any serious migration project, you will find there are some options
 * which are common to the individual migrations you're implementing. You can
 * define an abstract intermediate class derived from Migration, then derive your
 * individual migrations from that, to share settings, utility functions, etc.
 */
abstract class MenuMigration extends DynamicMigration {

public function __construct() {

# Always call the parent constructor first for basic setup.

parent::__construct(MigrateGroup::getInstance('Menu'));

}
}

```

We now create a class that extends the above.

```
class EducationalGuideMigration extends MenuMigration {

public function __construct() {

parent::__construct();

#Define variable for the default user id (user="grammateia") wherever it is used (uid, revision_uid, etc.).
$user=36;

# Human-friendly description of your migration process. Be as detailed as you like.

$this->description = t('Migrate the "Studies Guide" menu');

```

We create the mapping in the database and our query.

```
$this->map = new MigrateSQLMap($this->machineName,
    array(
      'mlid' => array('type' => 'int',
                       'not null' => TRUE,
                       'description' => 'Menu link ID',
                       'alias' => 'ml'
                      )
    ),
    MigrateDestinationMenuLinks::getKeySchema());

$query = Database::getConnection('default', 'migrationDB')
           ->select('book', 'b');
$query->leftJoin('menu_links', 'ml', 'ml.mlid = b.mlid');
$query->fields('b', array('nid', 'mlid'))
        ->fields('ml', array('menu_name','mlid', 'plid', 'link_path', 'router_path', 'link_title','options', 'module', 'hidden', 'external', 'has_children', 'expanded', 'weight', 'depth','customized', 'p1', 'p2','p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'updated'))
        ->condition('bid', 30, '=')
        ->orderBy('ml.mlid');

```

As you can see we create our mapping based on the mlid (menu link id) primary key. You can find this key in the menu\_links table and the book table. The book table holds only keys, namely nid, mlid and nid. The menu\_links table holds all the info pertaining any sort of navigation menu in your drupal site, from your custom menus to administrative ones.

Luckily, Migrate provides us with a migration class for our mapping called "MigrateDestinationMenuLinks".

We use left join to join the two tables mentioned above. Obviously we need to know from which book we have to get our data so the book with id=30 is the one I was interested in.

We then execute the query and provide the destination menu plus anything we won't migrate (these unmigrated fields get default values).

```
# Create a MigrateSource object, which manages retrieving the input data.
$this->source = new MigrateSourceSQL($query);

# Set up our destination menu
$this->destination = new MigrateDestinationMenuLinks();

/**
 * SOURCE FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedSources(array ('module', 'options', 'has_children', 'depth','hidden', 'updated', 'external', 'customized', 'expanded', 'link_path', 'router_path', 'mlid', 'menu_name', 'mlid'));

    /**
 * DESTINATION FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedDestinations (array('module', 'options', 'has_children', 'depth','hidden', 'updated'));

```

Now it's time to map the fields that we do need to migrate.

```
  /**
 * FIELDS TO BE MIGRATED
 */

$this->addFieldMapping('menu_name')
        ->defaultValue("menu-studiesguide");
$this->addFieldMapping('plid', 'plid')->sourceMigration($this->getMachineName());
$this->addFieldMapping('link_path', 'link_path');
$this->addFieldMapping('router_path')->defaultValue('node/%');
$this->addFieldMapping('link_title', 'link_title');
$this->addFieldMapping('external')->defaultValue('0');
$this->addFieldMapping('expanded')->defaultValue('0');
$this->addFieldMapping('weight', 'weight');
$this->addFieldMapping('customized')->defaultValue('1');
$this->addFieldMapping('p1', 'p1')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p2', 'p2')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p3', 'p3')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p4', 'p4')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p5', 'p5')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p6', 'p6')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p7', 'p7')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p8', 'p8')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p9', 'p9')->sourceMigration($this->getMachineName());

```

In the menu name mapping we provide as a default value, our menu's machine name. (whatever name you gave is appended with the "menu-" prefix by Drupal).

Now you will notice that for the fields plid and p1 to p9 I have added this argument:

```
->sourceMigration($this->getMachineName());

```

First of all plid and p1 to p9 are all menu link ids. Plid is the immediate parent of every mlid and p1 to p9 is essentially our navigation menu for every menu branch.

What the argument does is pretty simple. It prety much tells our migration, "You know what, I got all the mlids from the query so any parent id you create is gonna be one of those menu link ids". (Note: that is why in our query we order by mlid).

So now ok, we have our menu, however the menu items are supposed to have links that correspond to nodes right? Well the book I had to migrate had 2 different content types which I also migrated, but their nodes were not assigned to these menu links. Also the nids I can get from the Drupal 6 are not the ones I need to assign to my menu links. So what do we do? Enter prepareRow().

```
function prepareRow($row) {

    $current_nid=$row->nid;

    $querymmi = Database::getConnection('default')
            ->select('migrate_map_idrimata', 'mmi');
    $querymmi->fields('mmi', array('destid1', 'sourceid1'))
            ->condition('sourceid1', $current_nid, '=');

    $resultmmi = $querymmi->execute();

    if($resultmmi->rowCount()==0){

        $querymms = Database::getConnection('default')
            ->select('migrate_map_studies', 'mms');
        $querymms->fields('mms', array('destid1', 'sourceid1'))
            ->condition('sourceid1', $current_nid, '=');

        $resultmms = $querymms->execute();

        if($resultmms->rowCount()==0){
            print "EVALA TH XAROULA EDW \n";
            print "path: node/9118 \n";
            $row->link_path = "node/9118";
        }

        else{
            print "STUDIES PATH INSERTED SUCCESFULLY \n";
            $row->link_path = "node/" . $resultmms->fetchField(0);
        }
    }

    else{
        print "IDRIMATA PATH INSERTED SUCCESFULLY \n";
        $row->link_path = "node/" . $resultmmi->fetchField(0);
    }
   }

```

So what we do here is this. Every time you migrate nodes a migrate map is created that corresponds drupal 6 nids to Drupal 7 ones. So we query those tables (as I mentioned earlier my book had 2 different content types) and we compare every nid we get from this migration's query with the source nids from our map tables.

We use this "if" condition to handle any case where no results are returned in our comparison:

```
if($your_result_variable_here->rowCount()==0)

```

The first condition checks if we have nids from our first map table, if not go check the other one. The second does the same check, but the reason to actually have it there is to provide a default value to a menu link if our condition doesn't return true (highly unlikely but it happens).

And finally how do we provide the correct nid to our menu link? Well be it either a default value or one of the node ids this is what we do:

```
$row->link_path = "node/" . $resultmms->fetchField(0);

```

Get the link\_path field from every row of our query, concatenate the string "node/" with the nid that we get from our result set. The fetchField(array index # here) does that.

So that was it. Hope my explanation was clear enough and it actually helps out.
> 4 votes

---
Tags: routes, migrations, nodes
---


# Question
Title: How to select all the field in content type
How to select all the fields created in custom content type using select query.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node', '=') // select nodes
 ->propertyCondition('type', 'testimonials', '=') //type testimonials
 ->propertyOrderBy('created', 'desc') //most recent first
 ->range(0,2) // limit
 ->execute();
$testimonials = node_load_multiple(array_keys($result['node']));

```

# Answer
If you don't mind my saying, you *don't* want to do that manually. Drupal has a rich API which you should use.

The standard method to load a node and all of its fields/extra data, is `node_load()`:

```
$node = node_load($nid);

```

If you're trying to avoid the overhead of the 'extra' (non-field) data, then you can use `field_attach_load()` along with a basic DB query to get a reasonable node object with all fields attached.

```
// Get base node data (aka 'properties')
$node = db_query('SELECT * FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();

// Attach the fields
field_attach_load('node', array($node));

```

It is possible, of course, to query the database manually for all of this data, but when the functionality has already been written for you there doesn't seem any point.
> 1 votes

---
Tags: entities
---


# Question
Title: How can I notify an admin when a user is contacted?
On my Drupal 7 site, I have a user contact form. How can I alter the form so that an admin is notified when the form is submitted?

# Answer
> 3 votes
In a custom module

```
hook_form_alter() yourForm.

```

Add custom submit handler, it will run alongside with your defaut submit

```
$form['#submit'][] = 'yourSubmitFunction';

```

Inside your custom submit handler use drupal\_mail() or any other result you need

```
function yourSubmitFunction($form, &$form_state) {
  drupal_mail()
  ....
}

```

Note: the form\_state array contains all the submited values.

---
Tags: forms, emails
---


# Question
Title: custom MailSystemInterface implementation
I need to create a custom implementation of `MailSystemInterface`.

I created a file called `my_module.mail.inc` but I don't know how to load it and how to tell Drupal to use it by default.

I installed the **mailsystem** and **autoload** modules but don't know what to do next.

Any help would be greatly appreciated. Thanks

# Answer
for mailsystem to work, you need to implement MailSystemInterface class and enable your new mailsystem class as default, for example in module hook\_install():

```
    variable_set('mail_system', array_merge(
       variable_get('mail_system', array('default-system' => 'DefaultMailSystem')), // Previously set mail_system variable
       array('login' => 'MyCustomMailClass')   // My new key(s) which ADD to the previous keys
    );

```

Note: `array('login' => 'MyCustomMailClass')` "login" is a module name, which will be used to identify your new mailinterface.

Next you should call your new mailsystem from hook\_mail(), like:

```
drupal_mail('login', 'registration', $form_state['values']['register_email'], language_default(), $params, 'mail@exmaple.com', true);

```

And class implementation could look someting like:

class MyCustomMailClass implements MailSystemInterface {

```
/**
 * Concatenate and wrap the e-mail body for plain-text mails.
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 *
 * @return
 *   The formatted $message.
 */
public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);

    if ($message['module'] == 'login') {
        $body =  $message['body'];
        $message['body'] = array();

        // Convert any HTML to plain-text.
        $message['body']['plain'] = drupal_html_to_text($body);
        $message['body']['plain'] = drupal_wrap_mail($message['body']['plain']);

        // Wrap the mail body for sending.
        $message['body']['html'] = drupal_wrap_mail($body);
    } else {
        $message['body'] = drupal_wrap_mail($message['body']);
    }

    return $message;
}

/**
 * Send an e-mail message, using Drupal variables and default settings.
 *
 * @see <a href="http://php.net/manual/en/function.mail.php
  " title="http://php.net/manual/en/function.mail.php
  " rel="nofollow">http://php.net/manual/en/function.mail.php
  </a>   * @see drupal_mail()
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 * @return
 *   TRUE if the mail was successfully accepted, otherwise FALSE.
 */
public function mail(array $message) {
    $mimeheaders = array();

    if ($message['module'] == 'login') {
        $separator = md5(time());
        // carriage return type (we use a PHP end of line constant)
        $eol = PHP_EOL;

        // main header
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Content-Type'] = "multipart/alternative; boundary=\"".$separator."\"";

        // message
        $body = "--".$separator.$eol;
        $body .= "Content-Type: text/plain; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['plain'].$eol;

        // message
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: text/html; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['html'].$eol;
        $body .= "--".$separator."--";

        foreach ($message['headers'] as $name => $value) {
          $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $sendM = mail(
          $message['to'], mime_header_encode($message['subject']),
          preg_replace('@\r?\n@', $line_endings, $body),
          join("\n", $mimeheaders)
        );

        return $sendM;
    } else {
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

        if(isset($message['customMode']) && $message['customMode'] == 1) {
            $message['headers']['Content-Type'] = 'text/plain; charset=UTF-8; format=flowed; delsp=yes';
        }

        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $heads = join("\n", $mimeheaders);

        $sendM = mail(
          $message['to'], mime_header_encode($message['subject']),
          // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
          // on Unix and CRLF on Windows. Drupal automatically guesses the
          // line-ending format appropriate for your system. If you need to
          // override this, adjust $conf['mail_line_endings'] in settings.php.
          preg_replace('@\r?\n@', $line_endings, $message['body']),
          // For headers, PHP's API suggests that we use CRLF normally,
          // but some MTAs incorrectly replace LF with CRLF. See #234403.
          $heads
        );

       return $sendM;
    }
}}

```
> 1 votes

---
Tags: 6, emails
---


# Question
Title: How hierarchical taxonomy comparison works
I'm bit confused about how hierarchical taxonomy comparison will work when using Views.

For an example (using Taxonomy and Menu block modules) I've 2 level deep taxonomy:

1 Animal(10)
1a Tiger(2)
1b Deer(5)

What should normally be is whenever I want to search for Animal type then the View search should return total of 10+2+5 = 17 nodes.

I've just now checked that it will instead return 10.

How to get this correct functionality?

# Answer
try structure -\> taxonomy -\> (edit your vocabulary) and at the bottom there is a checkbox

```
"Select to rebuild the menu on submit."

```

Please note:

```
"Rebuild the menu on submit. Warning: This will delete then re-create all of the menu items. Only use this option if you are experiencing issues like missing menu items or other inconsistencies."

```

Hit save and it should help
> 0 votes

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


# Question
Title: Ho to add mixed multiple fields in a node
I'm searching for a way to add unlimited amount of multiple *mixed* fields in a node.

In few words there is such a situation: let's say, I have a content type with fields "picture" and "text", and for both of them "number of values" is set to "unlimited", which lets user to add unlimited amount of photos and unlimited amount of text blocks.

What I want to achieve is that content editor could mix those two fields together, like it is possible to change places of entries of one field. The example of entry could be like this:

editor is adding a block of text, then a picture, then another picture, then again a block of text, etc.

The problem is that it is not clear what could be the amount of these elements and their sequence may change depending on circumstances.

I know that it is possible to do this with Views, but that makes the work of editor much more complicated and he/she cannot see the "full view" at the same time, so maybe it is possible somehow to merge two types of fields?

# Answer
Have you looked into Field Collection module ?

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

It allows to combine multiple fields and treated as a single field.

Here is the doc.

Hope it helps.
> 1 votes

---
Tags: entities, media
---


# Question
Title: Get view output without rendering (with substitutions)
I've got a view that I'm accessing via code and used to pull fully rendered view code and work great. But after one of the updates (looking like 6.x-2.15 or 6.x-2.16 maybe changed it?), I can no longer reference fields that are using views' field token replacement logic. All I appear to have access to now is the text that contains the token arguments, and not the final rendered code.

This is the code that used to work:

```
function _custom_module_get_view_options() {
    $view = views_get_view('VIEW_NAME', true);
    $view->pager['items_per_page'] = 0;
    $view->execute();
    $view->execute_display();

    $items = array();
    foreach ($view->style_plugin->rendered_fields as $display) {
        $items[$display['FIELD_NAME_1']] = htmlspecialchars_decode($display['FIELD_NAME_2'], ENT_QUOTES);
    }

    return $items;
}

```

The `$view->style_plugin->rendered_fields` doesn't appear to exist any more in the executed view...

As I mentioned above, anything else I have tried only gets me the un-replaced text patterns.

Site is on Drupal 6, and currently using Views 6.x-2.16 but was previously using Views 6.x-2.12 when it functioned as expected.

# Answer
The `$view->execute()` and `$view->execute_display()` no longer return `rendered_fields`.

I swapped those two lines with `$view->render()` and I now get the expected rendered\_fields element in the `$view->style_plugin` object.
> 0 votes

# Answer
There were several changes between these versions. If you check out Releases for Views you can see a list of changes for each version, and you can download each intervening version. I would suggest you peruse the list, and maybe roll back your current version, until you discover the specific change which broke your site. Then open an issue on the Views project page.
> 0 votes

---
Tags: views, 6, tokens
---


# Question
Title: Textarea not populating with previous value
So I have been buildign a simple form used to populate a block on the sidebar of my drupal 7 site. However I have run into a problem, the textarea on this form does not seem to populate with the sidebars previous value.

What has me stumped is that a textfield with the same defaultvalue code populates correctly.

```
//a debug textfield that works
$form['debug'] = array(
    '#type'        => 'textfield'
       ,'#title'       => 'Debug'
       ,'#default_value' => $sidebar_content[$key] ? $sidebar_content[$key] : ''
       ,'#description' => t('Please enter a suitable heading for the left sidebar.')
     );

//the broken textarea
 $form['body'] = array(
        '#type' => 'textarea'
        ,'#title' => t('Body')
        ,'#rows' => 15
        ,'#description'   => t('Body text for sidebar')
        ,'#value' => $sidebar_content[$key] ? $sidebar_content[$key] : ''
    );

```

Edit: After disabling WYSIWYG the text area started populating again. More digging revealed the reason it wasn't populating as a rich text box was because when an editor is used it submits the value as an array with two items; value and format. Consequently, this meant that the text editor was being given an array to display rather than a string.

Altering the #default\_value to $sidebar\_content\[$key\]\['value'\] resolved this issue.

# Answer
After disabling WYSIWYG the text area started populating again. More digging revealed the reason it wasn't populating as a rich text box was because when an editor is used it submits the value as an array with two items; value and format. Consequently, this meant that the text editor was being given an array to display rather than a string.

Altering the #default\_value to $sidebar\_content\[$key\]\['value'\] resolved this issue.
> 1 votes

# Answer
Your code is correct (except #default\_value instead of #value)

If you have a wysiwyg, try to inactivate it for testing

Or maybe 'body' is already taken in your form, try to change this field name
> 0 votes

---
Tags: 7, forms, wysiwyg
---


# Question
Title: How do views Contextual Filters behave with Pathauto?
I have Pathauto installed, so URLs to nodes are not like `node/3`. My question is that if I write a View with a contextual filter for looking for `node/3`, will it work?

Note: This contextual filter is in a block. See this question.

# Answer
> 2 votes
You would get the node id(nid) as argument. Internally the system gets its data from the unaliased url, not the browser url created with path\_auto.

# Answer
> 1 votes
pathauto only generates aliases. the nid stays the same. so contextual filters based on nid no problem.

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


# Question
Title: Why doesn't the "auto-create feature" in the Ftools module work on Features 2.x?
I've been using the Ftools module for a long time to create features more easily; this module provides a "auto-create feature" link on the features configuration page.

However, when I upgraded from Features 1.x to Features 2.x., "auto-create feature" no longer works; it simply removes everything from the .info file. What am I doing wrong?

# Answer
Features 2.x has this functionality built in, so you don't need to use ftools anymore. Go to the feature configuration page, click `Advanced options`, set the **Path to Generate feature module**, and then click *Generate feature*.
> 1 votes

---
Tags: features
---


# Question
Title: How to Hide Specific Pages to Anonymous Users
I need to be able to block the user's URL to be seen by anonymous users. Specifically:

http://www.mysite.com/users/user\_name and http://www.mysite.com/user (which are the same page but different URLs).

# Answer
> 0 votes
The first can be done by not giving the permission to view user profiles to anonymous users. The latter is not the same page as for anonymous users that's where they login. Blocking it would prevent anyone from logging in.

---
Tags: users
---


# Question
Title: Webform save draft after each field update
I need to save a draft of the webform after each field change. I know that you can save a draft by clicking a button (or between pages in multi-page forms) and my initial tough was to do a form\_alter, add an ajax callback to fields and call the submit handler for save\_draft. Had anyone tried something like this?

Some conditions:

* If there is an existing draft for the current user, it needs to update that one (not create a new one);
* it needs to work for anonymous users as well.

Drupal 7 + Webform 7.x-3.x

I'll post the answer here if I manage to do it, but any feedback would be appreciated if there are people who've done this before.

# Answer
> 0 votes
Ok, I've found this http://drupal.org/node/1319926 and based on it I've managed to make it work. This is my ajax callback (it can be attached using hook\_form\_alter(), based on your needs):

```
function _my_module_js_draft($form, &$form_state) {
  global $user;
  $draft_sid = _webform_fetch_draft_sid($form['#node']->nid, $user->uid);

  $form_state['values']['details']['sid'] = $draft_sid;
  $form_state['values']['op'] = !empty($form['actions']['draft']['#value']) ? $form['actions']['draft']['#value'] : t('Save Draft');

  $form_state['save_draft'] = TRUE;
  webform_client_form_pages($form, $form_state);
  webform_client_form_submit($form, $form_state);

  return $form;
}

```

For having the save draft functionality available for Anonymous I've used this patch: http://drupal.org/node/1932560#comment-7185674

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


# Question
Title: How do I import latitude/longitude into geofield?
I have a CSV file with a id column, a latitude and a longitude column, and some other data in each record. I have created a content type to hold this dataset. Each record will be mapped to a content. I used Geofield to store the location. How do I import the CSV file and create these contents?

# Answer
You can use the Feeds module to import your csv file and map it to your content type.
> 0 votes

---
Tags: importing-exporting, location
---


# Question
Title: An illegal choice has been detected when I submit my webform module
I am getting this error

> An illegal choice has been detected

when I am submitting my webform and that is happening only on the select fields , as i read on the internet it suppose to have default value but i don't know how to put it in the code I am editing my webform-form-16.tpl and I have the code like this.

```
$form['submitted']['material']['#title']='';
$form['submitted']['material']['#prefix']='<div class="row"><label>Material:</label><br><span class="select" id="selectselect"> </span>';
$form['submitted']['material']['#options'] = array('Steel'=>'Steel','Yellow Gold'=>'Yellow Gold','White Gold'=>'White Gold','Steel and Yellow Gold'=>'Steel and Yellow Gold');
$form['submitted']['material']['#suffix']='</div>';

```

# Answer
> 1 votes
Editing webform-form-\**.tpl or any template file is designed to alter the theme or display of the webform. It seems you are having issue with the forms content, specifically default values.

If you are using the Form API to create your form in your own module, you will need to declare it as described in the FAPI documentation.

```
<?php
  $form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
    '#default_value' => $category['selected'],
    '#description' => t('Set this to <em>Yes</em> if you would like this category to be selected by default.'),
  );
?>

```

The error that you are getting tends to occur when form elements are submitted that were not defined in the original form. And by the look of your template edit, that could easily be the case.

Check out your log at Administer \> Logs \> Recent log entries to see what is causing the error.

To get an empty entry submitted from the select options force the 'empty option' form declaration. Works like a treat.

```
'#empty_option'=>t('- Select -'),

```

Good luck. xK

# Answer
> 0 votes
You say you're using "webform" but you have a FAPI select box. If you're making webforms using the Webform module -- then the correct approach is to create a custom webform Component in a custom module. Here is an example implementation from a blog from the internet.

From the blog post:

```
/**
* Private implementation of hook_webform_select_options_info().
*
* @see webform_webform_select_options_info()
*/
function general_webform_select_options_info()
{
  $items = array();

  $items['people'] = array(
    'title' => t('People'),
    'options callback' => 'general_people_options'
  );

  return $items;
}
/**
* Option list containing the site users
*/
function general_people_options()
{
$q = db_query("SELECT `name`
                FROM {users}
                WHERE 1
                ORDER BY `name` ASC
               ");

$options = array();

while ($r = db_fetch_object($q))
{
  $options[$r -> name] = $r -> name;
}// WHILE

return $options;
}

```

---
Tags: webforms
---


title: Seach API Solr database service

text:
# Question
Title: Seach API Solr database service
I have a Drupal 7 installation on Linux with Tomcat 6 and Apache Solr.

Drupal can connect to Apache Solr, but the search only works for the "database service" class, even though I used the same settings when I created the server with "Solr Service" class.

Is there any way to troubleshoot the Solr index directly from linux box or Tomcat?

# Answer
Does `{Your drupal site}/admin/config/search/search_api` show a "working" (Green tick/check mark) next to your server settings? If so press 'edit' and this should provide you with a connection link to your solr installation being served by tomcat. The URL should be something like

> http://{IP of server with Solr on}:8080/solr

If in a browser you do to `http://{IP of server with Solr on}:8080/solr/admin` you should see a solr web query page that will allow you to query the solr server directly.

This should help indicate if solr is indexing the drupal content or not. On my localhost server a URL to return everything would be

> 127.0.0.1:8080/solr/select/?q=*%3A*&version=2.2&start=0&rows=10&indent=on

In the event you can't contact the tomcat server (And assuming your firewall is correctly configured, not all systems allow 8080 through by default) I found the article very helpful for installing and configuring Solr on Tomcat 6.
> 1 votes

---
Tags: search
---


# Question
Title: Records with identical uid and timestamp in node_revision
I'm investigating an issue on a D7 site where a handful of node revisions have apparently gone missing. The issue was discovered on 3/5, and I just noticed in my node\_revision table that several records were created on 3/4 with the same uid and the same timestamp (1362422613). How is this possible? Might it indicate a MySQL problem?

# Answer
# DISCLAIMER : Not a Drupal Developer, just a pure MySQL DBA

Here is a sample `node_revision` table:

```
mysql> show create table node_revisions\G
*************************** 1. row ***************************
       Table: node_revisions
Create Table: CREATE TABLE `node_revisions` (
  `nid` int(10) unsigned NOT NULL DEFAULT '0',
  `vid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL DEFAULT '0',
  `title` varchar(255) NOT NULL DEFAULT '',
  `body` longtext NOT NULL,
  `teaser` longtext NOT NULL,
  `log` longtext NOT NULL,
  `timestamp` int(11) NOT NULL DEFAULT '0',
  `format` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`vid`),
  KEY `nid` (`nid`),
  KEY `uid` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=227825 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql>

```

Strictly in terms of MySQL, there is nothing in place to prevent the same UID and timestamp from entering this table multiple times. The index `uid` is a non-unique index on the `uid` column. What you need is a UNIQUE INDEX to prevent this at the database level.

Run this query:

```
SELECT uid,timestamp,COUNT(1) ut_dups FROM node_revisions
GROUP BY uid,timestamp HAVING COUNT(1) > 1;

```

and this will uncover other UIDs with the same timestamp issue.

If you want to block rows from entering this table with duplicate `(uid,timestamp)`, change the indexes as follows (making a backup first):

```
#
# Backup node_revision
#
CREATE TABLE node_revision_backup LIKE node_revision;
INSERT INTO node_revision_backup SELECT * FROM node_revision;
#
# Change Indexes
#
CREATE TABLE node_revision_new LIKE node_revision;
ALTER TABLE node_revision_new DROP INDEX uid;
ALTER TABLE node_revision_new ADD UNIQUE INDEX uniq_uid_timestamp (uid,timestamp);
INSERT IGNORE INTO node_revision_new SELECT * FROM node_revision;
DROP TABLE node_revision;
ALTER TABLE node_revision_new RENAME node_revision;

```

The UNIQUE INDEX `uniq_uid_timestamp` physically prevents `(uid,timestamp)` from appearing more than once. Check the contents of `node_revision` and make sure it is proper.

If it looks good, you could run:

```
DROP TABLE node_revision_backup;

```

or keep the backup.

If it does not look good, run this:

```
ALTER TABLE node_revision RENAME node_revision_old;
ALTER TABLE node_revision_backup RENAME node_revision;
DROP TABLE node_revision_old;

```

Give it a Try !!!

# CAVEAT

You will need to check all modules involved that writes to the `node_revision` table.
> 0 votes

---
Tags: database, nodes
---


# Question
Title: Use a view's result as a javascript setting
I am trying to integrate the Supersized javascript library (http://buildinternet.com/project/supersized/) into my site.

It requires an array of image urls when initialized.

I would like to use a view to populate this array so that my content editors can easily update the site with new background images.

Does anyone know how to do this with Drupal 7?

I have seen the http://drupal.org/project/supersized module, but as far as I know it doesn't work with views.

# Answer
> 0 votes
It looks like Supersized wants a slides array with the information about each image. You could build the slides array dynamically from the view.

Two fields in the view: (1) The image, (2) The image thumbnail

The slides array wants these properties: image, title, thumb and url.

You could derive the image src, the title and the url from the image field (make sure it links to something). You could derive the thumbnail src from the image thumbnail field.

And here is some code that with modification should work just fine (taken from Supersized demo page):

```
jQuery(function($){

  var slidesFromView = [];

  $(".view-supersized .views-row").each(function(){
    var rowImage = $(this).find(".views-field-image img").attr('src');
    var rowTitle = $(this).find(".views-field-image img").attr('title');
    var rowThumb = $(this).find(".views-field-image-thumb img").attr('src');
    var rowUrl = $(this).find(".views-field-image a").attr('href');
    slidesFromView.push({image: rowImage, title: rowTitle, thumb: rowThumb, url: rowUrl});
  });

  $(".view-supersized").hide();

  $.supersized({

    // Functionality
    slideshow               :   1,          // Slideshow on/off
    autoplay                :   1,          // Slideshow starts playing automatically
    start_slide             :   1,          // Start slide (0 is random)
    stop_loop               :   0,          // Pauses slideshow on last slide
    random                  :   0,          // Randomize slide order (Ignores start slide)
    slide_interval          :   3000,       // Length between transitions
    transition              :   6,          // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
    transition_speed        :   1000,       // Speed of transition
    new_window              :   1,          // Image links open in new window/tab
    pause_hover             :   0,          // Pause slideshow on hover
    keyboard_nav            :   1,          // Keyboard navigation on/off
    performance             :   1,          // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
    image_protect           :   1,          // Disables image dragging and right click with Javascript

    // Size & Position
    min_width               :   0,          // Min width allowed (in pixels)
    min_height              :   0,          // Min height allowed (in pixels)
    vertical_center         :   1,          // Vertically center background
    horizontal_center       :   1,          // Horizontally center background
    fit_always              :   0,          // Image will never exceed browser width or height (Ignores min. dimensions)
    fit_portrait            :   1,          // Portrait images will not exceed browser height
    fit_landscape           :   0,          // Landscape images will not exceed browser width

    // Components
    slide_links             :   'blank',    // Individual links for each slide (Options: false, 'num', 'name', 'blank')
    thumb_links             :   1,          // Individual thumb links for each slide
    thumbnail_navigation    :   0,          // Thumbnail navigation
    slides                  :   slidesFromView,

    // Theme Options
    progress_bar            :   1,          // Timer for each slide
    mouse_scrub             :   0

  });
});

```

---
Tags: views, javascript
---


title: Random image with Cycle

text:
# Question
Title: Random image with Cycle
I'm using Drupal Cycle module and list field\_images items. I check 'random' button, but it is not working. I want get random image every refresh page. How can do it? field\_sort\_items or anyway solution?

# Answer
> 1 votes
You can do this in lots and lots of ways. This is 1 way without Views.

I did this for a homepage. I made 5 variables that hold `FIDs` for files uploaded using FAPI `file_managed` fapi element in an admin settings form.

Then using `hook_page_build` if I'm on the homepage I created a render array that simply calls `theme_image` using a random file id by loading my 5 variables into an array and using PHP's `array_rand()` to extract 1 random array value.

Lastly, if you can get this far -- and you have page caching turned on ... you'll only get 1 image ever and it'll never be random. For the render array inserted using `hook_page_build` you have to set `#cache => FALSE` within the render array so Drupal will not cache your images and it will be random every pageload.

# Answer
> 0 votes
If you used views, you might try Views Javascript Random module which randomizes on the client side. Sadly, it looks like it is only for D6.

> Adds a new sort type to views. It's under sort criteria -\> Global: Javascript Random.

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


# Question
Title: Drupal multilingual monthly archive using views
I have multilingual website in Drupal 7 and I am trying to implement news and monthly archive by using views. I am facing some problems with the monthly archive (I am cloning the default Archive).

For each language I have created news pages - f.ex. www.mywebsite.com/news (in English) and www.mywebsite.com/da/nyheder (in Danish). I also have created different views ("news", "monthly archive") for each language. The switch between the news including the views "news" works fine. But the switch between the monthly archives does not work in the way that I would like to. For example when I am on the page www.mywebsite.com/news/201301 and switch to Danish I am going to the page www.mywebsite.com/da/news/201301 but I would like to go www.mywebsite.com/da/nyheder/201301.

In every view I am specifying the language (content language and field language) to English or Danish. Any idea how I can solve the path problem?

I have also tried to use one view for news and one view for monthly archive (using current user's language) but then the problem is the title page. I can not translate the title for the different languages (accessibility issue).

Can somebody explane which is the right way for implementation of news monthly archive for multilingual website please.

# Answer
> 0 votes
Does the following similar question - How can I have a multilingual URL for a views result page depending on the language? help? It suggests the use of path translations and translations sets (part of i18n which I assume you already have installed and configured)?

---
Tags: views
---


# Question
Title: How to optimize APC when running many sites with common codebase?
When having many (+100) drupal sites on a server with a common codebase, what is a good setup to achieve good APC performance?

a) Increase APC memory to something really large (\>10GB)

b) Less sites per server

c) Drupal multisite

d) Pseudo multisite. Shared Drupal core symlinked to each site.

e) ?

I would prefer option d). Will APC cache the absolute path to each file?

# Answer
I think the key here is to limit the total number and size of your PHP scripts. You've already taken the first step by running them off a shared codebase. The next step is to make sure you're not duplicating modules or themes that are shared. For example, you should have `sites/all/modules/views`, not `sites/site1.com/modules/views` and `sites/site2.com/modules/views`.

Once you've done that, I can't imagine that the total size of your php files would be more than, say, 200MB.

The next step is to configure APC and figure out exactly how large all of your php scripts are. For a production server, I like to permanently cache my php scripts. Place the following in your apc.ini file:

```
apc.enabled=1
apc.shm_segments=1
apc.shm_size=512
apc.cache_by_default=1
apc.stat=0
apc.ttl=0

```

Note the `apc.shm_size=512` setting. We've purposely set it to something much larger than we think we will need. Once this is set (and you've restarted Apache), you should hit every single php script on your site so APC caches each of them. This includes the module admin page, views, theme pages etcetera for each of your sites. Once you're done with that, load up the apc.php script and see how much memory APC is actually using and adjust the `apc.shm_size` downward accordingly.

I have detailed instuctions on configuring APC for Drupal on Github.
> 6 votes

---
Tags: multi-sites, caching
---


# Question
Title: How to get the standard text format widget for a custom field type?
I've created a custom field that loads content from a given URL. The content is rendered with the given input format. That works fine.

Currently, I just gabe a list of available text input using filter\_formats and show this with a select widget. How can I replace this with the standard input format widget that is available underneath the node body textarea?

This is how it's done now:

```
/**
 * Implements hook_field_widget_form().
 */
function remote_content_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $url = isset($items[$delta]['url']) ? $items[$delta]['url'] : '';
    $tformatter = isset($items[$delta]['tformatter']) ? $items[$delta]['tformatter'] : 0;

    $widget = $element;

    $widget += array(
        ...
    );

    $widget['url'] = array(
        ...
    );
    $widget['tformatter'] = array(
        '#type' => 'select',
        '#title' => t('Text format'),
        '#options' => _remote_content_create_format_options(),
        '#default_value' => $tformatter,
        '#description' => t('Choose the appropriate text format.'),
    );

    $element = $widget;

    return $element;
}

function _remote_content_create_format_options() {
    global $user;

    $formats = filter_formats($user);
    $options = array();

    foreach($formats as $f) {
        $options[$f->format] = $f->name;
    }

    return $options;
}

```

# Answer
> 2 votes
You are looking for `'#type' => 'text_format'`. Usage example:

```
$form['text'] = array(
  '#type' => 'text_format',
  '#title' => t('Text'),
  '#default_value' => $text,
  '#format' => $format,
);

```

You will get the text in `$form_state['values']['text']['value']` and the format in `$form_state['values']['text']['format']`.

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


# Question
Title: jCarusel + colorbox, show one thumbnail and open different image
I have a jcarousel view, a colorbox, and content type that have two fields: thumbnail and full\_image. This is because I don't want to be depend on Drupal scaling/cropping . I would like to show thumbnail in jcarousel and after click - open full\_image.

In Views there is "Colorbox trigger" field, so I first loaded two hidden fields of both images, and then "Colorbox trigger". I set thumbnail as trigger field, and token of full\_image as popup content but it doesn't work (after click, resized thumbnail appears). I feel that I'm just missing something obvious but I'm not sure what. Or maybe is this more complicated?

# Answer
> 1 votes
Ok, I figured this out and I'm putting answer here for future generations. I realized that my invisible Thumbnail field had set colorbox as formatter. It was blocking Colorbox trigger from working. Silly trap, I hope someone will be able to avoid this mistake because of this.

---
Tags: 7, javascript
---


# Question
Title: How to make Imagefield slideshow display full width
I use Drupal 7.20 and try to make my imagefield just like PULLANDBEAR.

This is what I've already done: I'm using field slideshow to make node slideshow (this works as I want it to).

Then I want my image on click to open a bigger image that respects width and height (this part is really confusing).

Can someone give me the right directions or clues? I still haven't found the right ones. Maybe I used the wrong keyword(s) to find them? Right now I'm still using a trial and error approach as in the question How to zoom in an image using jquery?

# Answer
I have not used the field slideshow module, but if it allows you to select the image style, then you could use the Lightbox2 module http://drupal.org/project/lightbox2. Lightbox 2 is not the only option for displaying the image in an overlay/popup type thing, there are many, here is a comparison of some of them http://drupal.org/node/266126. I just mention lightbox2 specifically as it is the one I usually use.
> 0 votes

# Answer
I think Cloud Zoom should work. It's what's used on a lot of fashion magazine-style websites. Here is an excerpt about it from the module's project page:

> ... integrates the Cloud Zoom JQuery addon with CCK ImageField and ImageCache (or Drupal 7's core Image module).

This addon provides a small, thumbnail sized image, with an on-hover popup, zoomed and centred on a larger version of the image.
> 0 votes

---
Tags: javascript
---


# Question
Title: how to add multiple tables in hook_schema() in .install file while creating custom module?
Is it possible to add multiple tables in hook\_schema() while creating a custom module? I have created a custom module with the help of Drupal entities. Will it be possible to store two different table in the modulename.install file?

# Answer
You definitely can! In your hook\_schema implementation, your first array key is the table name. You can add as many as tables in this array:

Ex:

```
function quotes_schema(){
  $schema = array();
  $schema['quotes'] = array(
    'description' => 'Base table for Quotes. Contains all submitted data from initial page.',
    'primary key' => array('qid'),
    'fields' => array(
      ...
     ),
  $schema['quotes_access'] = array(
    'description' => 'Access tokens to quotes.',
    'primary key' => array('qid'),
    'fields' => array(
      ...
     ),

    ...
  return $schema;
}

```

This will create both `quotes` and `quotes_keys` tables.
> 7 votes

# Answer
Or you just create your tables in phpmyadmin or whatever GUI or terminal you prefer and let Schema module do the rest , give it a try it will save you ton of time.
> 3 votes

# Answer
There is no limit to the number of table schemas defined in an implementation of `hook_schema()`. It is enough to see how many tables the System module defines in system\_schema().
> 0 votes

---
Tags: database
---


# Question
Title: Reference to parent node on entity form type
I have a "Request more info" Entity Forms Type form that is accessed from basically every content type in the website, with a Menu Tab link created via Views. I attempted at adding both a NodeReference and Entity Reference with Prepopulate without successs. The closest I get is having a Select List displaying all Nodes from all referenced Content Types (Hundreds). Is it possible to have this field pre-populated instead of the user having to choose from a long list of Node Titles?

# Answer
> 2 votes
Prepopulate works by lifting values from the request url and inserting them into the rendered form. If it is not in $\_GET it will not appear. Using views with a menu tab will mean that you will have to add parameters to the url whether you use Prepopulate or not. I think you should back up and reconsider your approach.

I would suggest exposing the form as a block right on the pages you want. That way the page is easier to identify. If you use Bean it is a simple matter to create a block for your Entity Form Type.

1. Enable the Bean and Bean UI modules.
2. Go to **/admin/structure/block-types** and click 'Add new block type'.
3. Give the block type a name (eg Entity Form Type Block).
4. Under 'Manage fields' add an 'Entity reference' field. Select box widget is fine.
5. Under 'Manage display' select 'Rendered entity' and 'Render as full content'.
6. Go to **/admin/content/blocks** and click 'Add new block'.
7. Give the block a Label (eg. Request more information block) and a title.
8. Select your form from the dropdown, and save.
9. Go to **/admin/structure/views/add** and create a view called 'Node List' showing 'content' of type 'all'. Uncheck the 'Page' display. You are creating the master only. Click 'Save and Continue'.
10. In the view edit screen, Add a display -\> references.
11. Configure the 'Title' field and uncheck everything (no label, no link).
12. Under 'Advanced' configure a contextual filter in Content:NID. Check 'Provide default value' and select 'Content ID from URL'. Save your view.
13. Go to **/admin/structure/entityform\_types** and click 'Manage fields' for your entity form. Edit the nodereference field and set it to required, number of values = 1, and at te bottom under 'Views - Nodes that can be referenced' select your 'Node list - references' view.
14. Go to **/admin/structure/block** and set your block to display on the nodes you want, and for the roles you want. It is important to note that the block permissions will override any access permissions you have set on the form.

The entity form will now display on the selected pages, and the user will be required to select the node reference to submit the form. The list presented will be limited to the current page.

---
Tags: forms, nodes, entities
---


title: Fix Faq Ask Email Layout Question

text:
# Question
Title: Fix Faq Ask Email Layout Question
I am using FAQ Ask along with the FAQ module. Everything works well but the emails are coming all bunched up. I need to be able to re-arrange the layout as I want (simple text with active links).

Below is what I see:

# Answer
These emails are assembled in the **faq\_ask\_mail** function (faq\_ask,nodule, line 1013). The body is assembled beginning at line 1077.

If you wish to open up the body, you can go in and include some newline ('\n') characters into the text.

Since this hacks the module core, perhaps you should submit a patch as a feature request.

EDIT:

**faq\_ask\_mail** is an implementation of hook\_mail. You can define your own hook\_mail in a custom module to override the output. You must, however, adjust the weight of your custom module so it is processed after the faq\_ask module. You would handle it as follows:

```
function MYMODULE_mail(&$key, &$message, &$params) {
  $body = $message['body'];
  switch ($key) {
    case 'notify_expert':
    case 'notify_asker' :
      /*** Change the formatting of $body ***/
      $body = str_replace("\.", "\.\n\n", $body);
      break;
  }
  $message['body'] = $body;
}

```

Remember that this will have no effect if it is executed before the faq\_ask\_mail function.
> 1 votes

---
Tags: 7, emails
---


title: How to send email in drupal

text:
# Question
Title: How to send email in drupal
I have drupal site in that ,i want to send a email to charities when donor post a donation..,and i want to send a email notification to charities,so how i send email using drupal7

```
$message = array(
  'to' => '"'. addslashes(mime_header_encode('new donation')) .'" <test@example.com>';
  'subject' => t('Example subject'),
  'body' => "<html><head></head><body><b>Hi user! a donor added a new donaion! So please     check the site for more infomation!<br/>Thanks,<br/></b></body></html>",
  'headers' => array(
          'From' => 'test@test.org',
          'MIME-Version' => '1.0',
          'Content-Type' => 'text/html;charset=utf-8',),
);

drupal_mail_send($message);

```

# Answer
First you must enable the following modules:

**1**. Mailsystem module http://drupal.org/project/mailsystem
**2**. Mimemail module http://drupal.org/project/mimemail (it contains the mail actions and sending mail function) or you can use htmlmail module http://drupal.org/project/htmlmail
**3**. Rules module http://drupal.org/project/rules

After that you will do some steps:

**1**. Create new rule in admin/config/workflow/rules/reaction/add and select the "React on event" is "After saving new content".
**2**. Add a condition. Choose Node (Content is of type) for condition and choose your custom content type in the "Content types" list box.
**3**. Add another condition. Choose User(User has roles()). Choose data selector is "node:author" and choose the role of donor.
**4**. Add the action. Choose System (Send HTML email). You'll change the To, CC, subject, content here.
**5**. Try to test that.

Be sure that you can send email using your system. If you use the htmlmail module. It will have the send test email in its setting.
> 7 votes

# Answer
You may use Rules module to send email automatically.

The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).
> 1 votes

---
Tags: 7, forms, emails
---


title: hook_menu how to render the layout

text:
# Question
Title: hook_menu how to render the layout
```
function test_menu()
{

    $items['test'] = array(
    'page callback' => 'test_test',
    'title' => 'test',
    'menu_name' => 'navigation',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => true
    );

    return $items;
}

function test_test()
{
    echo 555;
}

```

when I access to url /test, i see '555', but how to render the layout itself and in the content of the page show '555'?

# Answer
> 2 votes
You should change "echo 555;" to "return 555;"

---
Tags: routes
---


# Question
Title: How do I add administrator approval on webform submitted data?
I have the functionality that when any anonymous user submits a webform, then I display the submitted webform data in my new page, but I need admin approval before that submitted data displays on another basic page in Drupal 7.

Does anyone know about admin approval for webform submitted data?

# Answer
> 0 votes
Use the Rules module to create a rule that sets a node to unpublished when it is saved. You might also want to have a look at the Content Approval module.

> a module that enable the approval of a content (node) by an administrator prior its publication (like the existing feature for comments).

---
Tags: 7, webforms, users
---


# Question
Title: Subscriptions does not send out "update" notifications
I am logged in as user/1 and have subscribed to a particular node. I then edited the content of the node and have ticked the "Send subscriptions notifications" option.

I did not receive an "update" notification. Why might this be the case?

By the way, I've enabled the following modules: * Subscriptions UI * Subscriptions Mail (+ Mail Editor + Token) * Content Subscriptions

I am logged in as user/1 and subscribed to a number of nodes. Updating them does not send email notifications.

The settings I've got turned on are as follows:

**admin/config/system/subscriptions**

Unlisted content types - none

Blocked content types - none

Node form position - Fieldset above node links

Node form visibility - Always display the fieldset

Expand the node form fieldset

**admin/config/system/subscriptions/userdefaults**

Nodify poster of own posts Send interval - As soon as possible

On updates - ticked

Send interval - Hidden

On updates - hidden

**admin/config/system/subscriptions/intervals**

1|As soon as possible 900|Every 15 minutes 3600|Hourly 10800|Every three hours 86400|Daily

Do I need to enable "\* Taxonomy Subscriptions (e.g. forums!)" for the subscriptions to work?

Also, not sure if this is required, but I went to admin/config/system/mail-edit and added a template fornode-type-basic\_page for the Subscriptions Mail module. However, this made no difference in email updates being sent :(

# Answer
* First you need to check your email sending capacity of your website.
* Second check that you did the correct configurations for subscriptions module.
* Finall you must run the cron (or set the timer for cron) for sending email updates for subscriptions

If you want to test at the final step, just run cron manually
> 1 votes

---
Tags: notifications
---


title: How to override system.menus.css

text:
# Question
Title: How to override system.menus.css
`system.menus.css` has it's own styles for the menu block. How can I override this style?

Would creating a folder called CSS in my theme and adding a file `system.menus.css` override it?

# Answer
add your css file through your themes's `.info` file

> stylesheets\[all\]\[\] = myStyle.css
> 0 votes

# Answer
You can not override css just by making a file with the same name. If you implement a theme you can for instance use the custom.css or navigation.css (in genesis theme) to override styles from the system.menu.css. If for instance someting has a border of 2px and you want no border you can add to the style `.class { boder:0 none; }`
> 0 votes

---
Tags: theming
---


# Question
Title: Javascript running twice when not logged in
I have this issue that any custom js (added into theme.info file) script file is runned twice. However, I noticed that it will be runned only once if I am logged in. This happens in Drupal 7.

What is the cause?

The js script is a clear only having alert("Entered js file");

Also it is not added twice in the info and also looking into source code not there twice either.

The function is triggered while nothing rendered on page and second time when all DOM elements are loaded.

# Answer
> 2 votes
I finally found out what was causing this issue. It was a module named Drupal for Firebug. So, if anyone finds this, disable this module and you will be fine.

---
Tags: theming
---


title: How to get the values on the other form

text:
# Question
Title: How to get the values on the other form
I would like to save the form field values by using `mymodule_admin()`. How can I get the values saved in `mymodule_admin()` on the other form without using the database?

```
function subscription_admin() {
  $form = array();
  $form['txtSubscription'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter The Subscription Amount'),
        '#default_value' => variable_get('txtSubscription', '500'),
        '#size' => 20,
        '#maxlength' => 20,
        '#description' => t('This text field tells the subscription generation amount'),
        '#required' => TRUE,
  );
return system_settings_form($form);
}

```

This is the admin view form. If the administrator user changes the value, it would be changed.

# Answer
`mymodule_admin()` is not the function that does the trick saving your variables. It's `system_settings_form()`.

You can retrieve variables saved by `system_settings_form()` using variable\_get() function. So, in your case, you can get the value like this:

```
$txtSubscription = variable_get('txtSubscription', '');

```

Second parameter of the `variable_get` function will be returned if the variable is **not set** (not necessarily empty). Notice that we used the same key as your form array's key.

During the Drupal bootrap, *all* variables are loaded to `$GLOBALS` (Thanks to kiamlaluno for the correction). Do not use this to store all your data because all of these variables will be loaded on every bootstrap.
> 1 votes

---
Tags: hooks, forms
---


# Question
Title: Different User Points for different nodes
I am using the User Points module to assign points to users if they post some content and so on. Works great. Now the admin can set some tasks to the users in the form of nodes. To be clear, a node would describe to perform some tasks and then upload a blog about it. IN that node the admin would assign a field CREDITS which tells how many points a user would get for creating a content related to this node. To relate the nodes i am using References module which works fine. So my question is is there any way to do this, i.e, when admin uploads a new node he can provide the user points in a field which would be the user point assigned to the users when they post a content about this node. I hope i am clear. If any doubt please ask i would only be happy to clarify my doubt.

Any suggestions?

# Answer
User points can be assigned based on default points or their particular points defined in content type form page.

If you want to override that points use hook\_userpoints function. In that function points before case will execute before user points is assigned to users.

second parameter in hook\_userpoints, you will get points and entity\_id using that you can change points based on your condition.
> 0 votes

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


title: User Relationships and viewing content

text:
# Question
Title: User Relationships and viewing content
I have installed User Relationships for a project. User A is friends with user B. When user A posts a piece of content, currently it shows up on his front page, as well as user B's front page.

I just want any user to view their friends' content if they are viewing a friend's user profile. I created views for the content as menu tabs for the users. If someone is a friend, they should be able to view the content. Otherwise, it should remain private for the user.

To rephrase my desired functionality, a user's content should only be viewable by the owner, and by any friends, via a user menu tab.

# Answer
> 1 votes
There are two ways to manage access to content with the User Relationships module.

The node access module allows you to open up access to nodes to friends but does not provide any way to remove that access, you'll need another module to do that.

The panels module allows you to show and hide panes based on whether or not a relationship exists.

# Answer
> 1 votes
I have an idea with a little and simple module, tell me if it's what you wanted to do.

---

For this exemple you have to create in your DB a field that i will call vuid (for view uid : your uid + your friends uid).

---

Then use this function :

```
function get_list_art() {

//Place there what I describe after

  $sql = " SELECT {node}.nid,
                  {node}.created,
                  {node_revisions}.title,
                  {node_revisions}.body
           FROM {node}
           INNER JOIN {node_revisions}
            ON {node}.nid = {node_revisions}.nid
           WHERE {node}.uid = ".$vuivalues."
           AND {node_revisions}.body != ''
           ORDER BY {node}.created DESC
          ";

  $result = db_query(db_rewrite_sql($sql));

  $i = 0;
  while($art = db_fetch_array($result)) {
    $arts[$i]['nid'] = $art['nid'];
    $arts[$i]['date'] = format_date($art['created']);
    $arts[$i]['title'] = $art['title'];
    $arts[$i]['content'] = $art['body'];
    $i++;
  }

  return theme('list_art', $arts);
 }

/**
 * Implementation of hook_menu().
 **/
 function list_art_menu() {

  $items = array();

  $items['list_art'] = array(
    'title' => "",
    'page callback' => 'get_list_art',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

/**
 * Implementation of hook_theme().
 **/
function list_art_theme() {
  return array(
    'list_art' => array(
      'template' => 'list_art',
      'arguments' => array('arts' => NULL),
    ),
  );
}

```

---

So now I will explain what is my $vuidvalues in the $sql.

You have first to go search all the vuid that refer to your actual $user and implode this array to an SQL expression ( '1' OR '2' OR for exemple)

---

```
global $user;
$uiduser = $user->uid;

$vuidtabsql = " SELECT {user}.vuid,
           FROM {user}
           WHERE {user}.uid = ".$uiduser.";

  $vuidtab = db_query(db_rewrite_sql($vuidtabsql));

$vuidvalues = "'".implode("' OR '", $vuidtab)."'";

```

---

That was for the .module

Then display the .tpl.php with :

```
<?php
// $Id$
?>
<h1>Your and your friends stream</h1>
<br>
<br>
<?php foreach($arts as $art) : ?>
<div class="node-blog-fond">
  <div class="node-blog-haut">

      <h2><?php print l($art['title'] , 'node/'.$art['nid']); ?></h2>
       <span class="submitted"><?php print $art['date']; ?></span>
      <p><?php print $art['content']; ?></p>
  </div>
  <div class="node-blog-bas"></div>
</div>
<br>
<?php endforeach; ?>

```

---

I just start to learn Drupal and I'm not yet a master of developpement but I hope it's helped.

Give me some feed back !

---
Tags: 7, users
---


# Question
Title: Show a region outside page tpl or check node type to show it
I'm developing a new custom theme and I need to show a region of the theme only in a specific sections of the site.

I tried looking about how to render a region outside the page template, but I didn't found anything.

Now, if it is possible, how can I do that?

If isn't possible, how can I check if a node is generated by a view from the Views module from the page template? So I could show the region from the correct place when I want to.

I hope my question is clear enough.

Thanks in advance, Mat.

# Answer
> 1 votes
You might also consider using the Context module to define different contexts for the different cases. But as mentioned elsewhere, the simplest and commonest solution would be to use blocks:

1. Create a block (or blocks) with the content you wish to show conditionally in it.
2. Assign that block to the region.
3. Configure the visibility setting for the block so it only displays on pages with the view on it. An empty region is not displayed on other pages, so if no blocks are visible neither is the region.

If there's a lot of mixed content to be displayed in that region you might also use Panels to create a mini-panel which is then effectively a single block with one visibility setting but having various different items within it (which may also be context-sensitive).

# Answer
> 0 votes
The simplest way I can think of to do this would be to put the content you want to show only on some pages into blocks. When you configure the block, set it to display only on the section-specific pages you want to see it on. If the content is in nodes, you can use the NodeBlock module to display them in blocks. Or, if it's dynamic content, you could use Views to create a block that displays the content, configuring the View to show the appropriate content inside the block.

Another way to do this would be to create a second, section-specific, page template. If you add the region to your theme's .info file but then include rendering/display for it only in your special-purpose template, it will only appear on the section-specific pages.

---
Tags: 7, theming
---


title: Adding media icon to text editor. How?

text:
# Question
Title: Adding media icon to text editor. How?
I've enabled the Media editor and would like an Add Media icon to be available in my text editor (CKeditor). How would I enable this feature?

# Answer
Do you also have wysiwyg module installed. You can go to admin-config- ckeditor there you can choose for different editor types like full-html which buttons are availible. To upload images i like to use the kcfinder module.
> 0 votes

---
Tags: media
---


# Question
Title: Filtering link associated with view based on permissions
I have a view, print a list of meetings. Using the 'custom text' option I added a link related to the meeting - 'clone meeting'. If the person has a particular permission for the meeting then I would like display the link, but only then.

I don't want to filter the whole record, so can't see a way using hook\_views\_pre\_render(). I could regex the rendered content in hook\_views\_post\_render(), but this seems error prone. How should the conditional link be added?

Drupal 7. Views 7.x-3.5.

# Answer
Resolved by:

1. Installing views php
2. Creating a static class with the permission logic in it.
3. Editing the view to have Global:PHP as a field.

The class is autoloaded via module.info file. files\[\] = 'MyClass.inc'. Static function is just a facade to the module function so that it will be in scope.

```
class MeetingClonePerms {
  public static function accessCloning($nid) {
    // Calls module function here.

```

The php in Global:PHP views field is in 'output code':

```
<?php
if (MeetingClonePerms::accessCloning($row->nid)) {
  print  '<a href="/meetingclone/clone/' . $row->nid . '">clone</a>';
}
?>

```
> 0 votes

---
Tags: views
---


# Question
Title: Redirect loop after installing SecureLogin module
I have only just installed the SecureLogin module and after enabling it, I cannot access any user pages or forms that have been configured to enable HTTPS.

I only ever get 310 redirect loop errors.

**Edit:**
I have managed to fix the issue by commenting out the **$base\_url** configuration I had set up in *settings.php* . Now the site redirects correctly but still shows some unsecured content (styles and scripts from the header mainly).

# Answer
I have managed to fix the issue by commenting out the `$base_url` configuration I had set up in `settings.php`. Now the site redirects correctly but still shows some unsecured content (styles and scripts from the header mainly).
> 1 votes

---
Tags: redirection
---


# Question
Title: Override an url with hook_menu_alter : problem with the file path
In 'mymodule', i try to override a menu url with hook\_menu\_alter, like this :

```
global $base_url;

$items['node/%node/delete'] = array(
  'page arguments' => array('myfunction', 1),
  'file' => $base_url .'/'. drupal_get_path('module', 'mymodule') .'/includes/custom_node_delete_confirm.inc',
);

```

I have an error because the file path is relative and begins with a "/"

```
Failed opening required
'/http://localhost/mysite/sites/all/modules/mymodule/includes/custom_node_delete_confirm.inc'

```

and this doesn't work too:

```
'file' => 'includes/custom_node_delete_confirm.inc'

```

How can i do this ? Thank You

# Answer
> 8 votes
You can set the `file path` explicitly:

> **file path:** The path to the directory containing the file specified in "file". This defaults to the path to the module implementing the hook.

So your code might look like:

```
$items['node/%node/delete']['page arguments'] = array('myfunction', 1);
$items['node/%node/delete']['file'] = 'includes/custom_node_delete_confirm.inc';
$items['node/%node/delete']['file path'] = drupal_get_path('module', 'mymodule');

```

Be careful not to completely overwrite an existing router item unless you absolutely need to, in your example you're removing the required `access callback`/`access arguments`, and also the title; instead only change the values you need to as in the example above.

# Answer
> 0 votes
Try out this

```
'file' => drupal_get_path('module', 'mymodule') . '/includes/custom_node_delete_confirm.inc',

```

---
Tags: 6, routes
---


# Question
Title: Drupal Rules: How do I check if node is updated via edit form or via VBO?
I'm trying to build a reaction rule that fires on the event `After updating existing content`, but with the condition to only run after the node has been manually updated using the node edit form, *not* as part of a Views Bulk Operation action that updates nodes. My issue is I can't find a condition that achieves this.

Does anybody have an idea? Thanks for thinking along :-)

# Answer
This answer is slightly experimental as I have done something similar but not precisely the same. You may need to do further work, but here's the outline which will require a custom module that uses Entity API. What it does is create a custom node property which says where it was updated from:

1. Implement hook\_node\_submit() to check which form the node update has been submitted from and if it's a node\_edit, add a custom member item to the node object, eg `$node->is_node_edit = TRUE;`
2. Implement hook\_entity\_property\_info\_alter() to add a custom property to the node entity type corresponding to the custom member as above.
3. Implement the getter callback you declared in that hook to be something like:

function mymodule\_node\_update\_from\_edit($data, array $options, $name, $type, $info) { $node = $data; return (boolean)@$node-\>is\_node\_edit; }

You can then check the value of the property in a Rules condition.
> 2 votes

---
Tags: rules, views, actions
---


title: Using Varnish with multiple vhosts

text:
# Question
Title: Using Varnish with multiple vhosts
I have varnish configured and "working" on port 80. I have apache running a few instances of Drupal 6 on port 8080. One for dev, review and one for production. I used the four kitchens vcl file as a guide in setting things up. But I'm wondering if I need to do more configuration in the VCL to separate these environments? Perhaps separate backends? I'm not sure when this is necessary.

In addition to this, I am not getting any (or very few) hits, mostly misses which indicates something isn't working correctly.

For reference, my vhosts looks like this...

```
NameVirtualHost *:8080
<VirtualHost *:8080>
        ServerAdmin info@mysite.com
        ServerName www.mysite.com
        ServerAlias mysite.com
        DocumentRoot /var/www/prod/httpdocs
        ErrorLog /var/www/logs/prod_error.log
        CustomLog /var/www/logs/prod_access.log combined

        <directory "/var/www/prod/httpdocs/">
                Options Indexes MultiViews FollowSymLinks
                AllowOverride All
                Order allow,deny
                Allow from all
        </directory>

</VirtualHost>

<VirtualHost *:8080>
        ServerAdmin info@mysite.com
        ServerName test.mysite.com
        DocumentRoot /var/www/test/httpdocs
        ErrorLog /var/www/logs/test_error.log
        CustomLog /var/www/logs/test_access.log combined

        <directory "/var/www/test/httpdocs/">
                Options Indexes MultiViews FollowSymLinks
                AllowOverride All
                Order allow,deny
                Allow from all
        </directory>

</VirtualHost>

```

Feel free to call out anything else you see wrong with how I have configured things in apache.

Additionally, what can I do if I want my dev environment to skip caching all together?

Thanks

# Answer
You may setup different VCL configurations for your environments.

It can be easily done with wrapping them by host condition:

```
sub vcl_recv {
if (req.http.Host ~ "^example.com")
 {
 ...
  if (req.url ~ "^/something") {
   return(pass);
  }
 ...
}
}

```

Please, take a look on my blog post http://blog.tenya.me/blog/2011/12/19/varnish-simple-virtual-hosts/, it describes how to do configuration separation.
> 1 votes

---
Tags: caching
---


# Question
Title: Limit number of upload in Imagefield depending on a specific field
On my website, members can pay for 3 different offers (Gold, Silver, Bronze). I would like to limit the number of pictures a member can upload, depending on the offer he picked.

I'm using Drupal's user\_form and add an "Imagefield" field, with illimited upload. Offers are 3 taxonomy terms, and all contain a field with the max number of images allowed.

I'm able to get the amount of images allowed, from the taxonomy term, but how would i go about applying that limit to the imagefield?

Thanks a lot!

# Answer
> 2 votes
This will need customising to your specific situation, but the basic idea is to add a validation handler to the node form and perform a check in there, e.g.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_form_id') {
    $form['#validate'][] = 'MYMODULE_images_validate_limit';
  }
}

function MYMODULE_images_validate_limit($form, &$form_state) {
  $images_submitted = count($form_state['values']['field_image'][LANGUAGE_NONE]);

  if ($images_submitted > function_to_get_limit()) {
    form_set_error('field_image', t('Too many images'));
  }
}

```

---
Tags: taxonomy-terms, media, files
---


# Question
Title: Building the sidebar content on each node
Im going to build a version content heavy site that will contain over 100 of pages. All pages are created in a "Two column layout" the main column contains the Title and body text of the node. And then theres the sidebar, i like the admin of the site to be able to "build" the sidebar for each node.

I like to provide the admin with two types of elements a "text box" and a "image with text box". The admin should then be able to create any number of each box in the sidebar, and they just get listed under each other. These boxes should be attached to the node, and is not general for all nodes.

Basicly im hoping for a solution where they can setup the node, when they visit the node they could hover over the "sidebar" region and in the dropdown select "add textbox" -\> "add image box" and those teasers get assigned only to the specific node

It should be very intuitive as the admin is not very techinical (for example they wont be able to create views etc) so im hoping for a simple solution, please advice me :)

# Answer
There probably is a better solution, but this is what I thought of.

* Make two new content type of 'sidebar-block-text' and 'sidebar-block-image'. And in those content types add a node (or entity) reference field. (Make sure to use the same field, so create it once, and for the other content type choose it from existing fields!)
* Build a view-block.

+ Let it display the whole rendered node.
    + Add a contextual filter of the current node id and link it to the reference field.
* Place the block in the template sidebar region.

All the administrator will have to do is to add a new piece of content (sidebar-block-text or -image) and reference it to the 'parent node'.
> 0 votes

---
Tags: blocks, nodes
---


# Question
Title: Apache solr search integration at live site
I have a Drupal site configured to use the Apache Solr module for searching. I developed it using a local server on my machine. This works fine once everything is indexed.

I need to make this live, but I have shared hosting, which doesn't support Tomcat.

What can I do in this situation? Does the Apache Solr module support running the webserver and Solr server on different hosts?

# Answer
You can't run a solr instance on a regular hosting service; the most of them give you a database server and Apache Server.

However, you can use a Free or Paid solutions like OpenSolr, for example.
Once you have this configured, you just need to copy and paste the Solr URL into your Drupal Solr configuration.
> 2 votes

---
Tags: 7, search
---


# Question
Title: How to output specific php depending on value of content type radio
In my 'Basic page' content type I've added a yes/no radio field. Currently that is outputting as the value chosen. If yes is chosen I want to output a specific button, if no was chosen I don't want to output anything. How do I go about overriding the basic page template to achieve this?

--EDIT-- I don't want the radio option showing for the site visitor, only for the content editor. I want either the button or nothing showing to the site visitor.

# Answer
> 0 votes
By using @Neograph734's advice I did use conditional fields. Within the content type structure I added a field a link field(the button I wanted to conditionally show). Then used the conditional field to show this link when needed.

---
Tags: theming
---


# Question
Title: Editing canonical links without a module, contained in $head?
I've not been using Drupal for long (\< 3 weeks) but have good knowledge of standard PHP, so I really don't know the 'Drupal' way of doing things yet.

What I'm trying to do is edit the canonical tag for a mobile site. The current path is realtive, however I need it to be absolute, and link to the desktop version of the site.

As far as I can tell the current implementation is not using any module to insert the canonical tag.

By looking at the source code of the rendered page the code appears to be contained in the `$head` variable which is in `html.tpl.php` as below

```
<head profile="<?php print $grddl_profile; ?>">
<?php print $head; ?>
<title><?php print $variables['field_meta_title']; ?></title>

```

I've come across a couple of pages like this one that mention things like template\_process\_html, drupal\_get\_html\_head() and hook\_html\_head\_alter() as relevant functions, but in that example the request is to remove the canonical tags, not to edit them.

I wouldn't mind using a module (providing it would allow me to change the link from `www.mysite.com...` to `m.mysite.com...`) but I would need to remove the current canonical tags which comes back to my orignial issue of not being able to find where it is.

# Answer
You need the Meta Tags module.

After you activate it, go to **/admin/config/search/metatags/config/global** and, under advanced, you can change the default canonical link.

Look at the path patterns used for PathAuto and prefix them with the desired base url.
> 1 votes

---
Tags: uri
---


# Question
Title: how to know this query related to which block
I have a website with a very large number of blocks, some of them have been created using Views module. now i am seeing in slow query log some queries generated by Views like

```
SELECT DISTINCT(node.nid) AS nid,
  node.type AS node_type,
node.vid AS node_vid,
node.title AS node_title,
node.language AS node_language,
node.created AS node_created
FROM node node
LEFT JOIN term_node term_node ON node.vid = term_node.vid AND term_node.tid = 193
LEFT JOIN term_node term_node2 ON node.vid = term_node2.vid AND term_node2.tid = 194
LEFT JOIN term_node term_node3 ON node.vid = term_node3.vid AND term_node3.tid != 194
WHERE (node.type in ('article')) AND (node.status = 1) AND (node.language in ('ar')) AND (term_node.tid IS NULL) AND (term_node2.tid IS NULL) AND (term_node3.tid = 0) GROUP BY nid ORDER BY node_created DESC ;

```

Now, is there any way to know this query related to which block? i couldn't figure it out by checking in preview query of views!!

# Answer
There is some hint on last line. the block in showing Article(node type) which are published to site and created in arabic language.

So, remind that where u seen this kind of content block in the site.
> 1 votes

# Answer
This answer is helpful you are convenient with mysql. Please follow the steps to find which view this query is running

In this query you have mentioned content\_type = article, whatever option we have provided in view it can be stored in views\_display table. So you can use this query which view is related with query.

`SELECT *
FROM`views\_display`WHERE`display\_options`LIKE '%article%'`

Then you will get vid of that view then you can check views\_view table for identify view name.

If you are getting more than a vid, you can find which view is appearing your page where did you get this slow query.
> 1 votes

# Answer
There is a more definitive way. If you suspect a particular block, you can edit the view, and under 'Advanced -\> Query Settings' you can add a comment to the query like 'This query came from blockname.' and the comment will be appended to the sql.
> 1 votes

---
Tags: views, blocks
---


# Question
Title: Query nodes with a specific word in them
I'm very new to Drupal and I need to grab all nodes that have a certain word in them, for example I want to grab all nodes with the Word 'Hello' inside the body field. I need to use the EntityFieldQuery class too. I'm assuming I need to use the fieldCondition method but not sure how to set that up as there's not a lot of documentation...

Thanks Alex

# Answer
I'm not sure I'd agree there's not a lot of documentation out there (there are *tons*, just search Google for *EntityFieldQuery*).

That said, something like:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'some_type')
  ->fieldCondition('body', 'value', '%' . db_like($input_string) . '%', 'LIKE');

$results = $query->execute();

```

is probably what you're looking for
> 1 votes

---
Tags: 7, database
---


# Question
Title: How to use entity_metadata_wrapper in hook_boot
I am trying to create an entity with entity\_metadata\_wrapper from within hook\_boot. I know everyone will say "use hook\_init" but for performance reasons, I'm going w/ hook\_boot :) .

I have a couple modules loaded like so:

```
require_once DRUPAL_ROOT . '/includes/common.inc';
drupal_load('module', 'entity');
drupal_load('module', 'field');

```

This is what I have:

```
$entity = entity_create('myentity', array('type' => 'click'));
$ew = entity_metadata_wrapper('myentity',$entity);
$ew->field_myentity_url_reference->set($row->rid);
$ew->save();

```

The above works fine if run normally (like from form\_alter or something), but not from hook\_boot.

I am getting the following errors:

```
Warning: class_implements(): object or string expected in entity_create() (line 367 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/entity.module).
Warning: in_array() expects parameter 2 to be array, boolean given in entity_create() (line 367 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/entity.module).
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/includes/entity.wrapper.inc).

```

Anyone know what else I need to drupal\_load to get this to work?

## **EDIT - Figure out how to do this:**

I used the background process module: http://drupal.org/project/background\_process. I added the code below to hook\_boot:

```
//load the required modules needed to do background_process
require_once DRUPAL_ROOT . '/includes/common.inc';
require_once DRUPAL_ROOT . '/includes/path.inc';
drupal_load('module', 'background_process');
drupal_load('module', 'progress');

background_process_start('shurly_create_click_log', $row);//  drupal_load('module', 'entity');

```

Then I put the entity code in a new function:

```
function shurly_create_click_log ($row){
    $entity = entity_create('linkpin', array('type' => 'click'));
    $ew = entity_metadata_wrapper('linkpin',$entity);
    $ew->field_linkpin_url_reference->set($row->rid);
    $ew->save();
}

```

Basically, the shurly\_create\_click\_log function gets ran at full bootstrap in the background, so it doesn't slow down my pageload/redirect from hook\_boot.

# Answer
> -3 votes
Here's a solution.

Add this to the top of your hook\_boot() function:

```
function hook_boot() {
  global $user, $base_path;
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
...
}

```

drupal\_bootstrap keeps track of what level it has been called so this trick effectively pushes hook\_boot to being later in the boot process.

---
Tags: entities, hooks
---


title: Multi language Poll output

text:
# Question
Title: Multi language Poll output
I am developing a multilingual site, where the front page outputs the poll block with the following code.

```
    $block = module_invoke('poll', 'block_view');
    print render($block['content']);

```

The output does not change when the language changes. How do I translate that output with the i18n module?

# Answer
You need to do the following steps in order to achieve what you need:

1. Download `Poll aggregate` patch file from here
2. Apply the patch file the way you want. Good Drupal reference here.
3. Goto Modules list page `admin/modules` and install/enable the following modules:
    * **Multilingual content module**
    * **Multilingual select module**
    * **Field Translation**
    * **Synchronize translations module**
    * **Poll aggregate**
4. Then goto Poll content type settings page `admin/structure/types/manage/poll` and enable Multilingual support by choosing **Enabled, with translation**
5. Create a new poll content with its options and select default language from the **Language** dropdown list and save the node.
6. Create translation Poll content for the same node by clicking on translate tab.
7. Replace default language content with the second language.

I hope this will solve your issue.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Pathauto not updating path portion of new path
When using the following replacement pattern for all nodes (to get 'hackable' urls that respect the menu hierarchy):

```
[node:menu-link:parents:join-path]/[node:title]

```

I then create a node with title 'Subnode' which is a child of the node 'Parent node'. This will give me a node with the alias /parent-node/subnode. Now when I move the node one level up and change its (menu)title, so that Subnode is now a 'toplevel' node. The \[node:title\] part gets changed but the \[node:menu-link:parents:join-path\] not.

The 'Generate automatic URL alias' checkbox is checked.

Now when choose 'Update URL Alias' from the dropdown list in the content pane (/admin/content) the url does get updated properly.

Why doesn't it get updated right away?

# Answer
I'm running into the same problem, I tried to trace the code and it looks like that token replacement is never called. Not sure if its a bug in token or pathauto module.
> 0 votes

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