# Question
Title: What does exacly mean by Entity CRUD API?
Here in the documentation comment for `entity_export()` says:

> Note: Currently, this only works for entity types provided with the entity CRUD API.

So, what does it actually mean?

**Background info:** We are going to create two modules. One for defining an entity type using `hook_entity_info()` and other providing UI for adding, editing, managing etc. There will be two drupal 7 installations. One will be installed with both of above modules and other only with first module defining entity type.

On first drupal installation, we will be creating/editing entities of type what we defined. And exported to second installation. So, we are checking for the capabilities of `entity_export()` and `entity_import()` functions for integration of entity export/import functionality.

# Answer
> 2 votes
The CRUD API is the set of functions that allows an entity to be Created, Readed, Updated and Deleted.

An entity has a CRUD API when its entity controller implementes de EntityAPIControllerInterface. The EntityAPIController class, the default Entity API entity controller class implements this interface.

So you only have to define your entity using the Entity API contrib module and use that class as controller (or your custom subclass of that class).

If you read the entity\_export code you can see:

```
 if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
    return entity_get_controller($entity_type)->export($entity, $prefix);
  }

```

The function checks if the entity controller implements EntityAPIControllerInterface interface; if yes the export method is called.

---
Tags: 7, entities, importing-exporting
---


# Question
Title: Checking for an empty entity reference field in hook_node_validate
In checking whether a form field contains an entry, it has been typical to do something like:

```
if (sizeof($form_state['values']['my_field'][LANGUAGE_NONE]) > 0)

```

because an empty field would still be an array, but an empty one. With entity reference fields, an empty field looks like:

```
$form_state
  values
    my_field
      und
        0
          target_id=''
          add_entityconnect_my_field_0_ = "New content"
          edit_entityconnect_my_field_0_ = "Edit content"

```

so that testing for the empty array fails. One could check to see if the target\_id is empty, but I'm wondering if there's a way to test the form field for empty without needing to go down to that level.

# Answer
> 1 votes
Take a look at entityreference\_field\_is\_empty(), which at least will get you up a level by checking if target\_id is empty on your behalf.

---
Tags: 7, forms, entities
---


# Question
Title: How do i disable price, shipping and payment in ubercart
I need to set up a "shopping cart" to allow users to collect URLs from my local database. All my products are free. Based on which URLs are in the users "basket" I fetch files and pack them in a tar file and send the user a URL where the tar file can be downloaded.

How can I turn off or hide price, payment and shipping in ubercart?

# Answer
You can use UC Price Visibility Module.

> Often, you want to advertise your products without revealing the prices, and show something like, "contact us for pricing." This Ubercart module allows you to show or hide product pricing per role, on a product-by-product basis. You can configure what message should be shown when the price is hidden, and which field should be replaced with this message (either the display price, sell price, or add to cart button).
> 0 votes

---
Tags: ubercart
---


title: How to use set_items_per_page?

text:
# Question
Title: How to use set_items_per_page?
**Background**

I'm having a go at porting the JavaScript random views module from 6 to 7.

**Problem**

One of functions I think is intended to override the default pager value to load extra rows per page. (i.e. pager says load 8. This overrides it and says load 20).

To accomplish this it uses hook\_views\_pre\_execute

```
function views_javascript_random_views_pre_execute(&$view) {
  .....

  // Here it saves the current settings of the pager for use later
  .....

  // Set new settings
  $view->set_items_per_page($sorts['js_random']['client_node_count']);
}

```

Unfortunately the `set_items_per_page` function doesn't seem to work. While it still sets:

`$view->items_per_page`

This then seems to have no effect on how many rows are then loaded in:

```
function views_javascript_random_preprocess (&$vars, $hook) {
   ....
   dpm($vars);
}

```

In `$vars->rows`, it still only loads the number of rows set by the pager (i.e. 8 not 20)

The API function definitely still works in 7. Could someone explain why it's not working correctly in this case?

# Answer
> 2 votes
I have successfully used `$view->set_items_per_page()` in `hook_views_pre_build()`. The problem might be that in `hook_views_pre_execute()` the pager settings have already been built, so you might have to update those as well, with something like `$view->display_handler->get_plugin('pager')->get_items_per_page()`.

# Answer
> 1 votes
I couldn't get `hook_views_pre_build()` to work as for some reason the hook wasn't being called, but did get it working by slicing the `result` array in `hook_views_pre_render()`:

```
/**
 * Implements hook_views_pre_render()
 */
function MYTHEME_views_pre_render(&$view)
{
  if ($view->name == 'MY_VIEW' && $view->current_display == 'MY_PAGE') {
    // Keep only first item
    $view->result = array_slice($view->result, 0, 1);
  }
}

```

---
Tags: 7, views
---


# Question
Title: Make visible the article in Draft and Needs Review mode to other members of the community group
I am facing a permission issue, I found not yet a resolution. I am using Workbench, Workbench Moderation and Organic Groups.

User1 creates a content in a community (organic groups) Then he creates content setting its moderation mode to: Draft

Now User2 ask permission to join group, but he is unable to see the above article until is set to Published mode.

How can they share the article set in Draft mode?

# Answer
> 0 votes
Is the below permissions checked from permission tab ? If it's not then set the below permissions:

Workbench Moderation:

1. View all unpublished content
2. View the moderation messages on a node
3. View moderation history
4. Use "My Drafts" workbench tab
5. Use "Needs Review" workbench tab

Also let me know which version of workbench moderation module you are using .

---
Tags: organic-groups, workbench
---


# Question
Title: How do I access a function provided by a service resource module?
Just getting started with Services so this is probably an easy question.

I'm attempting to allow users to access their private messages from a web app using this sandbox module. At this point, after referring to the documentation on testing resources, I can get a JSON collection of the messages when I visit **http://example.com/drupalgap/privatemsg**, and I can get a specific thread if I visit **http://example.com/drupalgap/privatemsg/threadID**.

I understand the basic syntax is example.com + endpoint (drupalgap) + resource (privatemsg) + query.

However, the sandbox module includes a function for getting the number of unread messages, which I would like to do. Here's the code:

```
 /**
 * Get the number of unread private messages of the logged-in user.
 *
 * @param int $uid
 *      User ID.
 *
 * @return int
 *   The unread count.
 */
function _privatemsg_services_unread_count($uid = '') {
  global $user;

  if (!user_is_logged_in()) {
    return services_error(t('This user is not logged in.'), 403);
  }

  /*
   * If a user id other than the current user's ID is passed, validate that the
   * authenticated user has the correct permissions to read another user's
   * messages.
   */
  if (is_numeric($uid) && ($uid != $user->uid)) {
    if (user_access("read all private messages")) {
      $account = user_load($uid);
    }
    else {
      return services_error(
        t('This user does not have permissions to use this service.'),
        403
      );
    }
  }
  else {
    $account = $user;
  }

  // Return unread count.
  return privatemsg_unread_count($account);
}

```

My question is, how do I call this with services? I've tried things like **http://example.com/drupalgap/privatemsg/unread\_count/** and **http://example.com/drupalgap/privatemsg\_unread\_count** but I get no results.

# Answer
Functions are exposed via service resources, by a module implementing `hook_services_resources()`.

You should take a look at whatever module your using to provide Services functionality for the private message module, specifically its implementation of `hook_services_resources()`.

If you see an entry with a callback of `_privatemsg_services_unread_count`, then the function you want is available via a resource. If not, it currently isn't, and you can implement `hook_services_resources()` yourself to expose it.
> 1 votes

---
Tags: services
---


# Question
Title: How does 'access content' permission string works?
I've written a question and gotten an answer. The is fine but not fulfill my requirements. The question is below:

It will be helpful, if anyone explain the full meaning of the string 'access content' because I've not found 'access content' string on '/admin/people/permissions' page. On the other hand, if I use following code, it will be work.

```
function custom_menu_menu(){
    $items = array();
      $items ['status'] = array(
        'title' => 'My Status',
        'menu_name' => 'main_menu',
        'page callback' => 'status_page',
        'access arguments' => array('access content'),
      );
    return $items;
}

/*
  *Definition of the menu callback function.
  */
function status_page() {
    return 'Hello world!';
}

```

My Questions:

1. Is 'access content' a 'permission string'? if answer is 'yes' then please explain how does it works? \[note: it is not listed in '/admin/people/permissions' page. So, How determinate that user's rules has this permission\]
2. **What is the meaning of 'access content' permission?** example: 'Page: Create new content' permission means if user has this permission then user can create 'Page' content but if user has 'access content' permission then what can do user on this link page.

# Answer
Read: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7

1. 'access content' means 'Node: View published content' on permission list. Check this link for list of permissions provided by node module: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_permission/7
2. 'access content' will be passed as a first argument to `user_access()` which is default `access callback` for new menu items. You can change default access callback like this:

```
function custom_menu_menu(){
  $items = array();
  $items ['status'] = array(
    'title' => 'My Status',
    'menu_name' => 'main_menu'
    'page callback' => 'status_page',
    'access callback' => 'custom_menu_access_callback',
    'access arguments' => array('access content', 'something else'),
  );
  return $items;
}

function custom_menu_access_callback($arg1, $arg2) {
  // arg1: access content
  // arg2: something else
  // if this function returns TRUE user will get access to page callback
  // if this function returns FALSE user won't get access to page callback
}

```
> 4 votes

---
Tags: users
---


# Question
Title: Search all content fields with "find content" module instead of title
I want to search all fields instead of the title only.

Right now I'm using the "find content" module. Tried to find another one which is similar but am not able to find.

# Answer
> 0 votes
Your best option is to use the Administration views module and edit the view to suit your needs. Edit the view with an exposed search filter.

Replaces administrative overview/listing pages with actual views for superior usability.

Features

> Filter all administrative views via AJAX. Perform any kind of bulk/mass operations on items in administrative views. Filter content by title, node type, author, published status, and/or vocabulary. Filter comments by title, author, node title, or published status. Filter users by name, ban/blocked status, or user roles. \*Note: If you are upgrading from an older version of Administration views and the default views have been overridden (saved in the database) you could encounter issues or not see any new changes unless you revert these views, so the default in-code views are used. This can be done in the views UI listing or using drush (drush cter views\_view --module=admin\_views)

---
Tags: search
---


title: Unset search after leaving page

text:
# Question
Title: Unset search after leaving page
In my drupal admin content page when I search for something it keeps displaying the searched items.

Even when I leave the page and go back it is still displaying items from the search querie

When I press the Clear button the results are normal again. How can I fix this when I leave the content page that it automatically clears the search results?

Thanks in advance!

# Answer
> 1 votes
on line 41 in the find\_content.module the default value gets filled in.. you could comment this out.

# Answer
> 1 votes
If you are using Admin Views you can edit the view and change the exposed filters and uncheck "remember the last selection".

A screenshot to illustrate this for the content:title field:

---
Tags: search
---


# Question
Title: Form select type: setting default based on options' value
So I've got this form:

```
$form['color'] = array(
        '#type' => 'select',
        '#title' => t('Kleur'),
        '#options' => array(
            0 => t('Wit'),
            1 => t('Geel'),
            2 => t('Groen'),
            3 => t('Rood'),
        ),
        '#default_value' => 'Rood',
  );

```

As expected, this doesn't currently set the default value to 'Rood'. How would I get it so that the default value can be accessed by it's value?

Note that this example shows the string 'Rood', but in practice it would be a variable string that is pulled from the database.

Thanks in advance!

# Answer
> 2 votes
Default value should point to key, not a value.

In your example, default\_value should be as in below.

```
'#default_value' => 3,

```

Hope below link will help you.

https://www.drupal.org/node/240783#comment-1794710

# Answer
> 0 votes
I think you should probably use for loop to do this. Like:

```
// options is a array variable contains the data as
// options[0] = "Wit"
// options[1] = "Geel"
// options[2] = "Groen"
// options[3] = "Rood"

$string = ""; // $string will come from database that you want to be default.
for($i = 0; $i < strlen(options); $i++){
  if(options[$i] == $string){
    $catch_key = $i;
  }
}

```

and then at form field creation time

```
'#default_value' => $catch_key,

```

---
Tags: forms
---


# Question
Title: How to adding our own sorting to a view on Drupal?
I have develop a drupal view with table format.

* Here table rows are **Name** and **Date**.
* I am sorting a **Name** column with default sorting in views,it's working fine.
* But when user click on views page automatically views page redirected to default sorting in views.
* Here problem is when user click on sorting with (asc/desc) that order permanently store in database.

how can we achieve this.

# Answer
You could alter your view query with hook\_views\_query\_alter to add your custom sorting.

```
<?php
/**
 * Implementation of hook_views_query_alter
 * @param type $view
 * @param type $query
 */
function mymodule_views_query_alter(&$view, &$query) {

  //simple example: change the order of the master display
  //if you want to do it only  on a certain display add something
  // like  "&&$view->current_display == 'panel_page_1'"
  if ($view->name == 'VIEWNAME') {

    //to find out what the fieldname ist: use devel and add your desired field as
    //first filter ( =>orderby[0]). install devel and uncomment the next line
    //dpm($view->query->orderby)

    $view->query->orderby[0]['field'] = "CASE FIELD_NAME WHEN 'apple' THEN 1 WHEN 'zebra' THEN 2 WHEN 'banna' THEN 3 ELSE 4 END";
  }
}
?>

```
> 0 votes

---
Tags: views
---


# Question
Title: Share one back office (database) over three drupal websites
I'm wondering if there is a way to have one back office for three drupal websites with different domaine names, so I can share users over the three websites, I think I'm gonna have one database for all my drupal websites, but I'm not sure how I can achieve this using drupal.

# Answer
> 1 votes
Teeyo,

You can do this with the domains module that can be found here: https://www.drupal.org/project/domain

The installation instructions can be found here: https://www.drupal.org/node/477372

Don't forget to edit your settings.php file ;-)

I used the module myself a couple of times, so if you need any assistance, just let me know :-)

---
Tags: database
---


title: Programmatically get a form in Drupal 8

text:
# Question
Title: Programmatically get a form in Drupal 8
The documentation states:

> The argument passed to the getForm() method is the name of the class that defines your form and is an implementation of \Drupal\Core\Form\FormBuilderInterface.

How do I find out the name of the class that defines the *website feedback form* provided by the core *contact* module (the form id is: `feedback_contact_message_form`).

When I `dpm()` the form I can see that there is a class defined:

```
$input array(30)
  →'#attributes' => array(1)
    →'class' => array(3)
      string(29) "feedback-contact-message-form"
      string(20) "contact-message-form"
      string(12) "contact-form"

```

I tried various forms of this as the parameter to pass to:

```
\Drupal::formBuilder()->getForm();

```

but no luck. Thanks

# Answer
> 13 votes
This renders within a block plugin:

```
class myModule extends BlockBase {
  public function build() {

    $default_form = \Drupal::config('contact.settings')->get('default_form');
    $entity = \Drupal::entityManager()->getStorage('contact_form')->load($default_form);

    $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $entity->id(),
      ));

    $form = \Drupal::service('entity.form_builder')->getForm($message);

    return $form;
  }
}

```

---
Tags: 8
---


# Question
Title: How do I enable authenticated users to be able to add ubercart products?
I’m new to drupal, so I apologize if my questions are too basic

Any help would be appreciated

I’m using drupal 7 with Ubercart version 7.x-3.8

With Ubercart Auction module version 7.x-1.x-dev

I’m trying to create a car auctioning website, where users can place a car up for auction and other users can bid on it.

How do I enable authenticated users to be able to add ubercart products?

# Answer
> 0 votes
Ubercart products are nodes, so access is controlled in the normal way:

Visit the permissions page, and assign whatever roles make sense to the "create", "edit", etc permissions for the relevant product content type.

---
Tags: 7, ubercart
---


title: How to programmatically take a quiz?

text:
# Question
Title: How to programmatically take a quiz?
I need to programmatically make some users take an existing quiz. The quiz has only one question, which is a long answer one, and I have the text needed to fill it. I just can't find any function in the Quiz module that I can call to submit the answer. Is it possible?

# Answer
I found a way to solve that:

```
// Load user who will take the quiz
$account = user_load($quiz_taker_uid);
// Load quiz and question nodes
$quiz = node_load($quiz_nid);
$question = node_load($question_nid);
// Create a new result id
db_query("INSERT INTO {quiz_node_results} (nid, vid, uid, time_start) VALUES (%d, %d, %d, %d)", $quiz->nid, $quiz->vid, $account->uid, time());
$rid = db_last_insert_id('quiz_node_results', 'result_id');
// Submit the answer
$result = quiz_question_evaluate_question($question, $rid, $long_answer_text);
quiz_store_question_result($quiz, $result, array('set_msg' => FALSE));
// Finish the scoring and properly invoke hooks
$score = quiz_end_scoring($quiz, $rid);
quiz_end_actions($quiz, $rid, $score);

```
> 2 votes

# Answer
It is also possible to do this using Selenium or Behat (defining the steps to click).
> 1 votes

---
Tags: quiz
---


# Question
Title: Add html to taxonomy_menu_block taxonomy terms
I am trying to edit the html of the taxonomy terms printed from the module taxonomy menu block.

Is there a way to add a theme wrapper or to override a template so I can add html to each and every taxonomy term?

# Answer
Looking at this module it does not employ a theme template file so overriding with your own template file is not a possibility; therefore, you will need to use Drupals theming later and processing hooks in your theme to alter the HTML output of the module without hacking the module. A start would be to look at hook\_block\_view\_alter
> 0 votes

---
Tags: routes, taxonomy-terms
---


# Question
Title: How to translate admin interface in Drupal Commerce Kickstart?
I have translated my site in Japanese. But it is not translating all the content. I want to translate all the strings available on the site, including admin panel.

I searched for the string in the translate interface, but I couldn't find it. I used Translation template extractor to search the strings. But this thing also didn't help me.

Please tell me how to change the admin side text?

Here's the image showing what kind of strings I want to change :

# Answer
I did a search on my computer, I found product.html which contains the text you were looking for:

```
  <header id="header">
<h1>Help on products</h1>
<p>Each product has both a display and can have many variations (size, color, etc). This page lists all of the products grouped by display.</p>

```

```
<p>To see the variations of a product, click on â€œQuick Edit.â€ Using bulk updates (located at the bottom of the page) more than one product can have various actions applied.</p>

<h2>More Information</h2>

<ul>
  <li><a href="http://www.drupalcommerce.org/commerce-kickstart-2/product-management-overview">Product Management Overview</a></li>
  <li><a href="http://www.drupalcommerce.org/commerce-kickstart-2/choosing-between-page-or-variation">Choosing between Products and Product Variations</a></li>
  <li><a href="http://www.drupalcommerce.org/commerce-kickstart-2/adding-new-product">Adding a New Product</a></li>
  <li><a href="http://www.drupalcommerce.org/user-guide/product-attributes-variations">What are Product attributes and variations?</a></li>
  <li><a href="http://www.drupalcommerce.org/user-guide/product-displays">What are Product Node Displays?</a></li>
</ul>

```
> 0 votes

---
Tags: i18n-l10n, commerce
---


# Question
Title: What is the proper way to set up Drupal 7 on load balanced servers so that CSS and JS files are in sync?
We're moving our website to new Cloud Load Balanced servers on Rackspace. It's all a bit of a new experience for us, we've ironed out most of the issues, apart from one.

We've set up the new servers to lsync from Server A to Server B (Server A is master).

From time to time we see css/js files 404. We can guess what's wrong, it's file syncing not happening fast enough between servers, and when a cache clear occurs on Server A, such as a cron run, then Server B is requesting the old CSS/JS files, and that request may go to Server A.

What is the proper way to set up Drupal 7 on load balanced servers so that CSS and JS files are in sync and don't cause 404?

# Answer
Use csync2 / lsyncd to keep uploaded files (or all files) in sync.

An example configuration for Drupal can be found at http://www.severalnines.com/blog/scaling-drupal-multiple-servers-galera-cluster-mysql

Also, ensure your load balancer is configured for sticky sessions. In this way, if a user uploads a file or causes Drupal to generate new css/js files, those files will be served from the same server. Otherwise the files may be uploaded/generated to one server on a POST, but then another server may serve the response page before it gets the files.

We have used the above and had excellent production stability across three web-servers. We have about 100k+ nodes, ~40 content types, ~60 content providers, ~80k hits per day.

Originally I created a module which stalled Drupal page loads until file synchronizations completed, but we found it wasn't necessary.
> 5 votes

# Answer
Drupal's core aggregation does not work on a cluster because it creates the aggregates during the page rendering. Once the page is stored into the cache another server of the pool will read from the cache so it will not render the page again meaning that the CSS or JS aggregation will not be done locally.

To solve this problem, I created a NFS share between the servers just for the "css" and "js" folders. It was running ok for a while but under heavy load Drupal was sometimes generating empty files (2 servers creating the file at the same time). So even keeping in sync the servers is clearly not a solution.

But just as Beebee said, you can use the Advanced CSS/JS Aggregation module. This one is clever enough to be able to rebuild an aggregate just from the URL, because it stores in the database a mapping of the files that are part of the aggregate.

Advagg is also able to handle groups of aggregated files. This can reduce your bandwidth usage if your visitors navigate across different pages because the common files can be merged into a separate aggregate and the delta files merged into another aggregate.
> 4 votes

---
Tags: 7
---


title: Move people search to list page

text:
# Question
Title: Move people search to list page
Is there a way or module that allows me to move the search tab of the People page to the List tab?

# Answer
> 1 votes
https://www.drupal.org/project/admin\_views makes the users and content page a lot friendlier. On of the things it does is putting a search field on the users page.

One of the modules I use on every project.

---
Tags: users, search
---


title: Metadata stripped?

text:
# Question
Title: Metadata stripped?
Why does it seem that when I upload images through Drupal the metadata disappears? How can I preserve it? I am having trouble finding an layperson's answer here.

# Answer
You are probably using image styles. These images are created based on your original upload. So they are new images.
> 2 votes

---
Tags: 7, media
---


# Question
Title: Is there a module that displays a field only when a condition is met?
I am looking a module that will only display some fields if a condition is met. Basically only administrators or editors should be able to see those fields in the display. In editing mode it should be alright as only editors have the right to view those fields.

I have checked the documenation for Conditional Fields module and Field Conditional States which enable this but they do it based on field contents, but I want run if a PHP condition is met. Are there any other similar modules which implement this?

# Answer
> 4 votes
Have a look at the Field permissions module. It allows for role-based conditional display.

---
Tags: 7, entities, database
---


title: Add html markup to Drupal Webform

text:
# Question
Title: Add html markup to Drupal Webform
I want to extend the simple text the Webform module allows for radio buttons to include HTML markup.

The *Drupal Options Markup* module purports to add markup to the text for radio buttons. It does, but it also seems to be very buggy and causes missing index errors in the Webform module.

Hand coding seems to be a better option. Digging into hook\_form\_alter, I can see where the array is built.

Here is the question: How do add markup to the plain text of the #options array. From the forms api reference, the t function is used. Can I insert HTML into that?

```
   '#title' => t('Selected'),
   '#options' => array(
      0 => t('No'),
     1 => t('Yes'),

```

The result I want can be seen in the Illustration from webform options markup.

# Answer
> 1 votes
You can't add html to the t() function. A quick (and maybe dirty way) is to just do something like this:

```
   '#title' => t('Selected'),
   '#options' => array(
      0 => t('No') . '<span class="markup">Markup</span>',
     1 => t('Yes') . '<ul class="markup"><li>Markup</li></ul>',

```

# Answer
> 0 votes
You can add html to the t() function but i do not like it and i think it is not recommended.

quoting @thumbson

> The multiple checkboxes/radios field types do not support field\_prefix or field\_suffix, though #prefix or #suffix should be possible. However, given that he's trying to add HTML to each option rather than the field, I don't think this will work.

Maybe this can help to achieve what you want #field\_prefix:

> Description: Text or code that is placed directly in front of the textfield. This can be used to prefix a textfield with a constant string.

And #field\_suffix

> Description: Text or code that is placed directly after a textfield. This can be used to add a unit to a textfield.

---
Tags: webforms, forms
---


# Question
Title: Is there an Input Filter without built-in restrictions?
Is there an Input Filter without built-in restrictions? The built-in Drupal filters and some of the other filters I have checked seem to come with their built-in restrictions, eg

The Drupal's own HTML Filter format has its own built in restrictions; a list of HTML tags that can be used. JavaScript event attributes, JavaScript URLs, and CSS are always stripped.

The WYSIWYG Filter has built-in restrictions; the following elements cannot be whitelisted due to security reasons, to prevent users from breaking site layout and/or to avoid posting invalid HTML: applet, area, base, basefont, body, button, embed, form, frame, frameset, head, html, iframe, input, isindex, label, link, map, meta, noframes, noscript, object, optgroup, option, param, script, select, style, textarea, title.\`

Is there any input filter module without built-in set of restrictions, or that allows the administrator to override them, for use with the Full HTML text format?

# Answer
> 2 votes
You can always just make your own text filter through the admin.

If you head to /admin/config/content/formats and click "+ Add text format," you'll be able to customize your own text format, which includes the roles who can use it, what filters you would like to use (using none should allow for any html tag to get through).

If there are some html tags you don't want showing up in your text format, use "limit allowed HTML" tag, and list the tags you want, like this:

```
<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <blink>

```

You could event throw (as your example) a tag in there to let it through. There is however, one big warning I need to leave you with:

**====================WARNING ========================**

Allowing users to place javascript on your page is a huge, huge security threat. If you decide to give users this privilege, make sure it's only with people you absolutely trust. If a text field allows JS to be placed in it, your basicly opening a door for a cross site scripting atttack.

Same holds true for the PHP filter, in fact the php filter is going away in D8, so I would really advise against using that.

# Answer
> 0 votes
the "PHP Code" input filter lets you do whatever you want, but that includes PHP too, use with EXTREME caution.

---
Tags: 7, taxonomy-terms, input-formats
---


title: Multiple pagers in one page

text:
# Question
Title: Multiple pagers in one page
I have a view with two separate displays that is used in one single page. Both the displays are using a pager. To get things working I set a unique id for each pager under `pager options`. This works and I can use each pager independently. The problem is that the separator used in the url to distinguish between the two pagers is encoded as `%2C`. So my question is if there is a way to avoid this and if possible even change the character used?

# Answer
I believe this is only possible by hacking the core pager functionality, so I wouldn't suggest it.

You could add this to your theme

```
function MYTHEME_pager_link($variables) {
  $text = $variables['text'];
  $page_new = $variables['page_new'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $attributes = $variables['attributes'];

  $page = isset($_GET['page']) ? $_GET['page'] : '';
  if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
    $parameters['page'] = $new_page;
  }

  $query = array();
  if (count($parameters)) {
    $query = drupal_get_query_parameters($parameters, array());
  }
  if ($query_pager = pager_get_query_parameters()) {
    $query = array_merge($query, $query_pager);
  }

  // Set each pager link title
  if (!isset($attributes['title'])) {
    static $titles = NULL;
    if (!isset($titles)) {
      $titles = array(
        t('« first') => t('Go to first page'),
        t('‹ previous') => t('Go to previous page'),
        t('next ›') => t('Go to next page'),
        t('last »') => t('Go to last page'),
      );
    }
    if (isset($titles[$text])) {
      $attributes['title'] = $titles[$text];
    }
    elseif (is_numeric($text)) {
      $attributes['title'] = t('Go to page @number', array('@number' => $text));
    }
  }

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

```

You'd need to change this line `if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {` to use the separator you wanted.

But you'd also have to change a line in Drupal's core pager include (/includes/pager.inc)

In this function you'd change the character in the explode to what you want to use.

```
function pager_find_page($element = 0) {
  $page = isset($_GET['page']) ? $_GET['page'] : '';
  $page_array = explode(',', $page);
  if (!isset($page_array[$element])) {
    $page_array[$element] = 0;
  }
  return (int) $page_array[$element];
}

```

Edit: keep in mind, this will break pagers that are not using your theme which means your admin pagers probably won't work unless you do the same for your admin theme.
> 0 votes

---
Tags: 7, views, paging
---


title: Login Redirect to Internal Path

text:
# Question
Title: Login Redirect to Internal Path
I am using Drupal-7 and I have installed login redirect module to redirect my page after login.

I read that this module allows redirect towards non-Drupal location. So, does the Login redirect module is only for to redirect non-Drupal location? Can we redirect to the internal path thru login redirect module?

If this module allows internal path redirection as well, then what to write in Parameter Name?

For example, if we want to redirect it to google after login, then we have to write in parameter name like this: user/login?destination=http://www.google.com

But, I am not sure about internal path. Can any one please guide me on that?

Thank You!

# Answer
Short answer is no, Login Redirect is set up to only use external addresses.

Looking at the module code, you'll see this function

```
function login_redirect_perform_redirect($destination) {
  drupal_goto($destination, array('external' => TRUE));
}

```

that external flag is hard coded, and means as long as you use this module for redirecting, the redirect will always think it's pointing to an external site.

If you want to redirect to an internal link, there are other modules out there you can try. Drupal has a fairly good rundown of them. Personally I favor creating a rule to do this.

=======EDIT=========

To do this with rules, you first need to download and enable rules if you haven't done so yet (make sure you enable the ui as well).

Then swing over to admin/config/workflow/rules, add a new rule (top of page). This will bring you to the first add page where you will name the rule and select "React on event," you will want to set this as "user has logged in"

Hit save and you'll see the "edit rule" page, here there are three sections, events, conditions, and actions. The event should be pre-populated. If you want, you can add conditions, like if a user has a specific role, but you don't need to. For action, you'r gonna want to select "System/page redirect." The url value takes both drupal paths, aliases, and external urls, so in this case if the url your looking to redirect to is at yoursite/contact-us page, you should be able to just put "contact-us" in the url value box. That should get you where you want to be. It's a bit more in-depth than some of the other modules out there, but I personally feel the flexibility with internal vs external and conditions make it a really good choice for this sort of thing.
> 1 votes

# Answer
For internal path you can also specify `user/login?destination="page name here"`

will redirect to your internal path

**For example** you have a page called "contact-us" specify `user/login?destination="contact-us"` will automatically redirect to that page after login

Go through the README.TXT in login\_destination module to get more info

hope this helps
> 2 votes

---
Tags: redirection
---


# Question
Title: Image Cache only clears when clearing my browser cache
When I update my image style (for example adding a water mark overlay) the only way I can see the change is if I clear my browser cache. I am using the ImageCache Actions module.

I downloaded a fresh copy of Drupal and installed the Imagecahce Actions module and the problem doesn't happen on that site. It updates without requiring me to clear my browser cache.

Anyone have an idea what could be causing this issue?

# Answer
> 2 votes
Drupal some times uses cache in Images for better user performance.

if you want to view the image after the update or change you can use this code

```
<?php
 //get the image fiels
 if (isset($data->field_field_profile_pic) && !empty($data->field_field_profile_pic[0]['rendered']['#item']['uri'])) {
        $Logo = file_create_url($data->field_field_profile_pic[0]['rendered']['#item']['uri']);
 }

?>
//print the image tag
<a href="#"><img  src='<?php print $Logo.'?'.time();?>' alt=''></a>

```

Here the main code here is appending time stamp after your image as query string so **time()** will append the image tag with latest timestamp which will get the latest image from your server.

will reduce your burden from clearing your cache every time.

this is a quick fix we used in our project.

---
Tags: 7, caching, media
---


# Question
Title: It's possible to pass custom variables into Views?
It's possible to pass custom variables into Views ? I'm trying to manipulate some elements from a Views by using the administration page.

This how I ask the custom variable ...

**custom\_module.module**

```
/**
 * Implements hook_menu().
 */
function custom_module_menu() {
    $items = array();
    $items['admin/structure/custom_module'] = array(
        'title' => 'Custom Module Integration',
        'description' => t('Custom Module'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('custom_module_form'),
        'access arguments' => array('administer  custom module configuration'),
        'file' => 'custom_module_form.inc',
    );
    return $items;
}

```

**custom\_module\_form.inc**

```
/**
 * custom_module
 */
function custom_module_form($form, &$form_state) {

    $form['custom_variable'] = array(
        '#type' => 'textfield',
        '#title' => t('custom_module configuration page'),
        '#default_value' => variable_get('custom_variable'),
        '#description' => t('Enter my variable'),
    );

    return(system_settings_form($form));

}

```

The variable is store in my Drupal variable\_get which I can confirm on variable editor. So my goal is to be able to used `custom_variable` on Rewrite Results or Global: Custom text on Views. Which I have try it but does not translate to the variable value.

What I'm doing wrong ? Or is not possible to used variable on Views ?

# Answer
You have to write a custom module that creates a suitable handler (for example, a Views area handler). In that handler you can read your custom variable and act accordingly.

Keep in mind Views cache. So, if you change that variable you should invalidate the cache object for that view or views that uses that handler.
> 1 votes

---
Tags: views
---


title: Vocabulary contains too many choices

text:
# Question
Title: Vocabulary contains too many choices
Hello I've created a vocabulary which contains a lot of ingredients can i make it easier to choose them. At the moment it is a long list. If it is somehow possible to make a search form where i can select multiple ingredients it would be great. Modules or other soloutions?

# Answer
I would suggest trying the Chosen module. It provides autocomplete functionality with multiselect capability. Using the multiselect field you can hold ctrl while selecting to keep the list open. Here's a demo.
> 2 votes

---
Tags: taxonomy-terms
---


title: Why is my content not hidden?

text:
# Question
Title: Why is my content not hidden?
I set up a rule that blocks access to a specific piece of content. In fact, for simplicity's sake, I made a rule that blocks everything:

```
function namhost_node_access($node, $op, $account)
{
    return NODE_ACCESS_DENY;
}

```

The problem is, if I go to:

```
/node

```

And browse through all the content, I still see data that I deliberately blocked. Why are these showing? Is `/node` some kind of view with full access to anonymous users? Is my access rule not being enforced for some other reason? Am I not understanding what the point of `/node` is and if I just block that path will I be fine?

Also, are there any other ways that people can access content types I've blocked? It's making me worried that I am able to access content that has been deliberately blocked.

# Answer
> 7 votes
Look at the documentation for hook\_node\_access, here:

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_access/7

The key is where it says:

Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.)

You probably want to check the link following that comment, i.e. the node access rights description, which got more complicated in D7 from D6.

Another thing to pay attention to is: if you're logged in as user id 1, then you won't be affected by those node access grants.

# Answer
> 1 votes
The /node path is a default setting that was created to allow for an easy feed of content to users.

You will most likely want to set your default homepage to something other then /node

This will allow you to use a static page, a generated view or a panel.

You can update that setting at:

/admin/config/system/site-information

If you do want to leave it as the default /node but not have any items show up, you can put something like this in a custom module or your theme.

```
function MYTHEME_preprocess_page(&$vars) {
  if (drupal_is_front_page()) {
    // Removes message "no front page content is created".
    unset($vars['page']['content']['system_main']['default_message']);
    // Removes welcome message page title.
    drupal_set_title('');
  }
}

```

---
Tags: 7, users
---


# Question
Title: Enabled Panels In-Place Editor module but cant see the edit icon
I am using Panels and have enabled the Panels In-Place Editor module but cannot see the edit icon on the page, the one that should be in top rhs corner.

What am I doing wrong?

# Answer
> 1 votes
you need to select the Renderer mode:

Standard or In-Place Editor

Standard Renders a panel normally. This is the most common option. **In-Place Editor Allows privileged users to update and rearrange the content while viewing this panel.**

# Answer
> 0 votes
I think you mean the little gear icon that allows you to edit fields (Panes) in a panelized page?

That would be FAPE, the Fields API Pane Editor. It should be part of ctools, but is a separate module.

Yes, In-Place Editor sounds like it would edit content, but it works on the panels layouts.

# Answer
> 0 votes
In addition to enabling the "Use the Panels In-Place Editor" permission for your desired role, ensure that the "Use Page Manager" is checked.

Before I enabled the "Use Page Manager" permission the gear would actually appear for block and node areas, but it wouldn't appear for the entire Panels page. Enabling the "Use Page Manager" allowed the gear icon to appear for Panels areas as well.

# Answer
> -1 votes
You need to see the permissions of the use "in place editor."

---
Tags: panels
---


# Question
Title: Rules to Flag a node referenced by Commerce Order Line Item
I have a site selling edit access to specific nodes. The site uses Drupal 7, Commerce, Commerce License (selling a Role with edit permission), Rules and Flag. On the Add to Cart I have a Line Item Entity Reference where the customer selects the Node they want access to. Upon payment a 12 month license is generated and the Role with edit permissions is added to the User. That all works fine.

Here's what I need: When the payment is successful I need a Rule to trigger and set a Flag (premier\_listing) on the Node that was selected during the Add to Cart process. However I can't seem to access the Node Entity in Rules or access the Line Item Entity Reference that the User selected. Anybody have an idea how this could be done? Thanks

# Answer
> 0 votes
I believe you'll either need to access the node ID from the line item entity using a loop within the Rules UI or what I think a simpler way would be to create a custom Rule that accomplishes the same task.

Something like: Event: order is completed. I guess you could use order paid in full. Conditions: Here is where a custom condition would come into play. You'd need to dig through the order line items to the user-selected node, and then pass that node\_id to the Rules action as a parameter. Note: you could also do this entire check within the action and then programmatically set the flag to avoid passing the node\_id as a parameter. Actions: Set a flag on a node. (The node parameter).

---
Tags: commerce, rules, entities, flags
---


title: Getting the nid for a teaser

text:
# Question
Title: Getting the nid for a teaser
I know how to get the nid for a node, but not for a teaser. I want to show a button in the teaser, created by a field with the PHP filter, that allows printing the node to pdf, but that requires the nid. The functions that work in the node, like menu\_get\_object(), don't work in the teaser.

Googling this has only brought up methods of printing a teaser if you already know the nid, not getting the nid if you only have the teaser. It should be available; it appears in the id for the teaser.

EDITED: I went with the suggestion posted below by f0ns. I don't understand why the nid is not available when it's in the teaser's id in the html, but that seems to be the case.

# Answer
> 4 votes
Use hook\_node\_view and for $view\_mode == teaser you can add your logic.

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_view/7

---
Tags: nodes
---


title: Views not showing all all field options

text:
# Question
Title: Views not showing all all field options
**Problem:** I'm trying to add Views Filters to this display, but I cannot see any of the fields attached to this Content Type.

**Question:** How may I create exposed filters on these two fields Showcase City and Showcase Field (shown below) if views does not see them? How do I begin to debug a situation like this?

*Managed Fields tab of Content Type*

*Manage Display tab of the Content Type*:

But I cannot see them as options in Views...

*Filtered for all Content Fields:*

*I also attempted to package them into a Feature to move along the Dev-Stage-Prod chain:*

**Updates based on additional information from answers or comments**

*Based on a suggestion below I created the following hook:*

```
/**
 * Implements hook_field_views_data_alter().
 */
function debug_field_views_data_alter(&$result, $field, $module) {

  $string = implode(',', array_keys($result));
  $filtered = strstr($string, 'showcase_headshot');

  if (strlen($filtered) > 1) {
    //dsm($filtered);
    dsm($field);
  }
}

```

Which allowed me to see this:

*jQuery Update Module settings:*

*Export of the view*:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['css_class'] = 'theatre-nominal-showcase-wrapper';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '12';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'nominal_showcase_page' => 'nominal_showcase_page',
);

/* Display: nominal Showcase Block */
$handler = $view->new_display('block', 'nominal Showcase Block', 'block_1');

```

# Answer
> 1 votes
If you're running on a dev environment which uses memcached for caching then views can occasionally not display all the fields because of caching issues.

Possible solutions are to:

1. Set: `$conf['cache_class_cache_views'] = 'DrupalDatabaseCache';`

This means views will no longer use memcached for a cache bin.

2. In views Views 7.x-3.7+ disable views data caching in the advanced menus.

This will probably heavily impact your performance if you're relying on views caching.

3. Run the older memcache extension instead of memcached.

This was the solution I ended up using by accident because I was already running memcache and so managed to avoid the issue on my live machine and only run into it on my dev machine.

The Drupal thread is here.

# Answer
> 1 votes
Data about eligible fields is compiled and cached by Views using hook\_views\_data() and hook\_views\_data\_alter().

Since your "Content:" group is showing only base properties and no fields at all, that leads me to believe that the problem you're seeing happened during the views\_data compile process.

Views module implements "field\_views\_data()" on behalf of Field module to read that information. That would be a good place to start debugging. Put debug breakpoints or dpm() calls inside that function and clear all caches, then revisit the edit interface for the view. See if you can figure out why the function may not be returning any $data.

# Answer
> 1 votes
Any chance that there's some jquery bug involved here? I remember times, when just things like that happened with the wrong jquery version...

https://www.drupal.org/node/1869988

---
Tags: views, features
---


# Question
Title: How can I access location information via rules, to include the City of a node in an email?
I have a rule, which works like this: After saving new content, Fetch users who have flagged a Taxonomy term, Loop, send email. The emails get sent perfectly, to users who have flagged the specific term.

Now I would like to include the location, from the new content item which is saved, in the email.

If I look for the relevant Replacement Patterns \[node:location\] is available, but does not print anything when included in the email. I'm guessing this is because \[node:location\] is an array and I need to do something else to explode the array to get "City" out and print it in the email...

Does anyone know how I would do that? Or a better way to access the specifics (i.e. City) from a node location?

NB: The Location information for my content type is NOT added as "fields" but is added to the content type under "Locative information" (next to Comment Settings and Menu Settings in D7) I am only collecting City and Postcode (and forcing Country to the default)

# Answer
The Location module defines tokens for each piece of info (see below from location.tokens.inc)

So based on this, \[node:location:city\] should work for a single value, or \[node:location:city:0\] for the first value if there were multiple values.

```
  $location['name'] = array(
    'name' => t("Location Name"),
    'description' => t('Location Name (If there are multiple locations, N is the iteration, starting with 0).'),
    'dynamic' => TRUE,
  );
  $location['street'] = array(
    'name' => t("Street"),
    'description' => t("Street (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['additional'] = array(
    'name' => t("Additional"),
    'description' => t("Additional (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['city'] = array(
    'name' => t("City"),
    'description' => t("City (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['province'] = array(
    'name' => t("State/Province"),
    'description' => t("State/Province (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['province_name'] = array(
    'name' => t("State/Province Name"),
    'description' => t("State/Province Name (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['postal_code'] = array(
    'name' => t("Postal Code"),
    'description' => t("Postal Code (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['latitude'] = array(
    'name' => t("Latitude"),
    'description' => t("Latitude (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['longitude'] = array(
    'name' => t("Longitude"),
    'description' => t("Longitude (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['country'] = array(
    'name' => t("Country"),
    'description' => t("Country (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['country_name'] = array(
    'name' => t("Country Name"),
    'description' => t("Country Name (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );

```
> 1 votes

---
Tags: rules, location
---


title: Displaying Images in Search Results

text:
# Question
Title: Displaying Images in Search Results
I have a Resource content type that has an image field (field type and widget are both 'image'); the standard image type. The title of this field is 'Icon' and the machine name is 'field\_icon'. I created my teaser so that the title, date, image, and description fields show and customized my search-result.tpl.php and template.php files so they are displaying the teaser/snippet. That works fine.

However, now I'd like to be able to format the returned results a bit more. I see how I can put HTML directly in the .tpl file, fine. But I want to customize the image field so it appears to the LEFT (float or align left) of the other returned teaser elements.

My problem is I can't figure out how to get the variable that represents the image so I can manipulate it in my .tpl file. I tried the following, but it just returns the number to indicate there IS an image or not:

```
$result['node']->'field-icon';

```

Can someone please tell me how to get the proper variable or link to the icon itself so I can manipulate it in my .tpl file?

Thank you.

Note, here's my current search-result.tpl.php code:

```
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_suffix); ?>
  <div class="search-snippet-info">
    <?php if ($snippet): ?>
      <?php print $snippet; ?>
    <?php endif; ?>
  </div>
</li>

```

# Answer
Perhaps something like this will help:

```
/**
 * Implements hook_preprocess_search_result()
 */
function MYTHEME_preprocess_search_result(&$variables) {
    $node = $variables['result']['node'];
    if (is_object($node) && $node->nid) { // if the result is a node we can load the teaser
        $variables['teaser'] = node_view($node, 'teaser');
    }
}

```

That will provide the variable $teaser to your search template. In search-result.tpl.php you can then access your field data:

```
<div class="search-snippet-info">
    <?php print render($teaser['field_icon']); ?>
    <h2><a href="<?php print $url; ?>"><?php print $title; ?></a></h2>
    <?php if ($snippet): ?>
      <?php print $snippet; ?>
    <?php endif; ?>
</div>

```
> 4 votes

---
Tags: media, search
---


title: How to use field_groups in admin only?

text:
# Question
Title: How to use field_groups in admin only?
I want to use field\_groups in my content type to make it easier to deal with a long content type, but I don't want that group (probably a fieldset) to be rendered at all on the client-facing side.

How do I control that?

# Answer
Use CSS to change the div created by the field group. Set margin, padding, border and font-size to 0.

Don't hide the div because that will hide the contents of the div.
> 1 votes

---
Tags: 7, entities
---


title: Date math in View table

text:
# Question
Title: Date math in View table
Sorry for any incorrect terminology; I'm new to Drupal so it's possible that I'll mess up the Drupal-specific vocabulary.

I'm putting together a View-\>Page with a Table Format.

I've got a field in my data set called "registrationdate", and I can display that just fine. However, what I *need* to display is registrationdate *plus* 14 days. I haven't been able to figure out how to add a number of days to the value so I can display the adjusted value.

I know how to do this in SQL, but since Drupal acts as an abstraction layer between me and the database, I can't do so in this case.

Thanks in advance for your help.

# Answer
You can change the value using a field template.

1. Add the date field to your view
2. Look in Advanced -\> OTHER -\> Theme: Information for a suitable file name for a field template that will only affect the field in this specific view. They are listed in order from least specific to most specific so the final one in the list for that field is probably the best one to use. The link on the filename will show you the default contents for such a file.
3. Create a file in your theme where you keep template files with that filename
4. Start with the default contents in that file and refresh your cache
5. Install devel module and use `dpm($output)` in your new template file to see the structure of the output
6. Use PHP to edit the appropriate portion of the output, you may need `strtotime()` and `date_add()` to achieve this.

Clear your cache often. If you haven't already got drush installed, do it, it is a very useful tool.
> 2 votes

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


# Question
Title: Intercept 404s for pages in certain path
I have a site that regularly adds & removes event nodes based on a third party system. When these nodes are removed, any other articles that link to them get 404 pages. Is there a way I could intercept the 404 results for pages with a certain path and redirect them to the event landing page instead?

I have tried adding the following to `template.php` but I get a redirect loop

```
function MYTHEME_preprocess_page(&$vars)
{
    // Redirect expired events
    $status = drupal_get_http_header("status");
    if ($status == "404 Not Found" && preg_match('/\/events\//', request_uri())) {
        drupal_set_message('Sorry, this event is no longer available','error');
        drupal_goto('/events/');
    }
}

```

# Answer
> 3 votes
Use the Match Redirect module to redirect specific pages that matches urls.

Summary of drupal project page :

This module provides redirecting based on path patterns with wildcards. This functions much like how block page visibility works. You specify a pattern like "old-blog/\*" and a target like "new-blog" and all pages under old-blog will be redirected to the page new-blog.

Features Pattern matching allowing wildcard redirects Redirect code choice (301, 302, etc) Filters out existing pages so they won't be redirected (unless overridden) Loop protection (no chaining redirects allowed)

# Answer
> 1 votes
You could just modify what you had implemented

```
function MYTHEME_preprocess_page(&$vars)
{
    // Redirect expired events
    $status = drupal_get_http_header("status");
    if ($status == "404 Not Found" && preg_match('/\/events\/.+/', request_uri())) {
        drupal_set_message('Sorry, this event is no longer available','error');
        drupal_goto('/events');
    }
}

```

This would redirect a path matching /events/ followed by at least one more character, which would prevent the redirect loop.

---
Tags: redirection
---


title: Entityform redirect from query

text:
# Question
Title: Entityform redirect from query
I am struggling to get the appended parameter from the url when redirecting an entityform.

I have an entityform that user can get to from multiple pages on the website. I want to redirect the user back to the page they came from versus just sending them to a generic landing page after filling out the form.

I can get the path into the url - `www.website.com/form-page/?source=page-I-came-from` However, when I go to redirect them, What do I put into the redirect field so it redirects them to `www.website.com/page-I-came-from`

I have tried:
`%get[url]`
`%get[q]`
`[url:absolute]`
`[url:path]`

If I put `[current-page:url]` I get the entityform page url - How do I get the path from the url from the referring page to show up. I have tried many things and I am falling short.

I have not found anything that can help me to get this to work and I have spent hours trying.

Please does anyone know how I can do this?

# Answer
> 2 votes
It looks like there is a token `[current-page:query:?]` you just need to replace the ? with your query parameter, so `[current-page:query:source]` should do the trick.

# Answer
> 1 votes
From your example you can do something like this :

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORMID') {
    if (isset($_GET['souce'])) {
      $form_state['redirect'] = $base_url . '/' . $_GET['souce'];
    }
  }
}

```

---
Tags: tokens
---


# Question
Title: Drupal Commerce: How to prevent (or suspend) checkout where no shipping rate is defined?
I am using the physical products module to calculate weight based shipping rates.

My client sells heavy items for which they sometimes need to arrange negotiated shipping rates for offshore delivery areas, such as UK Highlands and Islands.

Because a shipping rate cannot always be provided, this can result in a situation where the system returns a shipping service option of 'No shipping rates found for your order. Please continue the checkout process'.

From this situation it is then possible for a buyer to complete checkout without incurring a shipping cost at all!

What is the best method for preventing (or suspending) checkout in such situations? In such a way that the shop owner can provide a quotation based shipping rate before the buyer resumes checkout?

I understand that the shop owner can manually edit a cart order to include a manual shipping rate and I am also aware the Rules can be used to direct the order flow.

But how to prevent (or suspend) checkout before a shipping rate has been quoted?

# Answer
> 0 votes
Look at https://www.drupal.org/project/commerce\_rules\_extra (Commerce Rules Extra) which allows you to alter (including disabling) checkout panes based on conditions.

---
Tags: commerce
---


# Question
Title: Contextual links for custom blocks: Add "Edit block content"
has somebody an idea, how to customize the contextual links in D8?

I have created a custom block type and it would be wonderful to have a link in the contextual links menu: "Edit block content".

# Answer
The missing "edit" link was a bug in early Drupal 8 betas, and has been fixed as of beta5: https://www.drupal.org/node/2284917
> 1 votes

---
Tags: blocks, 8, navigation, entities
---


title: Ubercart import catalog

text:
# Question
Title: Ubercart import catalog
I’m using drupal 7 with Ubercart version 7.x-3.8

I would like to now if there is a way to mass import different taxonomy vocabulary from a csv file.

# Answer
Here is the module that you need to import taxonomy from csv https://www.drupal.org/project/taxonomy\_csv
> 1 votes

---
Tags: 7, importing-exporting
---


title: No front Page Content Error

text:
# Question
Title: No front Page Content Error
While creating a new view and after added the specific content to it.It's not showing the content which I've created instead it's showing

"no front page content has been created "

# Answer
create a basic page or article and promote to front. or

1. create view
2. go to " configuration\>site information"
3. input path of the view I just created as a default front page.
    * you can see the PATH on View list ( structure \> views)

I am using drupal 7.

" Welcome to YOUR SITE NAME " and " No front page content has been created yet." message are gone !

or in D7, I personally have used and like two edits in my theme's 'page.tpl.php' template:

1.) To remove the default message, anywhere within the page is added

```
<?php if(drupal_is_front_page()) {unset($page['content']['system_main']['default_message']);} ?>

```

2.) To remove the default page title,

```
<?php if ($title): ?> is changed to
<?php if ($title && !drupal_is_front_page()): ?>

```

Alternatively, one could use a template override ('**page--front.tpl.php**') and specify this output to be omitted.

or refer this module https://www.drupal.org/project/empty\_front\_page

or You don't need to add modules for small changes: you can override your template file and add the followning code :

```
function MYTHEME_preprocess_page(&$vars) {
if (drupal_is_front_page()) {
unset($vars['page']['content']['system_main']['default_message']); //will remove message "no front page content is created"
}

```

refer this link for more https://www.drupal.org/node/1049290
> 1 votes

# Answer
Go to "`admin/config/system/site-information`" to set front page.

Bottom section of this page there is a option for set "Default front page".

Give the view link in "Default front page" textbox. You will not able to see that message.
> 3 votes

---
Tags: views, blocks
---


# Question
Title: Using Features with an existing content type?
I'm trying to use features to deploy some changes from a local development site to a staging site on a seperate server, the problem is that I've got an existing content type on my dev and staging environment, let's call it hero\_feature.

Here is an example breakdown of the fields that exist in this content type on both dev and staging:

**Dev**

* Hero Type (Machine Name: field\_hero\_type)
* Main Image
* Main Title
* Sub Title

**Staging**

* Main Image
* Main Title
* Sub Title

So there's a field on my dev environment (Hero Type) that I want to transfer from Dev to Staging using features. I'm not sure if it's significant but it's a text select widget.

I've tried creating the feature in a number of ways (selecting the content type itself in one instance, and only the fields that need transferring in another) but every time I get the same error message, which is something like:

> DatabaseSchemaObjectExistsException: Table field\_data\_field\_hero\_type already exists. in DatabaseSchema-\>createTable() (line 657 of /sites/drupal/includes/database/schema.inc).

Which I understand is because the code is trying to create the content type for the field when it already exists.

This is really starting to drive me crazy.

Is it possible to do something like this with Drupal features? Or should I have featurised this before initially deploying to staging in the first place?

(I realise that in my example I could rather easily replicate the changes manually on the staging site, but in reality I have a number of fields and other changes that need porting over to the Staging site, and I'm not happy with manually making these changes everytime something like this needs deploying.)

# Answer
If you want all your content type to be transferred to another site without any changes you can import all content type from your **dev environment** and export it in **stg environment** and remove the validation.
> 0 votes

---
Tags: 7, drush, features, deployment
---


# Question
Title: Why did Views just jump from 3.8 to 3.10 (what happened to 3.9)?
There was a security advisory issued for Views yesterday, but the new version is two ahead of the last (3.10 to 3.8). What happened to 3.9?

The Views release page doesn't list a 3.9, or a reason why there is no such version.

Is this some new security rule I don't know about?

# Answer
> 4 votes
I can't say exactly what's happened in this particular case, but:

It's fairly common practice to do a double release in the case of security updates. Core for example, does this every time, although I couldn't find a reference to the practice right now.

Let's say you've released version X.Y.

Working on X.Y + 1, you've made some number commits on top of X.Y. Now you find a security problem in X.Y, and need to address it. You *can* now quickly rush out X.Y + 1 along with your additional feature work, *and* the security fix.

However, your new feature work isn't as well tested as it should be, because you hadn't prepared for a security emergency release. So although it might function perfectly well, likely, your work is "more buggy than usual".

Also, big sites are likely to be careful in upgrading versions, they'll need to take their time testing the site, making sure everything keeps working.

Any delay in the security update process is bad however, so we'd really like to be able to help people upgrade as soon as possible.

So what can we do? We can take the security only fix, and make a separate release of only that.

In this particular case, it looks like the feature release was done first, and then the security release. If I wanted to security patch my 3.8, I would have to pull out the diff between 3.9 and 3.10 and apply it. I could then take my time upgrading to the real 3.10.

If you look to Core for a similar example, check `git log 7.31..7.32`, which will show you that "SA-CORE-2014-005" was fixed on October 15th, however, the *later* release, 7.33 (`git log 7.32..7.33`) will contain commits from both *before* October the 15th and after. Gits history was re-written, such that the security update alone ended up in the next release, and any additional work then went into a new release. This requires more git trickery, but further lowers the bar for upgrading. In the case of SA-CORE-2014-005, this was important. Not so much in the case of the Views issue, which was minor.

# Answer
> 1 votes
There's definitely a tag for 3.9 in the repository. So for whatever reason the maintainers decided to increment the minor version before 3.9 was released. The same was done on the 6.x-2.x and 6.x-3.x branches.

---
Tags: views, security
---


# Question
Title: How to apply patches on Term Reference Tree
while using Term Reference Tree module it shows me following error. I have found the PATCH for this error.

I am new to drupal. I don't know how can I apply this patch. Please help me to solve this problem. Thank you very much.

```
Notice: Undefined property: stdClass::$vid in i18n_taxonomy_term_name() (line 461 of /home/lawand9/public_html/law/sites/spanish.lawandmoney.info/modules/i18n-7.x-1.11/i18n/i18n_taxonomy/i18n_taxonomy.module).
    Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /home/lawand9/public_html/law/includes/entity.inc).
    Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 350 of /home/lawand9/public_html/law/includes/entity.inc).
    Notice: Undefined property: stdClass::$vid in i18n_taxonomy_term_name() (line 461 of /home/lawand9/public_html/law/sites/spanish.lawandmoney.info/modules/i18n-7.x-1.11/i18n/i18n_taxonomy/i18n_taxonomy.module).
    PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.i18n_tsid' in 'field list': SELECT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, base.language AS language, base.i18n_tsid AS i18n_tsid, v.machine_name AS vocabulary_machine_name FROM {taxonomy_term_data} base INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid WHERE (base.tid IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] => 1 ) in DrupalDefaultEntityController->load() (line 191 of /home/lawand9/public_html/law/includes/entity.inc).

```

# Answer
> 1 votes
If you would take one second and google how to apply patches, you would come across this page: https://www.drupal.org/patch/apply. It explains how to apply patches.

---
Tags: taxonomy-terms
---


# Question
Title: Custom redirect after "admin create user"
For usability of the system when a admin role creates a new user. The admin wants to edit user details but to do this he/she now needs to go to the user and click on "Edit" first.

Is there a way to redirect to this created user's "Edit" page immediately after creating that user?

Thanks in advance!

# Answer
You can use form alter and redirect to any page you want

```
function custom_form_alter(&$form, &$form_state,$form_id) {
  switch ($form_id) {
    case 'user_register_form':
          $form['#submit'][] = 'custom_user_register_submit';
      break;
  }
}

function custom_user_register_submit($form, &$form_state) {
  $uid = $form['#user']->uid;
  $form_state['redirect'] = 'user/'.$uid.'/edit';
}

```
> 0 votes

# Answer
Try to use Login Destination module. This may solve your query.

Or you can do this by using Rules module.
> 0 votes

---
Tags: redirection, users
---


title: Changing SQL JOIN type via PHP in Views

text:
# Question
Title: Changing SQL JOIN type via PHP in Views
How do I change the JOIN type in a SQL query that Views creates?

For example, in this code

```
<?php
function eb_mine_views_query_alter(&$view, &$query) {
  if ($view->name == 'statuser') {
    dsm($query, 'before');
    $query->where[0]['type'] = 'OR';
    dsm($query, 'after');
  }
}
?>

```

Will change

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM
{node} node
INNER JOIN {taxonomy_index} taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = :views_join_condition_0
INNER JOIN {taxonomy_index} taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = :views_join_condition_1
WHERE ((( (taxonomy_index_value_0.tid = :db_condition_placeholder_2) )**AND**( (taxonomy_index_value_1.tid = :db_condition_placeholder_3) )))
ORDER BY node_created DESC

```

to

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM node node
OUTER JOIN taxonomy_index taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '9'
OUTER JOIN taxonomy_index taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '6'
WHERE ((( (taxonomy_index_value_0.tid = '9') )OR( (taxonomy_index_value_1.tid = '6') )))
ORDER BY node_created DESC LIMIT 5 OFFSET 0;

```

As you can see the query changed from AND to OR through the use of OUTER JOINs.

Now I want to change the same code like this:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM node node
LEFT OUTER JOIN taxonomy_index taxonomy_index_value_0 ON node.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '9'
LEFT OUTER JOIN taxonomy_index taxonomy_index_value_1 ON node.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '6'
WHERE ((( (taxonomy_index_value_0.tid = '9') )OR( (taxonomy_index_value_1.tid = '6') )))
ORDER BY node_created DESC LIMIT 5 OFFSET 0;

```

rather than using `OUTER JOIN` I want to use `LEFT OUTER JOIN`.

So how do I do this in my hook?

# Answer
> 0 votes
You can use query alter will help you out

```
function custom_views_query_alter(&$view, &$query) {
    if($view->name == "tag_cloud"){
        print_r($query);// before modifying the query.
        $query->table_queue['taxonomy_index']['join']->type = "LEFT OUTER JOIN";
        //sample field change where  ever you want
        print_r($query);// after modifying the query .
    }
}

```

hope this helps

---
Tags: views
---


# Question
Title: How to show only published node in Drupal Facets (Facet API + Search API)?
I have some taxonomies and node belongs to these when i have created search with facet then all node displaying(publishe + unpublish). i want only published node will show.

# Answer
You need to click the "Filters" tab in your search API index, then check the "Exclude unpublished nodes" option.
> 4 votes

# Answer
* Try with re indexing all your site content once or run the site cron
* Did you try with the search api query alter hooks,

> ```
> function yourmodule_search_api_query_alter(SearchApiQueryInterface $query) {
>   $info = entity_get_info($index->item_type);
>   $query->condition($info['schema_fields_sql']['base table'], 6, '=');
> }
>
> ```
> 0 votes

---
Tags: search
---


# Question
Title: How to change URL alias when importing books?
I am importing some books and would like the url to reflect the category name i.e. `sample.com/fishing-books/booktitle` where `fishing-books` is the product category.

There is a field on the URL alias page (patterns): *Default path pattern* (which applies to all content types with blank patterns below) which I'm trying to make it work, but I haven't been successful. I want something like `[cat]/[node:title]`, but it doesn't work.

# Answer
> 1 votes
Have you created a vocabulary for these books?

If not:

1. Create a vocabulary, e.g. "books\_category"
2. Add to your content type field, e.g. "books\_category" (field type: Term reference), choosing the vocabulary you previously created as reference

After that, click at replacement patterns (admin/config/search/path/patterns); choose group "Tokens related to individual content items," or "nodes"; you will find a group of patterns related to your "books\_category" field.

I assume you installed the Pathauto module.

# Answer
> 0 votes
Url alias will give your user a better understanding of what your page has

For more Read it http://www.ziuby.com/url-alias-drupal-user-understandable-names/

---
Tags: taxonomy-terms, commerce, nodes, path-aliases
---


title: Drupal 6 on php 5.5 compatibility

text:
# Question
Title: Drupal 6 on php 5.5 compatibility
I have running 20+ Drupal 6 sites on php 5.4 without large issues, but what about php 5.5?

# Answer
I am doing it. The only problem I found was with Panels, but this post fixed it. Also, I had to turn down the default error reporting, but I've not had the site crash.
> 3 votes

# Answer
I just encountered an issue with PHP 5.5.14 and Drupal 6. The problem was that logging in was not working. It would refresh the screen and nothing happen.

The issue is that PHP 5.5.14 has very long session id's in the eyes of Drupal 6. Longer than the 64 characters allowed in the sessions table. I had to increase the size of the sid field in the session table to 255 characters in order to get login working. Once I did this, it fixed the problem. There is a similar issue for accesslog but I have not corrected that yet as it is optional and does not seem to affect functionality of my site.
> 1 votes

# Answer
I'm also on PHP 5.5.

I ran in several problems, not all specific to PHP, but the main problem with PHP was the large number of notices that appeared. I have a version, on my end, that fixes most of these. I get a few when I do some obscure administration once in a while.

However, the hardest was to lose XCache. That's not directly linked to PHP, it's more to do with the fact that they upgraded to a much newer version of XCache and it caused tremendous problems with views (on all pages, not specifically on a page with a view, it's in link with loading the PHP files because the views programmers have what XCache considers bugs in there...)

I've done it a while back and I don't recall, but I think I turned off a couple of modules that would generate many errors and I was not really fond of so I could lose them.
> 0 votes

---
Tags: 6
---


# Question
Title: Using a Views Output as Options in a Webform in Drupal 7?
I have a list of articles on my site and currently I have a View that lists all of these articles. I want to be able to build out a webform where a user can select certain articles and then have it emailed to an address. I basically want to turn the Views list of articles into a radio button box where it can be selected for inclusion into the webform.

Are there any modules that can do this? Or how would one go about doing this if there is no module that supports this.

# Answer
> 3 votes
I'm a big fan of webform, but in this use case, I would probably use Entity Form and References instead.

Install both modules, and create your entity form.

Add a node reference field. On the field settings, narrow the results by content type "article".

Note, this would show all articles. If you were hoping to narrow down your results using views filters, you might want to investigate the sandbox project that Volker suggested.

Update: The References module allows you to use a view as a list of referenced nodes. This is very useful for drilling your results down to the exact nodes you want to show.

---
Tags: 7, views, webforms
---


# Question
Title: getting the value of line item entity field in CommerceLicenseRemoteBase class
I am extending CommerceLicenseRemoteBase class for remote synchronization. I have added a custom line item and require that value in

```
CommerceLicenseSynchronizableInterface::synchronize().

```

How can i fetch the value of custom line item. I have tried

```
$license = entity_load_single('commerce_license', $id);
entity_metadata_wrapper('commerce_license', $license)

```

but that did not work.

Thank you

# Answer
Generally you'd do something like this:

```
$wrapper = entity_metadata_wrapper('commerce_license', $license);
$wrapper->PROPERTY_YOU_WANT->value();

```

(See here for more detail: https://www.drupal.org/documentation/entity-metadata-wrappers)

You could always ask in the issue queue for the module:

https://www.drupal.org/project/issues/commerce\_license?categories=All
> 0 votes

# Answer
entity\_metadata\_wrapper did not work because commerce\_license was not referencing commerce\_line\_item entity, it was the other way around. I got it working by querying the commerce\_line\_item entity with commerce\_lincese condition and then called commerce\_line\_item\_load on the line\_item\_id, here is the code i used.

```
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'commerce_line_item')
  ->fieldCondition('commerce_license', 'target_id', $license_id);
$results = $query->execute();

dpm($results);
dpm(commerce_line_item_load($line_item_id));

```

Please let me know if there are any other way to get the line\_item id from license\_id.

Thank you
> 0 votes

---
Tags: 7, commerce, hooks
---


title: Customize admin menu item "Content"

text:
# Question
Title: Customize admin menu item "Content"
Is there a way to change this link to only a #. In the backend it's not possible to change this..

I want this only to be a activator for a dropdown and not a link to the content page because this page is not going to be used.

# Answer
Just make sure your user does not have access to 'Access the content overview page' or any super admin permissions.
> 1 votes

---
Tags: users, routes
---


title: Writing JS/PHP code in feature?

text:
# Question
Title: Writing JS/PHP code in feature?
Is it normal practice to write code (JS/PHP) in feature?

I was thinking that feature should contains ONLY settings, however I've read that some developers write code there and they believe it's fine.

the reason why I ask I found a video on drupalize where they write code in feature so I'm in doubt now.

Any pros and cons to that?

# Answer
> 2 votes
Yes there is no problem inserting code in a feature. I guess the con is that you do not need to introduce a new module.

---
Tags: features
---


# Question
Title: Add js file in .info theme file. And set it to load first
I added this line in my-theme.info

```
scripts[] = js/my-file.js

```

The files is loads but in last place. I need it to be loaded before all modules js files.

How can I set the weight?

I also tried (same results) in template.php with:

```
function MY-THEME_preprocess_page(&$variables) {

  $file =  path_to_theme() . '/js/my-file.js';
  $options = array('weight' => -1000);

  drupal_add_js($file, $options);

}

```

# Answer
You can add the scope (header/footer) where to load the JS and also add a weight.

Example options:

```
$options = array('type' => 'file', 'scope' => 'header', 'weight' => 5));

```

Play around with these to get the file loaded on the right position that suits your needs. For more detailed information check the documentation.
> 1 votes

---
Tags: javascript, .info
---


# Question
Title: Migrating to XAMPP local install - Configure the temporary directory
I have copied a site I have on a VPS down to run from XAMPP on my local machine. When I restore the site using Backup and Migrate I get the error message on all pages of the site:

> The specified file temporary://filemy1oSK could not be copied, because the destination directory is not properly configured.

I have clean installs of drupal running fine on XAMPP. On the File System configuration page (admin/config/media/file-system) they use '/Applications/XAMPP/xamppfiles/temp/' so I have tried using this and '/Applications/XAMPP/xamppfiles/private/' but this doesn't fix the error.

There is a similar Drupal Answers Question, about moving a site from local up to a VPS I have tried to work through the suggestions there to no effect. The top answer recommends advice from this site. Following this to avoid starting the file paths with a forward slash I tried using 'sites/default/files/private/' and 'sites/default/files/temp/'but this doesn't fix the error either.

As this is a local install, security is less of an issue. I have been setting the above directories to 777 to ensure that there are enough permissions. I have also made 'sites', 'sites/default' and 'sites/default/files/' 777.

Possibly incidentally, clean URLS weren't working on the the local install, even though they work fine on the fresh installs of Drupal. This stopped the links on the site working. I disabled them by going to http://localhost/sitename/?q=admin/config/search/clean-urls and the site links now work without clean URLS

Also possibly incidentally, I got an error message when I used the site files I downloaded to install with a clean database. I did this so I could install the backup migrate module and restore the site properly. At the end of the install I got the error:

> Deprecated function: preg\_replace(): The /e modifier is deprecated, use preg\_replace\_callback instead in \_acquia\_profile\_create\_node() (line 158 of /Applications/XAMPP/xamppfiles/htdocs/sitename/profiles/acquia/acquia.profile).

I don't have any admin menu and the overlay admin screens aren't working. I am assuming this is a result of the temporary files error.

Any advice?

# Answer
This issue has nothing to do with Drupal config. Its related the your tmp folder permission. You got to update the tmp folder permission, so that apache user have proper write permission.

`chmod -R 0700 chmod -R 0700 /tmp`
> 1 votes

# Answer
If you set the tmp directory to same path as for working local drupal instance: Try cleaning all cache tables (cache and everything with cache\_) via db (e. g. phpmyadmin) and see if this helps.

Maybe you can also try to set the tmp directory to the XAMPP path before exporting from the VPS. Set it back immediatelay after export.

If it still does not work:

You can try to just copy the files by FTP down to your local server and importing sql dump via db (e. g. mysql command line or phpmyadmin) and see if it works like this (without Backup and Migrate module). Here maybe better to also set the tmp directory before exporting.
> 0 votes

---
Tags: files
---


# Question
Title: A responsive thumbnail grid in Drupal 7 node
How to create a responsive thumbnail grid in Drupal node? I need simple thumbnail grid with description under the pictures, without expanding image. Something like this example. All thumbnail containers should have the same size, say 210px x 210px, but size of images can be diffferent. I installed a lot of modules, include Views, Chaos tool suite, Picture, Brilliant Gallery, but it mostly suitable for image galleries, not for simple thumbnail grid.

Is there method to create responsive picture grid without editing templates or altering core? (i.e. adding code directly in the body of 'Article' or 'Basic page' content, while text format is full HTML) I have read *Views* and *Views Fluid Grid* modules manual, but got no idea how to use them for this task, not even sure whether this will be suitable for this purpose.

# Answer
When you get to this level of customization you need to start considering creating your own page/node templates.

If I was doing this, my pages for this content would get their own content type, then I would create a corresponding page template.

These links may be helpful: https://www.drupal.org/node/982122 https://api.drupal.org/api/drupal/modules!system!page.tpl.php/7

Inside that page template, I would then load the raw data for the node, using node\_load and then access the fields directly and put them inside the appropriate markup.
> 1 votes

---
Tags: views, 7, chaos-tool-suite, theming, media
---


# Question
Title: All page access only to administrator in
I want to restrict my page access. Only an administrator should be able to see the page.

I followed this tutorial

```
function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'example_user_has_role',
    'access arguments' => array(1, array('adminstrator')), // Argument 1 loads the user, argument 2 is the role name.
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function check_user_has_role($user, $roles = array()) {
    foreach ($roles as $role) {
        if (in_array($role, $user->roles)) {
            return TRUE;
        }
    }
    return FALSE;
}

```

But I was able to access the URL even after I logged out. What is my mistake or is there a better way to achieve this?

# Answer
> 3 votes
I think the name of your access callback is wrong. (`example_user_has_role` =\> `check_user_has_role`). Also, you made a mistake on the role name (`adminstrator` =\> `administrator`).

Anyway, you can achieve this in a more simple way like this (avoiding the argument in the URL)

```
function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'check_user_has_role',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function check_user_has_role() {
  global $user;
  if (in_array('administrator', $user->roles)) {
    return TRUE;
  }
  return FALSE;
}

```

# Answer
> 2 votes
You did not follow the example as is.

The example uses auto loading, as in:

```
$items['example/%user']

```

Your path does not, hence your issue.

Just drop the $user as parameter to the access callback and arguments, and get the pseudo user object by using:

```
global $user

```

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


# Question
Title: How to completely hide a table header in views?
In views when you use the table layout and don't select labels it still creates an empty header, for example:

```
<th class="views-field views-field-field-address-1"></th>

```

I can hide it with CSS. What would I have to do to access the render array and unset the element before the HTML is generated?

Is there any other way to remove the `<th>` tag?

# Answer
> 8 votes
Implement `hook_preprocess_views_view_table(&$vars)` in theme or custom module and set `$vars['header']` to empty array. Template completely ignores thead when header variable is empty. For example:

```
function MY_THEME_preprocess_views_view_table(&$vars) {
  if ($vars['view']->name == "my_view") {
    $vars['header'] = array();
  }
}

```

# Answer
> 4 votes
A more general solution to the problem could be implemented in your theme by preprocessing the theme\_table.

In other words, in your template.php file of your theme, write a function like this:

```
function MY_THEME_preprocess_table(&$variables) {
  if (!empty($variables['header'])) {
    foreach($variables['header'] as $cell) {
      if (!empty($cell)) {
        return;
      }
    }
    $variables['header'] = array();
  }
}

```

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


# Question
Title: Try to theme a specific page using template.php and a sub theme
I have a theme called 'progressive'. It has a sub theme called 'progressive\_sub'.

I'm trying to exclude items from being displayed from a particular page in D7 (latest as of 12.2.15).

I have the following useful files:

/sites/all/themes/progressive/progressive\_sub/template.php

This contains:

```
<?php

/**
 * Implements hook_preprocess_page().
 */
function progressive_sub_preprocess_page(&$variables) {
  $path = request_path();

  if ($path = 'node/131') {
    unset($variables['page']['header']);
    unset($variables['page']['sidebar']);
    unset($variables['page']['footer']);
    unset($variables['page']['bottom']);
    unset($variables['page']['top']);
    unset($variables['page']['content_top']);
    unset($variables['page']['sidebar']);
    unset($variables['page']['bottom']);
    unset($variables['page']['footer']);
    $variables['theme_hook_suggestions'][] = 'page';
  }
}

```

You can see that I'm trying to remove a heap of regions from this page (page.tpl.php) template, in this case when /node/131 is called.

I also have:

/sites/all/themes/progressive/progressive\_sub/templates/page.tpl.php

which has all the usual including:

```
<?php print render($page['content']); ?>

```

My problem is that I cannot get this page.tpl.php to load when I'm viewing /node/131

Is there something that I'm doing wrong?

# Answer
Wy don't you just create a template with this name:

```
page--node--131.tpl

```

and then, rather than removing regions in your template\_preprocess\_page function, just do not print them in your new template.

A few other things:

In some cases where order matters you may consider adding the suggestion to the beginning of the array using array\_unshift.

Making use of request\_path() is not the best way to get the path. It returns the request url, which may or may not be the internal path (think aliases). Better to use menu\_get\_object.
> 0 votes

# Answer
This

```
if ($path = 'node/131')

```

should surely be

```
if ($path == 'node/131')

```

Nevertheless this should not affect use of page.tpl.php.

Is your subtheme working at all, do templates get loaded from subtheme at all?

Your path is /sites/all/themes/progressive/progressive\_sub. Does that mean the parent theme is at /sites/all/themes/progressive? If so, maybe try to give the subtheme a separate folder.
> 0 votes

---
Tags: theming
---