# Question
Title: Content Type - Image able to link to other website
I had create image field at content type. Without any views module or java-script, am I able create link to other website?

I am not using panel for my website. My question is ONLY related to CONTENT TYPE.

Example: When someone click on the image, it will link to www.google.com

Many Thanks.

# Answer
> 3 votes
you can do this by using any of the below modules :

1. Image Link Formatter

> This module is the result of the discussions around a requested feature to allow an image field to be displayed with a link to a custom URL

2. Image URL Formatter

> This module add a url formatter for image field. Then you can output image url directly.
>
> Most of the code, maybe more than 90%, is just copy from the drupal core. I think it is stable enough.
>
> I have created a content type, and add an image field instance to it, later i use views to export the data of this content type.And i want to output the data,then i could import it into another drupal 7 site with feeds module. What i need is the url of the image field, but i could not export the image url directly. That is why i create this small module.

3. Link

> The link module can be count to the top 50 modules in Drupal installations and provides a standard custom content field for links. With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

# Answer
> 0 votes
You can use "Link Image Field" module. After enabling this module when you add a new content type you can see "LInk Image" in the field type drop down. You will be able to set the maximum,resolution,file extensions,default image,whether to open the link in new tab or not etc.

---
Tags: 7, nodes
---


# Question
Title: Is it possible to make a custom facet that behaves like a Views grouped filter?
I am moving my user search from vanilla Views to the Search API/Solr backend/Facet API with Views.

On my site, I have a Countriesfield on the user profile, and I would like to give users the option to choose between two options: **from Japan** or **not from Japan**.

In Views, I did this using a grouped filter:

Now I am trying to make a facet that does the same thing. However, I don't think this is possible from the Facet UI, even with Facet API Bonus installed. There appears to be no way to provide users with the choice of **A** or **NOT A** for a facet that has 100+ values.

How can I implement this **A** or **NOT A** search using the Facet API for a specific facet?

# Answer
Based on this article, I was able to do this with the following code:

```
/**
 * Implements hook_entity_property_info_alter().
 */
function MYMODULE_entity_property_info_alter(&$info) {
  $info['user']['properties']['agg_nat'] = array(
    'type' => 'text',
    'label' => t('Search API Agg Nationality'),
    'sanitized' => TRUE,
    'getter callback' => 'MYMODULE_search_agg_nat_getter_callback',
  );
}

/*
 * Getter callback for agg nationality property.
 */
function MYMODULE_search_agg_nat_getter_callback($item) {
  // Need to load the user object to get fields
  $account = user_load($item->uid);
  $nationality = $account->field_gen_nationality['und'][0]['iso2'];
  switch ($nationality) {
    case 'JP':
      return 'ja';
    break;
    default:
      return 'en';
    break;
  }
}

```
> 0 votes

---
Tags: views, search
---


# Question
Title: Update pathauto alias without node_load?
I want to force an update of the URL alias without loading the node.

Can this be done? If not, any lighter ways to update a Pathauto alias?

# Answer
> 2 votes
Nope, not without circumventing the pathauto module logic (e.g. altering the alias directly in the DB).

The main function that gets executed in pathauto node updates/inserts, `pathauto_create_alias`, requires a parameter, `$data`, passed to it. In a node context, `$data` is the node object. Without this node object data, pathauto would not be able retrieve data needed for tokens pattens (e.g. `[node:title]`).

---
Tags: path-aliases, uri
---


# Question
Title: How to handle non-fatal errors during a batch operation?
Most tutorials about Drupal batch processing suggests that you provide something like the following as a callback for when the batch has finished.

```
function mymodule_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Success'));
  } else {
    $error_operation = reset($operations);
    drupal_set_message(t('At least one error occurred'));
  }
}

```

This is also how my finished-callback looks like (I know you can report more fancy statistics about the operations, but that is not relevant here. I want to keep this question simple).

I want to loop through a bunch of files in a batch and report at the end if any of them are not readable by the web server. I do not want to abort the batch when a non readable file is found.

My test site is a clean Drupal 7.37 + Devel and a custom module called "mymodule".

This is how operations function for processing a single file looks like:

```
function mymodule_process_one($file, &$context) {
  $context['results'][] = check_plain($file);
  if (!is_readable ($file)) {
    // I need some code here that indicates that this is an error.
  }
}

```

I've indicated with a comment were I *think* there should be some code that indicates that there is some non-fatal error. My question is: What should this code be?

I've made sure that one of files processed are not readable. Using Devel to print out the three variables passed into `mymodule_finished`, this is what I get:

`$success` is TRUE.
`$results` is an array with all the file names.
`$operations` is an empty array.

Since there is no actual code in the operations-function to mark an unreadable file as an error , my finished-callback *always* print "Success", even if there are one or more unreadable files in the batch. How can I make it report any errors at the end?

**PS**: I've searched the site and found examples on how to *terminate* the batch process if a *fatal* error occurs in an operation - e.g.: How to terminate a batch when an error occurs and Can a batch process be stopped. I am not interested in that. I want an answer that explains how to process *all* items and produce an error message in *finished* callback if one or more operations failed.

**Edit:** I know that I can accomplish this by using a global db variable as an error flag. However, I am not interested in workarounds. I want to learn how do this correctly using the batch API.

# Answer
> 3 votes
See here for more information on this: https://api.drupal.org/api/drupal/includes%21form.inc/group/batch/7

**Updated answer:**

After the comments I realized what you are trying to do, so I setup the example module and came up with this code to show if one error happened but others ran. You can take a look and hopefully use this to help come up with your final answer.

```
<?php

/**
 * @file
 * Outlines how a module can use the Batch API.
 */

/**
 * @defgroup batch_example Example: Batch API
 * @ingroup examples
 * @{
 * Outlines how a module can use the Batch API.
 *
 * Batches allow heavy processing to be spread out over several page
 * requests, ensuring that the processing does not get interrupted
 * because of a PHP timeout, while allowing the user to receive feedback
 * on the progress of the ongoing operations. It also can prevent out of memory
 * situations.
 *
 * The @link batch_example.install .install file @endlink also shows how the
 * Batch API can be used to handle long-running hook_update_N() functions.
 *
 * Two harmless batches are defined:
 * - batch 1: Load the node with the lowest nid 100 times.
 * - batch 2: Load all nodes, 20 times and uses a progressive op, loading nodes
 *   by groups of 5.
 * @see batch
 */

/**
 * Implements hook_menu().
 */
function batch_example_menu() {
  $items = array();
  $items['examples/batch_example'] = array(
    'title' => 'Batch example',
    'description' => 'Example of Drupal batch processing',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('batch_example_simple_form'),
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Form builder function to allow choice of which batch to run.
 */
function batch_example_simple_form() {
  $form['description'] = array(
    '#type' => 'markup',
    '#markup' => t('This example is modified for files and sets error if only one file is not readable.'),
  );
  $form['batch'] = array(
    '#type' => 'select',
    '#title' => 'Choose batch',
    '#options' => array(
      'batch_1' => t('batch 1 - load files'),
    ),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Go',
  );

  // If no nodes, prevent submission.
  // Find out if we have a node to work with. Otherwise it won't work.
  $nid = batch_example_lowest_nid();
  if (empty($nid)) {
    drupal_set_message(t("You don't currently have any nodes, and this example requires a node to work with. As a result, this form is disabled."));
    $form['submit']['#disabled'] = TRUE;
  }
  return $form;
}

/**
 * Submit handler.
 *
 * @param array $form
 *   Form API form.
 * @param array $form_state
 *   Form API form.
 */
function batch_example_simple_form_submit($form, &$form_state) {
  $function = 'batch_example_' . $form_state['values']['batch'];

  // Reset counter for debug information.
  $_SESSION['http_request_count'] = 0;

  // Execute the function named batch_example_1 or batch_example_2.
  $batch = $function();
  batch_set($batch);
}

/**
 * Batch 1 definition: Scan file directory /maintenance on test site.
 *
 */
function batch_example_batch_1() {

  $operations = array();

  $files = file_scan_directory('sites/default/files/maintenance', '/.*\.(png|jpg)$/');
  $i = 0;
  foreach ($files as $value) {
    $file_efq = new EntityFieldQuery();
    $file_efq->entityCondition('entity_type', 'file')
      ->propertyCondition('filename', $value->filename);
    $file_efq_result = $file_efq->execute();
    if (count($file_efq_result)) {
      // This will only add the first match from EFQ for this filename
      $fid = array_pop($file_efq_result['file'])->fid;
    }
    if (!empty($fid)){
       $operations[] = array(
        'batch_example_op_1',
        array(
          $fid,
          t('(Operation @operation)', array('@operation' => $i)),
        ),
      );
      $i++;
    }
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'batch_example_finished',
  );
  return $batch;
}

/**
 * Batch operation for batch 1: load a file.
 *
 * This is the function that is called on each operation in batch 1.
 */
function batch_example_op_1($fid, $operation_details, &$context) {
  // $node = node_load($nid, NULL, TRUE);
     $file = file_load($fid);
  // Store some results for post-processing in the 'finished' callback.
  // The contents of 'results' will be available as $results in the
  // 'finished' function (in this example, batch_example_finished()).
  if (is_readable($file->uri)){
    $context['results'][] = $file->fid . ' : ' . check_plain($file->filename) . ' ' . $operation_details;
  }else{
    $context['results']['error'] = $file->fid . ' : ' . check_plain($file->filename) . ' ' . $operation_details;
  }
  // Optional message displayed under the progressbar.
  $context['message'] = t('Loading file "@uri"', array('@uri' => $file->uri)) . ' ' . $operation_details;

  _batch_example_update_http_requests();
}

/**
 * Batch 'finished' callback used by both batch 1 and batch 2.
 */
function batch_example_finished($success, $results, $operations) {

  if (!$results['error']) {
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...
    drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _batch_example_get_http_requests())));
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = $results['error'];
    drupal_set_message(
      t('An error occurred while processing @operation',
        array(
          '@operation' => print_r($error_operation)
        )
      )
    );
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  }
}

/**
 * Utility function to increment HTTP requests in a session variable.
 */
function _batch_example_update_http_requests() {
  $_SESSION['http_request_count']++;
}

/**
 * Utility function to count the HTTP requests in a session variable.
 *
 * @return int
 *   Number of requests.
 */
function _batch_example_get_http_requests() {
  return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
}
/**
 * @} End of "defgroup batch_example".
 */
?>

```

You can see where I scan a public directory on my site, then I go in and set one of those files to not be readable by Drupal and I get my error message. Looking at the pages I included earlier that is exactly what you are supposed to do and the $operations variable would be anything that fails with a Fatal error. Hope that helps. If you need any explanations just let me know, and sorry about leaving examples in there, I will try to clean it up later.

**The main part of the code from above that answers OP's question is below with explanation:**

```
  if (is_readable($file->uri)){
    $context['results'][] = $file->fid . ' : ' . check_plain($file->filename) . ' ' . $operation_details;
  }else{
    $context['results']['error'] = $file->fid . ' : ' . check_plain($file->filename) . ' ' . $operation_details;
  }

```

**In the batch documentation it states:**

```
// The 'success' parameter means no fatal PHP errors were detected. All
// other error management should be handled using 'results'.

```

**So you would have to change your finished callback to include the error management also.**

```
// I don't recommend using this, I just used it as a test. You should use $success and your other error management handling together here.
if (!$results['error']) {
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...
    drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _batch_example_get_http_requests())));
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = $results['error'];
    drupal_set_message(
      t('An error occurred while processing @operation',
        array(
          '@operation' => print_r($error_operation)
        )
      )
    );
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
  }

```

While looking at some more of the doc pages I found a link to a github module that has another setup of error handling view $results array and how they use this. This may help to see what can actually be done here and other ways it can be setup. Here is the page for that module CSV Import. This is the documentation page that was linked to the module code that has the example there, you will notice that `$context['results']['failed_rows'][]` is what they use in their error handling.

*Old parts of answer, left b/c some of the information is relevant or could be to future observers.*

This is the way the example modules show to print errors and number of items that completed at the end with the callback function. It says the `$operations` variable shows the number of operations that did not run.

```
function batch_example_finished($success, $results, $operations) {
if ($success) {
  // Here we could do something meaningful with the results.
  // We just display the number of nodes we processed...
  drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _batch_example_get_http_requests())));
  drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
}
else {
  // An error occurred.
  // $operations contains the operations that remained unprocessed.
  $error_operation = reset($operations);
  drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array(
   '@operation' => $error_operation[0],
   '@args' =>  print_r($error_operation[0], TRUE),
    )));
  }
}

```

You can find more about this in the example modules: https://api.drupal.org/api/examples/batch\_example%21batch\_example.module/function/batch\_example\_finished/7

If you want to make sure that the success works (may not work with some non-core modules enabled) you can do a couple of different things to throw an error.

Explicitly set an error in the json callbacks

```
<?php
   function some_batch_operation(&$context) {
     // do stuff
     // if something goes wrong
     $result = array('status' => FALSE, 'data' => $message);
     die(json_encode($result));
   }
?>

```

Throw an exception.

```
<?php
   throw new Exception(t('My error message.'));
 ?>

```

# Answer
> 4 votes
**Preamble:**
The answer given by *burnsjermey* did help me find the solution. He deserves kudos for pointing me to the correct documentation and this project on github. Both helped a lot, so I've accepted his answer.

However, his answer contains a lot of stuff that has nothing to do with the question. Also, his code examples have bugs that stops them from working. Therefore, I also want to add a self-answer containing only code snippets that are *relevant* to the question asked.

---

**Self-answer:**
First, as pointed out in the API documentation, non-fatal error management should be handled using 'results'. Hence, when we encounter a non-fatal error, we add an error message to the results array:
```
function mymodule_process_one($file, &$context) {
  if (!is_readable ($file)) {
    $context['results']['error'][] = t('@file is not readable.', array('@file' => $file));
  }
  else {
    $context['results'][] = t('@file processed.', array('@file' => $file));
  }
}

```

Then, in the finished-callback, we put code that looks for these errors, and prints them out if there are any.

```
function mymodule_finished($success, $results, $operations) {
  if ($success) {
    if (isset($results['error'])) {
      drupal_set_message(t('There were !count non-fatal error(s):', array(
       '!count' => count($results['error']),
      )), 'error');
      foreach ($results['error'] as $error) {
         drupal_set_message($error, 'error');
      }
    }
    else {
      drupal_set_message(t('No errors.'));
    }
  } else {
    $error_operation = reset($operations);
    drupal_set_message(t('A fatal error occurred'));
  }
}

```

That's all folks!

---

**PS:**
If you want to learn how to handle *fatal* errors during batch processing, the best answer is the accepted answer to: Can a batch process be stopped.

---
Tags: 7, batch-operations
---


title: Smart_IP homepage redirect

text:
# Question
Title: Smart_IP homepage redirect
I have a multilingual site. I am browsing from Holland and with the Smart\_IP module i am redirecting to the correct language:

`http://landberg.at/nl/` or `http://landberg.at/de/`

My default language is English. But now as user from Holland for example (dutch browser), you are NOT able to switch to the English homepage. This is because the homepage URL in English is `http://landberg.at/` \>\> Then you are automatically redirect to `http://landberg.at/nl/`

Is there a solution for this?

# Answer
I don't know the Smart\_IP module's mechanism, but I think you should simply solve your problem outside of Drupal: adding an Apache redirection like `Redirect "landberg.at" "landberg.at/en"`. Somewhat brutal but should work...
> 0 votes

# Answer
Try to use IP to Locale module. I think this module definitely solve your issue.

> IP to Locale provides IP lookup and redirection services for Drupal sites.
> 0 votes

---
Tags: 7, i18n-l10n, redirection
---


# Question
Title: How to display a timetable for reservable resources?
Is there a module that will allow me to display a timetable in a grid similar to the attached image?

Rooms are vocabulary terms, and each of the time blocks (e.g. Elementary, Junior) are nodes of a specific content type (Time Block) which contain a starting and ending time (date field) and the term reference field pointing to the room name.

# Answer
Try to use any of below modules :

1. Field TimeTable

> A Fields module that creates a timetable field that can be display through an nice weekly grid. Can be use to display opening hours or working hours in a very neat way.
>
> If you need to display office hours in a graphical way you have now a proper solution !

2. Grid Field Formatter

> the Grid Field Formatter module provides a simple way to overridde the display of multi-value fields to show as a grid/table with a certain number of columns.
> 0 votes

---
Tags: theming
---


title: Update database to Drupal 6 to Drupal 7

text:
# Question
Title: Update database to Drupal 6 to Drupal 7
I upgraded my website to D6 to D7 successful but only with the development version (not in production) and I've new datas in production since (Drupal 6). So I'm wondering the best way for update the Drupal 6 database to the Drupal 7 database.

# Answer
> 0 votes
You could migrate DB data with the Migrate module (though it's not very light module and has an individual learning curve, so if you are not a programmer, or not yet, it might be better for you to find a Drupal programmer that will help you run it). Otherwise, if the site is small (i.e has only several or about fifteen pages) I would suggest of building it from the start... In most cases it shouldn't take much time..

Blessings,

---
Tags: database, migrations
---


# Question
Title: Change template of Drag & Drop module on node add form
I am using Drag & Drop Upload module for multiple images uploading.

But the template I see on node add form (FRONTEND) is this :

And I want to change it to this :

I don't know where can I find the HTML for this template, so I can change it.

Thank you so much for your help!

# Answer
You can do this by updating css into that module.

Or once try to use HTML5 Drag & Drop File module. Hope this module provided that you want.

> HTML5 drag & drop + HTML5 file upload with XHR2. Allows the user to drag & drop files into a Image/File Field and uploads it immediately behind the scenes. In theory it should work for as many files as the field allows.
> 0 votes

---
Tags: theming, media, nodes
---


# Question
Title: How to export user's content via features to new site in Drupal 7
Can anyone tell me how to export contents of users through some contributed modules?? like features,because I have a site which has 100 users,all contents are migrating through features but user's info and their images are not being moved with features module..

Your solicited help is needed.

# Answer
> 0 votes
You can use Data export import module Here ls the link of module - https://www.drupal.org/project/data\_export\_import

---
Tags: media, users, features
---


# Question
Title: How do I exclude the current user from the search?
In a normal Views user search, you can simply add a `User: Current` filter to remove the logged-in user from the search results.

I have a Search API Views search of a Solr index of users, and I want to do the same thing. However, the `User:Current` filter is not available. How can I achieve the same function?

# Answer
You could write a simple module using hook\_views\_pre\_view.

1. Be sure to index the User ID
2. Under Filter Criteria, add **Indexed User: User ID**, and set it to NOT EQUAL TO and use 0 (anonymous user, which will never be in this list).
3. Using `MY_MODULE_views_pre_view` with the global user value, replace **0** with the UID of the current user.

```
function MY_MODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'VIEW_NAME') {
    if ($user->uid) {
      $view->display['default']->handler->options['filters']['uid']['value'] = $user->uid;
    }
  }
}
```
> 3 votes

---
Tags: views, search
---


# Question
Title: field_groups - adding an inner div wrapper programatically
I have some older code that used this method to add an inner div containing inline style.

Much like the linked question above. I am using hook\_preprocess\_node to attempt this.

However, the $variables\['content'\] array no longer seems to contain the groups in it and I'm not sure exactly what's changed. I haven't managed to find much else on this in the issue queue and elsewhere.

# Answer
It is strange that this has changed and I can't really find any posts relating to it.

I'm going to update my code to use hook\_field\_group\_build\_pre\_render\_alter() as an alternative.
> 1 votes

---
Tags: 7, entities
---


title: How to display shops near by user

text:
# Question
Title: How to display shops near by user
I am creating a website in which I want to show the similar shops near by user location.

Like if a user selects `Bangalore -> M.G. Road` then the similar shops near by `M.G. Road` should be displayed.

However, I don't want to use *Google Maps*, because it will take too long to open.

Any suggestions about how I can do this in Drupal7?

# Answer
Using Google Store Locator module you can solve your query.

> This project uses Google's Store Locator Utility Library and Google Maps to create a 'Store Locator' page that your site visitors can use to find and get directions to one of your physical stores. It was born out of a need for a simple to install and easy to use locator feature for Drupal 7. This module is different from other 'locator' type modules (e.g. OpenLayers Locator) in that it doesn't require you to have any knowledge of it's dependant modules, and it allows developers to focus on implementing personal customizations quickly because the installation process is so light.
> 0 votes

# Answer
If you use the location module to store your addresses, then you can filter or sort by proximity / distance in views.
> 0 votes

---
Tags: location
---


title: How do I convert hook_menu()?

text:
# Question
Title: How do I convert hook_menu()?
I am having site built in Drupal 7 and in future I want to migrate my site to Drupal 8.

How can I write `hook_menu()` and `hook_menu_alter()` to routing.yml files?

# Answer
> 3 votes
Here is an example taken from All functionality of hook\_menu() is replaced by new systems for routing, menu links, local tasks, actions and contextual links:

**Drupal 7**

in modules/book/book.module:

```
function book_menu() {
   $items['book/export/%/%'] = array(
    'page callback' => 'book_export',
    'page arguments' => array(2, 3),
    'access arguments' => array('access printer-friendly version'),
    'type' => MENU_CALLBACK,
    'file' => 'book.pages.inc',
  );
    $items['node/%node/outline'] = array(
    'title' => 'Outline',
    'page callback' => 'book_outline',
    'page arguments' => array(1),
    'access callback' => '_book_outline_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'file' => 'book.pages.inc',
  );
...
  return $items;
}

```

**Drupal 8**

in modules/book/book.routing.yml:

```
book_export:
  pattern: '/book/export/{type}/{node}'
  defaults:
    # What's being returned is the entire response (not HTML, or even if HTML, we don't want additional blocks around it), so use _controller instead of _content.
    _controller: '\Drupal\book\BookController::export'
  requirements:
    _permission: 'access printer-friendly version'
book_node_outline:
  pattern: '/node/{node}/outline'
  defaults:
    _controller: '\Drupal\book\BookController::outline'
  requirements:
    # Indicates that the book outline access access system should be invoked.
    _book_outline_access: TRUE

```

# Answer
> 1 votes
Here is the link of blog to convert your `hook_menu` to `routing.yml` file.

Well to understand a simple routing.yml :

```
route.name:
  path: '/path/of/page'
  defaults:
    _title: 'Title of Page'
    _controller: '\Drupal\modulename\Controller\ClassName::methodName'
  requirements:
    _permission: 'permission name'

```

This is an example of simple routing.yml file.

**route.name :** Name of route which should start with your module name.

**path :** Path of the page.

**\_title :** Title of page

**\_controller :** Class that returns the content of page.

**\_permission :** Permission of page.

To set the access\_callback, parameter upcasting there are various different ways. To set the menu link and menu tab two more files that you have to write.

**webform.links.menu.yml** and **webform.links.task.yml**.

---
Tags: 8, routes
---


# Question
Title: page.tpl.php base on a field criteria in views
I'm working on creating different themes in different pages of a site base on several conditions.

first, I want to create a page.tpl.php for all view pages in my site.

second, I want to have tiny specialization on it base on the filter criteria field's value or selected field's value in a page view. I mean different page.tpl.php based on fields value criteria.

I need to change the overall theme so it is not duplicate of is it possible to have one views-view--VIEWNAME--page.tpl for multiple views?

I need to know how to access field's value in my "function MYTHEME\_preprocess\_page(&$vars, $hook) ".

# Answer
> 0 votes
Salam, You can do this using `hook_preprocess_views_view(&$vars)`. Your code should be like this:

```
function YOURTHEME_OR_MODULE_preprocess_views_view(&$vars) {
    $view = $vars['view'];
    // the values of the view, filter criteria and the value of fields are in $view
    if(CONDITION1 == true)
        $vars['theme_suggestion'] = 'views_view__custom_pages1'
    else if(CONDITION2 == true)
        $vars['theme_suggestion'] = 'views_view__custom_pages2'
}

```

Then create files `views_view__custom_pages1.tpl.php` and `views_view__custom_pages2.tpl.php` and theme the view. In this way different themes are defined for the same view.

You also said *I need to know how to access field's value in my "function MYTHEME\_preprocess\_page(&$vars, $hook) "*, what variables do you need to find it's value?

---
Tags: views, theming
---


title: Dependent selects in Ctools modal

text:
# Question
Title: Dependent selects in Ctools modal
I am experiencing a rather odd problem in Drupal 7.

I have a form in Ctools modal. It should contain 2 dependent select boxes (among other fields). I've done this dozen times on regular forms, but i can't make it work in the Ctools Modal form. Modal pops up, all the fields are there, all the counties are in the first select box, but it looks like it's not even reaching the ajax callback when a county is selected, so no dealer are returned. When I hard code the county id, dealers from that county show as expected.

My code is **similar** to the following:

menu item:

```
$items['modal-data/%ctools_js'] = array(
  'page callback' => 'core_modal_form',
  'page arguments' => array(1),
  'access arguments' => array('access content'),
  'delivery callback' => 'ajax_deliver',
  'type' => MENU_CALLBACK,

```

);

general modal handling:

```
function ni_core_modal_form($js) {

// Check whether js is enabled.
if ($js) {

  // Include ctools modal plugin.
  ctools_include('ajax');
  ctools_include('modal');

  // Create notify entity
  $form_state = array(
    'title' => 'Contact dealer',
    'ajax' => TRUE,
  );

  $commands = ctools_modal_form_wrapper('contact_dealer_modal_form', $form_state);

// If form was submitted.
  if (!empty($form_state['executed'])) {

    $commands[] = ajax_command_replace('#modal-content', theme_status_messages(['display' => 'status']));

  }

  print ajax_render($commands);
  drupal_exit();
 }
}

```

The form in ctools modal:

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

   // get all counties
  $counties = get_dealer_counties_list();

  // Check for the selected county
  $county = isset($form_state['values']['county']) ? $form_state['values']['county'] : key($counties);

  // get dealer for selected county
  $dealers = get_dealer_select_list($county);

  $form['wrapper'] = [
    '#type' => 'container',
    '#attributes' => ['class' => ['contact-dealer-form-wrapper']],
  ];

  $form['wrapper']['county'] = [
    '#type' => 'select',
    '#title' => t('Select your county'),
    '#options' => $counties,
    '#ajax' => array(
      'callback' => '_county_dealer_callback',
      'wrapper' => 'dealer-replace',
    ),
  ];

  $form['wrapper']['dealer'] = [
    '#type' => 'select',
    '#title' => t('Select your dealer'),
    '#options' => $dealers,
    '#default_value' => 0,
    '#prefix' => '<div id="dealer-replace">',
    '#suffix' => '</div>',
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#attributes' => ['class' => ['btn btn-primary'] ],
    '#value' => t('Contact'),
  ];

  return $form;
}

```

ajax callback:

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

  return $form['wrapper']['dealer'];
}

```

I will highly appreciate any suggestion!

# Answer
> 0 votes
Well, as it turns out, the problem was that the form definition was in an .inc file and Ctools couldn't find it. The solution was to simply put the form definition, submit handler and ajax callback for select in a .module file.

---
Tags: forms, chaos-tool-suite
---


# Question
Title: Step back button for Commerece offsite payment method
I'm writing an offsite payment method for Drupal Commerce (I need that to interact with my bank API). The thing is that when I create a form to send to payment server via `PAYMENT_redirect_form` I have the only button - **SUBMIT** there. I want to add one more button there - smth like **GO A STEP BACK** to return to checkout state. So, i've created one more button, but it performs the same action as SUBMIT - goes to payment server... I think i'm missing smth very simple, but how can i make that one more button in payment submition form to perform a step back like those we have in checkout proccess?

Will be very thankful for your advice :)

# Answer
> 0 votes
It's likely you can't, because the form's action will be on a PayPal domain. So it'll always be submitted to them, and your site will never know about it.

The simplest solution would be to use a styled link instead of an input.

---
Tags: commerce
---


title: how i display price bar slide in view

text:
# Question
Title: how i display price bar slide in view
i am a amateur in DRUPAL, i want CREATE a commercial page, i want display something like this in the PICTURE, what module i used ? AND WHAT is steps? because i can't FOUND any thing about this:

I want some thing simply and efficace Please someone can help me !???? tgojrtorjbojrojgbjogbjobgfjob

# Answer
You're looking for the Views Contextual Range Filter module.

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.

Image from module page.
> 1 votes

---
Tags: views, search, commerce
---


# Question
Title: How to create a custom menu in Drupal 7?
I need to create custom menu in Drupal 7. I don't need to add links on Main menu, but instead I need to create **new** menu with new menu links.

How can I do so?

# Answer
> 4 votes
# Step 1: Create the menu

Navigate to `admin/structure/menu/add` in your site and add the menu you want. Add at least the "Title" of the menu (like *Custom menu*), save it, and it will show up in `admin/structure/menu` also. From there you can start to add menu items (which will be the "new links" you are looking for).

# Step 2: Make the menu visible

Head over to `admin/structure/block` to indicate in which region of your theme you want that newly added menu (*Custom menu*) to be shown.

# Step 3: Clear the cache

And don't forget to clear the cache (since you're changing things that are cache sensitive ...). I think "menu" cache should be sufficient, but to be sure I usually just clear all caches ...

# Answer
> 1 votes
After adding your new menu, you might have to clear the caches so Drupal can rebuild the menus. Click "Empty all caches" at `admin/config/development/performance`.

---
Tags: routes, 7
---


# Question
Title: How do I display two different views for a single content?
I'm quite new to drupal and trying to learn this after working with a very different CMS system the past ten years. Here is my issue/question:

I have a content type that I'd like to have two distinctly different views. The first view contains a form (that does not use any drupal module). When a user submits the form, I'd like to show a 'confirmation page' view for that same content type (since it has info that I'd like to show in the confirmation view). What would be the url to use for the different view?

# Answer
You will need a module for your form in this content type, there is no other way. (unless you want something complicated within an iFrame).

Either write a custom module yourself, or use the usual Webform module
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Parameter upcasting in Drupal 8 with Form Controller
I have created a custom module with `mymodule.routing.yml` in which I am using own parameter `{my_menu}`. I have created a `mymodule.services.yml` file too in which I have used class for `param conversion`. Parameter conversion class is calling properly but I am not able to get the parameter in `Form Controller` class.

Code that I have written :

**mymoudle.routing.yml :**

```
entity.my_menu.mymodule:
  path: '/node/{my_menu}/mytab'
  defaults:
    _title: 'My Title'
    _form: '\Drupal\mymodule\Form\MyModuleformControllerForm'
  requirements:
    _permission: 'edit my page'
    _entity_access: 'my_menu.update'
  options:
    _node_operation_route: TRUE
    parameters:
      my_menu:
        type: my_menu

```

**mymoudle.services.yml :**

```
services:
  my_menu:
    class: Drupal\mymodule\ParamConverter\MyModuleParamConverter
    tags:
      - { name: paramconverter }

```

**src/ParamConverter/MyModuleParamConverter.php :**

```
/**
 * {@inheritdoc}
 */
public function convert($value, $definition, $name, array $defaults) {
  dsm($value); // Node id that exists.
  return Node::load($value);
}

/**
 * {@inheritdoc}
 */
public function applies($definition, $name, Route $route) {
  return (!empty($definition['type']) && $definition['type'] == 'my_menu');
}

```

**src/Controller/MyModuleformControllerForm :**

```
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  dsm($node); // It is null here
}

```

# Answer
> 2 votes
Your variable needs to be called my\_menu, check ControllerResolver

---
Tags: 8, routes
---


title: Add signature to features

text:
# Question
Title: Add signature to features
I love to work with features! I often work with several colleges on the same feature and I'ld like to add a signature to the features. So we can see who worked last on the feature (without having to dig in Bitbucket).

It must be possible since the example Features do so:

But all I get are Unavailable signatures :(

Any one know this magic?

# Answer
> 1 votes
I wrote a patch which will allow users to enter an "Author" name when creating/updating a feature.
When provided, the signature will take the Authors value, if not fallback on standard workflow.

Setting the signature was my goal and I succeeded. For those interested, here is the patch:

```
diff --git a/sites/all/modules/contrib/features/features.admin.inc b/sites/all/modules/contrib/features/features.admin.inc
index a4203a0..3c5c913 100644
--- a/sites/all/modules/contrib/features/features.admin.inc
+++ b/sites/all/modules/contrib/features/features.admin.inc
@@ -168,6 +168,15 @@ function features_export_form($form, $form_state, $feature = NULL) {
     '#size' => 30,
     '#element_validate' => array('features_export_form_validate_field'),
   );
+  $form['info']['author'] = array(
+    '#title' => t('Author'),
+    '#description' => t('Examples: Patrick, John'),
+    '#type' => 'textfield',
+    '#required' => FALSE,
+    '#default_value' => !empty($feature->info['author']) ? $feature->info['author'] : '',
+    '#size' => 30,
+    '#element_validate' => array('features_export_form_validate_field'),
+  );
   $form['advanced'] = array(
     '#type' => 'fieldset',
     '#title' => t('Advanced Options'),
@@ -832,7 +841,7 @@ function _features_export_generate($export, $form_state, $feature = NULL) {

   $module_name = $form_state['values']['module_name'];
   // Directly copy the following attributes from form_state
-  $attr = array('name', 'description', 'package', 'project path');
+  $attr = array('name', 'description', 'package', 'project path', 'author');
   foreach ($attr as $key) {
     $export[$key] = isset($form_state['values'][$key]) ? $form_state['values'][$key] : NULL;
   }
@@ -1083,7 +1092,10 @@ function features_admin_form($form, $form_state) {
       '#disabled' => $disabled,
     );

-    if (!empty($module->info['project status url'])) {
+    if (!empty($module->info['author'])) {
+      $uri = check_plain($module->info['author']);
+    }
+    else if (!empty($module->info['project status url'])) {
       $uri = l(truncate_utf8($module->info['project status url'], 35, TRUE, TRUE), $module->info['project status url']);
     }
     else if (isset($module->info['project'], $module->info['version'], $module->info['datestamp'])) {

```

---
Tags: 7, features
---


title: Mark deletion on custom fields

text:
# Question
Title: Mark deletion on custom fields
I am using mongodb as the backend for the node\_save functionality and I have migrated my custom fields. So for every node save it calls the `hook_field_storage_write()` . Thus the data is saved in the mysql and then calls the mongodb implementation. This hook inserts the document in mongodb and calls the `mongodb_migrate_write_helper`. In the function the migrated fields are set with the value of deleted column as 2.

Thus if I have migrated a field 'field\_email' from mysql to mongodb the mongodb\_migrate\_write\_helper sets the field\_email for the entity as deleted = 2. What does the deleted flag do? Are the rows marked as deleted = 2 deleted in a specific point of time or by some hook calls? . I have seen in many instances in the core modules where deleted is set as 1. Are there any purge scripts that are run at specific points of time for deletion of fields marked as deleted.

```
function mongodb_migrate_write_helper($entity_type, $entity_id) {
  $migrate_fields = variable_get('mongodb_migrate_fields', array()); // Migrated field names are stored in variable.
  foreach ($migrate_fields as $field_name => $v) {
    $field = field_info_field($field_name);
    db_update(_field_sql_storage_tablename($field))
      ->fields(array('deleted' => 2))
      ->condition('entity_type', $entity_type)
      ->condition('entity_id', $entity_id)
      ->execute();
    }
}

```

# Answer
The `deleted` column in a field table is:

> A boolean indicating whether this data item has been deleted

Therefore the only valid values are 0 and 1. Or, at least, 0 == false, and anything else is equivalent, and == true.

You'd need to ask the module developers for their motivation to be 100% sure why they're bucking the trend there and using '2' instead, but maybe it's some sort of hack to exclude certain records from being queried with `WHERE deleted = 1`, but still available for `WHERE deleted > 0`. Not sure though, that's just a guess.

As for what it does: it simply marks a record as deleted, so it won't be included in query results, and can be moved into a deleted data table, from which it's subsequently removed on cron runs.
> 3 votes

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


# Question
Title: What are the "Files" that Metatag module allows adding Metadata to?
In Drupal 7, if you go to `Configuration > Search and metadata > Metatag > Settings (Tab)` the module Metatag allows you to add Metatags to "Files"... What are these files?... As everyone are knows, files are not webpages and I guess there aren't very much good reasons to build themselves as web pages... So why would the module attach them \ associate them with meta tags???

# Answer
> 2 votes
They are all the files managed by Drupal through attachments, images & file fields. In D7, these managed files are entities. As such, the metatag module supports it.

This isn't useful with the metatag module alone, but if you had a configuration where files had their own display page (e.g. the file entity & media module), it could be utilized.

---
Tags: 7, meta-tags
---


title: How to add extra class in main menu?

text:
# Question
Title: How to add extra class in main menu?
I'm creating custom theme. I am struggling to create main menu with drop down. I created a menu with custom code:

```
 <?php
            $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
            print drupal_render($main_menu_tree);
          ?>

```

But it doesn't working as I want. I need to add class in that particular `<UL>` tags. How can I achieve that?

I tried to Hook custom function in templates file. But no luck. How to call custom function into view page?

Below are some more screenshots.

**Main menu with correct:**

**Menu with Wrong:**

How to call custom menu design in custom theme?

# Answer
You can use Menu Attributes Module to add classes.

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.

To custom code it, you can add class to menu links using hook\_menu\_link\_alter . Try something like this:

```
$item['options']['attributes']['class'] = array('class-one' , 'class-two');

```
> 1 votes

---
Tags: 7, theming, routes
---


# Question
Title: prevent user from putting 0000 in date field
How can I force date validation upon input of a content type so that a user cannot type in 0000 as the year which causes an error in Drupal 7.

# Answer
You can use Field Validation to check against the date, it has a sub module or feature that has date validation.

You could also do this with a hook, probably hook node validate would be your best option for this.
> 3 votes

# Answer
You can use this module to define fields as date fields:

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

Alternatively, you could add JS or PHP validation of expected formats to your form.
> 0 votes

---
Tags: 7, datetime
---


title: Add new date type?

text:
# Question
Title: Add new date type?
How can I add a new date type?

Under "Date type" I have "Long", "Medium" and "Short". How can I add a new option to this list?

# Answer
> 3 votes
1. Go to /admin/config/regional/date-time
2. Click "Add date type"
3. Fill in the details.

If you require a different format than those available, you can add a new one at /admin/config/regional/date-time/formats.

---
Tags: datetime
---


title: How do I translate to English?

text:
# Question
Title: How do I translate to English?
I have a Drupal 8 multilingual site (Spanish \[default\], English, Italian and Ukranian).

>

On admin/config/regional/translate I can translate to Spanish, Italian and Ukranian but not to English.

>

How can I translate strings to English with this UI?

# Answer
By default, if you have English configured, it is not available as a translation target. However, you are only one checkbox away from enabling that feature:

Go edit English and make it available for translation. This will make English behave as any other language and from then on, you can "translate" to English as well:

All strings will still fall back on the built-in English text (eg. if you also have Hungarian on the site, untranslated strings in Hungarian will fall back on Drupal built-in English text). However when English is used for display, all your overrides will be effective. (Cross-language fallbacks can be implemented in contributed modules now with Drupal 8's service architecture for string lookups).

Source: http://hojtsy.hu/blog/2013-aug-20/drupal-8-multilingual-tidbits-12-english-can-now-be-translated

Result:
> 12 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: Show commenter IP address to admins (Drupal 7 / AdaptiveTheme)
Once upon a time, with an older version of AdaptiveTheme, I got this to work by patching `templates/comment.tpl.php`. The patch I was looking looked something like:

```
-      print t('Submitted by !username on !datetime',
-      array('!username' => $author, '!datetime' => '<time datetime="' . $datetime . '">' . $created . '</time>'));
+      if ( function_exists('user_access') && user_access('administer site configuration') ) {
+          $authorstring = 'Submitted by !username on !datetime from !hostname';
+      }
+      else {
+          $authorstring = 'Submitted by !username on !datetime';
+      }
+      print t($authorstring,
+      array('!username' => $author, '!datetime' => '<time datetime="' . $datetime . '">' . $created . '</time>', '!hostname' => $comment->hostname));

```

That was for a much older version of AdaptiveTheme (7.x-1.x, I think).

Thanks to hints from Laryn, I now have a working patch that does what I need. Here it is:

```
From 8c064aca6e2fd35da411473c5e50ce471d30d3cf Mon Sep 17 00:00:00 2001
From: Zed Pobre
Date: Tue, 4 Nov 2014 02:54:21 -0500
Subject: [PATCH] Administrators see submitter IP addresses in comments

---
 at_core/inc/preprocess.inc |   24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/at_core/inc/preprocess.inc b/at_core/inc/preprocess.inc
index ef50fda..ba9b45e 100755
--- a/at_core/inc/preprocess.inc
+++ b/at_core/inc/preprocess.inc
@@ -832,13 +832,23 @@ function adaptivetheme_preprocess_comment(&$vars) {

   $vars['datetime'] = format_date($vars['comment']->created, 'custom', 'Y-m-d\TH:i:s\Z'); // Generate the timestamp, PHP "c" format is wrong

-  $vars['submitted'] = t('Submitted by !username on !datetime',
-    array(
-      '!username' => $vars['author'],
-      '!datetime' => '' . $vars['created'] . '',
-    )
-  );
-
+  if ( function_exists('user_access') && user_access('administer site configuration') ) {
+    $vars['submitted'] = t('Submitted by !username on !datetime from !ipaddress',
+                           array(
+                             '!username' => $vars['author'],
+                             '!datetime' => '' . $vars['created'] . '',
+                             '!ipaddress' => ip_address(),
+                                )
+                          );
+  }
+  else {
+    $vars['submitted'] = t('Submitted by !username on !datetime',
+                           array(
+                             '!username' => $vars['author'],
+                             '!datetime' => '' . $vars['created'] . '',
+                                )
+                          );
+  }
   // Unpublished?
   $vars['unpublished'] = ''; // Initialize for backwards compatibility
   if ($vars['status'] === 'comment-unpublished') {
--
1.7.10.4

```

# Answer
It looks like you're adding your code within the `adaptivetheme_preprocess_node` function but you should be working within the `adaptivetheme_preprocess_comment` function (a little further down the page).

Specifically the following could be modified with your code above as a starting point *(starting at line 835 in preprocess.inc for AdaptiveTheme 3.2)*:

```
  $vars['submitted'] = t('Submitted by !username on !datetime',
array(
  '!username' => $vars['author'],
  '!datetime' => '<time datetime="' . $vars['datetime'] . '" pubdate="pubdate">' . $vars['created'] . '</time>',
)
);

```
> 1 votes

# Answer
Also you can use module https://www.drupal.org/project/user\_ip\_address which allows to add field with submitter ip address
> 0 votes

---
Tags: comments, theming
---


# Question
Title: Display members of Organic Groups that are members of a given Organic Group in Views
Suppose I have an OG called "Color" Then, suppose I have OG Groups called: "Red" "White" "Blue"

Within of "Red", there are users that are members.

It is easy to define a filter to display members of "Red".

What I want to do is have a view that displays members of "Red", "White" and "Blue" because each of those OGs are members of "Color".

How do I do that without making each member belong to both "Red", and "Color"?

# Answer
> 0 votes
What you can do is add a relationship to the View for the User entity (current user). From there, you have the ability to create filters based on the OG group(s) that the user belongs to.

---
Tags: views, organic-groups
---


# Question
Title: Assign User Points in existing website which already contains content
Question specific to "User Points" module, backcopy of question from here due to no response: https://www.drupal.org/node/2492933

Drupal 7 -

I have a website which is already running for more than 2 years. Many users have been adding content to it and now I have a requirement where I need to assign points to the user. I came across this great module but this does not let me assign values to the user based on the content they have already contributed, revisions already worked on and also the comments provided already.

I have tried to google and also checked the module thoroughly but there is no way to do what I want to achieve. Is there a way to achieve this?

# Answer
I used User Points Contributed modules and I provided a patch with which points are awarded for nodes and revisions in past and also the points transactions are stored across with the dates on which the node was created or revision was made.

Issue and patch: https://www.drupal.org/node/1187616#comment-10004999
> 1 votes

# Answer
I think User Points Contributed modules is your best alternative available today. I. e. submodule **userpoints\_retroactive**. Excerpt from that project page:

> Award users points for their nodes, comments and votes that they have created so far, before userpoints was enabled on the site.

However, the port of this module to D7 still **needs work**. Maybe you can/want to somehow contriute to the finishing touch of that issue?

PS: there is also Berdir's Api documentation about this submodule ... (maybe that helps somehow).
> 1 votes

---
Tags: users, userpoints, rating, 7
---


title: Access callback called multiple times?

text:
# Question
Title: Access callback called multiple times?
I have this hook\_menu implementation

```
$items['lablab/%level/%unit/%tab/%section/%exercise/go'] = array(
        'title'           => 'My lablab',
        'title callback'  => 'lablab_form_set_title',
        'page callback'   => 'drupal_get_form',
        'page arguments'  => array('lablab_form',1, 2, 3, 4 ,5),
        'access callback' => 'lablab_access_exercise',
        'access arguments' => array(5),
        'file'            => 'lablab.forms.inc',
        'file path'       => drupal_get_path('module', 'lablab').'/includes',
        'type'            => MENU_CALLBACK,
    );

```

And then in the access callback

```
function lablab_access_exercise($w_exercise){
    dpm($w_exercise->value());
}

```

Then when i enter the hook\_menu page it shows me at least 4 dpms, is this normal?

# Answer
the wildcard %exercise was returning several entities.
> 1 votes

---
Tags: 7, routes
---


title: Page Caching wrong CSS

text:
# Question
Title: Page Caching wrong CSS
got a weird issue I was hoping someone could help with.

I have a site that uses multiple subthemes, with different ones being served depending on url var. IE, subsiteone.mysite.com, and subsitetwo.mysite.com get different themes, but the same content.

I am using a module to style each subtheme css via theme settings (https://www.drupal.org/project/style\_settings) and am having issues pages caching the wrong stylesheet.

The module setup works fine, rewriting modified css to files/style\_settings/subthemeone.css

* On initial save, all is fine, and page pulls correct (rewritten) files/style\_settings/subthemeone.css path.
* After a while, page caches (?) and reverts css reference to the old (unwritten) sites/all/themes/subthemeone/subthemeone.css

Clearing drupal cache results in the correct (rewritten) reference being called again. Would love to NOT have to resort to disabling caching/etc, so any thoughts appreciated!

**EDIT:** Using slightly modified code graciously provided below:

**style\_settings.module**

```
function style_settings_init() {
      setcookie('custom_theme', $GLOBALS['theme'], REQUEST_TIME + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
}

```

**settings.php**

```
// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
  //drupal_set_message($conf['theme_default'], 'status');
}
// Disable page cache if cookie not set so module can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

```

# Answer
Answer is in here: https://www.drupal.org/node/361832#comment-4204294

You'll need a cookie for the user saying what theme they are using. This is done in a hook\_init() call.

```
  // If no cookie is set, set a cookie with the value of theme_default.
  if (empty($_COOKIE['custom_theme'])) {
    setcookie('custom_theme', $GLOBALS['theme'], REQUEST_TIME + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
  }

```

Then you'll need to modify the page cache cid ($\_SERVER\['REQUEST\_URI'\]) in settings.php

```
// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
}
// Disable page cache if cookie not set so switchtheme can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

```

Code is from D6 but looking it over really quickly it should work for D7.
> 1 votes

---
Tags: theming, caching
---


# Question
Title: How to move node contents from local to server environments?
What is the best way to move node contents from a local environment to a server environment?

I don't want to go with the Features modules.

Any examples that we can go with dbscripts?

# Answer
> 1 votes
Consider using module Backup and Migrate. From the modules project page:

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

---
Tags: nodes, migrations
---


# Question
Title: Modifying views exposed filter query string
I'm looking for a way to modify views' resulting query string (URL) after applying a filter, but have been unsuccessful so far.

I have a view with exposed filters, taxonomy lists to be specific. Hitting apply generates something like: www.mysite.com/myview?foo=123
My goal is to have it instead generate: www.mysite.com/myview?foo=bar

I know views' exposed filters depends on tid for the filter to work when visiting a page (e.g. pasting a link and visiting the page), and I have some `hook_views_pre_build`code to handle that. My issue is going the other direction. What hook, function, or other approach can I use to modify that?

For reference I've tried replacing view object contents in `hook_views_pre_build`, `hook_views_post_build`, `hook_views_pre_execute`, `hook_views_post_execute`, and `hook_views_query_alter`, but nothing seems to have the desired effect. I do not want contextual filters due to the need for order independence.

# Answer
> 1 votes
Came up with a solution using `hook_views_pre_render` combined with a JS `history.replacestate`. More of a workaround, but it does the job. Would still like to find a way to modify the view object or a PHP hook though.

Here's a stripped down version of the php hook implementation:

```
function mymodule_views_pre_render(&$view) {
  if ($view->name == "myviewname") {
    $path_settings = array("mymodule" => array('query_params' => array()));
    foreach ($_GET as $key => $val){
      if (array_key_exists($key, $view->exposed_input)) {
        $path_settings['mymodule']['query_params'][$key] = $view->exposed_input[$key];
      }
    }
    drupal_add_js($path_settings, 'setting');
  }
}

```

Then in the module's js attached behaviors:

```
function tidyViewsQueryString() {
  currentLocation = window.location.href;
  for (var key in Drupal.settings.mymodule.query_params) {
    if (Drupal.settings.mymodule.query_params.hasOwnProperty(key)) {
      currentLocation = updateUrlParameter(currentLocation, key, Drupal.settings.mymodule.query_params[key])
    }
  }
  if (currentLocation != window.location.href){
    window.history.replaceState(null, document.title, currentLocation);
  }
}

//From https://gist.github.com/niyazpk/f8ac616f181f6042d1e0
function updateUrlParameter(uri, key, value) {
    // remove the hash part before operating on the uri
    var i = uri.indexOf('#');
    var hash = i === -1 ? ''  : uri.substr(i);
         uri = i === -1 ? uri : uri.substr(0, i);

    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        if (value.length > 0)
          uri = uri.replace(re, '$1' + key + "=" + value + '$2');
        else
          uri = uri.replace(re, '$1' + '$2')
    } else {
        uri = uri + separator + key + "=" + value;
    }
    return uri + hash;  // finally append the hash as well
}

```

---
Tags: views
---


# Question
Title: Can I show an image in place of a Drupal 6 message?
I have a form, that upon completion, goes back to the page it was called from and displays a message of success when everything is done. Is it possible to just display an image on that same page, or do I have to redirect to a new page to show the form submission success image?

# Answer
There is a way to do this.

One problem here is that the confirmation message is just that, a confirmation which is unrelated to any context.

What you could do is to use jQuery to react to the string of the message is being put out ... so if it's something along the lines of: "Success, your message was sent" - which you "could" assign a string-match on and create a reaction to it. Most likely you would append/prepend a container with a custom confirmation message or image at this point. This would involve a bit of a work-around however (Assign a .js script to handle it - which in Drupal means editing your template.php file).

I usually opt for the confirmation page either way. Users also often don't see the little confirmation message on the same page and a dedicated confirmation page can go a long way in keeping a user on your site - you could for instance use this to display a range of your latest blog entires/products etc. as a block on that page or even have an ad block to collect a few clicks, depending on the kind of site you're working on atm.
> 0 votes

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


# Question
Title: How do I create separate node/add forms for different uses and for the same content type?
I am using the agreservation module for a room reservation system/events calendar. As a result, the reservation content type has a large number of fields to accommodate info on speakers, contact info for participants, etc.

I have two uses for creating reservations: events, where more information is needed; and room reservations for maintenance issues, which require less info. However, having all of this info on one content type is essential: both uses require the room reservation and resource conflict functionality.

Restricting fields by role isn't an option as I have users who will need access to all fields; but when doing their work, both uses will be easier and quicker by having separate forms. It's more of a usability thing: people don't have to see fields they don't need for a particular use. Mainly, if someone needs to reserve a room for maintenance, the person making the reservation doesn't need to scroll through all of the fields for the event.

So, if a reservation node has fields a-j, how can I create separate node add forms so that fields a,b,c,d,e and f needed for creating registering an event are on one instance of the form and e,f,g,h,i and j are on another instance for the room reservation? There is overlap because the event involves the reservation of a room.

I thought about doing this via theming, but can a template be tied to a menu item?

# Answer
> 0 votes
You can use panels to create different a different views of the node add/edit forms. I've done something similar before but I had to add a query string to the URL and show the different view that I had setup. I will try to update with more information later.

**Update with Instructions of how this can be done**

Here is an overview of how I achieved this before. I used panels Panels and Context modules to set up this and show two different views for the node edit forms (Keep in mind your required fields will need to be present but this is just an overview of how you can achieve something like this.) First, some knowledge of both of these modules will be needed but you can learn as you go. First thing that I knew I needed was exactly what you said, two different node edit/add views where different fields showed at different times depending on the job being accomplished. I am going to run through a simple scenario that probably won't make much sense but it will show that it can be done with using these two powerful modules together.

First, I set up a context based on a query string. Go add a context in the context UI and add a condition based on query string. Then place your query string (mine is "view=maintenance") and not sure if you have to but I went ahead and added a body class by theme HTML in what the context does (you will see that in the context UI but you are going to really use this context in panels so just save it to use later).

Next go to Page manager and there is a page that you can use called Node Edit, you will need to turn this on and create your variant. You will want to choose node type in the context and restrict this to only the content type you want this to work with since it is specific to just that node edit form. For one of my views I wanted the whole form was needed. Use add content, Forms, and add general form. Now you have the form you had before just being controlled by panels. You will want to add a visibility rule and choose PHP code for the visibility rule. Then you can use the code below to find out if your context is present (Use Not if you want the full form to show without the query string).

```
$contexts_module = context_active_contexts();
if (array_key_exists('machine_name_of_context', $contexts_module)) {
  return TRUE;
}

```

So now you have the full form showing with or without the query string. At this point the form should not show on the other context. This is the only part that I don't really like but it works and its been the only way without writing a whole bunch of code that I have found can be flexible enough for others to change after I hand a site off to a client. You will have to add the fields that you want to show when the query string is present or not present (depending on what you chose earlier) and copy the code from above and either choose NOT or not choose NOT and also add the node submit buttons and choose that as well. (You of course can set each field up and hide the fields you want according to the query string or some other way, just play around with it until you learn it and understand what it can do).

I'm not really great at writing these instructions but hopefully you understood what it can do and how to do this. I will try to revise them over time to help future viewers. I am also including some screenshots below that will show this in action.

**Context UI Query String setup**

**Panel variant for clarity**

**This shows the whole form when the query string is present**

**This is the not code, so when query string isn't present show this**

**Shows url query string but (a partial screen shot) full form is shown to user**

**Shows form trimmed down for normal use**

---
Tags: theming, entities, nodes
---


title: hook_theme_registry_alter caches

text:
# Question
Title: hook_theme_registry_alter caches
this function caches the output, so it doesnt work if I want to change dynamically between two template files. For example user-profile.tpl.php and user-profile-project.tpl.php

Code:

```
function hook_theme_registry_alter(&$theme_registry) {
  $tmp1 = arg(0);
  $tmp2 = arg(1);
  $tmp3 = arg(2);

  if ($tmp1 == "user" && is_numeric($tmp2) && !$tmp3) {
    $user = user_load($tmp2);
    $roles = $user->roles;
    if (in_array('project', $roles)) {
     $theme_registry['user_profile']['template'] = 'user-profile-project';
    }
  }
}

```

So how can I do this differently?

# Answer
Implement `hook_user_profile_preprocess()` and add your template suggestion as last entry of `$variables['theme_hook_suggestions']`. Instead of using `arg()` as you are doing, use `menu_get_object('user', 1)`.

`hook_theme_registry_alter()` is not good because:

* Drupal caches what it gets from `hook_theme_registry_alter()`

```
  // _theme_registry_build()
  if ($cached = cache_get('theme_registry:build:modules')) {
    $cache = $cached->data;
  }

```
* It is never invoked for each page request Drupal gets; so you could not for which user the user profile is.

Then, the Drupal way would probably be to check the user has a specific permission rather than a specific role.

```
if ($account = menu_get_object('user', 1) && user_access('your permission', $account)) {
  $variables['theme_hook_suggestions'][] = 'your template suggestion';
}

```
> 1 votes

---
Tags: 7, hooks, theming
---


# Question
Title: Passing arguments to a URL with view blocks and contextual filters
I have a page that displays nodes of awards. These awards have taxonomy Year added to them. The url to them is : url.com/aboutus/awards. I have a block view created that pulls the awards and I've set a contextual filter that filters the awards by year.

When I type in a URL such as url.com/aboutus/awards/2013, I want only the 2013 awards to be listed. I've been trying to accomplish this with a dynamic field but the argument isn't passing.

Does anyone have any idea how I can solve this? (I am a newbie to Drupal, so apologies if my vocabulary isn't completely accurate.)

# Answer
Views comes with a (initially disabled) page that will display your taxonomy terms for you. If you look for "Taxonomy Term" in your views overview you should find it. It will display all of your taxonomy terms through a view.

It is recommended that you enable the view, clone it, disable the original and work with the clone, to begin with. However, be careful as it will turn all your taxonomy terms into a views page.
> 1 votes

# Answer
You simply follow the following steps in order to make it work.

Now add your dynamic field value say i.e year and pass the argument value as shown below.
> 0 votes

---
Tags: views
---


# Question
Title: Restore drupal commerce cart if paypal payment gets failed
I want my user to see what he added to his cart after redirecting from paypal, if his/her paypal payment gets failed or user by himself abort/cancel transaction(may be intentionally or by mistake). I want to preserve the state of cart for user.

Right now drupal commerce clears user's cart if payment gets failed. Please help.

# Answer
> 1 votes
Following solution worked for me

```
function custom_module_commerce_checkout_page_info_alter(&$checkout_pages) {
  $checkout_pages['payment']['status_cart'] = TRUE;
}

```

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: Views Group By with profile with aggregation and relationship
I am looking for solution for following problem.

**Problem:**

I have "article" content type. I have list of some users who are associated with different - 2 roles.

User having role "editor" can create articles. So editors type of user have created number of contents.

Now I need to display a list of featured articles on home page using Views-block with given conditions.

* Every author who have created most articles, his block should come in top of list with his recent one article.
* It should be followed by author name.
* I will show top 10 articles of different - 2 authors with correct author ordering. I mean author who have created most articles should come on top followed by rest of authors.

**Note:** In this block one author should come once with correct order.

**Resolution:**

* I created views block with filter criteria where content type = 'article'.
* I enabled aggregation.
* I make relationship with User and in fields choose `COUNT(DISTINCT
Content: Title) | Aggregation settings` option.
* I choose `Query settings: Distinct`.

I tried above possible solution but unable to get correct result. I am still getting duplicate result and also the order is not correct.

# Answer
> 0 votes
Consider using the Views Distinct module. From its project page:

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Curious to hear if this helps to answer this question.

---
Tags: views
---


# Question
Title: How to add a custom block on Print module?
I'm using the Print module. I wonder if there is a way to print a custom block on the `print.tpl.php`. Because I want to print a node but that node has its own custom blocks that is rendered on its `.tpl`. I want the PDF of the Print module to also get all those blocks on the display.

Any help would be greatly appriciated.

# Answer
> 1 votes
You can do this by using Display Suite module. It allows you to add the block as a field in the "Manage display" tab of your content type. You can then place it wherever you want on your node page.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

---
Tags: 7, nodes, files
---


# Question
Title: How to change logged-in user permission in hook_node_view?
Can anyone please let me know how can we achieve the following scenario

I want to change the role of the logged-in user before viewing the node. When you click on the node for viewing it, I want the roles to be changed and then display the content accordingly with the access permissions.

# Answer
> 1 votes
# Use Rules module

Consider using the Rules module for this. The actual details of your question need some further refinement (to better explain what you actually want to achieve, and to include some of your extra comments), but here is a draft version of the rule to do what you are lookiung for:

* **Event** : Content is viewed (located within "Node")
* **Condition** : logged in user = userid associated with the node
* **Action** : Grant role to user

However, since this event only seems to happen "after" the content is viewed, you probably encounter some access denied situation (refer to open issue 1336402 for more details). I haven't been able to find some event like "when a user encounters an access denied" (need to do more research if that's doable). Therefor consider the alternative described below also.

# Use Content Access module integration with the Rules module

Another approach might be to use the Content Access module, and the Content Access Rules Integrations module. So that "After saving content" (= Event), you "Give 'authenticated user' the permission to 'view own content' for the specific node" (= Action). That way, the permission is set when the node is edited already (which is not exacty what you are asking for in your question, but would achieve the same result) I believe.

This would be a variation of what is explained in this article also (within "Access Control Customized for Your Needs").

# Use Rabbit Hole module

In one of your comments you wrote "*I wanted to compare the logged in user is same as the one associated with the node ... if they are same then allow the access else deny access to the node*". Even though I've no experience with it, it appears to me that possibly the Rabbit Hole module might be a solution for you. Here is part of what it says on its project page:

> ... Perhaps you want a user to be able to view nodes that he has created, but no one else's.

# Answer
> 2 votes
using `hook_node_access()`,here you can check user role by using

```
global $user;
$roles=$user->roles;

```

# Answer
> 0 votes
You can do this by using below modules :

1. Nodeaccess

> Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

2. Userpoints Node Access

> The Drupal userpoints nodeaccess module enables you to sell access to a single node for a specific category and amount of userpoints.

---
Tags: nodes, rules, users
---


# Question
Title: How to add page content and webform as tab in a page?
I'm using drupal 7 and I have a content type "service".

And I have a enquiry page, built with webform with following fields:

* Name
* Email
* Service
* Message

In each service page, I would like to have a tab for page content, a tab "Enquiry", with the enquiry webform in the tab.

For service field, I would like it to show page title as default.

Is there any way I can do it?

# Answer
> 2 votes
There are two ways to do that :

1. Write a custom module and create a menu path "node/%node/enquiry" and return your enquiry form programmatically. In hook\_menu you can set `type = MENU_LOCAL_TASK` that will display the path as tab.
2. You can create a view page that displays webform and select the menu `Menu tab` under menu setting. Path of page should be `node/%/enquiry`, so that It will create a tab on `node/%` page. Screenshot for the second method :

# Answer
> 0 votes
Try Quick Tabs

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content.

Try out a demonstration

---
Tags: 7, webforms
---


# Question
Title: Add conditional javascript from CDN (external library)
I know it has been discussed here several times, but:

Is there a way to include conditional JS from CDN in the head section?

My goal is to somehow use drupal\_add\_js, external. That will stick in the head area, even if I move scripts to the bottom of the page. It is about html5shiv and respond.js

The classic way to add js was discussed here and here. So what I've managed so far is to bring

```
<?php
function THEMENAME_preprocess_html(&$variables) {
    drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.js', 'external');
    drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js', 'external');
}

```

The problem is conditional. One way to add conditional elements, with drupal\_add\_js. I know how to load local conditional js, using a variable I'm creaing in template.php, like so:

```
<?php
$html5shiv = array(
    '#tag' => 'script',
    '#attributes' => array(
        'src' => file_create_url(drupal_get_path('theme', 'THEMENAME') . '/js/html5shiv.js'),
    ),
    '#prefix' => '<!--[if lte IE 9]>',
    '#suffix' => '</script><![endif]-->'
);
drupal_add_html_head($html5shiv, 'html5shiv');

```

But this will only put the conditional JS even before the meta title element and I need this to be loaded at the end of my section, JUST BEFORE my scripts loaded from theme.info (scripts\[\] = js/main.js). And of course, this will load local JS, not external.

Any ideas?

# Answer
> 0 votes
The Boilerplate theme does it for CSS by adding to `template.php` in the theme:

```
function boilerplate_preprocess_html(&$vars) {
  if (!module_exists('conditional_styles')) {
    boilerplate_add_conditional_styles();
  }
}

function boilerplate_add_conditional_styles() {
  // Make a list of base themes and the current theme.
  $themes = $GLOBALS['base_theme_info'];
  $themes[] = $GLOBALS['theme_info'];
  foreach (array_keys($themes) as $key) {
    $theme_path = dirname($themes[$key]->filename) . '/';
    if (isset($themes[$key]->info['stylesheets-conditional'])) {
      foreach (array_keys($themes[$key]->info['stylesheets-conditional']) as $condition) {
        foreach (array_keys($themes[$key]->info['stylesheets-conditional'][$condition]) as $media) {
          foreach ($themes[$key]->info['stylesheets-conditional'][$condition][$media] as $stylesheet) {
            // Add each conditional stylesheet.
            drupal_add_css(
              $theme_path . $stylesheet,
              array(
                'group' => CSS_THEME,
                'browsers' => array(
                  'IE' => $condition,
                  '!IE' => FALSE,
                ),
                'every_page' => TRUE,
              )
            );
          }
        }
      }
    }
  }
}

```

Then added to the .info file:

```
stylesheets-conditional[lte IE 8][all][]  = css/compiled/ie8.css
stylesheets-conditional[lte IE 7][all][]  = css/compiled/ie7.css
stylesheets-conditional[lte IE 6][all][]  = css/compiled/ie6.css

```

I'm sure this could be easily adjusted for JavaScript instead

# Answer
> 0 votes
`drupal_add_js()` has a bunch of options you can pass along, including ones for `weight`, and `browsers`. You might have to play around with the weight a bit to get the desired effect, but something like this should work:

```
$options = array(
  'type' => 'external',
  'weight' => -100,
  'browsers' => array(
    array('IE' => 'lte IE 9'),
  ),
);
drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.js', $options);

```

(the `#attached` method of adding scripts should be preferred, but the options will still be the same).

You could also use the `drupal_add_html_head()` method, there's an example on the docs page.

Incidentally, you'll probably need to make sure these scripts come literally before any others in the head, as IE8 and below have very specific load behaviour based on the order of conditional scripts. See this for more info.

---
Tags: 7, javascript
---


title: Facebook Wall module

text:
# Question
Title: Facebook Wall module
I'm trying to use the Facebook wall module for the first time. I've installed it, created a Facebook App and thought that I'd entered all the right configuration information on both. However, the Facebook Wall/Settings/Page Information is telling me that it's "Not able to connect with Facebook".

Quite happy to accept that I've done something wrong but not a clue where to turn to diagnose what's happening as there doesn't appear to be any more information. Can anyone give me any pointers please?

If there's a good resource to guide me that would be really helpful - for example there seem to be different types of Access token, which one should I be using?

# Answer
> 0 votes
You have to check the permission to write to a user's wall, either during signup or doing it manually later - looks like you are missing that permission. You need to get appropriate permission from the facebook.

# Answer
> 0 votes
That module shows that error if it cannot connect to https://graph.facebook.com using CURL, so I suspect either CURL isn't installed on your server or you've entered the Page Name/Access Toekn incorrectly

---
Tags: social-network
---


# Question
Title: Change a output value of a field in a view
I've a view where one of the fields 'titleColor' has the option to return '#000000', '#FFFFFF' or '#FF0000'. I need to show instead of this values 'black', 'white', and 'red'. How can I do it? I've use in other cases Views Conditional module, but I only can insert one else clause.

I hope you can help me,

Thank you very much.

# Answer
> 1 votes
A possible solution is to use the views feature "rewrite result", combined with Views PHP module.

**Note**: this module only has an alfa version as of today, but it's used in over 71K sites anyway.

---
Tags: views
---


title: How to allow reload value in cck field?

text:
# Question
Title: How to allow reload value in cck field?
I have a problem. I wish I achieve for my preloading fields Content Type (Type list). (pre loader like a webform). Loading this list thereby synchronize on a table by the user.

I get to create my field and load the first time. But when you synchronize the table, it is necessary that the field starts to date.

How to allow reload value in cck field?

Thank

# Answer
> -1 votes
I find.

In my instance, I use :

```
 'allowed_values' => array(),
 'allowed_values_function' => '_get_list_catalogue',

```

---
Tags: entities
---


# Question
Title: Not able to get textfield value to generate a ajax dependent dropdown option
I am not able to get the textfield value to generate an ajax dependent dropdown option.That is when i am trying to enter a textfield value in the form and clicking a button to call the ajax function. The form value for the textfield i am getting is blank.Here's the code snippet:

```
/*
* function to add the images to the gallery
* @param: none
* @return: none
*/
function image_gallery_add($form, &$form_state) {
$form['#tree'] = TRUE;
$form['add_image'] = array(
    '#title' => t('Add images to gallery'),
    '#type' => 'fieldset',
);
$form['add_image']['gallery_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Please enter the gallery name'),
);

$form['add_to_dropdown'] = array(
    '#type' => 'button',
    '#value' => 'Add To Dropdown',
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'image_gallery_select_options_callback',
        'wrapper' => 'dropdown_gallery_replace',
    ),
);

$form_field_val = isset( $form['values']['add_image']['gallery_name'] ) ?  $form['values']['add_image']['gallery_name'] : '';
$form['add_image']['select_gallery'] = array(
    '#type' => 'select',
    '#title' => 'Select Gallery',
    // The entire enclosing div created here gets replaced when textfield gallery_name changes
    // is changed.
    '#prefix' => '<div id="dropdown_gallery_replace">',
    '#suffix' => '</div>',
    // when the form is rebuilt during ajax processing, the $selected variable
    // will now have the new value and so the models will change
    '#options' => automobile_get_model_dropdown_options($form_field_val),
    '#default_value' => '',
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
);
return $form;

}
/**
* Handle post-validation form submission.
*/
 function image_gallery_submit($form, &$form_state) {
    $name = $form_state['values']['add_image']['gallery_name'];
     print( $name );exit();
  }

 function automobile_get_model_dropdown_options($key = '') {
     //dpm($key);
   $options = array(
            t($key) => drupal_map_assoc(array(t($key))),
        );
     if (isset($options[$key])) {
          return $options[$key];
      }
      else {
           return array();
      }
  }

 function image_gallery_select_options_callback($form, $form_state) {
   return $form['add_image']['select_gallery'];
 }

```

Can anyone suggests what i am doing wrong? I am attaching a screenshot of the situation too...

# Answer
Not sure, but from the looks of it (I think) you need to set

```
$form['#tree'] = TRUE;

```

When building your form.
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: Views Contextual Filters and URL Aliases
Forgive me if this is a repost, but I have spent days trying to figure this out and everything I have found on drupal.stackexchange and elsewhere have been no help and I am struggling to understand the what views is doing exactly... Here's my problem:

I have a website that has 2 different content types: *category* and *static content*.

Within *category* content type, three pieces of content: little, medium, and big.

In the *static content* content type, I have a autocomplete entity reference field called "Category" that points back to the *category* content type. Next, I have three more pieces of content:

article1, article 2, article3.

Each has a unique title, no path alias set and the category reference field set to "little."

(Just using the "little" category for this question)

So, my goal here is to have the user enter the URL

```
www.example.com/category/article-title

```

and have a view generate the output (I don't want direct access to the node as I want to control all the content formatting).

Now, I can do a "simple" filter on the Content: Category (field\_category) for "little" and the view will display all articles where that condition in met. My problem comes in with the contextual filter and a URL alias.

No matter what I do in contextual filters, if I use a path alias, it will not work. However, if I use a node number (in this case, 2 for "little"), it will work properly. For instance:

```
www.example.com/little

```

will show no results. But,

```
www.example.com/2

```

works (2 is the node number for "little"). In this case, the view generates output with content from node 4 (an article with the title "Little Brown Jug"). This is what it is supposed to do.

I have used both page view and block view, I have created relationships linking the content referenced and the content referencing the category field. (I am sure this works as I can create related article pages with these relationships)

Whether I do this on the preview panel or directly on the URL, the results are the same. the term "little" generates no output, yet "2" does.

Any help here understanding this would be greatly appreciated.

I have added some screen shots

# Answer
> 1 votes
If you set the Views page path to `node/%` and add a Contextual Filter of Node ID and take the default argument from the URL you can use Views to override the node display.

However, this is probably not the best solution. You mention in your post that "I don't want direct access to the node as I want to control all the content formatting" but if you use the correct options you can fully control the node output. My recommendation would be to use Display Suite and control everything via the Manage Display tab of the content type and if necessary an override of `node.tpl.php`

---
Tags: 7, views
---


# Question
Title: node--content-type.tpl.php did not override
and now i stuck in using node override with content type. I followed these step.

1. Create new content type name post (machine name: post)
2. Copy node.tpl.php from module to my\_theme/templates/node/node--post.tpl.php
3. Go to admin-configuration-performance and click "Clear all caches"

Well, it did not work.

Sorry for create duplicated article, but when i followed from answer, it did not work too.

# Answer
If you created your sub theme correctly, the sub theme is located under drupal/sites/all/themes/ and NOT in the drupal/themes folder.

So your tpl.php file needs to be in

> drupal/sites/all/themes/commons\_child/templates
> 0 votes

# Answer
If you copied the `node.tpl` and renamed it to `node--post.tpl.php` then there is no differences between the codes. So how did you find out it was not overridden?

If you have modified the code and you are sure your node template file is not overridden, I recommend you to use theme hook suggestion as follow:

Install the entity module. If the post content type has the fields: title, field\_f1 and field\_f2 then use this code

```
function YourThemeName_preprocess_node(&$variables)
{
     $node = $variables['node'];
     if($node->type == "post"){
          $variables['theme_hook_suggestions'][]='page__post__file';
          $wrapper = entity_metadata_wrapper('node',$variables['node']);
          $variables['title'] = $wrapper->title->value();
          $variables['f1'] = $wrapper->field_f1->value();
          $variables['f2'] = $wrapper->field_f2->value();
      }
  }

```

Now create file `page--post--file.tpl.php` and use the variables `$title`, `$f1` and `$f2` in it.
> 0 votes

# Answer
Be sure that you also have a copy of node.tpl.php in your theme folder:

> NOTE: When using phptemplate node-\[type\].tpl.php suggestions, there must also be an original node.tpl.php template present in your theme directory or the template suggestion is ignored.

from: https://www.drupal.org/node/17565
> 0 votes

---
Tags: nodes
---


# Question
Title: Render picture module image in a custom module
I am trying to render a responsive picture module image from within a module. I cant find any functions that I can pass the picture mapping into. If I render the whole node from within the module it works fine but if I just render the image it does not work. Any thoughts would be great.

# Answer
Adding 'default' to the functions arguments sorted it out

```
$field = field_view_field('node', $node, 'field_image', 'default');

```
> 1 votes

# Answer
Here is my solution to build the render array of the drupal 7 picture module v2

```
//Load picture renderable array

$picture_name = 'mapping_name'
$fallback_image_style = 'large';

$image = $node->field_image[LANGUAGE_NONE][0];

$picture_mappings = picture_mapping_load($picture_name);

$breakpoint_styles = picture_get_mapping_breakpoints($picture_mappings, $fallback_image_style);

$picture = array(
        '#theme' => 'picture',
        '#width' => isset($image['width']) ? $image['width'] : NULL,
        '#height' => isset($image['height']) ? $image['height'] : NULL,
        '#style_name' => $fallback_image_style,
        '#breakpoints' => $breakpoint_styles,
        '#uri' => $image['uri'],
        '#alt' => isset($image['alt']) ? $image['alt'] : '',
        '#attributes' => isset($image['attributes']) ? $image['attributes'] : NULL,
        '#timestamp' => $image['timestamp'],
      );

print render($picture);

```
> 2 votes

# Answer
You could use the field\_view\_field() function.
eg.

```
$output = field_view_field('node', $node, 'field_name');

```

read more about the correct way to render node fields at this blog post
> 1 votes

---
Tags: media
---


# Question
Title: How to find bad PHP node that makes search_cron fail?
I can't run cron, manually or automatically. I installed Cron Debug module, checked all modules, and found out that the Search module makes cron stuck. When I disable it, cron is working.

I suppose the reason is one of my nodes has bad PHP code in it. I googled for "search\_cron errors", and found a solution in Drupal.org I tried it by editing **node.module**, but I got this error:

> Fatal error: Call to undefined function db\_fetch\_object() in /home/mysite/public\_html/modules/node/node.module on line 2616

Can you propose me a solution on how I can find the errorenous PHP code in nodes? I am using Drupal 7.12.

# Answer
> 5 votes
i was facing this issue after upgrading a big application from 6 to 7.This is what I did. From the database run this query

```
SELECT n.nid FROM node n LEFT JOIN search_dataset d ON d.type = 'node' AND d.sid =
n.nid WHERE
d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid asc

```

This will give you the last node that is giving you issues and has refused to be re-indexed. From there you can do what you want with that node. For my case I realized it was a whole content type that was not displaying well. I had to resave one of the fields to allow this content type to display.

# Answer
> 2 votes
The function `db_fetch_object()` doesn't exist in Drupal 7, it was replaced by the new Database API. Checkout Dynamic Querys, Ranges and limits or even Static querys for more details.

In this specific case, you don't need to write nearly as much code. This function that thread suggests editing, `node_update_index()`, looks like this in Drupal 7.

```
function node_update_index() {
   $limit = (int)variable_get('search_cron_limit', 100);

   $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

   foreach ($result as $node) {
     _node_index_node($node);
   }
}

```

According to that thread, you just want to store the nid of the nodes as they are indexed so you can tell which one is causing the problem. To do that, you just need to add the call to `watchdog()` in the `foreach` loop, like so...

```
function node_update_index() {
   $limit = (int)variable_get('search_cron_limit', 100);

   $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

   foreach ($result as $node) {
     watchdog('cron', "about to index node " . $node->nid);   /// ADD THIS TO DEBUG
     _node_index_node($node);
   }
}

```

# Answer
> 0 votes
create views page, add title field, field\_body, add exposed filter body - option "contain", save, open the page and try to find bad string **db\_fetch\_object**, then delete it or make it correct

# Answer
> 0 votes
Adding the Watch Dog line worked for me.

However, if you are working on an active live system:

I would suggest that you use drush with two terminals open to run the following commands:

1) drush search-index 2) drush watchdog-show

---
Tags: nodes, search, cron
---