# Question
Title: Performance: Efficient use of EntityFieldQuery (with node_load OR node_load_multiple) to update thousands of nodes with/without conditions
I have script that queries a system called Symplectic for publications of over 30 users (each authored over 300 publications). Most of the publications are authored jointly by more than one user. I have done the following using a combination of Entity API and other methods:

1. Programmatically creating publication nodes (with fields i.e. integer, text, lists, taxonomy terms, entity reference, etc).

I would like to avoid the following scenario:

1. Creating duplicate nodes of type publication

Every time I create a publication, I would like to check whether the publication already exist or not (most probably yes because, the users have authored so many publications together). I can achieve this when I am creating all publications at the same time :

1. I will lookup a structure the stores publication specific properties (i.e. Symplectic object id, doi, publication source id, last-modified-timestamp where source being pubmed, scopus, etc.). If not exist then create publications and update the structure, else reference the user to the already existing publication.

The actual use I am **Concerned** about is, **Updating** thousands of publications at a later date after they are created. I have the following options, which one do you think is most efficient:

1. Use EntityFieldQuery to query for all nodes of type publications (over 2500 nodes) at once, and store the properties useful for comparison in a structure. Use the structure to decide whether publication exist in Drupal, if no then create it, if yes then check for last-modified-date.
2. Use EntityFieldQuery with condition fields to check if a publication already exist in the Drupal system, if yes then check if update is avaiable, if no then create it. This method would require, N number of quries (2500 publication nodes would result in 2500 calls).
3. During initial create operation (when no publication node exists), create a structure and store the few publication fields that are expected to be unique (not timestamp) across all publications (i.e. symplectic object id, doi, publication source id, last-modified-timestamp), serialize the structure and store it in the file system. During update phase, load the structure from file system, unserialize it and use it to check whether a publication node already exist in the drupal system, if no then create it and update this structure, if yes then check whether update is required.

My worries in regards to above available options:

1. Loading over 3000 publication nodes (of course, EntityFieldQuery would retrun all nids, then I will have to use either node\_load\_multiple or node\_load) - Is this efficient? Would I not face memory problems?
2. 2500+ EntityFieldQuery does not seem to be the right choice due to query time. (Attaching conditions might increase the query time i.e. if symplectic id field of publication equals X)
3. This is my idea, I don't know if it makes sense.

I have Drupal 7 on CentOS 6.5, and a publication content type has the following number of fields: boolean - 2 text - 20 Double field - 3 Taxonomy - 1 List 2, title, body, etc.

What do you recommend based on your experience? I did have a look at Biblio module, it is not the way to go forward for our requirements. I also know that $conditions parameter of node\_load\_multiple is deprecated in D7.

Sorry for long description, I tried to be as descriptive as possible.

# Answer
If you can access the data via SQL then I think the Migrate module can do 80%+ of what you want with relative ease. Your hardest part may be either: 1) getting an SQL dump of the data you want from the remote system, or 2) build an SQL representation of the data from the data you can retrieve from the webservice using a Cron type task.

Assuming you can get an SQL version of your (by the way Migrate and what I'm talking about works on XML, JSON, CSV, text files ... and the framework supports "lists" of data from other sources -- but you'd have to develop some of your own `Classes` for exotic import sources ... I digress) ... migrate supports querying your objects like "I want to move item(s) from point A to B ... and either update or create them." as of Migrate 2.5+. Most people are comfortable with SQL or CSV files so I'll talk about that here. Being Object Oriented you're free to adjust Migrates behavior of course by extending a classes default behavior.

Once you have the SQL data you can use a Migration to import the data. By using Migrate 2.6's (stable release) `track_changes` option within a Migration class. The Migrate module will take the `fields` your migrating from point A to point B of your data and create a *hash value* of all the data. This hash value is used in subsequent calls to Migrate data to deem whether the given item should be `created` or `updated` from the data being fed into the Migration.

An example of this can be seen in this great little blog post: http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7

The key excerpt enabling `track_changes` from the blog post is:

```
class ExampleNodeMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
   $options = array('track_changes' => 1);
   $this->source = new MigrateSourceSQL($this->query(), $this->fields(), NULL, $options);
}

```

I say SQL would be easiest for this approach because you could easily build a query for your migration that is basically `SELECT id, doi, publication source id, last-modified-timestamp where source being pubmed, scopus, etc FROM my_remote_data` and put `$options = array('track_changes' => 1);` and Migrate is basically doing all the work for you -- and should be very little PHP code to consume the data.

I've actually done this process most recently with the Migrate modules default support for CSV files with a Migration that results in *6 different Drupal content types built out from the CSV in dependant-order* -- and objects are created/updated on-the-fly using track\_changes every time the system does an *sync* from the remote system ... so it's doable via SQL or CSV easiest I think.

> random tidbit: my CSV file is like 40 columns of data and each sub-migration only cares about a limited set of columns in the csv file. So I tell each migration to ignore unwanted fields for that migration by using PHP's `unset` function in the `prepare` for the Entity being built. By unsetting the values the `hash` function only hashes the relevant data I care about for that single drupal object I'm creating with that migration.

Anyways... I hope this rant helps and offers you a path do this. I've used Migrate on and off for single table or larger migrations of data since the Migrate 1.x days ... it can be complicated to learn if you've never used it.
> 0 votes

---
Tags: nodes, entities, database
---


# Question
Title: How to print username into url after user logs in?
Currently, I am developing a site where I need to add the username to the URL after users log in. I am using the Login destinations module. Usually, users aren't redirected, but they stay on the page they were before logging in, with few exceptions. This unfortunately has to stay, so I cannot redirect them to users/username.

I need to add the username to the URL after users log in. For example, not logged-in users will be at content/main-article; logged-in users will be at content/main-article?username.

I tried that with the Menu tokens module, but the tokens aren't replaced. A relative URL like node/1 becomes node/1/%5Buser%3Aname%5D.

If you ask why, it is for Piwik to easily recognize logged-in users.

# Answer
I am not sure how and where you append the username, but I assume that you try something like this:

```
$url = $current_url . '?user=name';

```

Instead you should try something like this:

```
$url = url($current_url, array('query' => array('user' => 'name')));

```

This will produce this URL: current\_url?user=name

Another thing: You have %5B and 3%A in your URL. I am not sure, but you want to have your URL look like this: url\[user:name\]. Queries in URLs should rather look like I did that and how Drupal's query options creates them: url?user=name

If that does not solve it, you could post some code ;)

Cheers, j
> 0 votes

# Answer
eventually i managed to do that with the menu tokens, by using current user mail with syntax like this node/1?\[current-user:mail\] and by setting method for users to random user it works like a charm and email is better for recognizing user anyway ... Thanks guys for help.
> 0 votes

---
Tags: routes, users, tokens
---


# Question
Title: Getting image SRC with xpath - Simpletest (WebTestBase)
I am developing a Drupal 8 test which will check for a image's existence. The image will not be loaded while running the test and I want to catch that using xpath().

The HTML I am trying to search is,

```
<ul aria-labelledby="ckeditor-toolbar-group-aria-label-for-media" data-drupal-ckeditor-button-sorting="target" role="toolbar" class="ckeditor-buttons ckeditor-toolbar-group-buttons ui-sortable">
  <li class="ckeditor-button" data-drupal-ckeditor-button-name="Blockquote">
  <a aria-label="blockquote" title="blockquote" role="button" class="cke-icon-only cke_ltr" href="#"><span class="cke_button_icon cke_button__blockquote_icon">blockquote</span></a></li>
  <li class="ckeditor-button" data-drupal-ckeditor-button-name="DrupalImage">
    <a aria-label="Image" title="Image" role="button" href="#">
      <span class="cke_button_icon">
        <img title="Image" alt="" src="http://local/">
      </span>
    </a>
  </li>
</ul>

```

In this HTML you can see that I need to find the SRC in the tag. The SRC is invalid and it should be `http://local/test.png`. I am searching the HTML with `$this->xpath('//span[@class="cke_button_icon"]/img[@src]');` but getting a blank array in return. How can I fetch this element?

# Answer
Perhaps you could try the following XPath: `//span[@class="cke_button_icon"]/img/@src`.
> 1 votes

# Answer
I'm not sure if you can directly get the property, I don't think so. What you want to do is get the img element and then the src property from it.

Something like this, untested:

```
$img = $this->xpath('//span[@class="cke_button_icon"]/img');
$src = $img[0]['src'];

```
> 1 votes

---
Tags: 8, testing, feeds
---


title: Drupal calendar issues

text:
# Question
Title: Drupal calendar issues
I am having an issue with completing my event calendar. Everything is in place but the header is all jacked up. For every month, it gives the header as August 1, 2014, September 1, 2014. It is VERY frustrating. I went through everything (the calendar View) and some of the PHP but cannot find anywhere the issue!

Does anyone know how to fix this? I tried looking online and I cannot seem to find the solution anywhere! I even went into the settings for time/date and could not find a single thing.

I want to say that the current date is August 22. I could see if it was August 1 for it to display like that but it is not! I would like it to say AUGUST 2014 or just simply August! Not the WHOLE date typed out.

weekly view:

looks fine!

So if anyone out there can please help me fix this issue, I would so much appreciate it! I have been playing around for hours and to no avail! It must be something simple, right?

Thank you!

# Answer
Here's the fix, the reference to it is here : click on this link and scroll down to item #20 : drupal.org/node/2294973 , however its pasted below just in case that link becomes broken...

Quick workaround for people unable to apply the patch:

STEP 1: Edit date\_views/theme/theme.inc and go find line 165.

Change these two lines:

```
$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

```

To these two lines:

```
$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

```

Note: the only difference is one underscore character added to each line.

Upload the changed file back to your web server.

STEP 2: Go to (YOUR\_WEBSITE)/admin/config/regional/date-time/date-views and click Save. If you get permissions errors, try clearing caches.
> 0 votes

---
Tags: 7, views, datetime
---


title: MySQL date format functions in Drupal

text:
# Question
Title: MySQL date format functions in Drupal
How can I do a MySQL date function in Drupal? I have this now:

```
$select = db_select('someTable', 'st');
$select->addExpression('DATE_FORMAT(FROM_UNIXTIME(created), "%Y-%m")', 'createdMonth');

$date = $select->execute()->fetchAll();

```

When I run this I get an exception that says:

```
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '%Y-%m' in 'field list'"

```

But if I print the $select object I see it should run

```
SELECT DATE_FORMAT(FROM_UNIXTIME(created), "%Y-%m") AS createdMonth FROM {someTable} st

```

And when I copy this to Sequel Pro it just runs.

What am I missing?

# Answer
You're a 'victim' of MySQL's `ANSI_QUOTES` SQL mode:

> Treat “"” as an identifier quote character (like the “\`” quote character) and not as a string quote character. You can still use “\`” to quote identifiers with this mode enabled. **With ANSI\_QUOTES enabled, you cannot use double quotation marks to quote literal strings, because it is interpreted as an identifier.**

Emphasis mine.

That explains why MySQL is trying to find a column called `'%y-%m'` rather than interpreting it as a string.

So you need to switch your SQL mode to something else, or (more reasonably), just use single quotes for literals:

```
$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(created), '%Y-%m')", 'createdMonth');

```

Many other DBMSs don't accept double quotes for string literals, so using single quotes is a good habit to get into anyway.
> 7 votes

---
Tags: database
---


# Question
Title: File upload functionality on node display page
I want to provide an upload button on a node display page. By clicking a button, it should be possible to upload files. Here is what I'm thinking of:

For this I am changing the `node.tpl` file.

```
 <?php //code added
     if($node->title=='Course Materials'){?>
        <form action="" name="uploadform" >
            <input type="submit" value="upload" name="upload"/>
        </form>
    <?php  }
    if(isset($_REQUEST['upload'])){ ?>
    <form  method="post" action="" enctype="multipart/form-data">
        <input type="file" name="file"  />
        <input type="submit" name="submit"  />
    </form>
     <?php //end
     }?>

```

And to save the files:

```
  if(isset($_REQUEST['submit'])){
    if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){

   //$file = $_FILES['file']['tmp_name'];
   move_uploaded_file($_FILES["file"]["tmp_name"], "C:/xampp/htdocs/drupal6upload/sites/default/files/".$_FILES["file"]["name"]);
    $node = node_load($node->nid);

        // Build the file object
        $file_obj = new stdClass();
        $file_obj->filename = $_FILES['file']['name'];
        **$file_obj->filepath = "C:/xampp/htdocs/drupal6upload/sites/default/files/".$_FILES["file"]["name"];**
        $file_obj->filesize = $_FILES['file']['size'];
        $file_obj->uid = 1;
        $file_obj->status = FILE_STATUS_TEMPORARY;
        $file_obj->timestamp = time();
        $file_obj->list = 1;
        $file_obj->new = true;

        // Save file to files table
        drupal_write_record('files', $file_obj);

        // change file status to permanent
        file_set_status($file_obj,1);

        $node->field_test1[] = (array)$file_obj;
        node_save($node);

        drupal_goto('node/'.$node->nid);
    }
}

```

But I am facing some problem to set the filepath and file\_copy instead of move\_uploaded\_file.

Any suggestions?

# Answer
> 1 votes
I am able to do it by creating custom module.

```
    function upload_course_form($form_id) {
    $form = array();
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['course_materials'] = array(
            '#type' => 'file',
            '#title' => t('Course Materials:'),
            '#size' => 60,
            );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#weight' => 10
    );
    return $form;
}

  function upload_course_form_validate($form, &$form_state){
  $field = 'course_materials';
  $directory = file_directory_path();
  if (file_check_directory($directory, FILE_CREATE_DIRECTORY, $field)) {
    $validators = array('file_validate_extensions' => array('pdf xls html doc txt docx'));
    if ($file = file_save_upload($field, $validators, $directory)) {
      file_set_status($file, FILE_STATUS_PERMANENT);
      $form_state['storage']['file'] = $file;

    }
  }
}

function upload_course_form_submit(&$form, &$form_state){
print_r($form_state['storage']['file']); //see the upload file details
//and add the code to save the node.

}

```

---
Tags: 6, theming, files
---


# Question
Title: db_update query in custom installation profile gets ignored
I am currenty working on a custom installation profile that enables modules, performs some db queries and so forth.

It also sets my default theme and admin\_theme...

Nothing too special ;-)

I have 2 db\_update queries as well, located in my .install file.

The first one works perfectly

```
// Enable the admin theme.
db_update('system')
->fields(array('status' => 1))
->condition('type', 'theme')
->condition('name', 'rubik')
->execute();

```

The second one gets 'ignored'

```
// Locate menus is right regions
db_update('block')
->fields(array('status' => 1, 'region' => 'sidebar_first'))
->condition('delta','menu-left-menu')
->condition('theme', 'mytheme')
->execute();

```

I have tried the last query with devel/php and then everything works perfectly.

What am i missing?

When i put the query in a .module file it works as well...

Thanks for any advice!

# Answer
> 0 votes
I fixed this issue by:

Changing my db\_update() query to a db\_insert query and move it in an install task in the .profile file.

This way i am sure that the query is ran at the latest possible moment.

Thanks all for your help

# Answer
> 0 votes
db\_update it is a selectable object. It builds SQL queries. https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_update/7

Yes. Everything is in database. You can changes by queries. You should use api functions or common approaches.

Theme data is stored as variables, for Drupal it is enough.

```
variable_set('theme', 'my_theme');
variable_set('admin_theme', 'theme_name');

```

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable\_set/7 It says that if you want change it by queries you need update the variable table.

Also when you manipulate with cache-able objects(blocks here) you need clean cache.

```
cache_clear_all();

```

---
Tags: installation-profiles
---


# Question
Title: Creating a Field in order to add Icons to content's Title
we want to add Icons before the Content's title just like the picture below (icon before *Glory of the Hero*):

but the problem about the stuff already existing in prior asked questions is that we're gonna work with that a lot in our site , so if we're gonna code it for EACH title, it wouldn't be useful for us \>\>\>\>\> **so we wan to add a field in our content types for example called *title's image* , and so each time we upload a file there, we'll have an icon before that content's title.**

I've already read:

and they didn't help at all... is there any way to do that?

# Answer
You can do this by creating node.tpl file.

```
    <?php print render($title_prefix); ?>
      <?php if (!$page): ?>
     //"print image here"
 <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
      <?php endif; ?>
      <?php print render($title_suffix); ?>

```

You can get all the field value here and just print the image before the title.
> 1 votes

# Answer
I think I have a solution for you, a bit tricky though. Do the following

1. Install/enable "devel" module
2. Override page.tpl.php to page--node--%.tpl.php (or you could use the page.tpl.php)
3. Find the title element in the page.tpl.php , looks like following

4. Make sure that you have a field called icon (note the machine name i.e. field\_icon) in your content type
5. Create a sample of your content type
6. Click on "Devel" tab and try to find the field\_icon or whatever you named the field, as shown in the following screenshots

and clicking on the field\_icon, you will see a structure similiar to this

Just before the h1 tag, in the screenshot of page.tpl.php shown in #3 add a code that looks like the following:

```
<img src="<?php
        $var = $page['content']['system_main']['nodes'];
        $element;
        foreach($var as $k => $v) {
        $element = $v ;
        #obtain the node id, usually first.
        break;
        }
        #$exist = $element[$element['field_icon']['#object']->field_icon['und'][0]['uri'];
        if(isset($element['field_icon'])) {
        print $element['field_icon']['#object']->field_icon['und'][0]['uri'];
        } else {
        #does not exist
        }
    ?> " />

```

The code above creates an image tag, and its src value would be the value of the URI of the icon. Use Devel (or kpr($page\['content'\]\['system\_main'\]\['nodes'\]); inside page.tpl.php) tab to figure out what to replace with $page\['content'\]\['system\_main'\]\['nodes'\], probably it might remain the same for you as well.

Once you got the content of the $page\['content'\]\['system\_main'\]\['nodes'\] or similar then loop through it to find the node-id (which can be anything). The reason I have a break in loop is because, I am interested in first element which is node-id, see below

And finally access the URI as shown in the following Devel Screenshot

Nothing will be printed in pages where there is no field\_icon (i.e. icon machine name), and the icon should be printed in pages that have that field in its $page variable. Good luck.

Here is the result:
> 0 votes

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


# Question
Title: How to set up no result behavior of View field that uses "Views field view"?
Im using "Views field view" module to display a secondary view inside a main view. The secondary view has a contextual filter. The problem is that when Im trying to set up no result condition it doesnt show up. I have tried this cases:

* Secondary view no result: nothing

Main view no result (In settings of the field with sec. view): text

Output: nothing
* Secondary view no result: 0

Main view no result (read "0" as no result option enabled): text

Output: nothing
* Secondary view no result: text

Main view no result: nothing

Output: text

In the last case views display the text but if it is an html with arguments from the main view the tokens wont be converted. If no result case is set to display 0 it will display nothing.

```
Views           7.x-3.0-rc3
Views Field View    7.x-1.x-dev
Drupal          7.9

```

# Answer
> 1 votes
*How does Views know that **The View Created By The Views Field View Module** is not returning a result - on a row-by-row basis?* I will hypothesize that Views is probably able to suppress the output of a field because very early on the process of creating/rendering the View, when the Views query is done, that field comes empty-handed from the database, and somewhere, internally, Views says: NO SHOW.

In my experience, I have never heard of a Views hook that allows a third-party module to short-wire this process and for example, arbitrarily command Views to render a field as it were populated, even if it is not, because a third-party module used that field as a contextual argument, created a view (or got data from somewhere else), and inserted that data into that otherwise empty field. This is what are you trying to do, and simply put, *I am not sure if it is possible at all*, at least in the way that you are trying to do it.

It would be possible however, for you to:

1. Create a primary view.
2. Create a custom preprocessor or template for that field. You would look for the proper name of the template by clicking your View's theme information link. A few caveats: For a preprocessor to be called, a matching template must exist first; Views won't recognize the preprossor (won't call it) if you declare it in a custom module, you will need to put it in your template.php; It isn't really necessary for you to create a preprocessor, however if you want to keep your templates clean (and any *Drupalista* worth his salt should want to) a preprocessor implementation is in order.
3. In your preprocessor, if that field is not empty, pass the results of that field to your secondary View's filter. This will require you to instantiate that View programatically.
4. If your secondary View returns any results, append those results to the current field.

So in essence, I think that what you want to do is 100% possible. I think your requirement will be possible (with Views) depending on A) How comfortable you are hacking with Drupal and it's theming layer, B) The performance requirements of your application.

**If you are trying to do this for a high-performance site with a large number of visitors, I would be *very wary* of the solution that I am proposing, *even with full Views caching turned on***. So for performance and simplicity's sake, you can make your own database queries the ol' fashioned way. IMHO, your web server's CPU and whoever interacts with your site, clients and coders included, will appreciate it. Otherwise, if you still decide to go with my solution, here's a **PROTIP**:

1. Go to the Views advanced settings options.
2. Select show query.
3. Go back to your primary and secondary Views and test them. The query that is used to construct your Views will be revealed to you.
4. Copypasta this into your custom module for usage with db\_query().
5. ...
6. Profit!

# Answer
> 0 votes
Your problem is that your secondary view, even if not having any result *row*, will return an empty enclosing tag for the view itself. This is different from the way normal fields work (and you may consider filing an issue report). In effect, the secondary view output is different from both the empty string and `0`, meaning that it cannot trigger the "No results behavior" of your primary view as you want to.

As a solution, you can create a tiny module that will post-process the output in this case, to make it indeed empty. You have to implement hook\_views\_post\_render(), like this:

```
function mymodule_views_post_render(&$view, &$output, &$cache) {

  if ($view->name == 'your_views_name' && count($view->result) == 0) {
    $output = '';
  }
}

```

In addition, you may need to implement `hook_views_api()` to declare using the Views API, not sure about it. For other ways to check in code if the view result is empty, see Drupal issue #446798.

---
Tags: 7, views
---


# Question
Title: How do I add classes to read-more link and add-comment link on node for bootstrap 3
Witch preprocess function let me add btn classes from bootstrap 3 to the two links at the bottom of every teaser in Drupal 7?

I tried the following.

```
function meetu_preprocess_node(&$variables) {
   $variables['content'] ['links']['node']['#links']['node-readmore']['attributes']['class']
 [] = 'btn btn-primary'.
   $variables['content'] ['links']['node']['#links']['comment-add']['attributes']['class'][]
  = 'btn btn-primary';
  }

```

The result is that my "add comment" link is gone and the "read more" link has its new classes.

What's wrong here?

Is this the right way to add bootstraps btn calsses to the two links named above?

# Answer
> 1 votes
You were very close except at the end of your first line you had a "." instead of a ";".

```
function meetu_preprocess_node(&$variables) {
  $variables['content']['links']['node']['#links']['node-readmore']['attributes']['class'][] = 'btn btn-primary';
  $variables['content']['links']['node']['#links']['comment-add']['attributes']['class'][] = 'btn btn-primary';
}

```

---
Tags: theming, nodes, navigation
---


# Question
Title: how can i access a node variable inside of theme_preprocess_page function?
I'm trying to access a node variable, the id of a taxonomy term but i have to do it at the page level in theme\_prepocess\_page function. i did it in preprocess node like this

```
$libStatus = $vars['field_feature_library_status']['und'][0]['tid'];

```

in preprocess\_page i tried this:

```
$libStatus = $vars['node']['field_feature_library_status']['und'][0]['tid'];

```

but i get this error... *Cannot use object of type stdClass as array in….*

can someone explain how i can access this node variable in theme\_preprocess\_page function?

# Answer
> 0 votes
Have you tried field\_view\_values() and field\_get\_items()

```
function mytheme_preprocess_page(&$variables) {
    if (!empty($variables['node'])) {
      $output = '';
      $node = $variables['node'];
      $items = field_get_items('node', $node, 'field name');
      foreach ($items as $item) {
        $field_output = field_view_value('node', $node, 'field name', $item);
        $output .= render($field_output);
      }
      // Set $variables with the value you need.
    }
  }

```

Explained in here how to access node variables in region preprocess function?

I think you should also be able to use entity\_metadata\_wrapper as follow

```
$node = $variables['node'];
$wrapper = entity_metadata_wrapper('node',$node);
$libStatus = $wrapper->field_feature_library_status->value();

```

# Answer
> 0 votes
As reported in node.tpl.php, the field field\_feature\_library\_status is available as raw value as `$field_feature_library_status`, in the preprocess/process functions.

> Field variables: for each field instance attached to the node a corresponding variable is defined; for example, `$node->body` becomes `$body`. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, `$node->body['en']`, thus overriding any language negotiation rule that was previously applied.

---
Tags: theming
---


# Question
Title: drush_get_commands() does not return Feature Drush commands
I am expecting that drush\_get\_commands() will return all drush commands including from modules such as 'feature', but it is not when called within my Drush custom command. How to retrieve all drush commands available for the current drupal instance including ones provided from custom modules? Thank You

# Answer
It is important to remember that `drush_get_commands()` is sensitive to the bootstrap level that your command has reached. You must have bootstrapped a Drupal site before Drush commands associated with modules in that site are available via `drush_get_commands()`. There are several requirements for this to be true.

1. You must have selected a Drupal site when you ran your custom Drush command, either by using a site alias (e.g. drush @mysite), or via commandline options (e.g. drush --root=/path/to/drupal --uri=mysite.org), or by setting your current working directory to the same directory that contains the settings.php file for your site.
2. Your custom command must declare a bootstrap level that is high enough to bootstrap a Drupal site. For example, `DRUSH_BOOTSTRAP_DRUSH` is not sufficient, but `DRUSH_BOOTSTRAP_FULL` is. If your command has not bootstrapped to a high enough level, you may call `drush_bootstrap_max()` to finish bootstrapping the selected site.
3. Drush commands will only be loaded for enabled modules.

If you do all of these things, then you should see all commands for all modules when you call `drush_get_commands()`. If you don't, try `drush cc drush` to clear the commandfile cache.

(As a side note, do not use `drush_get_commands()` as a way to call other Drush commands from your custom commandfile. Instead, use `drush_invoke_process()`.)
> 3 votes

---
Tags: drush
---


# Question
Title: Possible to access source database in prepareRow() in Migrate module?
I'm doing a D2D migration that requires a mapping table to map tids from the source site to the destination site. In prepareRow(), I need to check the tid for a certain vocabulary and get the corresponding tid for the destination site. For a couple reasons, this mapping table is kept in the source site. However, the problem is that the default db connection that is being used in prepareRow() is the destination db, not the source db any more, so running my query throws an error. How can I switch the connection to use the source db so I can access this table and cache it? The short term method would be to copy this table to the destination site, but this will be an ongoing migration, and I don't want to have to update the table manually in the destination site every time the table is updated.

Thanks.

# Answer
What I ended up doing was to use method #1 as detailed by tenken above, with one addition.. I defined a separate connection in settings.php, and queried it directly in prepareRow(). However, I added caching to it (see here for instructions), so that the query isn't being run every time prepareRow() is run.

```
$target_channels = &drupal_static(__FUNCTION__);
if (!isset($target_channels)) {
  if ($cache = cache_get('nb_migrate_target_channels')) {
    $target_channels = $cache->data;
  }
  // Not cached, so we need to generate it this time through.
  else {
    $map_query = Database::getConnection('default', 'mrctv')
      ->select('my_table', 'mt')
      ->fields('mt', array('source_channel', 'target_channel'))
      ->condition('mt.target_site', 'my_target_site');
    $map_result = $map_query->execute();
    foreach ($map_result as $map_record) {
      $target_channels[$map_record->source_channel] = $map_record->target_channel;
    }
    // Cache the array.
    cache_set('nb_migrate_target_channels', $target_channels, 'cache');
  }
}

```
> 1 votes

# Answer
2 simple approaches:

You call the other DB explicitly like you do any other place to talk to it from drupal.

```
// Method #1
$query = Database::getConnection('default', 'for_migration')->select('source_table', 'st');
// $query = ....

// Method #2
db_set_active('my_other_db');
// ... code here ...
db_set_active();  // switch back to normal DB connection in-use. This is important.

```

Method 1 is outlined here: https://www.drupal.org/node/1014558 Method 2 is outlined here: https://www.drupal.org/node/18429

Your other option is to not do it in every `prepareRow()` explicitly. Think outside the box :P. Why re-query this information within every `prepareRow()` -- that just slows down your migration. You can define this custom `$tid_map` lookup array in your Migration class's constructor as a data member to the migration class itself. You only query it's value a single time (on migration startup). `prepareRow` then just checks the stored array whenever needed. You may or may not have to use a `static` variable to assure the value is saved and preserved throughout the Migration lifetime ... I'm not sure.
> 2 votes

---
Tags: database, migrations
---


# Question
Title: Node edit form with entity reference - show more than just the title in the autocomplete box
I have three content types: application, organization, and organization\_note. Application has an entity reference to organization and organization has an entity reference to organization note.

The application edit page has an autocomplete field for organization. When a user selects an organization which has a note, I would like the display to be different somehow, ideally a reminder to check the organization's notes.

This question is very similar to this one (unanswered).

I'm at a loss here, and I don't really even know if this is possible. How would I go about doing this? (This is Drupal 7, by the way.)

# Answer
> 2 votes
You can do this by creating an entity reference view.

Firstly, create a new view that displays the content type 'organization'. Do not add a page, but rather add an 'Entity Reference' display.

Your view should now have a format of 'Entity Reference list'. Now add a relationship to organization\_note, and then add the fields that you would like to see in the autocomplete list. When that is done click on settings in 'format', and select the field that you want to search on when typing in the autocomplete. This normally would be title. You can also rewrite the field values to your liking as you would probably need to for your use case, though I would leave title standard.

Now go back to the field settings for 'application', and edit the settings for the entity reference field to organization. In the 'Mode' for the 'Entity Selection' section, select 'Views: Filter by an entity reference view'. This will open a new select from which you select the view you created above.

---
Tags: entities, ajax, nodes
---


# Question
Title: Where to add track_changes option in migrate_d2d class
I have an ongoing migrate\_d2d migration where I will need to be able to detect changes on a node by node basis, and I would really like to be able to use the functionality in the Hash source rows to detect changes feature to do that. However, I can't find where to add that option so that the hashes are generated. I've tried this is my class (that overrides DrupalNode6Migration):

```
$this->sourceOptions['track_changes'] = TRUE;

```

but the option isn't added and used. According to this referenced post on this feature, I should add it in my source constructor, but that part is handled by migrate\_d2d in the abstract DrupalMigration class. Do I need to go down to that level to create my class just to access this property, or is there a way I can add it from my class that overrides Drupal6NodeMigration?

# Answer
> 0 votes
It seems you want to synchronize sites. http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7 If you follow on this example you have mentioned above, Filter nodes by the update time these are changed after you deployed at last. You use MigrateSourceSQL. So you able modify a query.

If you want to synchronize sites, use the module: services or feeds.

---
Tags: migrations
---


# Question
Title: How to make different users profile pages for different user types in Open Atrium2?
I have 3 different user types and I want to provide a specific profile edit page for each. The user type is set when registering for an account. I have the profile fields associated to each user type created in config/people/accounts, but I'm lost on how to create the separate pages for each user type and then to trigger the loading of the correct page based on the users type.

# Answer
> 0 votes
I have not find a such module in the OpenAtrium bundle. You can use the contribute module https://www.drupal.org/project/profile2 Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)

---
Tags: distributions
---


title: hook_views_data : join table node twice

text:
# Question
Title: hook_views_data : join table node twice
I try to configure a custom table in hook\_views\_data. I need to join the same table (node) twice. The problem is that i can't have the same key for 2 entries in my array :

```
$data['maz_composition']['table']['join'] = array(
    // Index this array by the table name to which this table refers.
    // 'left_field' is the primary key in the referenced table.
    // 'field' is the foreign key in this table.
    'node' => array(
        'left_field' => 'nid',
        'field' => 'aid',
    ),
);

```

Is there a solution for that ? Thanx and sorry for my bad english.

# Answer
> 1 votes
I know it is a bit late. But I had the same problem and ran into this page. So here is how I solved it. It is with my own case, but solution is generic, I hope it will help someone.

I join wootoon\_cached\_sets twice, **the key in $data\['whatever'\] is only the alias** in the query. **The actual table is given by the table property**. This is confusing because if ignored, this property defaults to the table key.

I end up With the following query:

```
LEFT JOIN {wowtoon_cached_sets} wowtoon_cached_sets_main
ON   wowtoon_owners.toon_key = wowtoon_cached_sets_main.toon_key
AND  wowtoon_cached_sets_main.active = '1'
LEFT JOIN {wowtoon_cached_sets} wowtoon_cached_sets_second
ON   wowtoon_owners.toon_key = wowtoon_cached_sets_second.toon_key
AND  wowtoon_cached_sets_second.active = '0'

```

Using the below code:

```
  $data['wowtoon_cached_sets_main']['table']['group']  = $data['avatar']['table']['group'];
  $data['wowtoon_cached_sets_main']['table']['join'] = array(
      'avatar' => array(
        'left_table' => 'wowtoon_owners',
        'left_field' => 'toon_key',
        'field' => 'toon_key',
        'table' => 'wowtoon_cached_sets',
        'extra'      => array(
          array(
            'field'    => 'active',
            'value'    => 1,
          ),
        )
    )
  );

  $data['wowtoon_cached_sets_second']['table']['group']  = "second spec";
  $data['wowtoon_cached_sets_second']['table']['join'] = array(
      'avatar' => array(
        'left_table' => 'wowtoon_owners',
        'left_field' => 'toon_key',
        'field' => 'toon_key',
        'table' => 'wowtoon_cached_sets',
        'extra'      => array(
          array(
            'field'    => 'active',
            'value'    => 0,
          ),
        )
    )
  );

  $data['wowtoon_cached_sets_main']['spec'] = array(
          'field' => array(
            'field' => 'spec',
            'title' => t('Spec'),
            'click sortable' => TRUE,
            'help' => t('wowtoon_cached_sets Spec'),
            'handler' => 'views_handler_field',
    ),
  );
  $data['wowtoon_cached_sets_second']['spec'] = array(
          'field' => array(
            'field' => 'spec',
            'title' => t('Spec 2'),
            'click sortable' => TRUE,
            'help' => t('wowtoon_cached_sets Spec 2'),
            'handler' => 'views_handler_field',
    ),
  );

```

---
Tags: views
---


# Question
Title: Uncaught TypeError: Only on Drupal edit pages
I'm using the BigSlide.js sliding menu on my drupal site, which i've built into the theme, and it works fine on every page, apart from on /edit/ pages. E.g. user/%/edit.
When clicking the target menu button nothing happens - the menu should slide out from the left.

In the chrome console i'm getting:

> Uncaught TypeError: undefined is not a function

As you can see from the image above it's referencing bigSlide.js, I've tried updating jQuery to 1.9 with the Jquery update module as i'm using 1.7 and that didn't help, and i've made sure all my JS files are being loaded on /edit/ pages.

What could be the problem?

Here's the issue spot within bigSlide.js

Any help much appreciated.

# Answer
I had installed the dev version of jQuery Update 7.x-2.3+15-dev, which allows you to specify different versions of jQuery for normal and administrative pages:

I'd done this because I had previously required jQuery 1.5 for something in the backend. It appears /edit/ pages are considered 'administrative' pages - (which seems odd to me) and therefor were using 1.5 which broke the bigSlide.js menu. Changing the admin pages back to 1.7 fixed the issue.
> 1 votes

# Answer
On a default Drupal install node/%/edit will run with the admin theme. Go to admin/appearance and switch of the setting for 'Use the administration theme when editing or creating content'. Then check if your menu works. If it does then you need to build the menu into the admin theme and it is not a javascript issue as you might suspect.

You also might have overlay running. This can cause issues with javascript menus as well. Once again, switch overlay off and check if it works without it.
> 0 votes

---
Tags: theming, javascript
---


title: Script Not Working

text:
# Question
Title: Script Not Working
I am trying to integrate 3rd party jquery plugin Turnjs 3rd edition available on github in my website.

For this I have uploaded turnjs script on my server and called it in website through my theme.info file and my layout.inc

Installed jquery update and selected jquery 1.7

created a content type and added multi image field through which I have created this node http://patelbrothers.com.pk/content/mag1

which displays all the images of the field like following

```
    <div class="field field--name-field-flipping-book-images field--type-image field--label-hidden">
<div class="field__items">
    <div class="field__item even">
<img typeof="foaf:Image" src="pages/01.jpg" width="300px" height="auto">
    </div>
    <div class="field__item odd">
<img typeof="foaf:Image" src="pages/02.jpg" width="300px" height="auto">
    </div>
    <div class="field__item even">
<img typeof="foaf:Image" src="pages/03.jpg" width="300px" height="auto">
    </div>
    <div class="field__item odd">
<img typeof="foaf:Image" src="pages/04.jpg" width="300px" height="auto">
    </div>
</div>
</div>

```

and the CSS

```
    .field--name-field-flipping-book-images .field__items{
width:600px;
height:392px;
}
.field--name-field-flipping-book-images .field__items{
background-color:#ccc;
background-size:100% 100%;
}

```

After that using js injector module I have inserted the following before the closing body tag but still the script is not working.

```
    $(window).ready(function() {
    $('.field--name-field-flipping-book-images .field__items').turn({
                        display: 'double',
                        acceleration: true,
                        gradients: !$.isTouch,
                        elevation:50,
                        when: {
                            turned: function(e, page) {
                                /*console.log('Current view: ', $(this).turn('view'));*/
                            }
                        }
                    });
});

$(window).bind('keydown', function(e){

    if (e.keyCode==37)
        $('.field--name-field-flipping-book-images .field__items').turn('previous');
    else if (e.keyCode==39)
        $('.field--name-field-flipping-book-images .field__items').turn('next');

});

```

# Answer
It worked :)

Just wrapped my code inn

```
(function ($) {
// All your code here
})(jQuery);

```

For Reference https://www.drupal.org/update/modules/6/7#javascript\_compatibility
> 0 votes

---
Tags: javascript
---


# Question
Title: How can I create a new content by adding another two contents of same content type?
How can I create a new content by adding another two contents of same content type? My situation is I have one content type 'Student' and in another content type 'Receipts' whi has one field called months (list field) which stores the fee paid for each term (eg. April, May, June). the student pays fee for term wise, for term2 fee another Receipt content is created...

Then I acreated a view (Student + Receipts), It displays like

No Name Class Paid Months 1 Sravan 10 A Apr, May, June 2 Sravan 10 A Sep, Oct, Nov, Dec 3 Manohar 9 B Sep, Oct, Nov, Dec (Joined only on Sep) 4 Sreeram 8 C (No Fee Paid Yet)

I want to find those who did not paid the fee for Apr, May, June..

but when I displayed it shows 'Sravan' in the list cause it searches in his 2nd Receipt for Sep, Oct, Nov, Dec. (Apr is not in that list)

How can I solve this..

Sorry for my lengthy question.. I would like to explain my situation in details...

# Answer
Entity Reference Module should be used for such cases

To use the entity reference field in views you should follow the link given below https://www.youtube.com/watch?v=4Pdii7aFIvc http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7

In the advanced section of views you have a relationship option where you will get an option to use a referenced entity for the view of content type A(student).
> 1 votes

---
Tags: views
---


# Question
Title: Drupal 7 Theme [Business] not pulling in to non-front pages
I am programming five custom modules for a client in Drupal 7. Tey have, well, **HAD**, a company in India doing their front-end work. *Something* went wrong and the India company stopped responding and developing the front end, so I have been tasked with finishing the pages and of course still complete the modules. Didn't think this would be a real big deal, but here is the rub--

The company created the front page template. I went in created a few pages, \[ie about, connect, meet the authors, etc\]. When I looked at the pages, they looked awful, no formatting at all, except for the top navbar/header which is actually pulling from the subtheme. I have enough css skills to realize these new pages are not calling the base theme, in this case, they are using the drupal business theme located here \[https://www.drupal.org/project/business\].

The former company created a subtheme, of sorts, off the "Drupal Business" theme and have the page--front and page.tpl.php along with css and js related folders and files.

i turned on devel\_themer and see the front/home page is calling the new front-page template. When I look and click on the body/node of my new pages below the top nav/header, the function call reference "theme-field", not the base theme or the subtheme that is in /sites/all/themes....

Since I am more a programmer and hence the reason I love Drupal, don't have to worry about all the theming stuff. I just need the new pages to apply the base theme's css and reference the settings correctly.

Could any of the theming pro's give me some insight, assistance please? It seems like there is a setting to apply the theme to the pages you want, but I can't figure that out.

# Answer
If you want page specific theme'ing, look at themekey module:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.
> 0 votes

# Answer
Does the child theme have `base theme = theme_name` defined in the .info file?

Does the child theme have an `html.tpl.php` file? If it does, does it contain the following inside the `<head>` element:

```
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $scripts; ?>

```

Failing that you can install the Theme developer module to tell you which files are being used to render the page.
> 0 votes

---
Tags: theming
---


title: Adding a widget to CKEditor 4.3.5

text:
# Question
Title: Adding a widget to CKEditor 4.3.5
I've installed CKEditor 4.3.5 on my Drupal 7 by simply copying it into the sites/all/libraries folder as described here: http://mtt.desk.com/customer/portal/articles/973377-how-to-install-the-ckeditor-on-drupal-7

I've done this successfully with CK Editor 4.3 and as of May 2014 it works fine with Wysiwyg 7.x-2.2.

I'm wondering if anyone has successfully installed CK Editor's widgets using the installation as in this method. There seems to be plenty of documentation for installing widgets if using the Drupal CK Editor module, which is an alternative installation route. However, I can't find any for this route.

Specifically, in the CK Editor widget tutorial, http://docs.ckeditor.com/#!/guide/widget\_sdk\_tutorial\_1, we are asked to register the widget in the extra plugins list, config.extraPlugins. This seems to be placed wherever CK Editor is first called. So in Drupal, where do I place this code?? I tried the config.js file in sites/all/libraries/ckeditor but it doesn't seem to work.

I'd be grateful for any ideas.

Thanks and best wishes.

# Answer
First off, you should create a basic custom module, containing an .info file and a .module file.

Call it for example "custom\_wysiwyg"

\[custom\_wysiwyg.info\]

```
name = My Custom Wysiwyg
core = 7.x
package = Custom
version = 7.x-1.0

```

\[custom\_wysiwyg.module\]

```
/**
 * Implements hook_editor_settings_alter().
 */
function custom_wysiwyg_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
    $settings['allowedContent'] = TRUE;
    $settings['extraPlugins'] = 'lineutils,widget,quote_box';
    $settings['extraAllowedContent'] = array(
      'img[src,title,alt,style,width,height,class,hspace,vspace,view_mode,format,fid]',
      'a[type,length,href]',
    );
  }
}

/**
 * Register a directory containing Wysiwyg plugins.
 *
 * @param $type
 *   The type of objects being collected: either 'plugins' or 'editors'.
 * @return
 *   A sub-directory of the implementing module that contains the corresponding
 *   plugin files. This directory must only contain integration files for
 *   Wysiwyg module.
 */
function custom_wysiwyg_wysiwyg_include_directory($type) {
  switch ($type) {
    case 'plugins':
      // You can just return $type, if you place your Wysiwyg plugins into a
      // sub-directory named 'plugins'.
      return $type;
  }
}

function custom_wysiwyg_wysiwyg_plugin($editor, $version) {
  switch ($editor) {
    case 'ckeditor':
      $module_path = drupal_get_path('module', 'custom_wysiwyg');
      $plugins = array(
        'lineutils' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/lineutils',
          'load' => TRUE,
        ),
        'widget' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/widget',
          'buttons' => array(
            'widget' => 'widget'
          ),
          'load' => TRUE,
        ),
        // Quote box is an example widget based on the Samples Simplebox widget.
        'quote_box' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/quote_box',
          'buttons' => array(
            'quote_box' => 'quote_box'
          ),
          'load' => TRUE,
        ),
      );

      return $plugins;
      break;
  }
}

```
1. The function "custom\_wysiwyg\_wysiwyg\_editor\_settings\_alter" alters the wysiwyg profiles' settings when rendering a wysiwyg textfield. We add some extra allowed elements and their attributes (bugfix for media module), and we define our custom plugins.
2. The function "custom\_wysiwyg\_wysiwyg\_include\_directory" describes our custom module's CKeditor plugins path subfolder "plugins".

You can than place any custom plugin folders in your module's "plugins" directory as follows:

```
/
/custom_wysiwyg.info
/custom_wysiwyg.module
/plugins
/plugins/lineutils/plugin.js etc...
/plugins/widget/plugin.js etc...
/plugins/quote_box/plugin.js etc...

```
3. The function "custom\_wysiwyg\_wysiwyg\_plugin" defines a list of our custom plugins which we have placed in our module's subfolder "plugins".

Note: The plugin "lineutils" is a dependency for the "widget" plugin and is not included in the Ckeditor Full download.

I hope this points you in the right direction.

greets, Kim
> 1 votes

---
Tags: wysiwyg, entities
---


# Question
Title: How to alter a form of content-type to prepopulate FieldCollection of EntityReference fields?
I have three content types :

* Classroom (some fields)
* Student (some fields and one EntityReference to Classroom)
* KMDone (some fields and a FieldCollection)

KMDone is a content type which contains : \- a date \- a FieldCollection "kmdone\_students"

The FieldCollection "kmdone\_students" contains itself \- an EntityReference to the Student \- a distance "go" (Numeric fied) \- a distance "back" (Numeric fied)

Everything works fine except one point :

The generated form for the KMDone content-type requires to click several times on the "Add More" button to have enough rows for every student, choose one student on each select of each row, and then fill the form. Which is not confortable and can give some encoding errors due to user.

So, I would like to alter the form and prepopulate one "row" for each student.

It seems I have to work with the `hook_form_alter` hook, but how can I can I prepopulate one "row" in the FieldCollection (as if the user clicked on "Add more" button) for each EntityReference ? To say it in other words : if the original form SelectBox have 17 students, I would like then to prepopulate 17 rows and set the EntityReference field for each student.

Many thanks in advance for your tips !

Kind regards,

# Answer
Short answer is : You can't via `hook_form_alter`

Long answer : there is a workaround there : https://www.drupal.org/node/1337804
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How Can I send sms confirmation when user creates a new account in my website?
Can I send sms confirmation when user creates a new account in my website?

How Can I? what modules I have to set for this?

# Answer
Rules module will allow you to do something when something happens in the system. You can send email or sms when an account is created. This is a very handy module, you should have it.

In regards to SMS, there are a few options.

1. SMS Framework module
2. Messaging module
3. VoIP Drupal module

In regards to the SMS framework, I don't know how stable is the 7.x development release. You need to make some decisions here.

There are a tons of video/other tutorials on how to use Rules module, I recommend googling it and you will come across several sources. Do try the free videos provided by DruaplizeMe, they are very useful.
> 1 votes

# Answer
For doing some action on user creation you have to implement hook\_user\_insert or you may use rules module.

For sending SMS from your site you can use SMS Framework or Use Third Party SMS service.
> 0 votes

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


# Question
Title: The content access permissions need to be rebuilt. Rebuild permissions?
My Drpal website asks

"The content access permissions need to be rebuilt. Rebuild permissions"

what is this means?

Can I go for Reubuild Permission?

Will it cause any problem for current modules?

# Answer
I cannot give you a full answer. Your answer is specific to your website.

> "The content access permissions need to be rebuilt. Rebuild permissions" what is this means?

From some Drupal 6 documentation:

> **Rebuild Permissions** If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Possible causes for permission problems are disabling modules or configuration changes to permissions. Rebuilding will remove all privileges to posts, and replace them with permissions based on the current modules and settings.
>
> Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, posts will automatically use the new permissions.

You then asked:

> Can I go for Reubuild Permission?

Sure. This process can take a long time though for a site with many nodes and content.

> Will it cause any problem for current modules?

Depending on your situation and the new modules you've installed that are changing how content permission is being assigned rebuilding permissions *may or not affect your users*. You must first verify what modules are affecting the content permissions and be sure you've assigned appropriate permissions to specific roles that may be using them. It is your responsibility as site owner to be aware of module dependencies.
> 2 votes

---
Tags: nodes, users
---


# Question
Title: Render admin pages (forms) alongwith their admin theme from within a custom theme
I am working on an already set up site where the custom theme was created very much manually and the head-region markup, incl. logo, main menu, user menu, etc. are manually rendered with a particular set of CSS based on twitter bootstrap. The admin theme was left alone, so it doesn´t have those head-region markup. But I do want admin pages/forms to seamlessly be rendered with the custom styled head-region. I tried isolating the css used in the head and added it to the admin theme´s page.tpl. This proves quite disastrous, since a hell lotta css conflicts come up, esp. because of bootstrap.css.

One lousy way would be to add element specific resets. But perhaps there´s a way to shield/wrap the head and the form so that they can still coexist on the same page with their own baggages of css+js?

# Answer
> 0 votes
Theme nesting is not implemented in Drupal. Too much risk of CSS conflicts, and HTML and CSS does not provide any way of isolation except for iframe. There is, quite literally, no way to write an universal solution. So you may:

* Implement resets as you need. Probably hard, but still infinitely easier than any attempt to make solution universal and foolproof.
* Trim the admin theme to remove footer, sidebars etc, and open admin pages in iframe
* Prepare your own theme in a way that will render admin pages in a convenient way, "borrowing" code from admin theme you like (probably it's GPL, so you are allowed to do it).

---
Tags: theming
---


# Question
Title: Unable to login while able to access without login
I am having a strange problem with my drupal website where site is working and anybody is able to surf it properly however the moment I try to login using my admin or account it shows offline message given below. What could be the reason

+++++++++++++ Site off-line

The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.

If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider's database server is running. For more help, see the handbook, or contact your hosting provider.

# Answer
> 0 votes
As you can not login from in your site the only way to do something is from database end, if you have access to database try doing this to come out of this mess up:

Try to empty the sessions and the cache tables. Not DELETE! Empty them. then see if you can login from http://www.yoursite.com/?q=user

Or look if your site is in maintenance mode if it is the follow instructions given here: https://www.drupal.org/node/276457

Hope above will work for you and you will get your site back to normal. Good luck!

---
Tags: 6
---


title: hook_cron_queue_info doesn't run

text:
# Question
Title: hook_cron_queue_info doesn't run
I am using hook\_cron in my module to create a queue. The queue will process a couple of non-drupal database tables and synch some data around (a process that can take close to 10 minutes). I'm creating a single item (`createItem`) and don't need to pass anything to the function. I'm passing null to `createItem` and I've also tried passing an StdClass object.

```
$queue = DrupalQueue::get("alltimesynch");
$queue->createItem(null);

```

However, `hook_cron_queue_info` never runs. I know this because the watchdog function never adds the string to the log

```
function timesdb_cron_queue_info() {
  watchdog("timesdb","timesdb_cron_queue_info called");
  $queues['alltimesynch'] = array (
    'worker callback' => 'timesdb_import_alltime_start',
  );
}
function timesdb_import_alltime_start($null) {
  watchdog("timesdb","Starting alltime import");
  timesdb_import_alltime();
}

```

What am I doing wrong?

# Answer
You have to return $queues in your hook\_cron\_queue\_info..

```
function timesdb_cron_queue_info() {
  watchdog("timesdb","timesdb_cron_queue_info called");
  $queues['alltimesynch'] = array (
    'worker callback' => 'timesdb_import_alltime_start',
  );
  return $queues;
}

```
> 2 votes

---
Tags: 7, queue
---


# Question
Title: Content Field Type Image not auto resizing
I am fairly new to Drupal, I am currently working through Tom Geller's excellent video series on Lynda.com. All is going well, except I am having a problem when trying to set display properties for any content types containing an image field. If I keep the display settings for the image field as the original image then it will display. However if I try to set an image style for example to use as a thumbnail for a teaser, the image does not show. In Chromium there is an empty frame of the correct size but the image does not display. In Firefox only an empty space is shown where the image should appear. I am running my site on a local Apache server which contains multiple sites, and the issue occurs in all the sites. I have the most recent stable versions of Apache, PHP and mySQL. I have come across other threads on various sites where people have had this issue however their fixes have not worked for me. I'm sure its simple fix but its been bugging me for hours! Thanks in advance, Jackson

# Answer
Verify that the images are being created by checking public://styles - `(/sites/default/files/styles) by default`. If you see that the images are not being created then you might have your folder permissions set up incorrectly. `/admin/reports/status` might hint at any permissions problems.
> 1 votes

---
Tags: media
---


title: Translation of fields

text:
# Question
Title: Translation of fields
By mistake I deleted a translation item instead o editing it in admin/config/regional/translate/translate, and now it seems to be gone. Is there any way to get it back to the list of translatable fields?

Cheers /bo

# Answer
> 1 votes
View the page this item is supposed to appear on, Drupal will encounter the item and add it to the translation interface again.

---
Tags: i18n-l10n
---


# Question
Title: Add new menu item in drop down admin menu
I have a node. I would like to create a link to the node in the administration menu. Adding an item in the administration menu is not working. Is this not possible? How can i do that?

# Answer
You can create more admin menu link from navigating to Management Menu, which you will find at this location -- **admin/structure/menu/manage/management**
> 1 votes

# Answer
You can add a View to Admin Menu by setting the path on the page display under "page settings" for the View to admin/content/whatever-you-want and adding a "Normal menu entry" of whatever you want to call it. Admin menu will pick it up. But... if you try to add the same link through admin/build/menu it won't work. Cost me an hour to figure that one out... Might as well share it. lol.
> 0 votes

---
Tags: 6, routes
---


title: Anonymous User gets cookie

text:
# Question
Title: Anonymous User gets cookie
I recently saw that when I open of my sites as a anonymous user, a session cookie is set. I checked the database sessions table, and there is a line for uid 0 as well. How can I prevent drupal from setting this cookie?

Greetings SG

This is what the cookie looks like in the session table:

Sry that the image is so tiny ...

# Answer
As mentioned in my comments above, the problem where provided by the "Pagestyle" module. The 7.x-1.0 is pretty old for now and its creating this cookie for any anonymous user.

You can fix the problem by updating the module to the newest dev release. After this you've to configure the module here: admin/config/user-interface/pagestyle

And set "Scripting languages" to "PHP + JavaScript + Optimized for performance"
> 0 votes

# Answer
Drupal7 unlike drupal6 does not use sessions for anon users. This is an improvement for performance reasons. If you see that there are sessions created it means that there is a contrib module that creates them, so it may be a bad idea disabling them. You can inspect the contents of the session to get an idea which module is using it.

If this is d6 site, you may check the pressflow distribution.
> 2 votes

---
Tags: sessions, cookies
---


# Question
Title: How to trim content from a heavy database
I would like to trim content from a heavy production database (1GB), to reduce transfering time, local mysql import time and generally make it easier to work with.

I know I can ignore cache, watchdog and index tables and this reduces size greatly (about 50%) and I looked into deleting old node revisions.

But I'm looking further to, for example, remove all content older than 1 year, or all users that have not been active in the last 6 months.

In the workflow these clean-up operations could be done in a (recently synched) staging environement before exporting the databse for local usage.

Anyone know how to accomplish removing older content from a database so it can be easier exported?

# Answer
> 2 votes
For content, I know two options, both based on Views:

1. Create a view of old content only, and use Views Bulk Operations to purge it from your site. This is literally what you asked for, but also something I would discourage.
2. Create a view of new content only, and use Views data export to only export nodes recent enough to matter. That way you will still have old content on site, and only lose it if site crashes and you need to restore from incomplete backup.

Also, I suggest you to evaluate Universally Unique IDentifier, it helps with consistency if you are exporting data individually, not as a complete snapshot of entire site.

---
Tags: 7, database
---


title: How to setup voting on user profiles?

text:
# Question
Title: How to setup voting on user profiles?
I've got a website where people vote on a user using a button found on the user's profile page, and where users are ranked on the homepage based on the number of votes to their name (along with some fields associated with their account).

I'm trying to implement this voting system using another module (because the voting API isn't particularly well documented). Unfortunately, the Rate module is only suitable for nodes and comments, and the Fivestar module is not suitable for this purpose (I just need a single vote button).

I've also tried adapting the Flag module, although this is proving to be difficult, because I need the ability for users to vote a maximum of once per week on a profile, and by default, it does not allow this.

I'm using Drupal 7, and I have access to cron jobs and full control of the drupal installation.

I'd be grateful if anyone who has experience with the voting API, or a different module could direct me on how to set up this system.

# Answer
if you end up getting stuck, you could create a Rule that populates a node when a user is created, and essentially create a node-based profile that the user can edit, then use Rate. Look at Node Limit to limit the profile count to 1 node per user, and set permissions on the content type to restrict the user being able to only edit (and not delete) their own content.

Rules:

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

Rate:

> This module provides flexible voting widgets for nodes and comments.

Node Limit:

> The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.
> 1 votes

# Answer
Choose the Flag module.

You should be able to disallow voting more than once per week by setting up a custom rule that saves the time of flagging in an additional field if it's unset, or looks up the last time of flagging if it's set and discards the flag if it's less than a week.
> 0 votes

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


# Question
Title: How to get a text field with each radio input in cck
I want to have a text field input in front of every radio input so, that when a user selects a radio input the appropreate textfield will appear infront of every radio input in node/add

# Answer
> 1 votes
It seems you are looking for the Double field module

> Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.
>
> For the moment it includes the following sub-widget types:
>
> * Textfield
> * Select list
> * Single checkbox
> * Textarea
>
> Consequently, in all there are 4 x 4 = 16 widget types.

You can also achieve that using Field collection module.

> This module Provides a field-collection field, to which any number of fields can be attached.

But this module requires the Entity API module. Also note that this 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.

---
Tags: entities
---


# Question
Title: Adding multiple HTML pages as nodes as part of workflow
I've just started using Drupal. I'm in the process of building my first web site (I'm not a web designer but have a reasonable knowledge of html, css and python and some comprehension of the DOM).

My workflow is to produce content in markdown and then produce html files locally before uploading to my site. I've looked at a few options to try and do this in Drupal but am struggling to make headway.

All I really want to do is grab a bunch of html pages at a time from a folder (in ubuntu linux) and add them in as basic page nodes with the filename as the node title.

I've tried the `feed` module and `import_html` and `migrate` but they all seem to be set up to take a SQL table rather than a simple html table. I don't need anything parsed or mapped other than full text to "content" as full html and file\_name to title.

Any help appreciated. This is pretty fundamental to the way I work, and after three days of trying to crack it, I'm stumped.

adding that I have reviewed the following question

How to add multiple HTML nodes in Drupal and viewed the video and followed the link but the former doesn't cover html and my import doesn't show up as a node and the latter has several PHP code fragments and I'm not sure how to bring them together into a single script and where to put that script.

# Answer
Tahnoon, This is a very unusual task you are trying to perform. Typically we use Drupal to generate new content and manage how that content is displayed. As you have experienced, there are a couple mechanisms in place to import data from databases, spreadsheets, CSVs etc, but not an easy way to import existing HTML files from a specific directory.

What you are trying to do CAN be done but it will take a certain amount of PHP coding \[not a whole lot\] to write a custom module that would do this.

Since your request is not a common case, you will not find a tutorial for it that exactly meets your needs. Rather, you will have to learn PHP and Drupal Module development techniques and write code to find that directory, parse through each file in it, extract out all of the markup between and and place it in the body field, change the filter to FULL HTML, take the file name and use it for the TITLE.

I can't possibly use StackExchange to teach you all of this, so I'll just get you started. 1\] get friendly with http://api.drupal.org this is where we store all of the documentation on the Drupal API 2\] specifically look up the hook\_menu implementation and create a page where your custom code will fire \[for this purpose you're going to hardcode the directory rather than build a user-interface that asks for it.\] 3\] study up on the family of Drupal file functions. I don't think you'll need any generic PHP file functions, but it could happen. 4\] download and install and enable the Examples for Developers module There is one example in there that is FILE related and it saved me A LOT of work last month. 5\] You also need to look at the Google results on how to programmatically create nodes http://goo.gl/A3hUP4 there are a few ways to do this.

Those 5 steps should get you where you want to be. Since you're somewhat new to PHP and Drupal this may take a long time, but it will be a tremendously great opportunity to learn!

If you can afford it, you may want to pay someone to build this OR to help you build it so that you learn in the process.

I hope you find this helpful! :-)
> 2 votes

---
Tags: nodes, feeds, migrations, importing-exporting
---


# Question
Title: How to Embed Views Exposed Filter for only one field
i have a view and many fields are exposed in it. I need to embed (render) a specific exposed filter in my template.

i have came across this article. But it shows all exposed filters of a view.

any idea how this can be done? thanks

# Answer
> 1 votes
Make a views tpl file with name *views-exposed-form--view-name.tpl.php* in your theme in this file `<?php print_r($widgets); exit; ?>` this will give you your widgets then print your widget like this: `print $widgets['your widget name']->widget ;` in end `print $button;`

---
Tags: views
---


# Question
Title: How do I get a link to an image CCK in Drupal 7 in the node view?
If I do this:

```
print_r($node);

```

I get this:

```
 [field_main_photo] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [fid] => 86
                        [uid] => 1
                        [filename] => 01.jpg
                        [uri] => public://01.jpg
                        [filemime] => image/jpeg
                        [filesize] => 28385
                        [status] => 1
                        [timestamp] => 1409510061
                        [alt] =>
                        [title] =>
                        [width] => 600
                        [height] => 400
                    )

            )

    )

```

How can I turn that information into a usable link? I want to know how to link directly to 01.jpg?

# Answer
> 1 votes
You want to use the Drupal link function l() for this.

```
  $link_html = l('some cool link text', $node->field_main_photo['und']['0']['uri'];

```

then you can either print that $link\_html variable OR you can return it some other function will be rendering it.

Bonus: You can replace the 'some cool link text' with the name of the file by using this:

```
$node->field_main_photo['und']['0']['filename']

```

So that would give us:

```
$link_html = l($node->field_main_photo['und']['0']['filename'], $node->field_main_photo['und']['0']['uri'];

```

Make sense?

Also... `print_r()` can often ve difficult to parse through. I recommend that you enable the DEVEL module and instead do the following:

```
dpm($node);

```

This will render the node on the page in a manner that you can click through and inspect each element and array and object. Even better, you can double click the value and the variable path to that value shows up for you to copy and paste into your code.

I hope this helps! :-)

---
Tags: media, files
---


# Question
Title: Programmatically create a node with alias and menu item using Entity API
I've seen the excellent documentation on Drupal.org about how to create a node in code, but that documentation doesn't address how to create the node's alias. I've seen code snippets that use `$node->path;` and `$node->menu` with `node_save($node);` which works, but with `$entity->path->set();` or with `$entity->menu->set();` I'm receiving the following error message:

> Unknown data property path. Unknown data property menu.

Why does this not work with entity api and how can I modify my code (below) to make it work?

```
<?php
/**
 * Testing programatic content creation.
 */
function mymodule_update_7000() {
  $about = _create_node_and_menu_item('About', 'about', 'main-menu', 'About the site');
  dpm($about);
}

/**
 * Helper function creates a node, with alias, and menu item, and
 * returns the mlid.
 * @param  string  $title      the title of the node
 * @param  string  $alias      the URL alias
 * @param  string  $menu_name  the machine name of the menu, eg 'main-menu'
 * @param  string  $menu_title the title of the menu item, if none is
 *                             provide, the $title will be used.
 * @param  integer $plid       the numeric id of the parent menu item
 *                             (defaults to 0).
 * @param  integer $uid        the numeric user id (defaults to 1)
 * @param  string  $body       the body copy to use on the node, defaults
 *                             to lorem ipsum.
 * @return Entity              the node entity object that was created.
 */
function _create_node_and_menu_item($title, $alias, $menu_name = '', $menu_title = '', $plid = 0, $uid = 1, $body = '') {
  if (!$body) {
    $body = '<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>';
  }
  $node = entity_create('node', array(
    'type' => 'page',
    'uid' => $uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  ));

  // Get a wrapper for adding meta-data.
  $entity = entity_metadata_wrapper('node', $node);
  // Using the wrapper, we do not have to worry about telling Drupal
  // what language we are using. The Entity API handles that for us.
  $entity->title->set($title);
  $entity->body->set(array('value' => $body));

  if ($alias) {
    // FIXME this line is broken :'(
    $entity->path->set(array('alias' => $alias));
  }
  if ($menu_name) {
    if (!$menu_title) {
      $menu_title = $title;
    }
    // FIXME this line is broken :'(
    $entity->menu->set(array(
      'link_title' => $menu_title,
      'menu_name' => $menu_name,
      'plid' => 0,
      'enabled' => 1,
    ));
  }
  // Save the entity and its meta-data.
  $entity->save();
  return $entity;
}

```

I realize there are other ways to create a path using `path_save()`, but this is predicated on knowing the node id first. A valid answer here would show how to do this purely with Entity API and one call to `$entity->save()`. Is it possible?

# Answer
I would suggest that you use the `node_save()` and have a `$node->path` set to create the desired path alias, rather than using `$entity->save()` because if inspect (via `dpm()`) the output of an `entity_load()` of a node, you would see nothing there related to the node's path alias.

Of course you could use `$entity->save()` \> then fetch the node/entity id \> and then use `[path_save()][1]` too.
> 3 votes

# Answer
For path alias you can add path alias settings to array which passes entity\_create function like this:

```
 $node = entity_create('node', array(
'type' => 'page',
'uid' => $uid,
'status' => 1,
'comment' => 1,
'promote' => 0,
'path'=>array('alias'=>'your-path-alias',
               'pathauto' => false), //if you use module pathauto));

```

Same principal should work with menu item settings.
> 3 votes

# Answer
After calling `$entity->save();`, the newly created id should be in the entity object. You can take a look with `debug($entity);`. Then you use `path_save()`.

Alternatively, use the `entity_id('node, $entity);` to get the id.

In order to have the entity API change the path for you, you can use `hook_node_presave()` and call `path_save()` in it.
> 1 votes

---
Tags: nodes, entities, path-aliases
---


title: Form '#theme' preprocess doesn't invoke

text:
# Question
Title: Form '#theme' preprocess doesn't invoke
I have form where `'#theme' => 'ebanq_transfer_theme'`. Template file is rendered but preprocess hook doesn't invoke. Any ideas?

```
/**
 * Implements hook_theme().
 */
function ebanq_transfer_theme() {
    return array(
        'user_accounts_form' => array(
            'render element' => 'form',
            'template' => 'user-accounts-form',
            'path' => drupal_get_path('module', 'ebanq_transfer') . '/templates',
        ),
    );
}

/**
 * Accounts form preprocess.
 */
function ebanq_transfer_prepocess_user_accounts_form(&$vars) {
    $form = $vars['form'];
    dpm($form);
}

```

# Answer
This function

> ebanq\_transfer\_preprocess\_user\_accounts\_form(&$vars)

must be called

> template\_preprocess\_user\_accounts\_form(&$vars)

So the Drupal bootstrap / hook system will know that.
> 0 votes

---
Tags: forms, theming
---


# Question
Title: Views: Display the value of multiple value field as a separate column/field?
I have a multi value select list field in the content type.

In views it is currently displaying as:

```
title: test title
field_name: value1, value2, value3

```

And I want it to display it like this:

```
title: test title
key1: value1
key2: value2
key3: value3

```

Where field\_name is the multi value field. Any Idea?

# Answer
In order to display the value of a field differently.

In the view, click on that particular field listed under FIELDS section. In the window that is opened select **MULTIPLE FIELD SETTINGS** then from there change ***DISPLAY TYPE*** to one of existing or ***Simple Seperator*** and provide *** html break line br *** as value of Simple Seperator.

Alternative approach:

Under FORMAT -\> SHOW select ***Content not Fields*** and choose the View Mode as ***Full Content*** then by default, all the values are displayed one per column.

If you want further editing then consider reading about

1. Delta
2. Module to allow adding PHP Code so you can iterate through values
3. Override a template
4. Preprocess function for that particular field.
> 2 votes

# Answer
For Multi value field there is an option in the views field settings like given below

Ordered List
Unordered List
Seperated
... so you can I guess achieve it using inbuilt views functionality
> 0 votes

---
Tags: 7, views
---


title: Default Event calendar view is missing

text:
# Question
Title: Default Event calendar view is missing
I have installed event calendar module and using Zen sub-theme.As event calendar module gives its own content type and view.I can see the content type however I am not able to find the default view Event Calendar in view list.Anybody know the reason please revert.

# Answer
It is made available as a view template.

Goto `admin/structure/views/add-template` and create a new calendar view based on the Date Field that you want to use.
> 0 votes

---
Tags: datetime
---


# Question
Title: Relate number of values to an integer field
I was wondering how to do this with drupal. You probably wonder why I don't just use the unlimited amount of values setting. That's because I want to require the user to fill in the amount of values related to the integer value.

For example, you want to create a group (*node*) for a specific category (*node*). A category which contains an integer field (*field\_members*). Now lets say you also have a node reference field (*field\_category*) at those group node its fields, which refers to a specific category (in this case *field\_members*). Then the user must add the amount of users related to the category its *field\_members* value.

# Answer
You will probably have to setup some way of two step process to enable the reference between both nodes (maybe entityreference). The field you are using will have to be an unlimited multi value field.

with this peace of code you will be able to reduce the items of that field (including the add button). Feel free to provide any other logic for looking up the settings node / proding a default limit etc.

```
<?php
function mymodule_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  if ($entity_type == 'node' && $entity->type == 'my_content_type') {
    $multi_values = array();
    foreach ($form['field_myfield'][LANGUAGE_NONE] as $key => $value) {
      if (is_numeric($key)) {
        $multi_values[$key] = $value;
      }
    }

    if (count($multi_values) > 1) {
      $multi_value_keys = array_keys($multi_values);
      foreach ($multi_value_keys as $key) {
        unset($form['field_myfield'][LANGUAGE_NONE][$key]);
      }

      // get the count of the asociated node, maybe using entity reference?
      $settings_node = node_load($entity->field_settings_node[0][LANGUAGE_NONE]['target_id']);
      if ($settings_node) {
        $limit = $settings_node->field_limiting_field[LANGUAGE_NONE][0]['value']; // e.g. textfield..
        if ($limit) {
          $i = 0;
          // add all the fields that are allowed, cut of the once that are too much (and remove the add button)
          while ($i < $limit && $i < count($multi_values)) {
            $form['field_myfield'][LANGUAGE_NONE][$i] = array_shift($multi_values);
            $i++;
          }
        }
      }
    }
  }
}

```

You might also want to look at How to dynamically set the maximum cardinality for a multi value field? for another example (setting the access attribute for those fields)
> 0 votes

---
Tags: 7, entities, nodes
---


# Question
Title: How can can I get theme callback to work for an error page?
I've created a custom error handler for 404 errors (page not found).

I've set up *Home » Administration » Configuration » System » Error Pages* for 404 errors to point to `http://example.com/myerrorpage`, and then I have the following in `hook_menu`

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items = array();
  $items['myerrorpage'] = array(
    'title' => 'myerrorpage',
    'access callback' => TRUE,
    'page callback' => 'myerror_page',
    'theme callback' => 'myerror_theme',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

When I enter a non-existing path (e.g. `http://example.com/bogus`) the *page callback* is invoked as expected.

However, the *theme callback* is not.

To get the *theme callback* to fire, I need to enter the following path: `http://example.com/myerrorpage`.

I do not understand why the *theme callback* does not fire at the same time as the *page callback*.

Is there any way to get the *theme callback* (or `hook_custom_theme()`) to fire when a non-existing path is given?

# Answer
> 0 votes
In `menu_get_custom_theme()`, you can see that *theme callback* on menu router would not be called if the menu router doesn't exist. But you can achieve that with `hook_custom_theme()`.

I'll go like this:

```
/**
 * Implements hook_custom_theme().
 */
function MYMODULE_custom_theme() {
  $router_item = menu_get_item();
  if (empty($router_item)) {
    return 'THEME_NAME';
  }
}

```

---
Tags: 7, theming
---


# Question
Title: Deoes any email is send when i open drupal webpage first time?
I heve a not nice "error/message" from time to time on the bottom of the page... It is sth like this:

```
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "220 poczta1.www.www.pl ESMTP Postfix "
SMTP -> get_lines(): $data is "220 poczta1.www.www.pl ESMTP Postfix "
SMTP -> FROM SERVER:220 poczta1.www.www.pl ESMTP Postfix
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "250-poczta1.www.www.pl "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl "
SMTP -> get_lines(): $str is "250-PIPELINING "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING "
SMTP -> get_lines(): $str is "250-SIZE 262144000 "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 "
SMTP -> get_lines(): $str is "250-VRFY "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY "
SMTP -> get_lines(): $str is "250-ETRN "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY 250-ETRN "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY 250-ETRN "

```

The strange thing is that this happens only from time to time and is displayed on the main page at the bottom (usser is not logged in). When user visit the page again (F5), information disappear, does that mean that the web template have hidden code to send an email about web template usage?

# Answer
> 2 votes
You have the SMTP module set up for debug mode, so it prints the protocol exchange details for every email sent. In addition, poormanscron (which is default in Drupal 7) is being triggered by the page request.

If you turn off the debug option for SMTP those lines will no longer appear. Also you may want to set up an automated cron job so cron runs in the background rather than when users are making requests.

---
Tags: theming
---


# Question
Title: View filter on date "Less than or equal" AND NULL(empty)
I just made a view with some filters (date), I wonder how can I choose the operator to mix the options "Less than or equal" and NULL, in just one request? I can't do that with "Grouped filters", Should I hook the code? If that's so, where?

Thanks so much

# Answer
> 0 votes
Well I could figured out this for myself, if anyone need it here is what you need to do:

1. Go to *sites/all/modules/views/handlers/views\_handler\_filter\_numeric.inc*
2. In there:

a. Inside the *function operators()-\>$operators = array(*

b.

```
'custom' => array(
'title' => t('Title you want for your operator'),
    'method' => 'op_custom',
    'short' => t('<='),
    'values' => 1,
 )

```

c. Then around line 255 or so create a new function:

```
function op_custom($field) {
  $or = db_or()
  ->condition($field, $this->value['value'], 'IS NULL')
  ->condition($field, $this->value['value'], '<=');
  $this->query->add_where($this->options['group'],$or);
}

```

And you can choose that operator now in your Data Filter.

I hope this helps, any questions let me know as PM or comments, take care

---
Tags: views, datetime
---


# Question
Title: Is it possible for the Contact page to have 2 URL aliases? or clone it?
My client is wants the Contact page to be available in more than one place in the menu system. Problem is this would interfere with how sidebar menus load. so ideally it would be nice to have 2 URL aliases for it, …or as alternative just clone the page.

Does anyone know how to do either of these options. I need to do the same for the User page.

big thanks in advance!

# Answer
The Redirect module would allow you to create another url for for your contact page. One would simply redirect to the other.
> 0 votes

# Answer
You can have as many aliases as you like that points to one page (which, in this case, is Contact)
> 0 votes

---
Tags: routes, uri
---


title: Stylize book index with images

text:
# Question
Title: Stylize book index with images
**Intro:** In the root page of the book, there's an index on the bottom that lists all the child pages. There are also links to previous and next page in each of those child pages. Not sure what the correct terminology is for that index.

**My problem:** What I would like to do is to completely re-design those links. Since the book contains mostly videos, I want each link to have a thumbnail of those videos. Of course, I would modify the content type of the page to upload that thumbnail image. If I could replace those pages with a panel and a view block for example, that would completely solve the problem. (but not sure if it's possible to create such view to list the child nodes)

**Question:** Is there a module to redesign those indexes and/or what are the templates I would need to modify to do that? Thanks!

Note: Using Drupal 7. Not a newbie, but not an expert either.

# Answer
> 0 votes
You actually don't need a module to do this

**The previous/next links** can be directly modified by 'just' overriding the file modules/books/book-navigation.tpl

```
<?php if ($has_links): ?>
    <div class="page-links clearfix">
      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('‹ ') . $prev_title; ?></a>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?></a>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print $next_title . t(' ›'); ?></a>
      <?php endif; ?>
    </div>
<?php endif; ?>

```

this is also described a bit more detailled in this answer to a very similar question:

Next/Previous button for nodes within a book

**The book tree** is quite a bit more complex. A good start would probably be to look at the functions template\_preprocess\_book\_navigation and book\_children and menu\_tree\_output and then override the parts you want to 'style' (theme) in your template.php – but that can be tough.

I ran into a similar problem a while ago – and *not* using the book module was the solution for me. Instead I dived into Entity reference and found it a way more flexible approach than using and theming the book module.

---
Tags: views, nodes, theming
---


title: jQuery getting loaded twice

text:
# Question
Title: jQuery getting loaded twice
I'm using the jQuery Update module and decided to choose a more recent version of jQuery so in the module settings I changed it from 1.7.1 to 1.8.2

The issue I'm having is that the previous version (1.7.1) keeps getting loaded. So at the moment two versions of jquery are being downloaded. Its worth mentioning that I selected the Google CDN delivery method so the file comes from there.

I have no idea how to solve this. I disabled and uninstalled the module, manually removed the `jquery_update_jquery_cdn` from the `variable` table, cleared the cache, cron, restarted nginx and php-fpm, but still the issue persists.

# Answer
The issue was memcached, apparently variables were cached in the service. Once the memcached service was rebooted the issue disappeared.
> 1 votes

---
Tags: javascript
---