title: How to set theme setting

text:
# Question
Title: How to set theme setting
i need to set theme setting programmatically. I use `mothership` theme. So for example:

```
$type = theme_get_setting('mothership_classes_view');
dpm($type);
//dpm displays 1 - so this setting is checked
//i need to uncheck it, set it to 0

```

i can't find a function to do this, what is the best way to set it?

# Answer
> 4 votes
As you can see in the code of `theme_get_settings()`, if data is not in cache, it's obtained from variables:

```
// Get the saved global settings from the database.
$cache[$theme] = array_merge($cache[$theme], variable_get('theme_settings', array()));

if ($theme) {
  // Get the saved theme-specific settings from the database.
  $cache[$theme] = array_merge($cache[$theme], variable_get('theme_' . $theme . '_settings', array()));

```

So usually when you need to change them from code, you will need to use good old `variable_set()`. And don't forget to clear the cache.

# Answer
> 5 votes
The actual answer is this:

```
// Get the settings
$mothership_settings = variable_get('theme_mothership_settings', array());

// Set the variable
$mothership_settings['mothership_classes_view'] = 0;

// Save our settings
variable_set('theme_mothership_settings', $mothership_settings);

```

This is perfect for an update hook to run, and doesn't seem to (in my case) need a cache clear afterwards.

This can be abstracted to any theme, Drupal stores the settings in the theme\_THEMENAME\_settings variable. As Pierre mentions, you can also do this in the .info file of the theme but this is only a good idea when you are extending a base theme (as you don't want to overwrite contrib .info files).

# Answer
> 2 votes
You can also set the default value for a theme setting fron the theme .info file.

```
settings[mothership_classes_view] = foo

```

---
Tags: 7
---


title: Drupal 7 template_preprocess_block

text:
# Question
Title: Drupal 7 template_preprocess_block
I am trying to alter content of the system main block but only on the front page. I have added template\_preprocess\_block() in the template.php file, but is\_front is FALSE even though I am on the front page of the site?

I use the Context module to control blocks, but the main block is the only one I have added using /admin/structure/block not Context.

*Update* I have also tested hook\_block\_view\_MODULE\_DELTA\_alter() but is\_front is not passed to this function.

*Update* Even though I disable the Main page content block front the Content region, I still see a node on the front page, publishing options set to published, promoted to front. Doing this on a fresh install locally.

Enabling the Main page content block and setting "All pages except those listed" to doesn't change anything - still looking at my node.

# Answer
Use function `drupal_is_front_page()`.
> 1 votes

# Answer
simplest and most straightforward solution: Create two versions of that block and from this textarea select where the block should be

then do the appropriate configuration.
> 0 votes

# Answer
you could try something like this, even if the conditions aren't exactly the same:

```
<?php
    // works with paths like 'home' too, as well as 'node/2'
    $is_front_page = ($_GET['q'] == variable_get('site_frontpage', 'node') || drupal_get_path_alias(current_path()) == variable_get('site_frontpage', 'node'));
?>

```

borrowed from here
> 0 votes

---
Tags: theming, blocks, 7
---


# Question
Title: Product image is not shown in View Mode Node:Product List
I'm starting with Commerce Kickstart 2 together with demo store.

I added a product and upload one image, this product has one of the demo store variation types (Bags & Cases) and the product display type associated.

It seems simple since I didn't change nothing. But when I click in main menu the products already there are listed fine, with product image, only my new product don't show the image.

I see in variation types Bags & Cases that the *Images field*, Column *Format*, is defined as *image delta*, Image style: **product\_medium**. And that is the point. In MySite/sites/default/files/styles directory are the styles of images. In that directory there is the product\_medium directory where the images showed when in *View Mode Node:Product list* (the list of bags listed when click in *To carry*).

Well, the fact is when I create the product there is no option to load an image that will saved in MySite/sites/default/files/styles/product\_medium directory. And that's the problem. Since when I manually copy the image to that directory, the image is showed up.

Where I define this product\_medium image?

# Answer
> 0 votes
Could it be that your file folders are not setup correctly? Checkout drupal.org/node/15368 Also check your database log if there are any file related errors reported, more info at drupal.org/documentation/modules/dblog

---
Tags: views, commerce, nodes
---


# Question
Title: Set username to the field firstname untill the field first name is filled
I am using profile2 module for user profiles and created a profile with first name and last name fields which are used for configuring real name. And I have set real name as page title. But there is machine name being displayed if the first name and last name fields are empty. I want to set user name to the first name field until the profile fields are filled. is there anyone who knows the solution?

# Answer
> 0 votes
use form alter for alter profile2 fields name, then put pass uid load user using userload function get username put this value as default value for the first name field in your profile 2 form ..

---
Tags: 7, users
---


title: form rendering through tpl file

text:
# Question
Title: form rendering through tpl file
I want to render drupal 6 form through tpl file. for that 1. I have written mytheme\_theme in template.php file and there I have define my template forms arguments and path for tpl file.

1. I have written tpl file
2. in form function at the end I have called theme by `'#theme' => 'my_template'`

doing all these thing my from is rendering through tpl but now its not going into `submit_hander()` and validation.

can any one help me these? I am not getting what's wrong in these.

see in my template.php contain:

```
function cs_theme(&$existing, $type, $theme, $path) {
  $hooks = zen_theme($existing, $type, $theme, $path);
  // Add your theme hooks like this:
  /*
  $hooks['hook_name_here'] = array( // Details go here );
  */

  // @TODO: Needs detailed comments. Patches welcome!

  $hooks['my_theme_example'] = array(
                  'arguments' => array(
                  'order' => null,
                  ),
                  'render element' => 'form',
                 'template' => 'mymodule_template',
                 'path' => drupal_get_path('theme', 'theme_name') . '/templates',
              );

  return $hooks;
}

```

In these way I have printed all the form fields in my .tpl file is:

```
   <?php print drupal_render($variables['order']['logo']);?>

```

# Answer
You need rewrite 'form' like this:

```
/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  $form_registry = &$theme_registry['form'];
  $form_registry['function'] = 'mymodule_form_theme';
}
function mymodule_form_theme($element) {
  // I'm not sure that $element has 'from_id' but you could pass it if you need.
  if ($element['form_id'] == 'yours_form_id') {
    return theme_form($element);
  }
  // Else return what you need I guess that better to use hook_theme()
  // and then call theme() function.
}

```

Look at `theme_form()` to understand what variables need to pass in form tag. I don't understand why do you need this. What is the reason to use template file?
> -1 votes

---
Tags: 6, forms, theming
---


title: Views show / hide filter via dropdown

text:
# Question
Title: Views show / hide filter via dropdown
Is there a way to show / hide filters via a dropdown select. What I want to achieve is, that there is a dropdown with all my filters, and only the one I select in dropdown will show up.

I've found the Composite Views Filter module. But this works only with one group. If I have two Dropdowns to select filters, it won't work.

# Answer
> 0 votes
The mentioned Module Composite Views Filter was extended by it's maintainer. It is still in patch-test-phase, but it is working now to bring in as much filter groups as you like.

> Allows you to create one filter condition that enables a bunch of filter conditions. Sometimes one condition isn't enough for your filter, but you still want the user to be able to change the filter (group).

---
Tags: 7, views
---


title: Duration of NEW marker for content

text:
# Question
Title: Duration of NEW marker for content
What is the duration of the 'NEW' tag that is being added when creating new content? How do I change it so it would last until the content is edited, after that the NEW marker would disappear.

You can find NEW marker in red in admin/content

I do not understand how this works, content added yesterday and today are all marked as NEW which is misleading. I'd like to be able to change it.

# Answer
> 3 votes
The default is 30 days, per the `NODE_NEW_LIMIT` constant.

> Nodes changed before this time are always marked as read.
>
> Nodes changed after this time may be marked new, updated, or read, depending on their state for the current user. Defaults to 30 days ago.

Since use of that constant is hard-coded in `node_mark()`, I imagine you'll need to provide your own 'marking' system if you want to do things differently to the core version.

---
Tags: 7, nodes
---


title: Changing Drupal database

text:
# Question
Title: Changing Drupal database
How would you think if a designer extends the database of Drupal for a desired system? (for example adding field to some tables)

Would it be really PRACTICAL?

# Answer
> 2 votes
Bottom line: it's your database, you can add as many fields to whatever tables you like.

Drupal won't know anything about them, obviously, and it may cause unforeseen issues further down the line, as you're potentially changing the way the core system works. It's not possible to be any more specific than that without knowing pretty much everything about your application, so you'd need to test until you're happy you haven't broken anything.

The correct way to extend core entities is through the use of fields, I'd strongly recommend using those rather than hacking at database tables.

---
Tags: database
---


title: Alter form button title

text:
# Question
Title: Alter form button title
I use this to alter field labels:

```
function ninesixty_form_user_login_alter(&$form, &$form_state) {
    $form['name']['#title'] = t('Name');
}

```

But how do I change the title of the button? The button is `<button>` not `<input>` and it's for node creation form. Form id is `titles-node-form`.

# Answer
Use this

In place of name put button name.

```
$form['name']['#value'] = t('Name');

```

Hope this will work
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Difference of two Dates in Computed Field
fields: (Date to - Date from) = Total Number of Days

How can I compute the total number of days between two dates using Computed Field?

# Answer
> 1 votes
Here is a sample snippet (to be used in Computed Code PHP Block inside of a computed field)

```
$food_date_value = array_pop(field_get_items($entity_type, $entity, 'field_food_date'));
$food_date = new DateObject($food_date_value['value'], '');
$current_date = new DateObject('now', '', 'm/d/Y');
$entity_field[0]['value'] =$food_date->difference($current_date, 'days');

```

field\_food\_date is a date in the Unix Timestamp format (another field in my content type). DateObject can then be used for doing any date calculations.

# Answer
> 0 votes
If the Machine name of your date-field is 'field\_example\_date', then the **Computed Code (PHP)** would be

```
$startdate = $entity->field_example_date['und'][0]['value']; // Value of start-date
$enddate = $entity->field_example_date['und'][0]['value2']; // Value of end-date

$datediff = strtotime($enddate) - strtotime($startdate);
/* The PHP Function STRTOTIME parses the english textual datetime description
 * into a Unix timestamp
 */

$num_leaves = $datediff/(60*60*24);
/* Since we need the number of days IN-BETWEEN,
 * we divide the resultant difference by 60*60*24 .
 *
 * Incase of counting no.of days "FROM" to "TO" days, add 1 to the above result.
 * $num_leaves = $datediff/(60*60*24) + 1;
 */

 $entity_field[0]['value'] = $num_leaves;

```

The **Display Code (PHP)** will have

```
$display_output = $entity_field_item['value'];

```

---
Tags: datetime, entities
---


# Question
Title: Disable transition effect field slideshow
I have installed the Field Slideshow module.

I want to set the transition effect to none in manage displays (content type). How can this be done, I tried to set the interval to 0 but the slideshow keeps going.

# Answer
> 0 votes
Set "Transition speed" to 0 (zero) and it won't have any transition effect, just the direct change of image.

If you want to stop automatic changing of images, set "Timeout" to 0 (zero).

---
Tags: nodes, media, entities
---


# Question
Title: How to compare new node title with already entered nodes in database
I am using node gallery module.While creating an album, when the user enters duplicate name then error message is displayed as

> This form requires that the fields Album name, Author are a unique combination. The specified values are already used.

I want to change this error message for duplicate album name. I have created a hook for this.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ('NODE form id' == $form_id) {
   $form['#validate'][0] = 'my_custom_validate';
  }
}

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

  //Add code to check the title using db_query
  $title = $form_state['values']['title'];

     //$fetch data from node table w.r.t this $title

  //if title exists
  form_set_error('title','custom message');
}

```

Here how can I compare new node title with already entered nodes in database?

# Answer
> 1 votes
Use an `EntityFieldQuery`:

```
$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'some_type')
  ->propertyCondition('title', $title);

$result = $query->execute();
if (!empty($result['node'])) {
  // Node with provided title already exists.
}

```

# Answer
> 0 votes
You can use http://drupal.org/project/unique\_field module. It performs additional validation when a node is created or updated by a user to require that a node's title or other specified fields are unique. Besides that

try this code may be helpful to you:

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

  //Add code to check the title using db_query
  $title = $form_state['values']['title'];

  $node_title = NULL;
  //$fetch data from node table w.r.t this $title
  $node_title = db_query('SELECT title FROM node WHERE title=:title',
        array(':title'=>$title))->fetchField();

  if (!empty($node_title )) {

    //if title exists
     form_set_error('title','custom message');
 }
}

```

---
Tags: hooks, forms, media
---


# Question
Title: What does xmlrpc.php do and how can I use it?
I have seen `xmlrpc.php` but I haven't found much documentation out there. Is it possible to use this directly without any additional modules? Where is the canonical documentation for it?

Is `xmlrpc.php` what is refered to here as "drupal's xmlrpc"? If that statement is correct `xmlrpc.php` would be only for the blog module in core.

# Answer
> 1 votes
You should be able to use it for other RPCs. Example xml-rpc post for user.update shows an example of a *user.update* method call.

```
<?xml version="1.0"?>
<methodCall>
   <methodName>user.update</methodName>
   <params>
     <param>
       <struct>
         <member>
           <name>uid</name>
           <value><int>38</int></value>
         </member>
       </struct>
       <struct>
         <member>
           <name>name</name>
           <value><string>diana.ruiz12</string></value>
         </member>
         <member>
           <name>mail</name>
            <value><string>ndy.r@eeuwkern.org</string></value>
         </member>
         <member>
           <name>pass</name>
           <value><string>candy9223</string></value>
         </member>
       </struct>
     </param>
   </params>
</methodCall>

```

It doesn't look like a widely used feature, and it will be moved out of core in Drupal 8.

See also Services Tutorials and Examples.

---
Tags: 7
---


title: Contact Form in custom Theme

text:
# Question
Title: Contact Form in custom Theme
I need to create one request information form that goes to each page in my website. That means I need to add that form into page.tpl.php page.

Form includes just basic information like name, email, phone, message and submit button.

So, what is the best practice to implement that form in my theme? I mean what are the steps to add form in Drupal?

I am new to Drupal and trying to learn it.

Thanks in advance!

# Answer
> 1 votes
You shouldn't add a form in the page.tpl.php.

Instead define your own form in a block, and then place your block in every page (using Drupal standard block system or a contrib module such Context

To define your contact form you have two options:

* Use Form API: The form API allows you to create forms and react to submit of those forms. There are plenty examples of this. You will need to write your own module (easy), define your form in it and implement the block hooks to define a block that contains your custom form (you'll need at least hook\_block\_info and hook\_block\_view).
* Use Webform module: This module allows you define forms that users can submit and the submitted data can be emailed to the email addresses you want. You don't have to write code and you can theme them with your theme.

Also Drupal has a simple module with contact forms, but I think is only to contact users.

---
Tags: 7, theming, forms
---


title: Custom field type with imagefield

text:
# Question
Title: Custom field type with imagefield
I'm creating a widget with an image field. But I keep writing 0 to the database. But i need the fid to be saved. I know I can manipulate the data with hook\_field\_presave(). But the items array only contains image =\> '0'.

mymodule.module

```
/**
* Implements hook_field_widget_form().
*/
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
...
  $element['image'] = array(
    '#type' => 'managed_file',
    '#name' => 'mymodule_custom_image',
    '#title' => t('Image'),
    '#size' => 40,
    '#description' => t(""),
    '#upload_location' => 'public://',
    '#theme' => 'mymodule_custom_thumb_upload',
  );
...
}

```

Edit:

```
/**
* Implements hook_field_widget_info().
*/
function mymodule_field_widget_info() {
  return array(
    'mymodule_polygone_widget' => array(
      'label' => t('Default'),
      'field types' => array('mymodule_polygone'),
    ),
  );
}

```

mymodule.install

```
/*
* Implements hook_field_schema().
*/
function mymodule_field_schema($field) {
  $columns = array(
    'image' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE),
    'zones' => array('type' => 'text'),
  );

  return array(
    'columns' => $columns,
    'indexes' => array(),
  );
}

```

# Answer
Found it: Forgot the 'input ...' in my custom theme function :).

```
function theme_mymodule_thumb_upload($variables) {
  $element = $variables['element'];

  if (isset($element['#file']->uri)) {
      $output = '<div id="edit-logo-ajax-wrapper"><div class="form-item form-type-managed-file form-item-logo"><span class="file">';
      $output .= '<img src="' . file_create_url($element['#file']->uri) . '" />';
      $output .= '</span><input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
      $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '">';

      return $output;
  }
}

```
> 0 votes

---
Tags: 7, forms, media
---


title: Alter display of jQuery Calendar Popup

text:
# Question
Title: Alter display of jQuery Calendar Popup
I've got a Date field on my content type and I'm using the jQuery pop-up calendar as the widget. The html rendered for it has extra stuff that I'd like to strip away, but I can't find a way to configure what it looks like.

Here's my current Edit form:

Notice with all of the non-date fields, the name of the field is bold and directly above the textfield/select box, etc.

However, with the date field, the field name is not bold, then there is a space, then a bold "Date" and THEN the textbox which is linked to the popup calendar.

I would like it to end up like this:

***I understand that I can try to just hack it by hiding things with css, but that's not what I'm looking for.***

I'm looking to find a way to configure drupal to render this field the same way it renders all of the others, instead of rendering tags that just take up bandwidth and get hidden by css.

EDIT: This isn't an issue of a special configuration. I just installed vanilla drupal in a new directory. I installed the `date` module. I enabled the date module along with the date popup module (comes with it). I added a date field to the Article content type and set it's widget type to be popup calendar. Went to add a new Article node and it appeared just like I said above.

# Answer
> 0 votes
So it turned out to be a two-fold issue. Thank you to Geoff and Clive who provided the larger part of the solution!

**Step 1** \- By default, the Date module renders a date field as a `fieldset` which is why the field name is differently styled and separated from the element a bit. The quick solution is to add a very short function to your template.php which tells the system to format a date field in the same way you'd format any other element. Like so:

```
function MYTHEME_date_combo($variables) {
  return theme('form_element', $variables);
}

```

I pulled that code from how to avoid fieldset in drupal date field

**Step 2** \- Edit the Content Type, Edit the date Field, expend "More settings and values", then expand "Advanced Settings", and change the Label position from "Above" to "None." That will get rid of the internal label.

---
Tags: 7, nodes, datetime
---


# Question
Title: Default installation of D8 treatment of .gif accesses?
If I request a non-existent URL, say, /ddddd I get Page not found (as expected). If I do th4 same with an unusual extension /dddd.xcf I also get Page not found.

BUT if I request /ddddd.gif there's an Apache error as opposed to a 404?

I'm guessing this has something to do with security, but can someone clarify this?

# Answer
By default drupal serves a different 404 page to save computational effort if it is matching the following regex:

```
'/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'

```

You can configure this in the settings.php (Fast 404 pages) or in the config('system.performance')-\>get('fast\_404.paths');
> 3 votes

---
Tags: 8
---


# Question
Title: Commerce: What field to join line_item in order to get product price in custom query?
I'm starting with line 'commerce\_line\_item' as a base table, and I want to get prices for each of the line item products attached to a Drupal Commerce Order, rather than just the order total. I need a listing of each product sold with prices, and neither views nor Entity Field Query offer enough options for me (I'm creating a master order statistics spreadsheet with phpexcel).

The only promising field I have in the 'commerce\_line\_item' table is an 'order\_id', which I can't find a way to relate back to 'commerce\_product' and a 'line\_item\_label', which does not join on the field 'commerce\_product.sku'.

So what would I join on to get pricing information?

I asked a similar question here, but this has me slightly more baffled.

Here's my code below for the query.

```
  $query = db_select('commerce_line_item', 'i');
  $query->fields('i', array('line_item_label', 'line_item_id', 'quantity', 'data'));
  $query->condition('i.type', 'product', '=');
  $query->leftjoin('commerce_product', 'cp', 'cp.sku = i.line_item_label');
  $query->leftjoin('field_data_commerce_price', 'fcp', 'fcp.entity_id = cp.product_id');
  $query->fields('fcp', array('commerce_price_amount'));
  $query->leftjoin('commerce_order', 'o', 'o.order_id = i.order_id');

```

snip-\>

Thanks for your help!

# Answer
This was totally the wrong way to go about this as pcambra points out.

Instead, I built a view based on the object Commerce Line Item with relationships to Commerce Order and through Commerce Order to Address Profile and then used `views_get_view_result()` to get an array of the results which I then handed to the function `phpexcel_export()` with a little bit of processing.
> 0 votes

# Answer
As you can see in the graph from the question you're linking, there's a field that relates the line item with the products, that's not a database field but a Drupal field. This means that there will be a database table for the field data and revisions and you don't want to deal with that in a db\_query, you should be using Entity Field Query instead that will know the database tables and fields to use in each case.

I'm guessing you want to get products from the line items you already have, or the order.

I'd get the line items with EntityFieldQuery:

```
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'commerce_line_item')
  ->propertyCondition('order_id', <-your-order-id->)
  ->execute();

```

Now you've got the line items there, wrap them and get the product price:

```
if (!empty($result['commerce_line_item'])) {
  foreach ($result['commerce_line_item'] as $id => $value) {
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $id);
    $product_wrapper = $line_item_wrapper->commerce_product;
    $price = commerce_price_wrapper_value($product_wrapper, 'commerce_price', TRUE);
  }
}

```

Also, all this data is exposed to views, so you can create a view instead.
> 2 votes

---
Tags: commerce, database
---


# Question
Title: theme_table() isn't respecting sortable fieldname
I generate some data in one of my modules and generate a table using `theme_table()`. I want the fields in that table to be sortable, but the table is being rendered with the wrong value in the links.

I'm getting `?sort=asc&order=Birth Date` instead of `?sort=asc&order=field_birthdate`.

Here is the code I'm using to generate my table:

```
$headerColumns = array(
    array('data'=>'Name', 'field'=>'title'),
    array('data'=>'Edit'),
    array('data'=>'Birth Date', 'field'=>'field_birthdate'),
    array('data'=>'Sex', 'field'=>'field_sex'),
    array('data'=>'Stars', 'field'=>'field_stars')
);

return theme_table(array(
    'header' => $headerColumns,
    'rows' => $rows,
    'attributes' => array(),
    'caption' => '',
    'colgroups' => array(),
    'sticky' => true,
    'empty' => 'You ain\'t got none.',
));

```

I believe I'm generating that array according to the instructions on the `theme_table()` api docs, but it's not working.

How do I get the sort link url to properly use the fieldname I'm giving it in the render array?

EDIT: As requested, here is the code I use to generate my query:

```
$query = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('uid', $user->uid)
            ->orderBy('type')
            ;

$direction = 'asc';
if (array_key_exists('sort', $_REQUEST) && $_REQUEST['sort'] == 'desc') {
    $direction = 'desc';
}

if (array_key_exists('order', $_REQUEST) ) {
    $fieldname = strtolower($_REQUEST['order']);

    $field_info = field_info_field('field_'.$fieldname);
    if ($field_info !== null) {
        $table_name = _field_sql_storage_tablename($field_info);
        $query->innerJoin($table_name, 'f', 'f.entity_id = n.nid');

        $query->orderBy(sprintf('f.field_%s_value', $fieldname), $direction);
    }

}

$query->orderBy('title', 'asc');

if ($entityType !== null) {
    $query->condition('type', $entityType);
}

$records = $query->execute();

```

# Answer
You're doing too much work.

For sorting:

```
$query = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('uid', $user->uid);

$sort_query = $query->extend("TableSort")->orderByHeader($headerColumns);
$records = $sort_query->execute();

```

Using the TableSort extension will simplify things immensely.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How can I add pagination to the comments of advanced forum in drupal 7?
I use Drupal 7 but don't see any pagination on the comment pages, how can I add a pager there please?

# Answer
> 0 votes
I think that this can help you.

Let me know if this is working.

---
Tags: nodes
---


# Question
Title: Scrolling in chrome shears text and elements
the testing version of a portfolio site I'm working on started behaving strangely in the past few days. This might or might not be a problem related to drupal itself, but I've never come across this on a non-drupal project.

http://beta.mattgrossdesign.com/about

On my Win7 machine, Chrome 36, scrolling the page causes all the fixed position elements to be rendered in multiple places or sheared off.

Image Reference: https://i.stack.imgur.com/dSvjq.jpg

Firefox & IE aren't having problems, any ideas?

Thanks a bunch

# Answer
> 1 votes
Try to add `-webkit-transform: translateZ(0);` to your fixed elements.

---
Tags: theming
---


# Question
Title: field slideshow module and image field caption
I want to use image field caption and field slideshow.

How can I set the caption field as caption for my slideshow?

I tried to apply the update but it didn't work.

# Answer
Did you try this particular patch? Do you use 'Long text' field? I think that this patch doesn't work with standard 'Text' field.
> 0 votes

---
Tags: nodes, media, entities
---


# Question
Title: hook_url_outbound_alter only for links in node body
I'm building a site with drafts/revisions as a major component. For now I'm using hook\_url\_outbound\_alter to check if "/draft" is at the end of the current URL, and if so to append "/draft" to all paths. The problem is that it's also altering the Menu URLs. Is there any way that I can explicitly target links in the node body using hook\_url\_outbound\_alter?

# Answer
> 0 votes
For the googlers:

Module:

```
/**
 * Implements hook_url_outbound_alter().
 */
function draft_links_url_outbound_alter(&$path, &$options, $original_path) {
  // Internal URLs only
  if (!$options['external']) {
    // Check if current page is draft page
    if (preg_match('|/draft(/?)$|', current_path())) {
      $options['alias'] = $path;
    }
  }
}

/**
 * Implements hook_preprocess_page().
 */
function draft_links_preprocess_page(&$variables) {
  if (preg_match('|/draft/?$|', current_path())) {
    drupal_add_js(drupal_get_path('module', 'draft_links') .'/draft_links.js');
  }
}

```

JavaScript:

```
(function ($) {
    $(window).load(function() {
        $('.node__content a').each(function(){
            href = $(this).attr('href');
            // Internal URLs only.
            if (href.match(/^\/?[0-9a-zA-Z]*/) && !href.match(/^(https?:)?\/{2}/)) {
                $(this).attr('href', href+'/draft');
            };
        });
    });
})(jQuery);

```

---
Tags: 7, hooks, nodes
---


# Question
Title: In which file to add the cache_clear_all function
In my situation I would like a certain block on my page with real time information to not be cached for anonymous users. Literature listed below:

> cache\_clear\_all('modulename', 'cache')

I added this on my module inside the hook\_block\_view() function. This does not work though. Any directions on where I can use this function.

Here is the function information:

Clearing specific entries in cache tables
The Drupal cache API can be used to clear specific items. Caching back ends can be switched (to memcache, to flat files, etc.) without having to rewrite any code.

```
cache_clear_all('content:' . $MYNID, 'cache_content', TRUE);

```

The example above clears all items from cache that start with 'content:$MYNID\*'. To ONLY remove one specific row, drop the $wildcard parameter (the "TRUE" statement in the function call) and change the format of the first parameter to omit the asterisk, which functions as a wildcard.

```
cache_clear_all('content:' . $MYNID . ':' . $MYNID, 'cache_content');

```

# Answer
> 2 votes
You can set the block's caching in `hook_block_info`, like so:

```
function MODULE_block_info()
{
    $blocks = array();

    $blocks["BLOCK_NAME"] = array(
        "info"  => "BLOCK TITLE",
        "cache" => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

```

---
Tags: 7, blocks, caching
---


# Question
Title: show order payment option in order (admin/commerce/order)
I am using commerce kickstart (In admin/commerce/orders) How to show payment options for (authenticate) user. As, i give all the permission for authenticate role.

admin page screenshot show quick edit option Edit, invoice, payment, and delete

authenticate role page screenshot show quick edit here it is not option for any of the above.

# Answer
> 0 votes
Enable permission "Use the administration pages and help" under the System section should do the trick.

---
Tags: commerce
---


# Question
Title: D7 Execute javascript on views exposed filters AJAX submit (Dropkick)
I need a tutorial on how to run a piece of javascript after the AJAX form of a views exposed filter group submits.

The problem is with using the Dropkick javascript plugin to style some dropdowns. The Drupal Dropkick seems to do a half-decent job of implementing this on the initial form, but after AJAX submit the dropdowns lose their styling.

If it helps, here's a copy of the Drupal Dropkick module js:

```
(function($) {
  Drupal.behaviors.dropkick = {
    attach: function(context) {
      $(Drupal.settings.dropkick.selector, context)
        .not('#field-ui-field-overview-form select, #field-ui-display-overview-form select') //disable dropkick on field ui
        .each(function() {
          $(this).addClass('dk-active').dropkick({
            change: function(value, label){
                $(this).change();
            }
          });
      });

      //add clearfix to parent .form-item to fix floats
      $('.dk_container').parents('.form-item').addClass('clearfix');
    }
  }
})(jQuery);

```

Any thoughts?

# Answer
> 4 votes
You need to use ajaxcomplete function of jquery to perform any script after the ajax call. I have not worked on "Dropkick" module, but I have implemented "Selectbox" jquery plugin in my site to format the dropdown.

May be it will help you.

```
$(document).ajaxComplete(function(e, xhr, settings) {

  if (settings.url == Drupal.settings.basePath + "?q=views/ajax" || settings.url == Drupal.settings.basePath + "views/ajax" || settings.url == Drupal.settings.basePath + "?q=system/ajax" ||  settings.url == Drupal.settings.basePath + "system/ajax") {
 // enable selectBox jQuery plugin for all <select> elements
    $("SELECT").selectBox();
    //Drupal.attachbehaviours();

  }
});

```

# Answer
> 1 votes
I run in the same issue and this solution works for me.

```
function($) {
  Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {
      $('select').selectBox({
        mobile: true,
        menuSpeed: 'fast'
      });
    }
  };
})(jQuery);

```

---
Tags: 7, views, forms, ajax, navigation
---


# Question
Title: How to edit a webform block (not the webform itself)
I have one webform block I would like to edit. I know I can use hook\_form\_alter, the problem is that any changes I make using it are affecting the actual webform plus the block.

How can change stuff just on the webform block? It's just a captcha component I want to disable, thanks.

# Answer
> 0 votes
probably the easiest way is to create a separate form for that block (a copy of what you have now, but dedicated to that block), and disable Captcha for that form name

---
Tags: blocks, captcha
---


title: Modal/dialog box

text:
# Question
Title: Modal/dialog box
This sound like a really dumb question, but for the life of me I cannot find something that works.

I want to trigger a modal/dialog box for some basic content. Its just HTML, not the login page or password reset or webform, or an image. I just want to pop some content into the modal box.

Whats the best way to do this? I ideally I would be able to control the dimensions of the window.

# Answer
> 0 votes
You can use lightbox module to achieve that, but note if you want to open a modal content you need to use `rel="lightframe"` as an attribute for the `<a>` tag.

Also don't forget the Library of the module.

# Answer
> 0 votes
Try the Overlay Paths module

> This is a simple module that enables site builders to use the built-in Overlay for non-admin pages.
>
> This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.
>
> This module provides a simple UI for defining paths to appear in the overlay, but developers can use it to define paths too, see the overlay\_paths.api.php file in the module for details.

---
Tags: 7, javascript
---


title: Views Slideshow constant cycle

text:
# Question
Title: Views Slideshow constant cycle
Is it possible to have a slideshow slide content constantly without stopping and no pause? That means it would always slide in fixed speed. I'd be using the scrollLeft effect or something like that.

It doesn't have to be Views Slideshow module, but it has to be Views displayed content which would scroll constantly from right to left.

Or should I just drop that and implement some custom javascript?

# Answer
You can achieve that using the jCarousel module. I've used this module and works fine for me.

> This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.

Image from module page.

There is another module called Owl Carousel

> This module integrates the wonderful Owl Carousel slider built by OwlFonk. The primary module is comprised of three sub modules providing a views style, field formatter & administration UI. The administration form leverages the variable module providing multilingual support out of the box.
> 2 votes

---
Tags: 7, javascript, views
---


title: Module bloat and performance tuning

text:
# Question
Title: Module bloat and performance tuning
We have a site with performance issues. And we are looking for advice on low hanging fruit or other strategies that can have a dramatic increase on performance.

The seemingly obvious culprit is massive module bloat with a total of 175 enabled modules. We are aware that this is an architectural flaw however we are not in a position to spend the amount of time necessary to resolve that in any big way. Most of the modules contributing to this bloat are contrib modules.

* We are using memcache for caching and also making use of APC.
* We have already identified so slow DB queries and re engineered some views to get an improvement here.
* We have tuned view and block caching through the site.

We have also applied a few of the common performance and scalability modules including \- entity cache \- Cache expiration \- Cache actions.

Due to other architectural considerations (a 3rd party product working as a reverse proxy) we are not in a position to utilise varnish in a very useful capacity.

The average time out of 5 calls via wget (with a cache clear before each before each call) is about 42.182 seconds on a dev instance. The average time out of 5 calls via wget (with a warm cache) is about 9.43 seconds on a dev instance.

We experience similar slow performance on the staging server. That server also serves a few staging instances of other sites that perform decently. Our sysadmins have configured the databases here so I do not consider the database configuration to be a likely cause of much of our performance issues.

If anyone has experience improving the performance of Drupal sites with large module boat you input is most welcome.

# Answer
Did you try boost module? If you have mostly anonymous traffic this is really a good start.

Additionally apart from block caching do you use the visibility settings per block when a block is not visible on all pages? My experience from many projects is that many times regions are simply not printed on templates and people think the blocks are not rendered because you do not see them. If you do not use the visibility settings to avoid block rendering every block is rendered on every page request which can lead to an enormous overhead.

Addionally depending on the view I realized that sometimes it gains better performance to use custom queries and page callbacks to render a result page instead of using the views module.

What often leads to big queries is the fields API with all these joins. For every field two tables with much data are created which is often not neccessarry. Therefore I started to use Entity API more often to decribe custom data structures instead of using nodes and content types with fields for that.
> 0 votes

---
Tags: performance
---


# Question
Title: Can a pager item point to an anchor on the page?
I'm building a page where, somewhere down in the middle of it, there's a pager of some stuff. The pager is working fine, but, when you click on one of the pager items, the page is redrawn showing the top of the page, which usually does not include the (now updated) contents of the pager. This is because the pager item URLs simply refer to the page as a whole. Is it possible to get a reference to an anchor inserted into the URLs of the pager items, so that the browser will redraw the page with the pager contents in view?

# Answer
Have you looked at theme\_pager\_link in Drupal 7. Your site's theme can customize any pager link by implementing `YOURTHEME_pager_link` and then add additional logic into a copied version of that function to embed anchors as needed.

You can probably embed the anchor as a `parameter` to the link to be inserted into the querystring:

> parameters: An associative array of query string parameters to append to the pager link.
> 4 votes

# Answer
The answer by @tenken although in the right direction, you don’t have any context within that function to target ONLY the comment pagers. Actually as far as I know you cannot only affect certain pagers period.

The way you could go about it is by using js, and target only the comment pagers:

```
// add js to insert anchor links to #comments in comment pagers
drupal_add_js("
  Drupal.behaviors.comment_pager_anchors = function (context) {
    var comment_pager_links = $('#comments .pager a');
    comment_pager_links.each(function(){
      this.href = this.href + '#comments';
    });
  }
", 'inline', 'footer');

```

You could add this for example within theme\_pager, theme\_pager\_link, or in hook\_nodeapi if you have comments for example.
> 0 votes

# Answer
Based on Manuel Garcia's answer I was able to make this work in **Drupal 7** with the following JavaScript:

```
Drupal.behaviors.pager_fragments = {
  attach: function (context, settings) {
    var pager_links = jQuery('#my-wrapper-id .pager a');
    pager_links.each(function(){
      this.href = this.href + '#myfragment';
    });
  }
}

```
> 0 votes

---
Tags: 7, paging
---


# Question
Title: How to make a style plugin available only for certain types of panes?
I'm trying to simplify the admin UX on a site with a few different custom style plugins. I have plugins A, B, C, and D.

I want plugins A and B only to be able to be applied to menu block panes.

I want plugin C only to be able to be applied to a minipanel when the minipanel is placed via something like Panelizer.

I see that I can easily `hook_form_alter()` the `#options` in the form but I don't seem to be able to find the kind of context information that I need to know which ones to hide.

How can I selectively hide style plugin options for irrelevant elements?

# Answer
I figured out two ways to do this.

## First way

It requires that any style plugins you want to filter be

1. provided by the module in which you're doing the filtering (unless you want to hand-code in a list of modules or something), and
2. named such that the machine name includes the name(s) of the content type(s) of the panes on which it should be able to be selected.

Inside a `hook_form_FORM_ID_alter()`:

```
// Only show style plugins relevant to the type of pane we have.
$type = $form_state['pane']->type;
$this_module = basename(__FILE__, '.module');

foreach ($form['style']['#options'] as $key => $style) {
  $style_info = panels_get_style($key);
  $module = $style_info['module'];
  // If the style plugin was defined by our module and it does not have the
  // current pane's type in the name, don't make it an option.
  if (($module == $this_module) && (strpos($key, $type) === FALSE)) {
    unset($form['style']['#options'][$key]);
  }
}

```

## Second Way

After doing it the first way, I wanted to make it more robust (not rely on naming conventions) so I submitted a feature request to Panels and attached some patches. Issue here: https://www.drupal.org/node/2320045

This way allows you to just add something like `'content type' => array('foo', 'bar', 'baz'),` (Where foo, bar, and baz are the machine names of Panels content types) to the `$plugin` declaration, along with the title and description and all that. If you have plugins that don't have that, they won't break, they'll just continue to appear as options for every content type. If you do specify some types, it will only appear as an option on panels of those types.
> 3 votes

---
Tags: chaos-tool-suite, theming, panels
---


title: How do I add jQuery Mobile.js?

text:
# Question
Title: How do I add jQuery Mobile.js?
I'm attempting to add jQuery Mobile.js to handle the *vclick* event.

What would be the easiest way to add this functionality for an administrator that is new to jQuery?

# Answer
> 1 votes
There are jQuery Mobile module and Mobile jQuery Theme available. Looks like exactly what you wanted.

> The Mobile jQuery Theme is a powerful theme built on the jQuery Mobile platform. The theme adapts some of Drupal's base output to work with the highly themable designs built into the framework.

> This is an enhancement module for the Mobile jQuery Theme. You can also hook into the module with you own theme if desired.

So you have the module to provide functionality you need, and theme you can use by creating subtheme, or as a reference.

---
Tags: 7, javascript
---


# Question
Title: Commerce checkout does not work when loading from AJAX
In D7, I have a dropdown form field that has an #ajax attribute pointing to a callback function that triggers when the drop down value is selected. In the callback function, I load the current Commerce order and then the Commerce checkout form using:

```
$commerce_form = commerce_checkout_router($order);

```

I then render the checkout form and display in the template:

```
$commands[] = ajax_command_html('#checkout-section', '');
$commands[] = ajax_command_append('#checkout-section', render($commerce_form));

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

```

When I do that, it looks like my checkout form does not get properly bootstraped and I lose all the interactivity of the checkout form I've set up using hook\_info's etc.

When I visit the checkout form without AJAX everything works well.

Do I need to somehow bootstrap Drupal Commerce inside AJAX callbacks if I want to use AJAX so all my hooks that customize the Commerce Checkout?

PS: I am doing a

```
require_once '../contrib/commerce/modules/checkout/includes/commerce_checkout.pages.inc';

```

inside the callback. Without this I get functions not defined errors on core Commerce functions. (The Drupal Commerce and all related modules are enabled and it only happens in the AJAX callbacks.)

Thank you

# Answer
> -1 votes
I had exactly the same Problem, i think this page should help you: Loading a form by ajax.

I have solved this problem, but I think its a little bit ugly. The Problem was that I have loaded the checkout form, but not the scripts which are necessary on the checkout page. So i have loaded the scripts from the checkout page, too. After that i have done a

```
Drupal.attachBehaviors();

```

So all scripts can attach there functionality to the checkout form.

---
Tags: ajax, commerce
---


# Question
Title: Make Commerce Checkout Form Submit via Ajax
I think its a simple question, but I havent find an answer yet.

I want to make the Commerce Checkout Form Submit as an Ajax Form Submit. I have searched for a while but I havent found something useful.

There is a module Asaf which can add Ajax Submit to every Drupal Form, but I havent find the important locations in code.

There is also a Drupal Page AJAX Forms in Drupal 7, so I have tried a form\_alter on the commerce\_checkout\_form\_checkout and added an Ajax Callback, but the page still reloads.

I have written this code in a custom module to test the ajax submit with an own function:

```
if($form_id == 'commerce_checkout_form_checkout'){
  $form['#ajax'] = array();
  $form['#ajax']['method'] = 'replace';
  $form['#ajax']['effect'] = 'fade';
  $form['#ajax']['callback'] = 'test_function';
}

function test_function(){
  drupal_set_message('test', 'error');
}

```

But no message is displayed and no ajax call is done.

Perhaps somebody cant put me on the right turn.

EDIT:

So I have learned that i have to add the \['#ajax\] to a specific button or submit element, and not to the whole form. The commerce\_checkout\_form\_checkout has a buttons array with the continue button in it, so i have added the functionality to this button array:

```
Array
(
    [#type] => submit
    [#value] => Kaufen
    [#attributes] => Array
        (
        [class] => Array
            (
                [0] => checkout-continue
            )
    )
[#suffix] =>
[#validate] => Array
    (
        [0] => commerce_checkout_form_validate
        [1] => commerce_stock_checkout_form_validate
    )
[#submit] => Array
    (
        [#ajax] => Array
            (
                [prevent] => click
                [callback] => test_function
            )
    )

```

)

But if I hit the submit button, the page still reloads and doesnt jump into my 'test\_function'.

# Answer
I see two problems with your code:

1. `#ajax` should be set on one of button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text\_format, textfield. You are setting it directly on form, not on form submit element, so it cannot work.
2. You should also set `['#ajax']['prevent']` if your form gets reloaded. In theory:

> Description: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image\_button'.

In practice, it often fails to work as expected and I found it safer to set it explicitly.

---

In the button's array, be sure your `#ajax` definition is on the same level `[#type] => submit` is. Don't put it under `#submit` or any other button's sub-array.
> 1 votes

---
Tags: 7, ajax, commerce
---


# Question
Title: Calendar Module Styling of upcoming events
I'm trying to remove the left margin/padding on the event items that show in Upcoming Events when you use the Calendar module(see attached pic). Could anyone advise what element it is that I need to change the CSS on, to remove the left margin or padding? I want the items under the heading to appear flush (left aligning) with the heading. I am also using Omega 3 so I'm not sure if thats relevant.

# Answer
In the View of the Upcoming Events, i changed the view option from HTML List to Unformatted List and the problem went away. See attached pic.
> 0 votes

---
Tags: theming, datetime
---


# Question
Title: Token Value to insert URL of page into field
I am trying to create a webform to appear at the end of all my site pages that asks if there is anything about the page that should be improved. This is dumped straight into the page. In order for this to make sense I need to be able to record the url the form was shown on.

I tried to dump these tokens into the default value for a field

%nid %title

but they output the nid of the webform not the page it is dispayed as a block on.

If the user is logged in I can use

%server\[SCRIPTNAME\]

which works but almost all my users won't be logged in.

Is there a way I can get this information into a field on my form? Otherwise my feedback for is useless.

# Answer
> -1 votes
you can use form alter .get the values from url put the values using form alter to default fields .

---
Tags: 7, webforms, tokens
---


title: Price Field Not Saving Programatically

text:
# Question
Title: Price Field Not Saving Programatically
**Price** *Field Type* from the **Commerce** *module* package is not exportable for **Feeds**. So as a work-around, I saved my prices ('min price', 'hot price' and "deposit price') into normal Float fields and just move the values to the **Price** *Field Types* on-the-fly. And so here it is (set using *Rules*: After an item is saved of content type 'Property'):

```
$node->field_price_amount['und'][0]['value'] = [node:field-current-price-temp];
$node->field_hot_price_amount['und'][0]['value'] = [node-field-hot-price-temp];

```

etc.

and then applying the node\_save($node) with $node-\>is\_new set to FALSE.

All the other values are saving properly except for the field type defined by the **Commerce** module. No actual data saved to tables at all.

"$node-\>field\_price" should be the right machine name I have defined for this field. But for some reason importing leads to error field\_price\_amount cannot be NULL. This is also weird. So I changed it to field\_price\_amount so it won't complain but still not saving despite no more errors in importing. (The db table is still named field\_data\_field\_price but for some reason it is complaining as 'field\_price\_*amount* should not be null ).

Anyone have ideas?

# Answer
> 1 votes
Commerce price fields have a different data structure from standard fields.

i.e not:

```
$product->commerce_price[LANGUAGE_NONE][0]['value'] = 500;

```

but instead

```
$product->commerce_price[LANGUAGE_NONE][0]['amount'] = 500;
$product->commerce_price[LANGUAGE_NONE][0]['currency_code'] = 'USD';

```

or just:

```
$product->commerce_price[LANGUAGE_NONE][0] = array('amount' => 500, 'currency_code' => 'USD');

```

They also have a 'data' property for additional price component information.

More info: `commerce_price_field_data_property_info`

---
Tags: 7, commerce
---


# Question
Title: Features local permission issue Warning: mkdir(): Permission denied in features_export_build_form_submit()
When I am trying to generate a new feature on local, it runs in permissions issue beginning with

> Warning: mkdir(): Permission denied in features\_export\_build\_form\_submit()

There is no www-data user on local. My environment is Mac OSX Mountain Lion.

This is an extension of this question Folder permissions, owner/groups

Which deals with a similar issue on the server level. I am looking for the response for my local.

Current permissions for sites/all/modules/features are

> drwxr-xr-x 22 myusername wheel 748 Aug 7 16:41 features

wheel is the group and root is its user.

Thus what user should own this directory to not run in to the mkdir permissions denied issue on Drupal frontend?

Thanks.

# Answer
The point is that your folder needs to runs under the \_www group (www-data is the group and user for linux machine). You can do it within a terminal or with the finder too. So find the webserver root folder (~/Sites/MYDRUPALSITES, for example) and pull up the Finder Get Info window.

Then on the bottom left corner, click the group icon (The picture with 2 people) and then hold Option then click the “+” button. This will allow you to select system users and groups. Find the World Wide Web group, select that and change the group priviledge to “Read & Write” and then use the cog-wheel to “Apply to enclosed items…”

Or just run the following chgrp (change group) command via Terminal : easiest way (y) !

```
cd ~/Sites

sudo chgrp -R _www MYDRUPALSITES/

```

---

That's the most revelant answer I can answer with your question. But it can also be the owner or a bad installation permissions set. Simple google : permission issue mamp/xammp. Or you could also run

```
sudo chmod 777 -R MYDRUPALSITES/

```

But I **clearly** do not recommend it on a online production (in local it's "acceptable").
> 3 votes

---
Tags: 7, users, features, files
---


title: Get selected value and submit a form

text:
# Question
Title: Get selected value and submit a form
I have a form, and I want to get the selected value of `$form['dropdown_third']` and then use the value to create my table.

What should I write in Submit function?

---

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

$options_first = find_tryk_filter_test_first_dropdown_options();
$value_dropdown_first = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

$form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'Type',
    '#options' => $options_first,
    '#default_value' => $value_dropdown_first,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'find_tryk_filter_test_ajax_callback',
        'wrapper' => 'dropdown_second_replace',
    ),
);

$form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Producent',
    '#prefix' => '<div id="dropdown_second_replace">',
    '#suffix' => '</div>',
    '#options' => find_tryk_filter_test_second_dropdown_options($value_dropdown_first),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'find_tryk_filter_test_2_ajax_callback',
        'wrapper' => 'dropdown_third_replace',
    ),
);

if (!empty($value_dropdown_second)){
    $options_second = find_tryk_filter_test_second_dropdown_options($value_dropdown_second);
    $value_dropdown_second = isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : key($options_second);
}else{
    $options_second = array();
    $value_dropdown_second = isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : key($options_second);
}

//echo $options_second;
$form['dropdown_third'] = array(
    '#type' => 'select',
    '#title' => 'Model',
    '#prefix' => '<div id="dropdown_third_replace">',
    '#suffix' => '</div>',
    '#options' => find_tryk_filter_test_third_dropdown_options($value_dropdown_second),
    '#default_value' => isset($form_state['values']['dropdown_third']) ? $form_state['values']['dropdown_third'] : '',
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Find trykluft element'),
    '#ajax' => array(
        'callback' => 'find_tryk_filter_test_ajax_result_callback',
        'wrapper' => 'result-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
        '#prefix' => '<div id="replace_hotelbook_div">',
        '#suffix' => '</div>'
    ),
);

$header = array('Navn', 'Shoplink', 'Brochure');

$options_third = find_tryk_filter_test_third_dropdown_options($value_dropdown_second);
$value_dropdown_third = isset($form_state['values']['dropdown_third']) ? $form_state['values']['dropdown_third'] : key(0);
$query = db_query("SELECT node.title, fdfs.field_shoplink_value, fm.uri
    FROM node
    JOIN field_data_field_model AS fdfm ON
    fdfm.entity_id = node.nid
    JOIN field_data_field_producent AS fdfp ON
    fdfm.entity_id = fdfp.entity_id
    JOIN field_data_field_shoplink AS fdfs
    ON fdfs.entity_id = fdfm.entity_id
    JOIN field_data_field_brochure AS fdfb
    ON fdfb.entity_id = fdfm.entity_id
    JOIN file_managed AS fm ON
    fm.fid = fdfb.field_brochure_fid
    JOIN taxonomy_term_data AS ttd
    ON fdfp.field_producent_tid = ttd.tid
    WHERE fdfm.field_model_value = '".$value_dropdown_third."'");

$rows = array();

foreach ($query as $row) {
    $rows[] = array($row->title, $row->field_shoplink_value, $row->uri);
}

$form['webform_results'] = array(
  '#theme' => 'table',
  '#rows' => $rows,
  '#header' => $header
);

return $form;

}

```

# Answer
> 1 votes
> What should I write in Submit function?

That's up to you, depends what you want to do. It sounds like you're just unsure how to get access to the submitted values. Those reside in `$form_state['values']`, so:

```
$value = $form_state['values']['dropdown_third'];

```

---
Tags: forms
---


# Question
Title: Altering button title it becomes inactive
The override function I use in my bootstrap sub-theme template.php:

```
function subtheme_form_titles_node_form_alter(&$form, &$form_state) {
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Activate'),
  );
}

```

I use this, so I could replace a default 'Save' title of the button to 'Activate'. Funny thing is that it does replace the button title, but then when using the form and trying to save it by pressing 'Activate', nothing happens, the page just refresh, but content doesn't get created.

Also for some reason it change button class from btn-primary to btn-default. This shouldn't be happening. I just want to replace button text and keep default btn-primary class.

# Answer
> 1 votes
You're removing the submit handler from the element (see `node_form()`, towards the end). You should just change what you need to instead of replacing the whole thing:

```
$form['actions']['submit']['#value'] = t('Activate');

```

> Also for some reason it change button class from btn-primary to btn-default. This shouldn't be happening.

That's not true, it *should* be happening. The `btn-primary` class is applied for submits with one of the following values:

* 'Save'
* 'Confirm'
* 'Submit'
* 'Search'

# Answer
> 2 votes
Your mistake is this line:

```
$form['actions']['submit'] = array(

```

It replaces original button with your own brand new array. Nothing in it, except what you put there. Original node form have submit function connected directly to a button, but you destroyed that with this line.

Instead of deleting original array and creating new one, consider simply altering values you need altered, like:

```
$form['actions']['submit']['#value'] = t('Activate');

```

---
Tags: 7, theming, forms
---


title: How to get the response in JSON format?

text:
# Question
Title: How to get the response in JSON format?
I am using Drupal 7 Services to expose an API. The following is the code I am using to get some of the details and it is giving the response interms of arrays. But I don't want the response to be in Arrays. I want the response in JSON format. What should be the proper solution for this?

The code I am using is:

```
function get_gold_product_items() {

  $query = db_select('node','n');
  $query->Join('field_data_field_gold_price', 'gold_price', 'n.nid = gold_price.entity_id');

  $query->Join('field_data_field_gold_product_type', 'p3', 'n.nid = p3.entity_id');
  $query->Join('taxonomy_term_data', 'gold_product_type', 'p3.field_gold_product_type_tid = gold_product_type.tid');

  $query->Join('field_data_field_gold_price_range', 'p4', 'n.nid = p4.entity_id');
  $query->Join('taxonomy_term_data', 'gold_price_range', 'p4.field_gold_price_range_tid = gold_price_range.tid');

  $query->Join('field_data_field_gold_gender', 'p6', 'n.nid = p6.entity_id');
  $query->Join('taxonomy_term_data', 'gold_gender', 'p6.field_gold_gender_tid = gold_gender.tid');

  $query->Join('field_data_field_gold_wearing_style', 'p8', 'n.nid = p8.entity_id');
  $query->Join('taxonomy_term_data', 'gold_wearing_style', 'p8.field_gold_wearing_style_tid = gold_wearing_style.tid');

  $query->Join('field_data_field_gold_color', 'p10', 'n.nid = p10.entity_id');
  $query->Join('taxonomy_term_data', 'gold_color', 'p10.field_gold_color_tid = gold_color.tid');

  $query->LeftJoin('field_data_field_gold_design_type', 'p12', 'n.nid = p12.entity_id');
  $query->LeftJoin('taxonomy_term_data', 'gold_design_type', 'p12.field_gold_design_type_tid = gold_design_type.tid');

  $query->LeftJoin('field_data_field_gold_purity', 'p14', 'n.nid = p14.entity_id');
  $query->LeftJoin('taxonomy_term_data', 'gold_purity', 'p14.field_gold_purity_tid = gold_purity.tid');

  $query->LeftJoin('field_data_field_gold_ring_size', 'p16', 'n.nid = p16.entity_id');
  $query->LeftJoin('taxonomy_term_data', 'gold_ring_size', 'p16.field_gold_ring_size_tid = gold_ring_size.tid');

  $query->LeftJoin('field_data_field_gold_image', 'p18', 'n.nid = p18.entity_id');
  $query->LeftJoin('file_managed', 'gold_image', 'p18.field_gold_image_fid = gold_image.fid');

  $query->fields('gold_price', array('field_gold_price_value'))
     ->fields('gold_product_type', array('name'))
     ->fields('gold_price_range', array('name'))
     ->fields('gold_gender', array('name'))
     ->fields('gold_wearing_style', array('name'))
     ->fields('gold_color', array('name'))
     ->fields('gold_design_type', array('name'))
     ->fields('gold_purity', array('name'))
     ->fields('gold_ring_size', array('name'))
     ->fields('gold_image', array('filename'));

  // ->condition('n.type', $content_type)
  //->condition('gold_product_type.name', $product_type);
  $result = $query->execute();

  while($record = $result->fetchAll()) {
    print_r($record);
  }

```

}

And the response I am getting is like this:

```
Array
(
    [0] => stdClass Object
        (
            [field_gold_price_value] => 5678
            [name] => Ring
            [gold_price_range_name] => 5000-10000
            [gold_gender_name] => Male
            [gold_wearing_style_name] => Daily Wear
            [gold_color_name] => Yellow
            [gold_design_type_name] => Classic
            [gold_purity_name] => 22 KT (916)
            [gold_ring_size_name] => 24.5
            [filename] => andaaaaaajvq_2.jpg
        )

    [1] => stdClass Object
        (
            [field_gold_price_value] => 12345
            [name] => Pendant
            [gold_price_range_name] => 10000-15000
            [gold_gender_name] => Female
            [gold_wearing_style_name] => Casual Wear
            [gold_color_name] => Two Tone
            [gold_design_type_name] =>
            [gold_purity_name] =>
            [gold_ring_size_name] =>
            [filename] => n651311f_1.jpg
        )

    [2] => stdClass Object
        (
            [field_gold_price_value] => 150000
            [name] => Bangles
            [gold_price_range_name] => 100000-150000
            [gold_gender_name] => Female
            [gold_wearing_style_name] => Party Wear
            [gold_color_name] => Yellow
            [gold_design_type_name] => Band
            [gold_purity_name] => 22 KT (916)
            [gold_ring_size_name] => 12
            [filename] => different-gold-options-india.jpg
        )

    )

```

How to get the response in JSON format?

# Answer
Replace this:

```
while($record = $result->fetchAll())
{
 print_r($record);
}

```

With this:

```
return $result->fetchAll();

```

And make sure you request the resource with the .json extension.
> 3 votes

---
Tags: 7, entities, services
---


# Question
Title: Translated node overwrites other languages
I have a content type with a multivalue text field. Each time I add a translation, the translated node overwrites the source node. Also happens in opposite direction. It seems that whatever I do, the field always overwrites. The node title doesn't though.

I have synchronisation turned off on my content type. What could it be?

# Answer
> 0 votes
Try to do editing of node using path prefix of language in which the node you edit is. So, this would look like:

\[site-domain\]/\[language-path-prefix\]/\[path-to-node-edit\]

You need to enable 'URL' detection method in '/admin/config/regional/language/configure'

Let me know if this is working for you.

---
Tags: 7, nodes, i18n-l10n
---


# Question
Title: When should one use #value_callback and when #element_validate?
I've tried to get into custom element creation but ran into problems with `#value_callback` and when `#element_validate`, more specifically their lack of documentation.

Imagine you have a **custom element** called *db\_connection* whose **output** is supposed to be a is supposed to be an **SQL connection string**.

The **element** itself **consist** of a **few select elements and one textfield**. The user then simply selects (let's say) the database in the first one, table in the second one, and writes numerical of desired row in the last textfield.

My question is, **when** should you go trough the **individual inputs** and **create the SQL connection** string from them? Should it be in `#value_callback` or in `#element_validate`?

---

The names suggest the latter should be more suitable but my experience so far say the very opposite... It also seems to me that other modules (date) do it in the former one.

If one should really do it in `#value_callback` then how should he approach validation? As far as I know, the value callback is called before validation happens so it might have to deal with invalid individual inputs from which it might be impossible to construct the final output (SQL connection string in our example)?

And if it in fact is to be done in #value\_callback than what purpose does #value\_callback serve? What should it do, what should it return, ...?

---

**As of my research**:

This article suggests that one should use `#value_callback` to transform 'default\_value' to element friendly data form and use `#element_validate` to transform inputed data to store / later use friendly form.

So basically it suggests to go with `#element_validate` for the *SQL connection string* creation and use the `#value_callback` only to properly set up the element in case the SQL connection string is given as default value.

---

In addition to this question I also have this one (that is more about `#value_callback`). Already partially answered.

# Answer
`#element_validate`:

> A list of custom validation functions. The validation functions must use form\_error() or form\_set\_error() to flag the element as having an error if the validation fails.

Use this when you want to validate the input into your custom element, and inform users of any failures. Code example of such a validation function:

```
function myelement_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}

```

`#value_callback`:

> Specifies the name of a custom value function that implements how user input is mapped to an element's #value property.

Use this when you simply want to change the state of something in your element based on contextual information. Don't use this method if that state-change has the potential to cause an error that the user should be made aware of; use a validate function in that instance instead.

Code example:

```
function file_field_widget_value($element, $input = FALSE, $form_state) {
  if ($input) {
    // Checkboxes lose their value when empty.
    // If the display field is present make sure its unchecked value is saved.
    $field = field_widget_field($element, $form_state);
    if (empty($input['display'])) {
      $input['display'] = $field['settings']['display_field'] ? 0 : 1;
    }
  }
}

```

So to your question:

> when should you go trough the individual inputs and create the SQL connection string from them?

If this is a process that needs to be *validated*, then in a validation function. If it's something that just needs to be done, regardless of the input, then it goes in the value callback function.

Reading through the code in a bunch of the core value callbacks should clear up the confusion even better:

Notice that nothing in any of those functions relates to *validation* of the input.

Also see `form_builder()`, where the callback is actually used.
> 5 votes

# Answer
If you're developing a module to be shared on drupal.org, certainly use #element\_validate. #element\_validate takes an arbitrary number of callbacks, while #value\_callback only one. So, leave #value\_callback for a third-party site developer who might have some use for it.

In your hook\_element\_info(), give your element both a #process callback and an #element\_validate callback.

In the #element\_validate, both validate the form values and use form\_set\_value() to transform the input fields into the connection string you want. (Or, build a data structure that contains both the input fields and the computed value.)

In the #process callback, be sure to accept, as #default\_value, the computed value from your validate callback. That is, you may have to parse the connection string to extract proper default values for the select elements and textfield.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Autocomplete entity reference - Required to select entity
I'm having problems with a required field that is an entity reference. This is my case:

I have a content type `advertisement` that has an **entity reference** `product`, what is an **autocomplete widget**. The entity reference is a required field (so when it's empty you have to fill something in).

When you start to type in the text field you get a list of suggestions to select from. But you can also type some text and DON'T select a suggestion, the form will submit and the content will be created. I don't want that. I would like to create an error that when you don't select one from the list you receive an error.

What happens when you don't select a suggestion: the advertisement is created but the product is empty!

Is there a way that I can create an error when you don't select one from the list?

# Answer
> 2 votes
Are you sure you are using the Autocomplete widget or are you using the Autocomplete (Tags Style)? I believe tags style allows for an entity to be created like taxonomy term.

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


# Question
Title: Drupal 8 - "Implement menu links as plugins", trying to build a menu tree
In a previous Drupal 8 menu question here, we determined that menu tree building was now a service. In my D8 contrib theme, I was then able to render the main menu tree as:

```
function gratis_preprocess_page(&$vars, $hook) {
// Build the main menu links tree.
  if (!empty($vars['main_menu'])) {
    // Build links.
    $config = Drupal::config('menu.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu');
    // When menu module is not enabled, we need hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    $vars['main_menu'] = \Drupal::service('menu_link.tree')->renderMenu($main_links_source);
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
  }
}

```

The key to this is the use of:

```
$vars['main_menu'] = \Drupal::service('menu_link.tree')->renderMenu($main_links_source);

```

This worked great to fix my main menu tree in Drupal 8 Alpha 11. However, there have been more sweeping changes to the menu system since then and now in Drupal 8.0.x Alpha14, this breaks again with the error:

```
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "menu_link.tree". Did you mean this: "menu.link_tree"? in Symfony\Component\DependencyInjection\Container->get() (line 303 of /Users/danny/Sites/Drupal/d8/drupal8/core/vendor/symfony/dependency-injection/Symfony/Component/DependencyInjection/Container.php).

```

The thing that stands out from the above seems to be:

```
Did you mean this: "menu.link_tree"?

```

I tried

```
$vars['main_menu'] = \Drupal::service('menu.link_tree')->renderMenu($main_links_source);

```

... but that does not work either.

I filed a core issue here and that lead me to "\[META\] New plan, Phase 2: Implement menu links as plugins" and the very same change notice which I used to upgrade this code originally. Admittedly, I am pretty lost here.

# Answer
You may need to render it as below:

```
  // Build the main menu links tree.
  if (!empty($vars['main_menu'])) {
    // Build links.
    $config = Drupal::config('menu_ui.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu_ui');
    // When menu module is not enabled, we need hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    // Allowed max depth.
    // @see MenuTreeStorage::MAX_DEPTH
    $level = 9;
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($main_links_source);
    $parameters->setMaxDepth($level);
    $tree = $menu_tree->load($main_links_source, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $vars['main_menu'] = $menu_tree->build($tree);
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
  }

```

P.S: Make sure you clear cache after update, as it looks like the cache-tag is aggressive and doesn't show same menu in all page at the first run.
> 6 votes

---
Tags: routes, theming, 8
---


# Question
Title: What does `OWNER` value mean in Rules export?
When exporting a rule from Rules module you get some serialized representation of that rule. I understand everything but the 'OWNER' property in the export string - it has 'rules' value, but what does it mean specifically?

If I want store this rule in code within my module, do I need to change this value to 'module\_name'? What are the implications here?

# Answer
OWNER means what module provided this rule. The reason for this is so we have a good way for contrib modules like drupal\_commerce to have a section in their administrative area to only show an interface for their rules and not ALL rules.
> 0 votes

---
Tags: rules
---


# Question
Title: Can I use Simpletest to test site upgrades?
Going through upgrades it's often a bit tedious to test site functionality such as creating and editing nodes. Can Simpletest perform this kind of functionality? Or do I need a solution like Selenium?

# Answer
> 3 votes
It depends of your Simpletest tests. Upgrade your site in a test environment (stagging ideally) and then run your Simpletest tests. If tests are ok you can be sure that everything covered by your tests is ok.

If your question is if Simpletest can create nodes, yes, it can. What Simpletest can't do is test Javascript. If you need to test Javascript you should use another tool like Behat. Behat is a BDD tool, so it allows you to describe the behavior of your app and test it. Behat has several drivers, one of them is the Selenium driver, that includes full JS tests (because the tests are performed by a real browser). There are otheres drivers and many posibliites.

In general Behat is better than Simpletest for integration tests, while Simpletest is better for functional testing.

If you are going to use Behat use the Behat Extension approach. Check the Drupal Behat Group too.

---
Tags: upgrading, testing
---


# Question
Title: How to minify JS and CSS in D7 without using modules
One of the most promising D7 module http://drupal.org/project/advagg for minification and aggregation of CSS and JS isn't ready for production sites yet.

In such a situation which is the best option?

I also checked http://drupal.org/project/core\_library but it sounds overkill.

What other good options we have inside or outside drupal?

# Answer
> 3 votes
This is actually a module, but the Speedy module minifies core JS, has a stable release, and is regularly updated.

# Answer
> 3 votes
When you select "Aggregate and compress CSS files" check box from "Performance" it will minify the CSS.

Minify is a module, for Javascript you can use Minify module to do the same. Minify module minify the JavaScript using Google compiler. It also works with "Boost" and "Aggregate JavaScript files" so you can also get advantage of combining multiple JavaScript files which is default option in Drupal 7.

Minify not only minify the Core JS, but also minify the custom JS.

Minify module also minify HTML.

For ref: How to minify Javascript in D7

---
Tags: theming
---


# Question
Title: How to increase the performance of my website in Drupal 7
I have tested my website on http://www.webpagetest.org/, and I found my website performance is very bad. I have used minifying of CSS and JavaScript, and reducing the pic size; performance is still very bad.
How do I solve this problem?

# Answer
You can guess all you want and experiment, but the only way to actually achieve meaningful results is to profile the system to figure out where the bottlenecks are. There are many ways to accomlish this.

You can use the Performance module to identify slow pages.

You can use xhprof and the Devel module to identify memory problems, and show slow functions and queries.

Are you running APC? If not, you should. Stick the apc.php file somewhere safe and check the statistics to make sure you don't have cache churn.

Install DB Tuner and see what the mysqltuner results and recommendations are, particularly with regards to buffer sizes and query cache size.

You can also read up on profiling and optimizing Apache

You could also experiment with Zend Server CE as it includes a PHP optimizer in addition to opcode caching.
> 6 votes

# Answer
In addition to what MPD writes: before you have a look at tools that complement Drupal, have a look at the settings in Drupal. Make sure you enable caching and CSS/Js aggregation on /admin/config/development/performance.

Also check your theme settings: some themes (like Zen) have a developer mode which forces the theme registry to be rebuilt on every page load, which can be handy for developing, but a huge performance hit at the same time.
> 2 votes

# Answer
You can use Minify module. Minify module minify the JavaScript using Google compiler. It also works with "Boost" and "Aggregate JavaScript files" so you can also get advantage of combining multiple JavaScript files which is default option in Drupal 7.

Minify module also minify HTML.
> 0 votes

---
Tags: 7, performance
---


# Question
Title: D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path
My file directories have not changed, but every time I move from local host to production, or just change the filename of a test site online, I loose the images.

**For example if I use the backup of prodcution server in local I am getting the path name like below:**

> http://localhost/sites/all/sites/default/files/images/image\_name.jpg

here the project name is missing. thats why I am not getting the images.

I have changed the base\_url in local as

> http://localhost/project-name

But even that doesn't helps. (Cleared the cache after changing)

Merely this is a duplicate of this question

But I didn't get what I need on that question. Thats why I reposted again.

Any help will be thankful and grateful...

# Answer
> 2 votes
Have you tried using http://drupal.org/project/pathologic?

Which way are you using to migrate your database and files? I would also suggest that you clear the cache before exporting.

# Answer
> 0 votes
I wanted to post an alternative solution mainly because I don't think that an Input Format is going to solve all the problems.

Basically, you can follow the instructions below.

1. Import your database
2. Within your database editing tool run this code : `update files set filepath=REPLACE(filepath, 'sites/OLD_SITE_PATH/files', 'sites/NEW_SITE_NAME/files')`
3. Log into your site and change your paths at

> admin/config/media/file-system

---
Tags: 7, uri
---


# Question
Title: Drupal 7 Webform Components Related To Individual Nodes
I am attempting to create a decision making "questionnaire" in Drupal 7. I am currently using the Webform module to create the questionnaire.

The questionnaire (webform) will create a list of related nodes based on the users submission. What I need is a way to relate the nodes to the webform components.

For example, if a user selects 'Coffee Shop' & 'Sandwiches' on one of the multiple choice questions, all nodes relating to 'Coffee Shops' & 'Sandwiches' will be added to the list.

Is there an available module that will allow me to relate webform components to nodes or would I some how incorporate taxonomies into this for the relationships?

Would EntityForm be a better module for this type of thing?

# Answer
I'm not sure what UX you want, but with Fieldgroups webforms can be multi-paged. As of webform 4.x Conditional Fields (on the same page, or across pages) is supported by webform. You can have hidden fields already in webform if you need a simple storage mechanism not seen by users ...

I imagine you could then use webform rules and upon final submission of the webform to examine whatever values have been submitted and use a custom rule to populate an available list of NIDs based on the submitted criteria.

You could maybe use Entity List and nodequeues to solve this:

* if component is selected on submission use Entity List X, which references a smart nodequeue to nodes of a certain content type ... etc.
> 0 votes

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


title: Add taxonomy term image to a view

text:
# Question
Title: Add taxonomy term image to a view
Can anybody tell me how I add an image field of a taxonomy term to a view of nodes with reference to the vocabolary?

I have a content type called "Product" and one called "Distributors". And then a have a vocabolary called "Product categories", where a term has two fields: a title field and an image field.

I am using the NAT module to add a term to the "Product categories" vocabulary every time a product is created, so that the title and image of the product becomes a new term with the value of these two fields.

When I create a distributor I am using these terms as term reference to which products the distributor sells.

The problem I am facing now is that I want a view of distributors, and I cant seem to get the image of the terms associated with each distributor-node. I can only get the titles. I assume that I might have to make some kind of relasionship, but I cant seem to figure it out.

I hope someone can help me.

# Answer
From what I understand you have a distributor node that has a term reference (multi value) to Product categories.

In your view that lists the distributors you must add a relationship: Content: Taxonomy terms on node. When presented with a choice of vocabularies you select 'Product Category'.

Then you add two fields: Taxonomy term: Name, and Taxonomy term: Image (your image field might be named slightly differently). For both of these fields, during the multi form process of adding them, you will be presented with a form that says for instance: Configure field: Taxonomy term: Name. Here you must select the Relationship as term.

This will create one row for each taxonomy term on the node, which might not be what you want. You can now group it under the content:title of the distributor.

There are two other ways that I can see by which you can group all of the images from one distributor under a single distributor.

**First method:**

Create a new field: global custom text. Make sure that it is below all of the distributor fields. Move the image field below it. In this global text field add all of the distributor fields (using html and replacement patterns) except for the image field. For instance, you might have something like this:

```
<div>[title]</div>
<div>[address]</div>
<div>[phone]</div>

```

Now go and hide all of the fields, the global text field as well, except for the image field. Then in your grouping, select this new global text field as the field to group on. Now apply some CSS to make it look good. And if you want to get rid of that pesky h3 tag around the grouping header, then override the theme view template. Click on Theme: Information in views and select one of the Style output templates.

**Second method:**

Install the Views Field View module. This allows you to create a field in a view that will be the result of another view.

Create a new view that takes as contextual filter the nid of the distributor, and then as before add a relationship to the terms etc. so that this view only outputs the pictures in groups.

In your original view remove the relationship to the terms, and insert a field to the new view, and make sure to pass it the parameter of the nid.
> 4 votes

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


title: commerce - add tax when creating order

text:
# Question
Title: commerce - add tax when creating order
I don't seem to see an ability to add tax to an order when it's created by admin through Store-\>Orders-\>Create Order. Can this be somehow configured?

I have it working on a standard checkout for a frontend user, it depends on the billing address entered. I'd like to have the same for when order is created 'manually'

# Answer
> 0 votes
This *used* to be handled by an external module called Commerce Checkout Admin 7.x-2.11 but since Commerce Kickstart 7.x-2.16 this apparently came as part of core. As a result, Commerce Checkout Admin 7.x-2.12 now does not include this feature.

Since updating my site the 'Add an Order' no longer seems to calculate tax, so I am looking for this solution as well. Using:

* Drupal 7.30
* Commerce Kickstart 7.x-2.16

---
Tags: commerce
---


title: hook never called

text:
# Question
Title: hook never called
File C:\wamp\www\sites\all\modules\custom\_user\custom\_user.info:

```
name = Custom User
description = Custom User
core = 7.x
dependencies[] = alter_ego

```

File C:\wamp\www\sites\all\modules\custom\_user\custom\_user.module:

```
<?php

function custom_user_views_api() {
  return array(
    'api' => 3,
  );
}

/**
 * Implement hook_user_view().
 */
function custom_user_user_view($account, $view_mode, $langcode) {
  dsm( $account );
}

```

File C:\wamp\www\sites\all\modules\custom\_user\custom\_user.views\_default.inc :

```
<?php

function custom_user_views_default_views() {

    $view = new view;
    $view->name = 'custom_user_views';
    $views[$view->name] = $view;
    dsm( $views );
    return $views;

}

```

If I add a syntax error within the "custom\_user.views\_default.inc" function, clearing all caches will return an error. So the function is parsed. But when I reload my page:

```
http://localhost:8080/?q=user/1

```

I can only see the dsm() from Called from: C:\wamp\www\sites\all\modules\custom\_user\custom\_user.module, line 15

I'm quite new to drupal. What am I doing wrong ?

**EDITED AFTER FIRST ANSWER.**

# Answer
> 0 votes
From https://api.drupal.org/api/views/views.api.php/function/hook\_views\_default\_views/7 ...

> This hook should be placed in MODULENAME.views\_default.inc and it will be auto-loaded. MODULENAME.views\_default.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.

The files\[\] element of module .info files can be a little confusing because, as you identified, they do get parsed. However, you will either need to rename your file according to the directions above (`custom_user.views_default.inc`) and implement hook\_views\_api() or manually use module\_load\_include() at another point in your module in order to include extra files.

## So, when do you use files\[\]?

One of the most common uses of the files\[\] line in your .info file is to take advantage Drupal's Autoloading feature (which is built on top of PHP5's autoloading) for classes. Classes defined in a file like that will have that file load automatically when you need to use that class, thanks to Drupal's auto-loading implementation. The views module stuff makes this a little confusing because it adds another separate auto-loading concept on top of this functionality.

---
Tags: hooks
---


# Question
Title: How can I load content on the same page from a search
So the idea is to load the results of the search on the same page. I was told to look into SOLR, but it looks like we have something similar to SOLR , and we just need to know how to load new page content into our drupal site. Alternate to iFrame.

# Answer
> 0 votes
you to load the search results on the same page - the same page as what? do you mean without a page refresh? If that's the case, then I think you're looking for Search API Ajax:

```
This module can ajaxify Seach API pages and views. Ajax made possible by
Drupal 7 core's jQuery BBQ (previous YUI3 History library is dropped).

```

and perhaps Ajax Facets:

```
This module allows you to create facet filters which working by AJAX.
Filters and search results will be updated by AJAX.

```

There are a few more suggestions here

---
Tags: views, 7, theming, ajax, javascript
---


# Question
Title: How do I create anonymous emails sent by users and allow other users to reply back to the anonymous email?
Would like to create something like Craigslist in terms of its anonymous emails so that Logged-in users can send email from the site. Once they do, their email will be changed to randomtext@domain.com instead of their original email. This is to prevent other users from knowing the real email of the authenticated users.

Other users should still be able to send them email with the randomtext@domain.com as To and that reply would be saved on the Users's profile.

How would you go about implementing this? The module I found that's close, but not sure how it works is Mailhandler with Singlebox . But there's rarely any documentation for it. Do you recommend other solutions?

# Answer
> 1 votes
You could use the following components:

* an email server you control to create temporary email accounts, or a mail relay service.
* use Relation or a custom user field for a user's anonymous email thru `user02193213@yoursite.com`. Enforce uniqueness of this field. Relation can do alot of this for you as a developer (create a `user <-> anonymous email` relation, attach category tags to the `Relation Entity` itself and use `relation_query` to build reusable lookup functions.
* store a mapping of Drupal `uid` to anonymous emails. In general this is outlined here: https://stackoverflow.com/questions/8179047/email-piping-in-php-like-craigslist-how-do-i-associate-real-emails
* upon content submission use Rules to lookup anonymous email addresses of content owner to logged in user and send the email. Your email server you control can then forward to real addresses.

Questions regarding email setup are not drupal setup and inappropriate here. I've just outlined an approach for the Drupal side of things.

---
Tags: emails, users
---


# Question
Title: Need a solution to search by sales person based on unique territory
I've been researching for hours for a solution, but I can't find a module or example of someone else needing this feature.

I have a list of 20-ish sales people, each person is assigned a range of zip codes. Some of them are entire states, but there are a few sales reps where the state is split between 2-3 people. I need a way for the user to enter in their own location and show which sales rep would be their point of contact.

Anyone have an idea of how I would go about doing that? Location module?

Thanks!

# Answer
> 0 votes
Found something that might help you Locator tutorial and use Location Map if you want to display the results in a map.

# Answer
> 0 votes
https://www.drupal.org/node/1944648 This link might help you out..

---
Tags: location
---


# Question
Title: Views boolean column if user has a specific role
I have a standard Drupal installation with Views and Administration Views modules installed.

By default, the Users view has a column Roles with ALL the users roles.

How to include a custom column (to replace the default Roles column) to show if the user has or hasn't a specific role (like a yes/no column)?

# Answer
I don't see an out of the box method. Maybe someone else will have a better answer. But what I did for a quick solutions is to add the Views PHP module, then add a PHP field with the following output code:

```
<?php

  $account = user_load($data->uid);

  $roles = array('YOURROLE', 'ANOTHER ROLE');

  if (count(array_intersect($roles, $account->roles))) {
    print 'Yes';
  }
  else {
    print  'No';
  }

?>

```

It will print yes if any user has either of the two roles.
> 1 votes

---
Tags: users, views
---