title: Including a view in a content type

text:
# Question
Title: Including a view in a content type
I have the panels module installed. So I have two types of pages:

1. Under the *Create content/Page*, the basic content type
2. Under *Site Building/Pages/Add Custom Page*, the page with panels

So, I've used the Panel pages all over the place and everything is easy; however, for a particular project, I have some content-types that were based off the basic Page (example 1 above).

I need to figure out how to add a view to that kind of page. There is a lot of HTML with jQuery setup to allow for a custom tab system on one page: Click on a tab and via show/hide the appropriate content shows up and adds a hash tag to the url for deep linking.

I'm guessing I will select PHP code for the input format, but I haven't found the right snippet to include a particular View within all the HTML code that is already there.

I tried to just use `<?php print $content; ?>` within the div for the last tab of content to see if I could get something to render but it didn't show anything so perhaps this isn't the right way anyway?

### Some notes

My view has four displays and I need to call the one "ISO 14001 docs" but, the view has an argument of "(Document) Content: Link" so that is probably why I have not been successful.

I've tried the following code, but I'm not getting anything and I'm not sure how to add that type of argument in this kind of call.

```
$viewName = 'sc_file_view';
print views_embed_view($viewName);

```

# Answer
> 2 votes
You can use Views Reference module that will give you a cck to choose from selected views. This will use with each type of content.

For a same view in all content of content type you will need to create a template file `node--type.tpl.php` and paste your code to include the view.

# Answer
> 0 votes
To embed a view with PHP use the following:

```
$viewName = 'sc_file_view';
$displayId = 'block_3';
$viewArg = 1; // Your view argument goes here
print views_embed_view( $viewName, $displayId, $viewArg );

```

The display ID is usually something like 'page\_#' or 'block\_#', it would not be named "ISO 14001 docs". You can find your $displayId by reading this link: How do I get the display id of a view in Drupal 6?

---
Tags: views, 6
---


# Question
Title: How can I allow users to opt out of receiving e-mails with one-time login links?
So I have been working on an update to my site to allow users to log in via one-time login links when they receive a Private Message. Unfortunately, this kind of feature recently has been in the news as a security issue, so I want to make sure that I give users a way to opt out.

The one-time login links are provided by the Login One Time module. The e-mail notifications are provided by the Privatemsg module's *PM E-mail Notify* submodule, but ideally the solution would also work for e-mails sent by Rules, system e-mails, etc.

**How I add the login link**

In the *PM E-mail Notify* UI, in the body of the "You have received a new message" e-mail, I insert the following token:

`[privatemsg_message:recipient:login-one-time]`

and the whole link is:

`[privatemsg_message:recipient:login-one-time]?edit[name]=[privatemsg_message:recipient:mail]`

This provides the user with a one-time login link that looks like this:

> http://localhost:8888/en/login\_one\_time/1173/1377182743/RZCfB7uwKRB\_bFVCeKPNwtOnDn2jFfGMO2FdaE\_cpxI?destination=?edit\[name\]=useremail@example.com

(Note: the `?edit[name]=useremail@example.com` part is a query string for the Prepopulate module which pre-fills the e-mail address on the login form in the event that the one-time login link has already been used.)

**What I want to do**

1. Add a boolean field to the user profile, "Do not send me one-time login links in my e-mail."
2. Somehow check the value of that field when sending e-mail notifications.

Is there a robust way to do this? Here is what I have thought of so far:

* Instead of using Privatemsg to send the e-mail notifications, attempt to create the notifications in Rules. But if I do this, then I cannot use any of the nice Privatemsg configuration settings (such as allowing users to choose when they would like to receive e-mails, e.g. every time they receive a message, only once per sender, etc.)
* I could somehow create a token that gives the one-time link if the user has not opted out or the regular link if the user has opted out. (I'm not really sure how to do this.)
* I could hack the *PM E-mail Notify* submodule to do what I want.

Ideally, I want to do the following: **if a user has opted out, I want to replace the one-time login link in any e-mail sent by the site with a link to the login form.**

Note: **My site is multilingual, and I am translating the e-mails sent with the site using the Variable and i18n modules. So, any solution needs to be robust enough to handle multilingual e-mails.**

# Answer
What I would do is define your own token.

Start off with copying `login_one_time_token_info()` and `login_one_time_tokens()` into a custom module, change the hook names and rename the token to something like login-one-time-optional or whatever you prefer :)

Then, change the implementation of the hook\_tokens() implementation so that you check the field on the $account and use either the existing function or `url('user/login', array('absolute' => TRUE))`. Keep in mind that existing users users might not have any data saved in that field, so add a default value, you might want to put something like this in a helper function:

```
if ($items = field_get_items('user', $account, 'your_settings_field')) {
  return (bool) $items[0]['value'];
}
else {
  // Default to use the one time login link.
  return TRUE;
}

```
> 2 votes

# Answer
I think you should add the boolean field that you want to the user profile and then use hook\_mail\_alter or a similiar hook of the email module to check the value of that settings. (Make sure the value is added to the $user global so you could read it)
> 1 votes

# Answer
Try out this.

Create a menu path some thing like `my-login/%user` and let all `my-login/%user/*` paths handled by this menu handler (may be with custom module, panel with php code content)

prefix the url with `my-login/%user` so that it looks like `my-login/[UID]/login_one_time/*`

on the menu handler, load the `%user` and check the boolean, if allowed, direct the request to `login_one_time/*` the actual path, or show the login block.

\*You can use the shorturl module tokens if that link looks lengthy.
> 0 votes

---
Tags: emails, tokens, users, privatemsg
---


title: Drupal 7 CDN whitelist issue

text:
# Question
Title: Drupal 7 CDN whitelist issue
My Drupal 7 site is working nice and most of my static files are served via CDN. I use **CDN module** with **Origin Pull** however CDN didn't pull the files from my `misc` folder where there are small `png` icons (*came with vanilla drupal installation*).

In CSS, I have used `url('sites/all/themes/mytheme/img/bg.png')` for background and I can see the background, and it is served via CDN. In the same CSS I have `url('misc/configure.png')` but this one is not working. I see **404** for `configure.png` while checking from Developer Tool.

So, I added the path in CDN module's whitelist like `misc/*.png` and did all those **flushing** and **cron** for CDN to recognize the file. Still CDN didn't pull the file. I have set the file permissions to **775** too, but nothing changed. Any help would be appreciated.

**Edit:** the 404 is only for the picture, I checked it via chrome's Developer tool. It shows the path `https://myCDN/misc/configure.png` (*which is missing*), whereas for background it shows `https://myCDN/mysite/sites/all/themes/mytheme/img/bg.png`.

However, the notable difference is in `configure.png` the name of my site is not present in CDN path. If I change the path via Chrome Developer Tool like `https://myCDN/mysite/misc/configure.png` It works, the image shows. It also works if I use absolute url in CSS like `url('https://mysite/misc/configure.png')`

# Answer
> 1 votes
I was doing the wrong practices with **Drupal Theme**, in **CSS** whenever I have to use the `url()` to declare the path, I was using `url('sites/all/themes/mytheme/images/bg.png')` which is considered as *Bad Practice*, so I changed that to `url(../images/bg.png)` and same for Images inside `misc` folder as `url('../../../../misc/configure.png')` from **CSS** and everything is working as expected.

To tell long story in short, **don't use absolute url from the *root* in CSS** but use relative paths.

# Answer
> 0 votes
CDN module generates for you address like https://cdn.example.com/misc/configure.png but the URL that works is https://cdn.example.com/mysite/misc/configure.png \- This means there is a bug in CDN module, in part responsible for URL generation / substitution.

The best, but not fastest course of action would be to report it in CDN module issue queue.

---
Tags: 7, cdn
---


# Question
Title: How to rewrite this theme call to drupal_render
I have this call to the theme function in my code :

```
print theme('image_style',
            array(
                'path' => $news_image['uri'],
                'style_name' => 'thumbnail',
                'alt' => $news_image['alt'],
                'title' => $news_image['title'],)
            );

```

However in the theme function documentation you can read :

> Avoid calling this function directly. It is preferable to replace direct calls to the theme() function with calls to drupal\_render() by passing a render array with a #theme key to drupal\_render(), which in turn calls theme().

So, how do I rewrite the above simple function using drupal\_render ?

# Answer
> 7 votes
Something like this...

```
$build = array(
  '#theme' => 'image_style',
  '#path' => $news_image['uri'],
  '#style_name' => 'thumbnail',
  '#alt' => $news_image['alt'],
  '#title' => $news_image['title'],
);

$rendered = drupal_render($build);

```

Where every named variable you would normally pass to the `theme()` function as the second parameter becomes a #-prefixed key in the render array.

---
Tags: theming
---


title: Custom Ajax Based Search Form

text:
# Question
Title: Custom Ajax Based Search Form
I'm trying to create a custom search form that uses ajax to perform the actual search and return the located objects as html.

Currently I'm doing something like this:

```
function example_module_search_form($form, &$form_state) {
   $form['title'] = array(
     '#type' => 'textfield',
     '#value' => '',
   );
   $form['submit'] = array(
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => 'example_module_search_callback',
        'wrapper' => 'bottom',
        'method' => 'replace',
      ),
      '#value' => t('Submit'),
   );
   return $form;
}

function example_module_search_callback($form, $form_state) {
   $title = $form_state['input']['title'];
   $objects = db_query('SELECT * FROM {node} n WHERE n.type = :type && title = :title', array(':type' => 'object', ':title' => $title))->fetchAll();
   $output = '';
   foreach($objects as $object):
     $output .= '<div style="border:1px solid red; width:200px; height:200px;">'.$object->title.'</div>';
   endforeach;
   return $output;
}

```

The above works fine the first time I submit the form, but in subsequent requests the `$form_state['input']['title']` is always the same?

Can someone point out what I'm doing wrong or perhaps there's a better approach. The reason why I would like to implement my own search form is that the form will have a very large set of controls which values will be used to query the database.

# Answer
Usually in Drupal, the ajax callback is business logic free. You should associate your title (ie string) directly in the form, when ajax had run. I use this :

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

$string = '';

//Retrive the string value
if (isset($form_state['values'])) { // Does ajax ran ?
   $string = $form_state['values']['string'];
}

$form['string'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
      'callback' => 'contact_contact_search_ajax',
      'method' => 'replace',
      'effect' => 'none',
  ),
  '#value' => t('Submit'),
);

// Display the result in the form, but should work if the results are outside of your form
$form['table'] = array(
  '#type' => 'item',
  '#prefix' => '<div id="search-table">',
  '#suffix' => '</div>',
  '#markup' => contact_contact_display_searches($string),
);

return $form;
}

function contact_contact_search_ajax(&$form, &$form_state) {

   $commandes[] = ajax_command_replace('#search-table',drupal_render($form['table']));

   return array(
     '#type' => 'ajax',
     '#commands' => $commandes,
   );
}

// Create your table
function contact_contact_display_searches($string) {
// The query
  $query = db_select('node', 'n')
      ->fields('n')
      ->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
      ->range(0, 20)
      ->execute()->fetchAll();

 // Prepare and clean the results
foreach ($results as $result) {
  $rows[$result->nid] = array(
      'type' => check_plain($types[$result->type]->name),
      'title' => l(check_plain($result->title), 'node/' . $result->nid),
      'email' => check_plain($result->field_pers_email_email),
  );
}

// Simple table theming
$out = theme('table', array(
    'header' => array(t('Type de contenu'), t('Intitulé'), t('email')),
    'rows' => $rows,
    'empty' => t('Aucun résultat avec ces critères de recherche')
        )
  );
}
return $out;

}

```
> 1 votes

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


# Question
Title: Register a new user programmaticaly having id proof
I want to create a user programatically. But I have a field `id proof` where user can upload files.

But I don't know how to save that file while creating user.

Here is my code

```
$form_state = array();
$form_state['values']['name'] = 'robo-user';
$form_state['values']['mail'] = 'robouser@example.com';
$form_state['values']['pass']['pass1'] = 'password';
$form_state['values']['pass']['pass2'] = 'password';
$form_state['values']['op'] = t('Create new account');
//need to know about files

drupal_execute('user_register', $form_state);

```

Can anybody tell me how to do this

Thanks

# Answer
> 1 votes
Hope this will help you.

In Drupal 7 you can use file\_save\_data and file\_usage\_add.

* **file\_save\_data** : Saves a file to the specified destination and creates a database entry.
* **file\_usage\_add** : Records that a module is using a file.

```

    global $user;
    $path = 'C:\...\Downloads\sample images\drupal_7_icon_0.jpg';//local path of id proof image
    $filename = drupal_basename($path);//get filename
    $file_temp = file_get_contents($path);
    //Saves a file to the specified destination and creates a database entry.
    //Dont forget to create id_proof folder inside files folder
    $file_temp = file_save_data($file_temp, 'public://id_proof/' . $filename, FILE_EXISTS_RENAME);

    // Record that the module (in this example, user module) is using the file.
    file_usage_add($file_temp, 'mymodule_name', 'user', $user->uid);//change the module name

    //Get the values to create new user
    $form_state = array();
    $form_state['values']['name'] = 'robo-user';
    $form_state['values']['mail'] = 'robouser@example.com';
    $form_state['values']['pass']['pass1'] = '1234';
    $form_state['values']['pass']['pass2'] = '1234';
    $form_state['values']['op'] = t('Create new account');
    $form_state['values']['field_user_id_proof'][LANGUAGE_NONE][0]['fid'] = $file_temp->fid;//change it as per your requirement
    drupal_form_submit('user_register_form', $form_state);
    drupal_set_message('User saved successfully');

```

---
Tags: 7
---


# Question
Title: Add conditional stylesheet CSS for internet explorer only
The following methods can be used to add CSS for specific versions of IE:

1. Paste the code into html.tpl.php:

`<!--[if lt IE 9]><link type="text/css" rel="stylesheet" src="/sites/all/themes/mytheme/less/ie.css"><![endif]-->`
2. Make use of the plugin Conditional Styles
3. Use drupal\_add\_css() function

I have always used option #1 above, and adding yet another plugin for something so simple seemed crazy. **BUT** working with LESS and calling in statically means the file does not get processed by the LESS pre-processor, so the question:

How do you include a stylesheet using drupal\_add\_css() for specific versions of IE?

# Answer
> 9 votes
I Found the solution in the comments on the drupal documentation for drupal\_add\_css():

```
drupal_add_css(
  path_to_theme() . '/less/ie.less',
  array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE
    )
  )
);

```

Using this resulted in the LESS file being compiled by the LESS pre-processor, and the style was included within `<!--[if lte IE 9]>` comment tags.

---
Tags: 7, theming
---


# Question
Title: Watermarking an image that is not in the Drupal filesystem using image_style
I get an image through the ImageMagick PHP extension because I don't want to start the PHP `exec()` function. This works.

But I'm not managing to create a watermarked image using `image_style` because this image is not in the Drupal file system.

How can I do this?

# Answer
> 1 votes
As you've probably already seen about `theme_image_style()`:

> This function does not work with images outside the files directory nor with remotely hosted images. This should be in a format such as 'images/image.jpg', or using a stream wrapper such as 'public://images/image.jpg'.

There's a beta release of a module called Imagecache External which claims to solve the problem:

> Imagecache External is a utility module to allow you to use imagecache(D6)/image derivatives (D7) with external images.

With that module installed your use of `theme_image_style()` would be replaced with something like:

```
print theme('imagecache_external', array('path' => $path, 'style_name'=> 'thumbnail'));

```

---
Tags: media
---


# Question
Title: How to create a pie chart using the chart module in Drupal 7?
I'm trying to create a pie chart using the chart module. I was able to create a pie chart that looks similar to the pie chart shown on https://developers.google.com/chart/ . But I am not getting any percentages.

**My Question**: What is needed to also show those percentages, or what might I be doing wrong)?

Note: I cannot do those interactive additions, but I can live without them.

# Answer
Yes it is possible to do so. Use the google chart tools to achieve that. This module also integrates with the views module nicely.
> 1 votes

---
Tags: 7, charts
---


# Question
Title: Using the l() function within a node description field
I'm converting an old site to Drupal, and I need to convert all the old URLs to the new system, which uses pathauto. I can turn the old links into node paths (eg. node/28), but I ideally want the aliased paths to show instead. I've found the l() function, but how do I go about applying it to links within the description field of nodes?

# Answer
> 3 votes
If you already turned old links into `node/28` format, you don't need to touch your content any more. You can simply use Internal Links module that will replace it live with the current alias. The benefit is - with this module if alias changes, content still links to a node by node's id, and links stays valid.

> The Internal Links Title filter inserts HTML title attributes into links to other nodes on a site (if no title attribute already exists) using the linked node’s title as the HTML title attribute’s value. **It also replaces href values** which are in the “normal Drupal path” form (e.g. ) **with a URL alias**, if one exists.

Emphasis mine.

---
Tags: path-aliases
---


# Question
Title: How do you format the exposed filter options?
I am guessing this is a easy question, but I am stumped for a couple of hours.
I am using Views with some exposed filters as shown below.

* Search keyword
* Drawing Type
* Type of Mould
* Customer Name

They are all in one line where "Customer Name" and the "apply" button are wrapped onto the next line.
How do I make "Search keywords" in one line, then "Drawing Type" + "Type of Mould" + "Customer Name" on another line, and "Apply" button alone on the last line?

# Answer
Views 3 for Drupal 7 kindly gives each exposed widget DIV a class with a unique name. Then it's a matter of adding clear and float attributes.

If you're using Views 2 you will have to override the views-exposed-form.tpl.php file in the views/theme folder. You can just copy and save this code in a file called views-exposed-form.tpl.php in your theme file path. It should override the original template file.

```
<?php
// $Id: views-exposed-form.tpl.php,v 1.4.4.1 2009/11/18 20:37:58 merlinofchaos Exp $
/**
 * @file views-exposed-form.tpl.php
 *
 * This template handles the layout of the views exposed filter form.
 *
 * Variables available:
 * - $widgets: An array of exposed form widgets. Each widget contains:
 * - $widget->label: The visible label to print. May be optional.
 * - $widget->operator: The operator for the widget. May be optional.
 * - $widget->widget: The widget itself.
 * - $button: The submit button for the form.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($q)): ?>
  <?php
    // This ensures that, if clean URLs are off, the 'q' is added first so that
    // it shows up first in the URL.
    print $q;
  ?>
<?php endif; ?>
<div class="views-exposed-form">
  <div class="views-exposed-widgets clear-block">
    <?php foreach($widgets as $id => $widget): ?>
      <div class="views-exposed-widget views-widget-<?php print $id ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>
          </label>
        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>
          <div class="views-operator">
            <?php print $widget->operator; ?>
          </div>
        <?php endif; ?>
        <div class="views-widget">
          <?php print $widget->widget; ?>
        </div>
      </div>
    <?php endforeach; ?>
    <div class="views-exposed-widget">
      <?php print $button ?>
    </div>
  </div>
</div>

```
> 5 votes

# Answer
After saving the above code as a template override in my theme folder I modified it to ensure all form elements and their "wrapper" DIVs have unique id="" attributes.

In my case, I was outputting the same view twice on a page. One Mobile (field list) version and one Desktop (table) (for responsive website layout). The original code didn't pass Web Accessibility Standards (Double A) - yaaawn!!

```
foreach ($widgets as $id => $widget):
  $id_attr = drupal_html_id($widget->id);
  ?>
  <div id="<?php print $id_attr; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
    <?php if (!empty($widget->label)): ?>
      <label for="<?php print $id_attr; ?>">

```
> 0 votes

---
Tags: views
---


# Question
Title: Blog with subscription option to send emails on new blog entry
I'm working with Drupal 7. How do I setup 'Subscription' option for my blog so that upon every New Entry of the blog, an email is sent out to the subscribers?

# Answer
> 2 votes
Another way is to use the MailChimp module but requires the extra step of registering on MailChimp.com.

> This module provides integration with the MailChimp email delivery service. While tools for sending email from your own server, like SimpleNews, are great, they lack the sophistication and ease of use of dedicated email providers like MailChimp. Other players in this field are Constant Contact and Campaign Monitor.

# Answer
> 1 votes
There are several modules that will provide this for you.

Check out Notifications first, as it may do what you need. There is also Notify and Subscriptions.

# Answer
> 0 votes
Try Rules

One of the highly flexible module i have ever came across.

The rules module allows site administrators to define conditionally executed actions based on occurring events

# Answer
> 0 votes
I made a module which solves this using mailchimp: mailchimp\_subscriptions.

Feedback is welcome! Planning to promote it to a full module soon.

---
Tags: nodes, notifications
---


# Question
Title: Notifications for anonymous users on nodes
I am looking for a module or some kind of workaround e.g. involving Rules, that will allow anonymous users to subscribe to new comments on nodes they have created. My user scenario is as follows:

1. An anonymous user wants to post a new forum topic
2. She clicks on the “Add new forum topic” button
3. On the URL node/add/forumtopic she is presented by the usual form
4. On the form there is an email field with a check box underneath with the label “I would like to receive an email when comments are posted to my thread”
5. She types in her email and marks the checkbox - yes, she would like to have email notifications
6. She submits the form and when a comment is posted in her thread, she gets a notification email with a link to the comment and a link that allows her to unsubscribe from the thread.

I have looked at this nice writeup on groups.drupal.org where different notification modules are compared, but none seems to be offering the functionality I am looking for.

I have installed Comment Notify that offers the desired functionality - but only on comments, not on nodes.

I have tried installing Watcher, but it is early in development and still seems pretty buggy.

This seems to me like a very common scenario - what would be the recommended way of implementing this feature? Any help is very appreciated.

# Answer
I would probably solve this with the following Rules-based setup:

1) Create a custom entity for anonymous posters with only a text field for email and an entity reference field for the node they created. Here's a pretty good writeup on creating custom entities: http://www.istos.it/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity

And here's Drupal.org: http://drupal.org/node/1026420

2) Create a rule for "Node-\>After saving new content" that checks if the poster was anonymous and if so, creates a new anonymous posters entity with the user's email + reference to the created node.

3) Create a rule for "Comment-\>After saving a new comment" that does a "Fetch entity by property" action and after a anonymous poster entity, sends an email out to them.

The only trick you need to figure out is how to play with rules upon fetching entities and accessing their fields. You need to create some rules component so achieve this whole flow since in order to access the field in the entity, you need to verify the type of the entity and this happens in "conditions", which can't be done after "actions" which is where the "fetch entity by property" magic happens.

So you'll basically have to create a Rules Component that does what needs to be done with the fetched entity.

This is definitely not the only way to achieve what you need to accomplish, but since I'm a strong believer in the endless powers of Rules, I like solving things with it. :)
> 1 votes

# Answer
You're welcome to try this new module I made which solves this problem using MailChimp: mailchimp\_subscriptions.

Feedback is welcome! Planning to promote it to a full module soon.
> 0 votes

---
Tags: 7, emails, notifications
---


title: custom multiple values form element

text:
# Question
Title: custom multiple values form element
I have a field with multiple values and i want to make form element more intuitive to work with.

I thought the easiest way would be to create custom html and include it in form, with the other elements. Is this ok?

Now the problem is, on form submit i can't access any of these values in this fields that are not native form elements. Is there a way to convince drupal to take in into $form\_state\['values'\];

I know the right way is to create custom form element but i am afraid it would took me too much time.

# Answer
> 1 votes
> Is there a way to convince drupal to take in into $form\_state\['values'\]

Yes...use the Form API :)

To expand; Drupal builds and caches the fields for a form on the server side, and uses that cache upon submission to make sure the form hasn't been altered. Drupal, rightly, sees the injection of arbitrary HTML into the structured form as an *attack vector*, a security hole which must be plugged up.

Consider what would happen if this weren't the case - a client using your form could inject some HTML form values, overriding your particular intentions for the form submission. As Drupal cannot possibly reconcile the context in which that HTML string was added, it has no way to know if it's come from a trustworthy source.

Bottom line - if you want to add a field to a form that's managed by the form API, your code absolutely needs to conform to the same API - the alternative is to fight against it, which is never fun.

It's physically possible to get around the validation, but the amount of time it would take to convince Drupal to accept your injected form values, and at the same time keep it secure, would far outweigh how long it would take to use the form API as it was intended.

---
Tags: forms
---


# Question
Title: Upgrading multiple modules at once crashes the process
Just upgraded from 7.18 to 7.23 and selected to upgrade all modules and all I got is neverending 'Preparing to update your site' on Installing updates page on /authorize.php?batch=1&op=start&id=40

So what if I refresh page or something will the site crash or something?

UPDATE: It just crashed after like 20 minutes of nothing and I got this error:

```
An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /authorize.php?batch=1&id=40&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {queue} WHERE (item_id = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 8656 ) in SystemQueue->deleteItem() (line 273 of /modules/system/system.queue.inc).Uncaught exception thrown in shutdown function.PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: UPDATE {batch} SET batch=:db_update_placeholder_0 WHERE (bid = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] => a:12:{s:4:"sets";a:1:{i:0;a:15:{s:7:"sandbox";a:0:{}s:7:"results";a:2:{s:3:"log";a:1:{s:5:"views";a:1:{i:0;a:2:{s:7:"message";s:57:"Installed <em class="placeholder">views</em> successfully";s:7:"success";b:1;}}}s:5:"tasks";a:0:{}}s:7:"success";b:0;s:5:"start";d:1377856599.71076107025146484375;s:7:"elapsed";i:0;s:5:"title";s:18:"Installing updates";s:12:"init_message";s:40:"Preparing to update your site<br/>&nbsp;";s:8:"finished";s:38:"update_authorize_update_batch_finished";s:4:"file";s:35:"modules/update/update.authorize.inc";s:16:"progress_message";s:29:"Completed @current of @total.";s:13:"error_message";s:22:"An error has occurred.";s:3:"css";a:0:{}s:5:"total";i:12;s:5:"count";i:12;s:5:"queue";a:2:{s:4:"name";s:17:"drupal_batch:40:0";s:5:"class";s:10:"BatchQueue";}}}s:16:"has_form_submits";b:0;s:11:"current_set";i:0;s:11:"progressive";b:1;s:3:"url";s:36:"/authorize.php?batch=1";s:11:"url_options";a:0:{}s:10:"source_url";s:0:"";s:8:"redirect";s:28:"/authorize.php";s:5:"theme";s:5:"seven";s:17:"redirect_callback";s:11:"drupal_goto";s:2:"id";s:2:"40";s:13:"error_message";s:110:"Please continue to <a href="/authorize.php?batch=1&amp;id=40&amp;op=finished">the error page</a>";} [:db_condition_placeholder_0] => 40 ) in _batch_shutdown() (line 537 of /includes/batch.inc).

```

# Answer
If you have drush try running drush updatedb.

Errors you are getting you should restore backup of your site and update modules one by one.

You can also login phpmyadmin and try to optimize and cleanup mysql if you don't have a copy as it seems your db is crashing and it could be pending database updates. If you don't have drush try going to yoursite.com/update.php to run db updates.

If at all possible use drush for managing your site gives you option to update as well as rollback any updates.
> 2 votes

---
Tags: 7, updating, upgrading
---


# Question
Title: Content type template only for viewing, not editing
I've added a page template to override certain content types

```
function THEMENAME_preprocess_page(&$variables) {
  if( !empty($variables['node']) ) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}

```

This successfully uses `page--node--vendor.tpl.php` instead of `page.tpl.php`

The problem is that it is also using this template when editing the node, which looks rather silly. How can I modify this to only use the template when viewing content and not when editing?

\** Yes, I do want Drupal to use this theme when creating/editing content, and not a separate admin theme.

# Answer
> 0 votes
You could also key off of the path, eg, `node/1` is the path for viewing node 1, whereby `node/1/edit` is the path when you are editing node 1, therefore you could look `if arg(2) != 'edit'` ...

# Answer
> 0 votes
This was the most convenient variable I found in the `$variables` array to check whether I was viewing or editing

```
function THEMENAME_preprocess_page(&$variables) {
  $is_editing = isset($variables['page']['content']['system_main']['#node_edit_form']) && $variables['page']['content']['system_main']['#node_edit_form'];

  if( !empty($variables['node']) && !$is_editing ) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}

```

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


# Question
Title: Hook_node_grants: how do I access a user account field?
Here is my implementation of hook\_node\_grants:

```
/**
 * Implements hook_node_grants().
 */
function gcac_node_grants($account, $op) {

    // Declare $user as having global scope.
    global $user;

    // Permit a user to view the node if the node and user are assigned the same
    // group.
    ** if ($user->field_group[LANGUAGE_NONE][0]['value'] == $node->group && $op == 'view') {
        $grants['gcac_view'] = GCAC_ALLOW;
    }

    // Permit the user to edit the node if the node and user are assigned the same
    // group, and the user is the author.
    ** if ($user->field_group[LANGUAGE_NONE][0]['value'] == $node->group && $user->uid == $node->uid && ($op == 'update' || $op == 'delete')) {
        $grants['gcac_edit'] = GCAC_ALLOW;
    }
    return $grants;
}

```

I have added a field to my user accounts called 'Group' and populated it with a value for several accounts. Yet, here is the error that is being thrown:

> Notice: Undefined property: stdClass::$field\_group in gcac\_node\_grants() (line 21 of /homepages/99/d99999999/htdocs/node-access2/sites/all/modules/gcac/gcac.module).

As you can see I'm trying to access the 'Group' of the current user so that I can compare it to the 'Group' assigned no a node. I just want to access the value. Originally, I tried accessing $account-\>field\_group\[LANGUAGE\_NONE\]\[0\]\['value'\], but I got the same error.

I can go grab it from the database, if I have to because I know I can access $user-\>uid, but surely the user module is providing my the field for me use? Thanks.

# Answer
As per your error statement, field\_group does not exist in $user object. The global $user object does not load the fields which are attached to user profile. if you want to load the complete user profile with attached fields, you need to use function "user\_load" in your code.

```
global $user;

$account = user_load($user->uid);
if ($account->field_group[LANGUAGE_NONE][0]['value'] == $node->group && $op == 'view') {
  //Do the needful
}

```
> 1 votes

---
Tags: users
---


title: Views filter by taxonomy if not empty

text:
# Question
Title: Views filter by taxonomy if not empty
I would like to filter views block content by taxonomy. I have multiple content types on same block, and only one of them has taxonomy. The goal is to output all the nodes from content types with no taxonomy, and from certain term if content type has taxonomy.

Shorter: If content type has taxonomy, filter by it.

And not to be too simple: taxonomy is hierarchical and I would like to it work so, that nodes in child taxonomy would also appear when filtering by parent.

I could of course filter all the other terms out, but the thing is that client can add terms by himself. Therefore limiting the terms out manually is not the best solution.

I am using Drupal 7.22 and Views 3.7.

# Answer
> 1 votes
Use the views filter condition OR groups. Also make sure that the taxonomy relationship optional (uncheck Require this relationship).

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


# Question
Title: Changing drupal_set_message red or yellow
I am looking to change `$errors[] = drupal_set_message(t(' Freshwater Shrimp should be a number!'));`

Into a red or yellow message at the top of the page. Looking at the doc I should do this in drupal 6

```
 $errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!', 'Warning',));

```

But I have no luck.

# Answer
> 6 votes
You've put `warning` as a 2nd argument for function `t()`. Look carefully at the syntax. It should be an argument to the `drupal_set_message` function instead:

Wrong:

```
 $errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!', 'Warning',));

```

Correct:

```
$errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!'), 'warning');

```

# Answer
> 1 votes
If you want to set a warning, you need to use `'warning'` type. It is **not** the same as `'Warning'` you have used. `'Warning'` is not defined, so `drupal_set_message` defaults to `'status'`. When setting options that are not meant to be human-readable, you need to remember that for a machine they are case-sensitive.

---
Tags: 6, status-messages
---


title: Where to override images rendering

text:
# Question
Title: Where to override images rendering
I created my custom content type and add field called 'Image' of type Image and set the content manager can set multiple images into it. Now this field is rendered as such html

```
<div class="field field-name-field-image field-type-image field-label-above">
  <div class="field-label">Image: </div>
  <div class="field-items">
    <div class="field-item even">
      <img typeof="foaf:Image" src="http://mydomain.com/sites/default/files/img1.jpg" width="400" height="314" />
    </div>
    <div class="field-item odd">
      <img typeof="foaf:Image" src="http://mydomain.com/sites/default/files/img2.jpg" width="400" height="260" />
    </div>
  </div>
</div>

```

I cannot find where are the template(s) which render this piece of html. I'd like to override it to render list of links, similar to

```
<div class="field field-name-field-image field-type-image field-label-above">
  <div class="field-label">Image: </div>
  <ul class="field-items">
    <li><a href="http://mydomain.com/sites/default/files/img1.jpg">img1.jpg</a></li>
    <li><a href="http://mydomain.com/sites/default/files/img1.jpg">img2.jpg</a></li>
  </ul>
</div>

```

# Answer
The function is `theme_field()` which could be customized by having the right *override* of the `field.tpl.php` template in your theme (through template suggestion, see the `theme_field()` function documentation.

Inside this function/template, the image is rendered by a field formatter. The `print render($item)` statement print that rendering. The exact used function/template depends on the configured formatter. If your are usign the default formatter, that would be `theme_image_formatter()`.

Note: See the `theme()` function's documentation for how to override the `theme_*` functions in your theme or module.
> 3 votes

---
Tags: media
---


# Question
Title: drupal_find_theme_functions called on every page - is our theme registry being rebuilt?
Our new D7 site was running very slowly so I did some profiling with devel/xhprof and found that D7 was doing millions of preg\_grep function calls within drupal\_find\_theme\_functions() in theme.inc. This happened on every page load.

It's my understanding that the drupal\_find\_theme\_functions function should only be called when the theme registry is being rebuilt - am I correct in that?

I made sure that "rebuild theme registry" was off in devel, and then disabled devel entirely. However, I'm still seeing those millions of function calls to preg\_grep in drupal\_find\_theme\_functions on every page load (I added a piece of code to theme.inc to log when the function was called).

We're using a theme based on Omega and if we are rebuilding the theme registry each time I'm not seeing how/why it's happening. We're turning off as many contrib modules as we can in the meantime. Any help/advice would be MUCH appreciated!!

# Answer
> 0 votes
Nice job on using XHProf to debug what's going on here. drupal\_find\_theme\_functions() should get called once per registry rebuild for the core and installed modules, then once again as each installed theme is utilized. Are you noticing it once per page load, many times per page load, etc? I'm going to send you down a slightly different path on this as you should be more interested on what's causing the rebuild, not what happens when the rebuild occurs.

I'm assuming that you're working with a recent release of D7. Use the devel module and put code below into drupal\_theme\_rebuild() at line 350 of includes/theme.inc to see what functions are being called on the way to the registry rebuild and that should give some clue as to what is triggering it.

```
dsm(debug_backtrace());

```

A quick note on what you should expect to see. I've done some testing and with a mostly empty Drupal install with only a few popular modules installed. The registry rebuild is only happening when I clear the theme cache or perform some action that causes it to be cleared. If you look at the functions being called prior to the rebuild, you should see some indication as to what was responsible for causing it.

When I clear caches from the normal admin screen (admin/config/development/performance) my call stack is 9 functions deep and it passes through a form submission handler that triggers the process. When I clear the cache from the admin\_menu contributed module, my call stack is 5 functions deep and it passes through a page callback that initiates the cache clear. Your case should be showing something a bit out of the ordinary.

# Answer
> 0 votes
Usually if that function is requested million of times, it's because in your theme settings, **"Rebuild theme registry on every page"** is checked. Uncheck it in production stage.

---
Tags: theming
---


# Question
Title: how to do a conditional subquery with db_delete
I currently am deleting by a manually constructed query, but there should be a better way to do this.

```
$query = "DELETE FROM {$table1} ";
$query .= "WHERE col1 = '$col1' ";
$query .= "AND table2_id in ";
$query .= "( SELECT id from {$table2} where col2=$col2 )";
db_query($query)->execute();

```

How do I do this using db\_delete?

Table2 has a covering index, so this should be done in one query.

# Answer
> 2 votes
I think your current way is that fine for multiple table handle like that. From this Delete from Multiple Tables using db\_delete link you can see that:

db\_delete takes a single string parameter to define which table the query is to be run against. There's no scope to provide more than one table at a time.

---
Tags: database
---


# Question
Title: how do I theme rounded corners in Panels 7.x-3.3
I looked through older questions & answers and some examples about styling rounded corners and they seemed valid but when I look into the code in Panels 7.x-3.3 I see an entire function that dynamically generates rounded-corners and tells Drupal where to find the image files.

I have new image files for the rounded-corners. How do I over-ride this function without hacking the module itself?

Ex. (This function is in rounded\_corners.inc)

```
/**
 * Generates the dynamic CSS.
 */
function _panels_rounded_corners_css($idstr) {
  $url = panels_get_path('plugins/styles/corners', TRUE);

  $css = <<<EOF

.t-edge, .b-edge, .l-edge, .r-edge, .wrap-corner {
  position: relative;
  /* hasLayout -1 ? For IE only */
  zoom: 1;
}
$idstr .t-edge {
  background: url($url/shadow-t.png) repeat-x 0 top;
  font-size: 1px;
}
$idstr .b-edge {
  background: url($url/shadow-b.png) repeat-x 0 bottom;
  font-size: 1px;
}
$idstr .l-edge {
  background: url($url/shadow-l.png) repeat-y 0 0;
}
$idstr .r-edge {
  background: url($url/shadow-r.png) repeat-y right 0;
}
$idstr .wrap-corner {
  background: #fff !important;
}
$idstr .wrap-corner .t-edge, $idstr .wrap-corner .b-edge {
  height: 11px;
}
$idstr .wrap-corner .l, $idstr .wrap-corner .r {
  position: absolute;
  top: 0;
  height: 11px;
  width: 11px;
  background-image: url($url/corner-bits.png);
}
$idstr .wrap-corner .l {
  left: 0;
}
$idstr .wrap-corner .r {
  right: 0;
  background-position: -11px 0;
}
$idstr .wrap-corner .b-edge .l {
  background-position: 0 -11px;
}
$idstr .wrap-corner .b-edge .r {
  background-position: -11px -11px;
}
$idstr .wrap-corner .r-edge {
  padding: 5px 24px;
}
$idstr div.admin-links {
  margin-top: -14px;
  margin-left: -12px;
}

$idstr .panel-separator {
  background: url($url/shadow-b.png) repeat-x 0 center;
  font-size: 1px;
  height: 30px;
}

$idstr .rounded-corner {
  margin-bottom: 1em;
}

EOF;

  return $css;
}

```

# Answer
> 3 votes
The functionality you refer to predates common browser support for rounded corners, when images was the only reasonable solution.

Today, I would most likely no use it, but instead implement it with the modern CSS approach.

If you really want to modify the existing functionality though, it's called a `Style`. You can see this question for details about implementing ctools plugins: What are Ctools plugin (content type, access, etc), and how does one create them?

---
Tags: panels
---


# Question
Title: How to re-generate Node Object from database stored Serialized Node Data .. and then Save as New Node?
In Drupal 7, for some reason, i am storing some `serialize($node)` objects into Database. So these data in the database (in `text` column) are storing like:

```
O:8:"stdClass":47:{s:3:"vid";s:5:"78629";s:3:"uid";s:3:"523";s:5:"title";s:12:"Sync Node #6";s:6:"status";i:1;s:3:"nid";s:5:"77429";s:4:"type";s:4:"page";s:8:"language"; ..... etc

```
* Now how can i transform these data back into Drupal `$node` Object please?
* Then how can i `node_save($node)` (as new node) upon them? (What tricks will i need?)

Any idea please?

# Answer
> 3 votes
> Now how can i transform these data back into Drupal $node Object please?

As said you can use the following code,

```
$node = unserialize($data);

```

---

> Then how can i node\_save($node) (as new node) upon them? (What tricks will i need?)

You can null the nid, vid and use `node_save` to save it as a new node like this:

```
$node->nid = NULL;
$node->vid = NULL;
node_save($node);

```

# Answer
> 1 votes
Call unserialize() on the serialized data.

# Answer
> 0 votes
I couldn't get unserialize() to work, it always returns 'false'. So, my solution was to:

```
$nodearray = drupal_json_decode($response->data);

$node = new stdClass();
foreach ($nodearray as $key => $value)
{
    $node->$key = $value;
}

unset($node->nid);
unset($node->vid);
unset($node->path);

```

It's messy, but it ends up creating a new node object that can then be saved using node\_save($node).

Frankly, this is messy, I would much prefer to have been able to use something like unserialize(). So if anyone has a hint as to why unserialize() is returning false for me, then please do let me know!

---
Tags: nodes
---


# Question
Title: How to create custom placeholders on hook_menu, like "%node"?
For example, for menus like `/node/%node`:
when `/node/1` is accessed, drupal automatically translates `1` as `node_load(1);`

I wanted to create something like `/path/%student` where, when `/path/1` is accessed, I could translate `1` into `student_load(1);`

# Answer
In order to use a placeholder like %student, you need to define a `student_load()` function in your module, or an enabled module should define such function. Drupal automatically uses that function when the placeholder is used; that is the reason why you should avoid any conflict between the used placeholders and the existing functions.

In your case, you should use code similar to the following one.

```
function student_menu() {
  $items['path/%student'] = array(
    'page callback' => 'student_page',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('see student page'),
  );

  return $items;
}

function student_load($id) {
  // Load information from the database; return FALSE in case of error, or when the equivalent database row is not found.
}

function student_page($student) {
  // $student is the value returned from student_load().
  // …
}

```

### Reference
> 5 votes

# Answer
if you use hook\_menu you can use

```
$items['path/%'] = array(
        'title' => '',
        'page callback' => 'my_fn',
        'page arguments' => array(1),
        'weight' => 0,
    );

function my_fn($student_id){
   $node = node_load($student_id);
   return $node->title;
}

```
> 1 votes

---
Tags: routes
---


title: AJAX added fields don't hide

text:
# Question
Title: AJAX added fields don't hide
I have a altered registration form with a check box that when checked adds few fields. The fields are wrapped in a specific div.

The callback function of check box is supposed to hide the dive when the check box is unchecked.

The adding works well but the unchecking doesn't. If I uncheck the checkbox the added fields remain there as nothing has happened. Checking it again doesn't change anything.

The weird thing is that the div is there (at least Firefox inspector sees it) and the callback function is probably fired as well (the POST is send).

I have even tried to debug it using dsm() but it doesn't show any message (no idea why).

```
    function fm_users_more_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  $form['fm_first_in_firm'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show form.'),
    '#ajax' => array(
      'callback' => '_fm_ajax_new_firm_form',
      'wrapper' => 'firm-reg-container-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['firm_registration_container'] = array(
    '#type' => 'hidden',
    '#attributes' => array('id' => array('firm-reg-container-div')),
  );
}

function _fm_ajax_new_firm_form($form, &$form_state) {
  if ($form['fm_first_in_firm']['#value'] == 1) {
    dsm('tst1');

    ...

    $firm_form = drupal_get_form('fm_firm_node_form', $node);

    $form_wrapped = array(
      '#prefix' => '<div class="firm-reg-container-div">',
      '#suffix' => '</div>',
    );

    $form_wrapped['register_form'] = $firm_form;
    return $form_wrapped;
  }
  else {
    dsm('tst2');
    return array(
      '#type' => 'hidden',
      '#attributes' => array('id' => array('firm-reg-container-div')),
    );
  }
}

```

# Answer
> 3 votes
To show or hide some form elements you can use #states attribute.

```
$form['fm_first_in_firm'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show form.')
);

$form['firm_registration_container'] = array(
  '#type' => 'item',
  '#attributes' => array('id' => array('firm-reg-container-div')),
  // make this form item visible only if "fm_first_in_firm" is checked
  '#states' => array(
    'visible' => array(
      ':input[name="fm_first_in_firm"]' => array('checked' => TRUE)
    )
  )
);

```

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


# Question
Title: How to edit a profile field from the node add form
My client has a user field `field_geolocation` of type Geofield.

And he has a content type `issue`, he allows people to create new issues (kinda like in drupal.org but private).

**What he wants is:** When someone is creating a new issue, he should be able to to set/edit the field in his profile identified by `field_geolocation`.

**My guess:** create a custom module which does the following

* Inject a widget for the user field `field_geolocation` inside the node add/edit form, prbably with FAPI
* Use Node API to save the data collected previously into the actual user.

Did I guess right? Or any better solutions?

Thank you.

# Answer
> 2 votes
You're on the right track. It should be a pretty straight forward thing to implement.

I would add a custom submit handler to the node form for your issue content type. Grab the submitted values for the geolocation field. Load the user using `user_load()`, if the value has changed, the update it and call `user_save()`.

---
Tags: nodes, users, forms
---


# Question
Title: Can I get the Node's content type in hook_flag_alter
In the following code, I'm changing a flag with a short title of "Follow" to include the name of Content Type. Is it possible to add the content type so that I can not say Follow node but perhaps Follow Question, Follow Person, FOllow Group?

```
function hook_flag_alter(&$flag) {

    //node, taxonomy_term, user,  comment
    $extra_text_of_type = "";
    switch ($flag->content_type) {
      case 'node':
        $extra_text_of_type = "node";
        break;
      default:
    }

    $flag->flag_short = $flag->flag_short . ' ' . $extra_text_of_type;
  }

```

# Answer
If you're using flag 2.x with Drupal 7, then this should give you what you want.

```
function hook_flag_alter(&$flag) {
    $type_text = "";
    switch($flag->entity_type) {
      case 'node':
        switch(reset($flag->types)) {
          case 'page':
            $type_text = t('Page');
            break;
          case 'blog':
            $type_text = t('Blog Post');
            break;
          default:
            $type_text = t('Node');
        }
        break;
      case 'user':
        $type_text = ('User');
        break;
      default:
    }

    $flag->flag_short = t('Follow @type', array('@type' => $type_text));
    $flag->unflag_short = t('Unfollow @type', array('@type' => $type_text));
}

```

Note: This code assumes that each flag only applies for a single content type.
> 2 votes

---
Tags: flags, 7
---


# Question
Title: What are my pages called for adding blocks?
I've searched for an answer, but cant find one. On my site I'm building I have 6 or seven main links/pages called things like Home, About us, Contacts, local issues, etc.

I want to add blocks to these pages individually, and I'm told when adding blocks that:

*"Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. Example paths are blog for the blog page and blog/\* for every personal blog. (front) is the front page."\*

OK, so I can use 'front' (in tags) for my home page, and that worked - but what are the other pages called? What do i put in the box other than 'front' (in tags) to get a block on say my 'Contacts' page.

I am a real newbie, and still rather overwhelmed with Drupal, so please don't asume I understand much!

Thanks

# Answer
> 7 votes
Assuming that you want to show your block on your 'Contact' page.
Now, have a look at your 'Contact' page URL, for example it can be `http://example.com/?q=node/2` without pathauto module.
Now, lets create a block under that choose `Only the listed pages` then write `node/2` in the field!

Now, save block and it should work.

---
Tags: blocks
---


# Question
Title: What does 'dev' mean for a release of a module with 'x-dev' at the end of it?
What does 'dev' mean for a release of a module with 'x-dev' at the end of it?

Does it mean that the module is not stable?

As an example consider the FusionCharts module for Drupal 7: it is a development release with dev at the end. So is it stable or not?

# Answer
> 2 votes
Yes, that means it is not a stable release as per developer/community.

The best way to judge development snapshot release before enabling it on any site is to look into the *Maintenance status* and *Development status* fields, if you mean to test the module before starting to use it. Then go through the issue queue and see what kind of issues are going on, if they are serious, if they are getting addressed, etc.

When you finally decide to install it, test it for your site. If you find issues, report them in the issue queue, help in development as you can (*reporting an issue is also a big help*), give more details if the maintainers need more information.

Use it if it still suits your need.

---
Tags: 7
---


# Question
Title: a little clarification about contextual filter
When we say "Content: Has taxonomy term ID" or "Content: Nid", what do we mean by *content*? Is it the element which is being viewed currently or the element that is about to be fetched from view(output of view).

When "Content: Has taxonomy term ID" is added to a view, will it compare with the currently viewing node whether it has term id or compare with the view's data that is being fetched, whether it has taxonomy terms?

# Answer
> 0 votes
1) Content refers to Node in Views 3.x

2) Contextual filters are filters. That means that any filter you add here is a dynamic filter fetched from context (page path arguments, node data etc). So they are filtering all the results (views data if you prefer it).

A good idea is to enable the display of the database queries (admin/structure/views/settings) so you can inspect what are you doing with every views settings.

---
Tags: views
---


title: Theming a new Panel Page

text:
# Question
Title: Theming a new Panel Page
I think I am missing something really silly here. I am trying to learn theming in drupal. So I downloaded a "starter" theme called Genesis and installed it. This theme has a barebones header and footer. And in the middle the content area is split into left sidebar, main content and right sidebar.

I created a panel page with 'flexible' layout. It has only one region defined and inside it I placed a custom view I had created earlier. Now when I hit this panel page url, it shows up correctly, but inside the main content area of theme. I mean the header, footer, left and right sidebars are still visible.

My question is: By default do panel pages render inside main content area? How can I customize a panel page such that I can do away with the header, footer or sidebars if I want to?

Appreciate any help!!

# Answer
> 0 votes
> By default do panel pages render inside main content area?

No, Panels should 'takeover' the page based on your ctools page manager assignments.

See /admin/structure/pages to confirm you have the path set in page manager ("Pages").

# Answer
> 0 votes
> By default do panel pages render inside main content area?

Yes, panel pages are output in the main content region.

Also, there's an option to disable all blocks/regions in your theme under the General settings for your Panel variant. This feature doesn't work for all themes though.

---
Tags: panels, theming
---


# Question
Title: Read and write files from external FTP server
I'm looking for a way to add (S)FTP support to my Drupal Commerce website.

It's rather simple. Once every night, a cron job should get all the files from the (S)FTP, process them and place other files back on the server. That's it :)

It's a store and all the products, customers and other data come from a different system. So the Feeds module should connect to the FTP and process the files.
But it looks like there is no decent FTP module around. I've looked into the Backup and Migrate, Storage API, Order FTP Export and Save to FTP, but nothing really met my requirements.

So is there an easy way to connect to an (S)FTP server and exchange files?

# Answer
> 1 votes
I think you better face this problem using system commands that adding FTP support to the Drupal stack.

For this you can use:

1) standard FTP. You can read here how to automate FTP commands from a bash script: http://www.stratigery.com/scripting.ftp.html

2) SFTP, FTP over SSH. If you can use SSH public key authentication this is the best way as you only will have to exec this command every day:

`scp your-remote-user@your-remote-server:/path/to/files/* /local/dir/for/files`

Once your files are copied locally you only have to process them with Feeds.

You can even use PHP exec and launch the script that retrieves your data from the Drupal Cron.

---
Tags: 7, files
---


# Question
Title: A lot of core JavaScript files not being included
For some reason a bunch of core JS files are not being loaded. I've had to manually add them in with a module `hook_js_alter` function like so:

```
function MYMODULE_js_alter(&$js) {
    drupal_add_js('misc/jquery.js', array('group' => JS_LIBRARY, 'weight' => -100, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/jquery.once.js', array('group' => JS_LIBRARY, 'weight' => -99, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/jquery.cookie.js', array('group' => JS_LIBRARY, 'weight' => -98, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/form.js', array('weight' => 19, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/collapse.js', array('weight' => 20, 'every_page' => TRUE, 'scope' => 'header'));
}

```

The only core JS file loading by itself is `drupal.js`, and a bunch of module scripts. Other than that I had to include the 5 above myself, otherwise various parts of the public site and admin areas were not working.

This works, but it feels really sketchy. And previously I had only included the first 3, until I noticed more admin form stuff breaking. So I hate to think that there may be MORE scripts that I will only discover missing through trial and error.

Any ideas why they are not being included??

**UPDATE**

I've narrowed it down, there are two custom modules which are breaking it. One of them is much simpler than the other so I'll just try to figure that one out first. This line of code, inside the .module file, and not within any function, is causing the issue ($form\_js is a string containing JavaScript)

```
drupal_add_js($form_js, array('type' => 'inline', 'scope' => 'footer'));

```

# Answer
> 1 votes
I figured out that using `drupal_add_js` outside of a `hook_js_alter` function in another file was causing the issue.

```
drupal_add_js($form_js, array('type' => 'inline', 'scope' => 'footer'));

```

Now that it is within the function, it's working fine.

I don't see anything in the documentation saying that this is required -\> also, `drupal_add_css` works fine outside of a function. I'm not altering any existing JS files, only adding new ones.

So while I don't understand **why** this is an issue, this is the solution

---
Tags: 7, javascript
---


# Question
Title: Where can I find the link within admin for running the cleaner module, and how to install it?
I want to run 'Cleaner' (provided by the Cleaner module).

But when I go to `administer > site > configuration`, nothing related to Cleaner is listed.

I have searched Drupal.org, where I learned that this is this link is what I need. Maybe this information is out of date?

Any suggestions?

**Edit**: I am new to Drupal. Can you tell me, how I install the Cleaner module?

# Answer
The Cleaner module must be installed before you can use it.
> 1 votes

---
Tags: 6, installation
---


title: Future editable select list option?

text:
# Question
Title: Future editable select list option?
I am building a car directory with 500+ car models x 10 years. Every car listing will have many computed fields calculating various aspects of car model like fuel cost, maintenance, insurance, model depreciation, price after 5 year etc.

Now in depreciation computed field it takes the set value from depreciation rate field (which is different for every car) while adding the car. This Depreciation is region specific and I might have to change or tweak few values as we progress based on people feedback, updated research etc. I need some solution, with which i can change the depreciation rate field and republish the nodes to take effect the new values. In current select list option i can't change any value once that value is in use.

I have tried Views batch update (as a tweak), and that's my last option if I can't get this functionality somehow.

# Answer
Instead of using the list field type, I'd suggest you to use taxonomy and term reference field. That way you can always update the referenced term independently, add new terms, delete terms etc.

1. Create a vocabulary for the field, for example, depreciation
2. Add as many terms as you want to have in the select list
3. Add a new field in your content type, and as field type select *Term reference*; as widget select *Select list*
4. In the field options you should assign the newly created vocabulary (e.g. depreciation) to that field

**UPDATE:**

I assume that you have

* a content type called 'car'
* a vocabulary called 'model'

You should create a new vocabulary for each list field that you need to make future editable/expandable. If I understood correctly, you want to have the 'depraciation rate' editable, so you should create a new vocabulary called `depreciation_rate`

1. Go to admin/structure/taxonomy/add
2. Name it 'Depreciation Rate' or whatever you like
3. Add as many terms as you want to have in your 'select list' field. The terms will be listed as options in that field.

Then, you need to create a field to reference this vocabulary on the car content type if depreciation rate is different for every car (or on the model vocabulary if the depreciation rate is different for every model).

1. Go to admin/structure/types/manage/car/fields
2. Add new field, name it 'Depraciation Rate' with the machine name 'field\_depreciation\_name', or whatever you like.
3. As field type select 'Term reference' and as widget 'Select list'
4. On the field settings, assign the vocabulary you created.
> 2 votes

---
Tags: 7
---


title: Testing the path module

text:
# Question
Title: Testing the path module
Taxonomy terms on my site are saved with the proper path alias assigned to them but attempting to go to the corresponding page results in a "page not found" error.

The core path module includes a test file (path.test.) Does anyone know how to use it? Thanks. :)

I welcome any suggestion on how to fix that problem. :)

# Answer
> 1 votes
Running tests is fairly straight forward:

1. Enable the Testing module at /admin/modules
2. Visit /admin/config/development/testing and choose tests to run (you'll find Path, Path API and Pathauto)
3. Run them and wait for the results

If you have stable versions of core and the contrib modules it's a pretty safe bet that they'll pass.

---
Tags: path-aliases
---


# Question
Title: How to show one page over another in custom way
I need to show one page over another for non-admin users much like

overlay feature in Drupal7 applicable for admin users. I tried out

overlay module and overlay UI module but not of much help.

All the overlaying pages are custom created and will be invoked on

working page after clicking a link.

Please refer me a solution which should work across all browsers and I

can adjust width and height of overlaying page.I want to implement this

solution for pop up messages, warning and alert also.Please see below

image for reference:

Need your much appreciated help.

# Answer
> 1 votes
I think you are looking for Popup module or Lightbox

---
Tags: 7, routes, modal-dialogs
---


# Question
Title: Using views to display KML of each node in respective maps for each node
I have been using OpenLayers and Geofield to try display the custom data layer (KML polygon) on the. First of all I havent been successful at it despite trying out many mays. Also I realized that the views approach discussed almost everywhere would show the custom maps on a 'new' Page or a 'new' block. But what I want is to show the map with the KML data layer right at each node.

Is this ever possible using Views (Data layer) + Openlayer + geofield in first case?

If so, how do I configure the geofield's map which is displayed in each node?

# Answer
If I understand you correctly, your question is how to attach a view to a node. You can check out the EVA module:

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

or this other question: Attach a view to a specific node
> 0 votes

---
Tags: views, javascript, location
---


# Question
Title: menu_get_object() not returning node object when view's display is Entity Reference
I needed get field's value and pass it as contextual filter to "entity reference view" just described as views and contextual filters with entity reference field.

But `$Node = menu_get_object()` is not retuning node object.

The scenario

**Nodes Items of custom content type**

Title : Sony LCD
Tags : electronic

Title : The godfather
Tags :Books
.
.
Items(n)

**Node of custom content type *Review.* It's node id is 10**

Title : Make a Review
Filter Tags : Taxonomy terms reference (e.x electronic, books, movies etc)

**Attach a entityform to above node using entity reference and also back referenced with enityreference\_current**

My Review Item : EnityReference field - Entity reference view - Autocomplete widget
Review : text area

When node/10 is viewed, user will have to fill "my review item",but should be filter based on "Filter tags" that was already set.

Code inside VIEWS PHP under Contextual Filter

```
$node = menu_get_object ();
$ Related_ids = array ();
    $ Related = field_get_items ('node', $node, 'field_filter_tags') // Get the term reference field
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related [$i]['target_id'];
      }
    }
    return implode (',', $related_ids);//to perform AND

```

Update : I also tried with `$node= node_load(arg(1));` , this time $node variable set but not type of *node*. Then I `dpm(arg(1));` it shows string *autocomplete*(yes just *autocomplete* not string entered in field).

# Answer
> 1 votes
The entityreference autocomplete paths are defined in `entityreference_menu()` as:

* entityreference/autocomplete/single/%/%/%
* entityreference/autocomplete/tags/%/%/%

The wildcard arguments are field name, entity type and bundle respectively. The `entityreference_autocomplete_callback()` function also accepts an optional entity id and string parameter (the last being the search string).

So while you're expecting the path to be `node/[nid]`, it'll actually be one of the above - which explains why `arg(1)` is giving you the string `autocomplete`.

I haven't tried it but you should be able to use `arg(6)` to get the node ID in your current context.

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


# Question
Title: Autocomplete term widget (tagging) - Insert as child
Is there a way to insert taxonomy terms as child of a parent term with the auto complete term widget?

I have found several modules such as "Content Taxonomy" or "Hierarchical Term Reference Autocomplete", but couldn't find this specific feature.

# Answer
I have done some research on this as we use the Autocomplete Deluxe module for our client's sites. Unfortunately I see no preexisting solution and I think you will have to create your own.

This could be quite visually problematical. How do you display this in a auto complete field: Prefixed with all its parents? with a parent attribute type key?

I agree that this could be quite useful as this would eliminate the need to give a non-technical user admin access to taxonomy more and more. But I think this would be better achieved with a custom coded mix of Autocomplete Deluxe and Hierarchical select
> 0 votes

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


# Question
Title: Allow the node preprocess function to be called after setting the theme function in hook_node_view()
In `mymodule_node_view()`, I set the theme function to be used with the following code.

```
$node->content['#theme'] = "my_custom_theme_function";

```

Now the node preprocess function (`mymodule_preprocess_node()`) is not called anymore.

How do I let Drupal run my node preprocess function, even if I set my theme function to be used?

# Answer
> 0 votes
With that line, you set the theme function for all the content shown for the node. Your code should be similar to the following one, taken from the documentation for hook\_node\_view().

```
function mymodule_node_view($node, $view_mode, $langcode) {
  $node->content['mymodule_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_custom',
  );
}

```

As to why your code is setting the theme function for all the node content, see the code executed by node\_view(). (The comments are mine.)

```
  // This is the function that invokes hook_node_view().
  node_build_content($node, $view_mode, $langcode);

  $build = $node->content;

  // $node->content['#theme'], the value you set, becomes $build['#theme'].

  unset($node->content);

  // The following lines don't set anymore $build['#theme'], since you have already set it.
  // It is similar to executing the following code:
  //   $a = array('first' => "I am the first");
  //   $a += array('first' => "The array will never get this value");
  //
  // If you print the value of $a, you will see it is as it was first set.

  $build += array(
    '#theme' => 'node',
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // Now the code is going to use your theme function, which means that not even
  // the node preprocess function is executed.

```

Normally, what you want to do is adding a new content to the render array for the node. That is what the code I show in the first snippet does.

If you really wanted to change the theme function used for the node, then you should simply implement hook\_theme\_registry\_alter(), and redefine the function associated with the `node` theme function.

Keep in mind that once you change the used theme function, also the preprocess function changes; in your case, if `theme_my_custom_theme_function()` is your theme function, then the preprocess function is `mymodule_preprocess_my_custom_theme_function()`.

---
Tags: 7, theming
---


# Question
Title: How to theme simplenews unsubscribe page?
I'am trying to theme Unsubscribe Page for my Newsletter to much the Newsletter Design. Does anyone know how to theme unsubscribe page in Drupal 6:

example.com/newsletter/confirm/remove/\*

# Answer
> 1 votes
I am going to answer this just so that people that are looking for the answer will see it.

As @AgA said:

You can install the Themer Module, you will require the Devel Module. Enable these modules and go to the path that you would like to theme.

The Themer module will give you suggested naming conventions that you can use to override that page's theme.

In your case it was the content type newsletter, coming to the suggested name of page-newsletter.tpl.php but there will be more suggestions which you can use to override an already overridden more general tpl.

---
Tags: 6, theming, emails
---


# Question
Title: How to order a view by access control on files?
I have a view that displays a series of nodes in a blog format. Each node has a file attached to it. How do I make the nodes with files that the user has to login to see come last in the list?

I've been looking through the options available in Views and have come up short there. I was hoping I could create a relationship on the file, but I can't find any properties that relate to access control.

My other thought was that I could do this in a template, but I'm not sure if there is a template that will let me change the order of the rows in the view. Are those variables passed to the template by reference?

Many thanks.

# Answer
In views under the Advanced section when you select the Theme: Information link, you can select to override a specific field.

Choose the most appropriate naming convention as this will dictate the scope of your override. Copy the text given by views and copy this into a new file in your theme called the .tpl.php file name you chose.

Once there you can add a conditional statement before outputting your field with user\_access to check if your user has the right permissions to view the downloads.

You might have to specify the permission in your own module with hook\_permission.
> 0 votes

---
Tags: 7, views, files, users
---


# Question
Title: How can I show only first level terms on a dropdown taxonomy exposed filter?
I have a 2 level taxonomy tree: Countries and cities. I also have a view of content, all of which are marked by first level terms (countries) of that vocabulary.

My taxonomy tree is like that:

* Country 1
    + City 1
    + City 2
    + City 3
* Country 2
    + City 4
    + City 5

In an exposed filter over the view, I want to show only the first level terms (countries) as options. Is it possible?

# Answer
> 0 votes
This question is very similar to How Can I add a Hierarchical taxonomy Select in views filters and when editing content in Drupal 7

I will say that the easiest method I can see is to add an exposed field by the name of "Content: Has taxonomy terms (with depth)" this way you can select the vocabulary(unfortunately only one) and also select the depth.

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


# Question
Title: Taxonomy menu limited to certain number of terms
Wondering if anyone can steer me in the right direction on this. I'd like to have a taxonomy menu where I have a few main terms listed with with around 5-7 children terms. When the user is on the page of the main taxonomy term, all of the child terms are shown.

For example, when the user is on the home taxonomy page that lists all of the terms then the menu would show this:

```
-Term 1
--Term A
--Term B
--Term C
--Term D
<more>

-Term 2
--Term A
--Term B
--Term C
--Term D
<more>

```

Clicking on or clicking on the Term 1 page would then show all of the children of Term 1:

```
-Term 1
--Term A
--Term B
--Term C
--Term D
--Term E
--Term F
--Term G

-Term 2
--Term A
--Term B
--Term C
--Term D
<more>

```

Here is a link to a site that already does this and that is where I got the idea.

Any help would be much appreciated!!

# Answer
> 0 votes
I believe the easiest way to do this is to create a view that block displays a set number of items in a list (HTML or unformatted list), with a global text field that will link to your term page. You can then style this with css to look like the rest of your menus (if you require to).

This unfortunately will mean that it will not go through the drupal core menu system. You will have to create your own "Admin" view to manage this "menu". I would suggest Draggable Views if you require a webmaster to control the sort order.

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


title: secondary navigation per page

text:
# Question
Title: secondary navigation per page
I created a secondary navigation that I display with $secondary\_menu in page.tpl.php. It seems to work fine, however, it displays on every page now and I of course don't want that, it should only show on a specific page (where I have a secondary navigation). Now in order to achieve this, am I creating a special page template for the page where I want to show the links or can I somehow set on which pages my secondary navigation should show up?

Thanks!

# Answer
Your secondary menu will be available as a block.

Go to `/admin/structure/block`, place the block in the page region you wish to use, and set it to display only on the pages you wish to have it on.

This is much easier than trying to set up specialized templates.
> 1 votes

---
Tags: theming, navigation
---


title: memory available to drush

text:
# Question
Title: memory available to drush
If one allocates additional memory to drush in drushrc.php or drush.ini (am I correct that these are potentially valid options on a shared server?), is there a way to confirm that this amount is actually allocated when running drush?

# Answer
Try:

```
$ drush ev 'print ini_get("memory_limit");'

```

This should print the memory\_limit value set for Drush. -1 means no limit.
> 4 votes

---
Tags: drush
---


# Question
Title: Why adding '--create-db' to sql-sync command throws the access denied?
The following command works without a problem:

```
drush sql-sync @alias1 @alias2

```

If I add "--create-db" I get:

```
ERROR 1044 (42000) at line 1: Access denied for user

```

Why might I be getting this error and what might I need to change? Do I need to add additional details to my alias file?

Also, is it correct that this is the best way to make sure that there aren't tables left over in `@alias2` that have been removed from `@alias1`?

# Answer
Try:

```
drush sql-sync @alias1 @alias2 --create-db --db-su=adminuser --db-su-pw=password

```

Substitute the appropriate username and password for your mysql admin user. Note that if @alias2 is a remote alias on a shared server, it is possible that other users on that same server might be able to observe your mysql credentials if you use this command. You might therefore prefer to use `drush @alias2 sql-drop` prior to sql-sync as an alternative method to dump your sql tables.

Of course, most of the time the remote alias will be the production db, and typically you will only sql-sync from production to dev, not the other way around, so the credentials leak is not usually a problem.
> 1 votes

---
Tags: database, drush
---


# Question
Title: How should I insert a row into a database table created by another module?
I'm attempting to insert a row into a table created by another module. This module was enabled in a previous `hook_update_N()`; I want to insert a row into the table with another `hook_update_N()` or the same one. Using two `hook_update_N()` works when the updates are ran at different times but if both updates are ran at once the second update fails because the table does not yet exist. I have tried using `sleep()` but that seems problematic.

```
/**
 * Enable commerce fees
 */
function mymodule_update_7004($node) {
  module_enable(array('commerce_fees'));
}

/**
 * create compliance fee
 */
function mymodule_update_7005($node) {
  // wait for commerce_fee table to be created
  sleep(10);
  if (db_table_exists('commerce_fees') == TRUE) {
      db_insert('commerce_fees')
    ->fields(array(
      'name' => 'non_compliance_fee',
      'title' => 'Non-compliance Fee',
      'display_title' => 'Refundable Non-compliance Fee',
      'description' => '',
    ))
    ->execute();

    // Clear the necessary caches and rebuild the menu items.
    commerce_fees_reset();
    entity_defaults_rebuild();
    menu_rebuild();
  }

  else {
    drupal_set_message('table commerce_fees does not exist');
  }
}

```

# Answer
> 2 votes
I recommend using DrupalUpdateException to make update 7005 fail if the table doesn't exist so that it can be ran again when the table has been added, or at least notify the web builder that the table doesn't exist and needs to be worked on.

# Answer
> 1 votes
Here is the working code after adding DrupalUpdateException.

```
/**
 * Enable commerce fees
 */
function my_module_update_7004($node) {
  module_enable(array('commerce_fees'));
}

/**
 * create compliance fee
 */
function my_module_update_7005($node) {

  if (!module_enable(array('commerce_fees'))) {
    throw new DrupalUpdateException('This version of My Module requires commerce fees module, but it could not be enabled.');
  }
  if (db_table_exists('commerce_fees') == TRUE) {
      db_insert('commerce_fees')
    ->fields(array(
      'name' => 'non_compliance_fee',
      'title' => 'Non-compliance Fee',
      'display_title' => 'Refundable Non-compliance Fee',
      'description' => '',
    ))
    ->execute();

    // Clear the necessary caches and rebuild the menu items.
    commerce_fees_reset();
    entity_defaults_rebuild();
    menu_rebuild();
  }

  else {
    DrupalUpdateException('The table commerce_fees does not exist');
  }
}

```

# Answer
> 0 votes
You can use hook\_update\_dependencies to ensure the correct update sequence.

---
Tags: 7, updating
---


title: XML Feed invalid in drupal 7

text:
# Question
Title: XML Feed invalid in drupal 7
Am trying to create xml feed through views feed generation to get the node content values. I have mapped the fields and i am getting the feed also, but a single space while generating feed in front of the xml feed. i.e before tag `"<?xml"` I am getting one single space. So that my feed page it's showing white space in Firefox and I can find the space in chrome browser. Is there config issue will be there or any thing else? Can anyone give me solution for this?

# Answer
> 0 votes
I wrote a detailed description about this problem and a possible debugging solution here: https://drupal.org/node/1275042#comment-7814971

In my case, Views Slideshow was problematic, I just created a tiny patch for that: https://drupal.org/node/2078689#comment-7815015

---

For convenience, I'm copying my post linked above:

> As **merlinofchaos** said, this really has nothing to do with Views. The "fix" in #6 is NOT actually a fix...
>
> In my case, I had two whitespaces in front of the `<?xml` tag, so the RSS feed started like this: " `<?xml`". I never thought I will find the source of the problem with such an ugly solution, but this is quick and works - it's really dirty, so use it only on a local development copy, do NOT test it on a production site: https://drupal.org/node/175137#comment-1526410
> in `includes/module.inc` file, in the `module_load_all()` function, after the `drupal_load('module', $module);`, **soyarma** suggests you to put in the following line temporarily: `print $module.'|';` This way you'll get a list of your modules in the beginning of the output separated by the pipe (`|`) character. When there are unnecessary whitespaces before the module's name and the pipe character, then you just found the buggy module.
>
> For example, in my case, **Views Slideshow was the source of the problem**:
> `views_bulk_operations|views_content| views_slideshow|views_slideshow_cycle` (this is just the end of the huge list)
>
> As you can see, there are two spaces before `views_slideshow`. This is where I should start searching for the source of the problem. I found it in `views_slideshow/theme/views_slideshow.theme.inc`: the code starts with two whitespaces, and the PHP block is just after that: " `<?php`" You can also see it here:
> http://drupalcode.org/project/views\_slideshow.git/blob/d9fd60c20add43a7b...
>
> And YESSS, after deleting the two spaces, http://validator.w3.org/ congratulated me that my RSS feed is valid. Thank you, **soyarma**!
>
> Don't forget to revert the changes in `module.inc` (**don't ever hurt the core's code! :)** ), and delete the `print $module.'|';` line.
>
> I'll report an issue to the Views Slideshow's queue, and I hope that this helped someone.
>
> ====
> EDIT:
> I reported the bug to the issue queue, and also created a patch, see #2078689: Unnecessary two whitespaces before the PHP code block in views\_slideshow.theme.inc, which can cause RSS feeds to get invalid.

---
Tags: views, feeds
---


# Question
Title: Could drush require significantly more memory than same action in Drupal
I am running Drupal 7.23 and drush 5.9

I can clear all caches in Drupal without an error but get "memory exhausted" if I try using drush cc all. I get "memory exhausted" when using "drush up", after it has downloaded and updated modules but was able to download and update the modules from within Drupal.

Is there anything that might be leading to a greater need for memory when using drush?

# Answer
> 4 votes
Probably not - but remember that in PHP 5, the command line or client interface for PHP was separated out and has its own ini file. if you search for your php.ini file, you'll probably see two versions, something like this

```
/etc/php5/cli/php.ini
/etc/php5/apache/php.ini

```

and you just need to match the memory limit in the (cli)ent ini file with what you have for Apache (or your web server).

---
Tags: drush
---


title: drush error - how to apply patch?

text:
# Question
Title: drush error - how to apply patch?
When I try to update modules or clear cache with drush on my local dev machine (Mac OSX) I get the following four times at the beginning of the command result, and it fails.

> Invalid argument supplied for foreach() pm.drush.inc:584

My sites are D7, and the drush version is 6.0-beta1. I can't find what the latest version is anywhere. Is this it?

I looked on drupal.org and found a patch here: https://drupal.org/node/2041875

But I don't know how to apply a patch to drush. Can anyone point me to that information or tell me how to do it?

# Answer
Drupal has a wealth of community documentation related to this:

However, for your first problem. Drush is pretty much version independant. If you have the latest version of drush it will work with drupal 7, 8 and most likely 6.

Finally, the issue you linked also mention that it's been fixed in the latest version of drush as well.
> 2 votes

# Answer
The latest version of Drush is 6.0.0. Drush has moved to GitHub, so you will need to look for releases there now. The Drush project on GitHub is https://github.com/drush-ops/drush

Ass chrisjlee said, you won't need to apply the patch you mention above to Drush, as that issue has already been fixed in 6.0.0. If you'd like help applying patches in the future, though, you might want to try the drush\_iq project. This is a Drush extension that provides useful commands such as `drush iq-apply-patch` and `drush iq-submit`. Makes applying and submitting patches much easier.
> 1 votes

---
Tags: 7, drush
---


# Question
Title: How to create dynamic drupal 7 taxonomy views
I have to create 1 view using taxonomy.

Let's take the example i have 8 categories: cricket, football, tennis, swimming.

I have to show this each category with their 5 latest articles.

Thew views should display database like

1. Cricket

1. List item
    2. List item
2. Football

1. List item
    2. List item

Like this all 8 categories with grid layout and 4 categories in row.

Right now what i am doing is creating 8 different views and showing on 1 page.

But this create issue when i am adding new category.

So it's dynamic view can help or i have to write code for this.

# Answer
> 1 votes
This is fairly simple in Drupal 7 with the help of EVA: Entity Views Attachment. You are able to then create only two(2) views.

The first view will render all your categories you have in taxonomy as well as calling in the second view into a field of this view.

Your second view will then display the entities associated with the taxonomy term, You will have to create a Term reference in your content types in order to have a field in your entity view to check against.

I have previously done this where there are categories or terms displayed with a list of entities below them, all displayed in a grid view. See Example below.

---
Tags: 7, views
---


# Question
Title: Drupal Commerce products sales limited by date
I'm building a foodhub site using Commerce. A foodhub works by having a collection day every week, so sales of products need to be attached to one of the collection days, such that what the consumer bought will be available on the day they selected (typically the next upcoming day). At a certain time, e.g. 24 hours before, sales for the next collection day should be disabled.

I am wondering how I can approach this using Commerce, or a with a Commerce extension.

I'm thinking one approach would be to create a "collection day" content type that would show all the products that have been purchased and added to that day. A number of collection day nodes could be created defining upcoming days. A field on a product would show which collection day it will be added to. This would show the next upcoming day but can be changed (I need to figure this part out).

Is this a good approach, or is there a better way to tackle this problem?

# Answer
> 0 votes
What you can certainly do is proceed as you've outlined it and then create a view of all products that don't have their collection day within the next 24 hours. This will display all the products that can be bought in time for your collection preparations.

Approach 2: Set up a rule that checks after an order has been saved or before payment is done whether there is any product that has its collection day within the next 24 hours and if so, display an error message and set the number of these products in the cart to 0.

Approach 3: Set up a rule that runs periodically (say every day) and loops through all the products and disables those that have their collection day within the next 24 hours.

If you want more detailed information on how to achieve any of these, comment.

---
Tags: nodes, commerce
---


# Question
Title: How to you add a table of contents in a pdf for a book that is exported using views_pdf?
I am using the book module in Drupal 7 and have successfully exported the whole book as a pdf using views\_pdf. However, I would like to add a table of contents on the first page to list all the node/page headers that are in the pdf. It would be nice if the table of contents could then link to each of the page titles in the pdf, but this is not absolutely necessary. Does anyone know how to do this?

I've looked at the code for views\_pdf\_template.php and think it can be modified to keep track of all the page headers and associated numbers, and then render it in the close() function. But I'm not sure if this is the right way to do it. Does anyone have any ideas? Or has done this before?

Thanks in advance.

# Answer
You could write a new view that only contains the table of contents (no idea how hacky this is) and include it into your PDF view as a header. (Header -\> Add -\> Global -\> View)
> 1 votes

---
Tags: files, nodes, views
---


# Question
Title: Unable to change the html of views field using theming preprocess function
Basically 1. I am trying to edit a view.
--\> For that I have copied the views-view.tpl.php file from the **views** module's theme folder
and placed it into my custom templates folder present inside theme folder.

--\> Also I have renamed the file views-view.tpl.php file to views-view-\[VIEW\_NAME\].tpl.php where \[VIEW\_NAME\] is just placeholder for actual view name.
--\> After this I have cleared the caches.
--\> Now In my custom theme function I have a template.php file.
--\> In that template.php file, I am using \[THEME\_NAME\]*preprocess*\[VIEW\_NAME\] function that is my\_theme\_preprocess\_view\_name(&$vars) function When I check the vars object I have found the following place where I need to put the html
for the field's html to change which is as follows :

```
$vars['view']->result[$key]->field_name[0]['rendered']['#markup']

```

**which contains the html of the field I want to alter** .So Using this vars variable I inserted the html as follows :
`$vars['view']->result[$key]->field_name[0]['rendered']['#markup'] = $html;` Where html is the variable which contains the altered html value for the field .
--\> After this I again clear the caches. --\>But the still the html value of the field does not change.
Can you please help me out on this ...
I tried doing this using hook\_views\_pre\_render(&$vars) inside a custom module. It works
there but I wanted all the code inside the template.php file as I have read that
hook\_views\_pre\_render() is not the proper way to alter the field value.

# Answer
Views are complex in the way they render.

The best thing to do is override things at the right level.

If you want to override things at the view level, for example the title of your view, you would use views-view.tpl.php; if you want to override something at the row level, you might use views-view-fields.tpl.php; if you want to override an individual field, you would likely use views-view-field.tpl.php.

Basically, if you look in the views-view.tpl.php file, you will see that individual fields are not being printed, which indicates that this is probably not the place to override that.

In your case try using views-view-field.tpl.php.

Check out the "Theme: Information" section of your view edit screen for suggestions on what to name your file along the lines of views-view-field--view-name--field-name.tpl.php

As for whether or not it should be in the theme or in a module, a good question to ask is: If I change themes, would I want this same change in the new theme? If so, it is more functional and probably should go in a module; if the answer is no, it probably should go in the theme as it is specific to that theme.

That's good as a basic guide, anyway; sometimes there are exceptions to rules.
> 3 votes

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