title: Check on save if Site already exist

text:
# Question
Title: Check on save if Site already exist
When a new page is created and the path already exists, drupal automatically converts it to path\_n .
Which behavior I want here instead:
A message that the path already exists, with two buttons one to go back and one to create path\_n.
How could I add this behavior?
(think hook\_node\_create is a good start, or is there even a module?)

# Answer
Unique Field is the closest module you'll find. Assuming you use a field like title on your url path this would work, but without the continue anyways option. Although looking at the module code might help you out in building your own custom module.
> 1 votes

---
Tags: 7, path-aliases, nodes
---


title: Features, Drush and Drupal 6

text:
# Question
Title: Features, Drush and Drupal 6
I'm using drush on D6 websites and i would to create and manage my features via drush.So i patched the 1.2 version like in this post :

Then i get an error when i try to create a feature for content types : https://www.drupal.org/node/2283617

```
  $ drush @sitebl fe --d --destination="sites/all/modules/_features"  briselames_content_type  node:page_lycee
....
Unknown option: --destination

```

Have you any idea about this ?

thanks

EDIT1

when i try whithout quotes (or single quotes '') this give an error

```
$ drush @sitebl fe --d -destination=sites/all/modules/_features  briselames_content_type  node:page_lycee
PHP Warning:  Module 'curl' already loaded in Unknown on line 0
Bootstrap to phase 0. [0 sec, 3.81 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.03 sec, 4.01 MB] [bootstrap]
Loaded alias @sitebl from file /home/xxx/.drush/aliases.drushrc.php [0.16 sec, 4.02 MB]                                             [notice]
Cache SET cid: 6.6-dev-alias-path--e9a42ca79125c2d266c093da6a27d238 [0.25 sec, 4.02 MB]                                                             [debug]
Cache HIT cid: 6.6-dev-commandfiles-0-29f4f0296708390047a2c57582fb56a8 [0.27 sec, 4.03 MB]                                                          [debug]
Bootstrap to phase 0. [1.9 sec, 9.59 MB]                                                                                [bootstrap]
Bootstrap to phase 5. [1.94 sec, 9.59 MB]                                                                                [bootstrap]
The drush command 'fe briselames_content_type node:page_lycee' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache[error]
if you have installed new extensions. [1.94 sec, 9.59 MB]
The directory 1 does not contain a valid Drupal installation [1.94 sec, 9.59 MB]                                                                [error]

```

# Answer
Try to specify the destination part of your drush command without the quotes, like so:

> --destination=sites/all/modules/\_features

Curious to see if this helps ...

**Updated answer**, now related to the new error after "edit1" in the question: Try running the comment again, but now with this slightly corrected command (note the "--destination" instead of "-destination"), like so:

> $ drush @sitebl fe --d --destination=sites/all/modules/\_features briselames\_content\_type node:page\_lycee
> 0 votes

---
Tags: 6, drush, features
---


# Question
Title: How to delete Panel variant programmatically
I have a "node\_view" panel pane, with a few variants.

Say a variant called `node_view_panel_context_9`, and I would like to delete this variant programmatically using code (from a hook\_update\_N hook to be specific).

What are the correct API functions/methods to use?

# Answer
I just had to do this recently. If the variant is exported to code (like in a Feature) this will revert it. Otherwise it will just delete it.

```
   function MY_MODULE_update_N() {
     ctools_include('export');
     $page = ctools_export_crud_load('page_manager_handlers', 'node_view__test123');
     ctools_export_crud_delete('page_manager_handlers', $page);
   }

```
> 1 votes

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


# Question
Title: Loading specific bootstrap mode in hook_menu
There is a way to define a specific bootstrap mode for a hook\_menu URL (MENU\_CALLBACK)?

I just want the request returns to me a result of a simple query in JSON and for that, I don´t need load the Drupal bootstrap in full mode, damaging the response performance.

Thanks!

# Answer
It's not possible, because `hook_menu()` is invoked when Drupal is completely bootstrapped, also because only when Drupal has been completely bootstrapped, all the modules are loaded; only in this case all the menu callbacks defined in `hook_menu()` are available.

If you really need to limit the bootstrap to a phase, then you can write a file that is similar to index.php, for example.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

```

An example of file used for a specific task is cron.php.

```
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  drupal_cron_run();
}

```

Generally, there isn't the need to limit the bootstrap, only to serve data in JSON format. Creating a file like cron.php should be done for a dedicated task that is time consuming, or for limiting the pages being served, as with install.php.
> 2 votes

# Answer
Try this module: https://www.drupal.org/project/js It does not let you choose the bootstrap level, but it allows you to define a callback that only loads the bare bone of drupal.
> 0 votes

---
Tags: 6, routes
---


title: Page arguments - hook_menu

text:
# Question
Title: Page arguments - hook_menu
I have this two test menu items:

```
  $items['test/%id'] = array(
    'title' => 'Test',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form', 1),
    'load arguments' => array('%map'),
    'access arguments' => array(1),
  );

  $items['test/new/%new_id'] = array(
    'title' => 'Test',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form', 2),
    'load arguments' => array('%map'),
    'access arguments' => array(2),
  );

```

Here is the fr\_module\_form function:

```
function my_module_form($form, &$form_state, $id = NULL, $new_id = NULL) {
  dsm($id, 'id');
  dsm($new_id, 'new_id');
  return '';
}

```

Here is the problem. When I visit (for instance): test/my-test-var
dsm(1) function returns $id =\> my-test-var
dsm(2) function returns $new\_id =\>

but when I visit: test/new/my-test-var
dsm(1) function returns the same as above which is:
$id =\> my-test-var so it's not $new\_id as I've expected.
dsm(2) is still empty

Moreover if I visit /test/new/my-test-var/my-second-test-var I get:
dsm(1): $id =\> my-test-var
dsm(2): $new\_id =\> my-second-test-var

Why do I 'tell' drupal in 'page arguments' which argument should be used? I always get the first argument from my\_module\_form.

How to separate it?

# Answer
Path parts are passed to the menu callback function with a zero index as the first path part i.e.

First url: `array(0 => 'test', 1 => '%id')`

Second url: `array(0 => 'test', 1 => 'new', 2 => '%new_id')`

Your form function expects two arguments but you only ever give it one.

In your form function arguments, this: `$id = NULL, $new_id = NULL` corresponds to this `array('my_module_form', first_argument, second_argument)` in your menu callback args. So you are only ever giving your form function one argument from the menu. Try this in your second menu item:

```
'page arguments' => array('my_module_form', 1, 2),

```

This will provide two arguments for the form callback function. Your first menu item will return null for `$new_id`, because you don't have further path parts to provide from the url.
> 1 votes

---
Tags: 7, forms, routes
---


# Question
Title: XML Sitemap Last Modified Date on a View
The site I am working on has a front page gallery view.

Is there any way to update the last modified date of the view in the XMLSitemap file? As currently it is just empty.

# Answer
The short answer is: No.

How are you including the views in the sitemap? I assume that you are just putting in custom paths? Without writing custom code, the only thing you can do for the custom path is to change the change frequency to a realistic amount. Don't exaggerate the frequency too much, or crawlers will start ignoring it.
> 0 votes

---
Tags: xml-sitemap
---


title: Update line item price

text:
# Question
Title: Update line item price
So I have a product named "Store Credit" which is added to the cart when the user wishes to use points to get discount. The discount is always different depending on how many points the user enters. If the user enters 500 points, I want to create a line item with a price of -500$.

```
function switch_addtocart_cart_line_item_refresh($line_item, $order){

    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $line_item_wrapper->commerce_unit_price->amount = 150;
    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
    commerce_cart_order_refresh($order);
    dpm($line_item);

}

```

My dpm indicates the price has changed but the price in my cart and order review page is still the same? What am I doing wrong.

# Answer
Check your hook\_name, I think thats the issue.

Default commerce hook is mentioned below.

```
hook_commerce_cart_line_item_refresh($line_item, $order_wrapper)

```

So, Your hook can be like (assuming switch\_addtocart is your module name)

```
function switch_addtocart_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

```

}

Please check and let us know.
> -1 votes

# Answer
You also need to change.

```
$line_item_wrapper->commerce_unit_price->data->components->price->amount

```
> -1 votes

---
Tags: 7, commerce
---


# Question
Title: How can I get a default value in a dropdown using form API?
```
$results = db_select('users', 'u')->fields('u', ['name', 'uid', 'mail'])->execute();
$options = [];
foreach ($results as $result) {
  $options[$result->uid] = $result->name . ' | ' . $result->mail;
}
unset($options[array_search(0, $options)]);
$form['user'] = [
  '#type' => 'select',
  '#title' => t('Select User'),
  '#options' => $options,
  '#default_value' => ('select a value'),
  '#states' => [
    'visible' => [
      ':input[name="data_set"]' => ['value' => 'education'],
    ],
  ],
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Expire'),
];

```

I have this dropdown , how can I get the default value like `Select a value` or something

# Answer
> 0 votes
For required items a `-select-` item is added automatically. If the form field is not a required one, you'll have to add it manually, for example with the following code.

```
  $options = array('_none' => '-select item-') + $options; //Places an extra option at the start

```

If it's the first item it should be selected automatically but if you want to be safe.

```
  // Use the array key, not the value.
  '#default_value' => '_none',

```

You'll have to filter it out the '\_none' value in the submit handler afterwards.

---
Tags: 7, forms
---


# Question
Title: Build an EntityFieldQuery that selects referenced entities
I am looking for the ID of the entity of type A and I know the ID of entity B that references A.

I found a few nice sources about EntityFieldQuery. I was amazed that i was getting results from .NET in google :) (is it a sign of Drupal's maturity ? :). But didnt manage to find this. Please help ...

### Some of the sources :

This is what it looks like with entity loads - you will understand i need that query :) The wrapper is there for practice mainly. Note that it loads the target entity - quite a lot of queries.

```
  $b = entity_load('B', array($id));
  $bm = entity_metadata_wrapper('B', $sl[$id]);

  $tsl = $slm->field_sl_tpref->value();
  echo $tsl->id;

```

# Answer
You can use `target_id` instead of `value` to retrieve entities based on the ID of referenced entities:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', <type-of-the-entity>);
$query->fieldCondition('<name-of-the-field-referring-the-other-entity>', 'target_id', <id-of-the-referenced-entity>, '=');
$results = $query->execute();

```
> 18 votes

# Answer
err, is the Relation Module what you are looking for? It sounds like defining relations between X and Y entities is what you want todo. it has its own RelationQuery (a wrapper around EFQ) and RelationQueryEndpoints to easily get this kind of information.
> 2 votes

# Answer
I know this is an older question but for people getting to this from Google I figured I would throw another approach in here.

From the description above the setup has 2 entity types, A and B. B references A with entity reference I'm assuming. So if you have the id of B you should have a field with the ID of A stored in the database.

Code Notes:

* Original NID - `$original_node->nid` This would be the ID of B
* Bundle type - `$type` this should be the type of A
* The field condition just looks for field that holds the reference
* For more info on how to use EFQ see this

Code

```
// Start a new EFQ
$query = new EntityFieldQuery();

// Define query, the user load is probably not needed but sometimes is.
$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', $type)
      ->fieldCondition('field_NAME_OF_FIELD', 'target_id', $original_node->nid, '=')
      ->addMetaData('account', user_load(1));

// Execute query, result with have node key
$result = $query->execute();

// If results it will be in node key
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  // This example has multiple nodes being referenced by one node
  $nodes = node_load_multiple($nids, array('type' => $type));
  // Devel module needed
  dpm($nodes);
}

```

You can also set up two way entity references and do the same query above backwards. You could use a module like CER to make sure those references are kept up to date. Or setup a rule to keep the reference up to date, I've used both.
> 2 votes

# Answer
a quite dynamic solution (a bit dirty too but I needed it quickly) so you do not need to hard code the name fo the referencing field and it is automatically handled with new referencing field you will add in the future :

in your custom module :

```
/**
 * Implement hook_field_create_instance().
 */
function MY_CUSTOM_MODULE_field_create_instance() {
  _MY_CUSTOM_MODULE_set_variable_node_back_references();
}

/**
 * Implement hook_field_delete_field().
 */
function MY_CUSTOM_MODULE_field_delete_field() {
  _MY_CUSTOM_MODULE_set_variable_node_back_references();
}

/**
 * Set Variable node_back_references.
 */
function _MY_CUSTOM_MODULE_set_variable_node_back_references() {
  $field_list = db_select('field_config', 'fc')
    ->fields('fc', array('field_name', 'data'))
    ->condition('fc.data', '%"foreign keys";a:1:{s:4:"node"%', 'like')
    ->condition('fc.deleted', 0);
  $field_list->innerJoin('field_config_instance', 'fci', 'fci.field_name = fc.field_name');
  $field_list->rightJoin('node_type', 'n', 'n.type = fci.bundle');
  $fields = $field_list->execute()->fetchAll();

  $fields_array = array();
  foreach ($fields as $field) {
    $unserialized = unserialize($field->data);
    if (isset($unserialized['settings']['handler_settings']['target_bundles'])) {
      foreach ($unserialized['settings']['handler_settings']['target_bundles'] as $bundle) {
        $fields_array[$bundle][] = $field->field_name;
      }
    }
  }

  variable_set('node_back_references', $fields_array);
}

function _MY_CUSTOM_MODULE_get_referencing_nodes($node) {
  $nids = array();
  $fields = variable_get('node_back_references', array());
  if (isset($fields[$node->type])) {
    foreach ($fields[$node->type] as $field) {
      $query = new \EntityFieldQuery();
      $query->entityCondition('entity_type', 'node');
      $query->propertyCondition('status', 1);
      $query->fieldCondition($field, 'target_id', $node->nid);
      $result = $query->execute();
      $nids = isset($result['node']) ? array_merge(array_keys($result['node']), $nids) : $nids;
    }
    $nodes = (!empty($nids)) ? node_load_multiple($nids) : array();

    return $nodes;
  }

  return $nids;
}

```

where you need to get the parent nodes given the child node :

```
$nodes = _MY_CUSTOM_MODULE_get_referencing_nodes($node);

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Get entities that share the Entity Reference field
Let's say that I have two content types:

* Article

+ title
    + body
    + field\_ref\_term
* Page

+ title
    + body
    + field\_ref\_term

Those two content types are sharing the same field: "field\_ref\_term" wich is a "Entity reference" field type, to another entity called 'Term' (or something else, it doesn't mind).

What I'm trying to do is, when displaying a particular content of type "Page", I would like to be able to display a list of content in a block who shares the same value for the "field\_ref\_term" field.

It's a bit like the "Content: Has taxonomy term ID" contextual filter from Views and Taxonomies, where you set the value to "Taxonomy term ID from URL" then check "Load default filter from node page, that's good for related taxonomy blocks".

Do you think this is currently possible with Entity Reference ?

Thanks

# Answer
I finally found a way to do it, here are the steps:

1. Add a relationship: Entity Reference: Referenced Entity, select the right field to match, select "Require this relationship"
2. Add a relationship: Entity Reference: Referencing Entity, selection the just add relationship in step 2 and check "Require this relationship".
3. Add a contextual filter: Content:nid, provide default value: Content ID from URL
4. Add a contextual filter: Content:nid, select the relationship "Content referencing...", provide default value: Content ID from URL, then in the More fieldset, check exclude.
5. Add a field "Title" and select the relationship "Content Referencing..."

I will close this question, feel free to comment or propose other solutions.

Thanks.
> 4 votes

# Answer
As opposed to the other answer, if you need it programmatically :

a quite dynamic solution (a bit dirty too but I needed it quickly) so you do not need to hard code the name fo the referencing field and it is automatically handled with new referencing field you will add in the future :

in your custom module :

```
/**
 * Implement hook_field_create_instance().
 */
function MY_CUSTOM_MODULE_field_create_instance() {
  _MY_CUSTOM_MODULE_set_variable_node_back_references();
}

/**
 * Implement hook_field_delete_field().
 */
function MY_CUSTOM_MODULE_field_delete_field() {
  _MY_CUSTOM_MODULE_set_variable_node_back_references();
}

/**
 * Set Variable node_back_references.
 */
function _MY_CUSTOM_MODULE_set_variable_node_back_references() {
  $field_list = db_select('field_config', 'fc')
    ->fields('fc', array('field_name', 'data'))
    ->condition('fc.data', '%"foreign keys";a:1:{s:4:"node"%', 'like')
    ->condition('fc.deleted', 0);
  $field_list->innerJoin('field_config_instance', 'fci', 'fci.field_name = fc.field_name');
  $field_list->rightJoin('node_type', 'n', 'n.type = fci.bundle');
  $fields = $field_list->execute()->fetchAll();

  $fields_array = array();
  foreach ($fields as $field) {
    $unserialized = unserialize($field->data);
    if (isset($unserialized['settings']['handler_settings']['target_bundles'])) {
      foreach ($unserialized['settings']['handler_settings']['target_bundles'] as $bundle) {
        $fields_array[$bundle][] = $field->field_name;
      }
    }
  }

  variable_set('node_back_references', $fields_array);
}

function _MY_CUSTOM_MODULE_get_referencing_nodes($node) {
  $nids = array();
  $fields = variable_get('node_back_references', array());
  if (isset($fields[$node->type])) {
    foreach ($fields[$node->type] as $field) {
      $query = new \EntityFieldQuery();
      $query->entityCondition('entity_type', 'node');
      $query->propertyCondition('status', 1);
      $query->fieldCondition($field, 'target_id', $node->nid);
      $result = $query->execute();
      $nids = isset($result['node']) ? array_merge(array_keys($result['node']), $nids) : $nids;
    }
    $nodes = (!empty($nids)) ? node_load_multiple($nids) : array();

    return $nodes;
  }

  return $nids;
}

```

where you need to get the parent nodes given the child node :

```
$nodes = _MY_CUSTOM_MODULE_get_referencing_nodes($node);

```
> 1 votes

---
Tags: 7, views, entities
---


# Question
Title: breadcrumb containing a link to a path that's deeper than the one of the page it's on
On my site i have the weird problem that for one of the menu pages the breadcrumb shows as one lvl deeper than the page it's on.

So it's showing: Home \> Page i'm on \> subpage i'm not on instead of: Home \> Page i'm on

In addition, contrary to other pages i have, the bottom level of the breadcrumb is clickable which makes no sense, as that's supposed to be the page i'm on (wel it's not due to the above described error, but anywho).

I've no breadcrumb-modules installed. I do have a hook to modify the breadcrumbs like so:

```
function mytheme_breadcrumb(&$variables) {
  if (isset($variables['breadcrumb']) && !empty($variables['breadcrumb'])) {
    $crumbs = '<ul class="horizontal-list horizontal-list--multilevel">';
    $breadcrumb = $variables['breadcrumb'];
    $array_size = count($breadcrumb);
    $i = 0;
    while ( $i < $array_size) {
     $crumbs .= '<li class="';
     if ($i+1 == $array_size) { $crumbs .= 'horizontal-list__last'; }
     $crumbs .=  '">' . $breadcrumb[$i] . '</li>';
     $i++;
    }
    $crumbs .= '</ul>';
    return $crumbs;
  }
}

```

Doesn't look like the theme\_breadcrumb function is responsible, as it uses the values it's getting from drupal by standard.

Anybody any ideas as to what might be causing this?

# Answer
> 0 votes
Is it possible that there is an old link to this page in your menu that is nested in the tree like. home -page --MY-PAGE

Because breadcrumbs seem to use the menu tree to build the breadcrumb items.

---
Tags: breadcrumbs
---


# Question
Title: Create a secondary form to fill data into an entity
I've an entity that models a contact (I'm using RedHen CRM) and obviously I can fill the data from the usual admin form. But if I want to publish another form for non admin users to insert their data and with less fields displayed, which module (or solution) can I use? I'm using webform, but I'm having some trouble with addressfield...

# Answer
I don't know about the webform solution/Redhen

but programmatically/basic drupal speaking I would just use HOOK\_form\_FORM\_ID\_alter to restrict access to certain form elements based on role/permission. Find the id of the form and have a look at the array via devel or something similar, every field normally has an '#acces' variable already included. Setting those to 0 for the fields does exactly what one expects it would do.

This way you can re-use the standard form for all purposes instead of adding a second one. So future edits to the entity fields will automatically be added to all forms and you don't have to fiddle around with all sorts of secondary processing in the submit handler.
> 1 votes

---
Tags: 7, forms, webforms
---


title: Configuration form settings

text:
# Question
Title: Configuration form settings
I would like to create a settings page for a user which allows them to save the options of a list which is to be used in a custom form. The list is called marketing source and it is added to a form which gets submitted with plain text values to an external API.

I know in field config for select lists you can do this but I want to do it on a custom config page for that specific list.

Foe example I would have a textfield in the config that had values like this

```
1|google
2|magazine

```

Then I need to convert that into a seralised array and store with variable set.

Is there a function that does that already for the field form?

Cheers Dan

# Answer
This is how I achieved what I wanted, rather than use key value pairs I just used an empty textfield and used one line for each option and then when retrieving the textfield for the form I used the following.

```
$raw_marketing_options = explode(PHP_EOL, variable_get('marketing_sources_sources'));

```

I then just used the variable directly in the form.

```
$form['Marketing_source__c'] = array(
  '#type' => 'select',
  '#title' => 'Marketing source',
  '#options' => $raw_marketing_options,
);

```

There may be a safer way to do it as I am not sure how secure variable\_set() is when storing plain text but only the administrator will see the textarea anyway.

Cheers
> 0 votes

# Answer
You can use a system\_settings\_form this is a 'shortcut' creates a form that saves input data via a variable\_set(). The tutorial also explains how to create a page for the form.

Tutorial on settings form

variable\_set/variable\_get always serialize/deserialize any array you pass to them.
> -1 votes

---
Tags: forms, configuration
---


title: webform blank page D7

text:
# Question
Title: webform blank page D7
The Webform module is installed. I go to /admin/content/webform to build new form, but the page is completely blank. The content is empty. What am I missing? Is there an additional library I need?

I do have Views and Chaos Tools installed. And my administrator role has permission to modify webforms.

# Answer
> 1 votes
There is a Webform issue which might be similar to this question here. Though that issue is after "upgrading", one could argue that after "upgrade" or after "install" of the module, the result is in both cases that you are using the newest version of the module, right?

So therefore, here are a few things in that issue that might help to get you going:

* **Clear the cache** and try again.
* if you did something like an update of that module (I think not, but you never know), then **run update.php** and try again.
* Try to **disable and then enable** the module, and try again.

Curious to hear if any of this helps ...

---
Tags: webforms
---


# Question
Title: How can I print a text field's database value with devel so that it displays on all nodes?
I want just the text field's data without an of the "field-" divs wrapped around it. It's a link so I want to do something like `<a href="foo.com"><?php print render($content['field_download_link']); ?></a>`.

`$...['content']['system_main']['nodes'][7533]['field_download_link']['#field_name']` is the path of the field I want to display, but I want it on every node of the content type feed\_item, not just 7533.

I tried placing `<?php dpm($node); ?>` at the top of node--feed-item.tpl and `<?php print dpm($node['content']['system_main']['nodes'][7533]['field_download_link']['#field_name']); ?>` where I want the field, but it just causes the page to load without any css.

# Answer
> 0 votes
If you need to check the full structure of $node try this:

**var\_dump($node)**

In this case looks like you need something like this:

**echo $node-\>FIELD\_NAME\['und'\]\[0\]\['value'\];**

If you want to get an image field.. you can use this:

**echo render(file\_create\_url($node-\>IMAGE\_FIELD\_NAME\['und'\]\[0\]\['uri'\]))**

# Answer
> 0 votes
Based on node.tpl.php, it says

> $node: Full node object. Contains data that may not be safe.

## Things I noticed that's not quite right:

1. `dpm()` doesnt need to be used with `print`
2. `dpm($node['content']['system_main']['nodes'][7533]['field_download_link']['#field_name']);` wouldn't work since $node is an object.

## Things to try:

1. Use only `dpm($node);` and see what's the output. If the field you're looking for exists then you can continue with manipulating its data
2. you could place the structuring of your link in `hook_preproess_node()` and just render it into your template file.

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


# Question
Title: What is wrong in my code for replacing the text of 'add to cart' button?
Can somebody tell me what is wrong in my code, please? I'm trying to replace the regular text for 'add to cart' button for two types of product. I'm using Drupal Commerce module. But something is wrong in my code. Works just first part of code.

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

  $product_types = commerce_product_types();

  if (isset($product_types['product']))  {
    $product = $form_state['default_product'];
    $price = commerce_product_calculate_sell_price($product);
    $price_display = commerce_currency_format($price['amount'], $price['currency_code'], $product);
    $form['submit']['#value'] = 'Buy this product ' . $price_display;
  }

  if (isset($product_types['product_2']))  {
    $product = $form_state['default_product'];
    $price = commerce_product_calculate_sell_price($product);
    $price_display = commerce_currency_format($price['amount'], $price['currency_code'], $product);
    $form['submit']['#value'] = 'Buy these products just for ' . $price_display;
  }

}

```

# Answer
try this

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {

  //drupal_set_message($form_id);

  $form['submit']['#attributes']['value'] = t('Buy Now');

  /*
  $current_product = $form_state['default_product'];
  if ($current_product->type == 'product') {
    // Make alternations for products...
  }
  */

}

```
> 1 votes

---
Tags: 7, commerce, forms
---


# Question
Title: How to modify the commerce price formatter label to match shipping service?
Please see attachment. Using Commerce Kickstart 2.

I have a working solution, but I am hoping someone can tell me how to improve it, as it 'feels' poor.

The footer for the default shopping cart view is a footer called commerce\_order\_total which shows a subtotal for each line item type... typically labeled 'Subtotal' for products and then a generic 'Shipping' label for shipping line items.

That generic 'Shipping' label is hated by our customers. They expect to see the actual shipping service (UPS, Fedex, etc.) So I created a work-around, which I show below, but I fear it is not an efficient solution... basically I just made a tweaked copy of the default commerce code for the price formatter.

What I hope to improve...

1. Surely there must be a more robust way for the footer to be 'aware' of whether the page being viewed is a cart or an order from history without having to look at the URI, right?
2. And is there a faster/cheaper way to retrieve the shipping service without loading the entire order -and- all line items?
3. I was thinking there must be a more granular way to override the description of 'Shipping' in that footer without having to re-invent the entire wheel. I just gave up and did the old cut/paste.

TIA,

---JC

```
function MYTHEME_commerce_price_formatted_components($variables) {
  global $user;
  $line_item_title = '';
  $order_number = '';
  $path_parts = explode('/', request_path() );
  if( sizeof($path_parts) == 4 && $path_parts[0] == 'user' && $path_parts[2] == 'orders') {
    $order = commerce_order_load($path_parts[3]);
    // dpm($order);
  }
  if( isset($order) && !$order )
    $order = commerce_cart_order_load($user->uid);
  if( isset($order) && $order) {
    foreach ($order->commerce_line_items['und'] as $line) {
      $line_item = commerce_line_item_load($line['line_item_id']);
      $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
      // line item TYPE display title
      $line_item_type_title = commerce_line_item_type_get_name($line_item_wrapper->type->value());
        // for shipping line items
      if ($line_item_wrapper->type->value() == "shipping") {
          // shipping data
        $shipping_data = $line_item_wrapper->value()->data;
          // shipping method display title
        $line_item_title = $shipping_data['shipping_service']['title'];
      }
    }
  }
  // Add the CSS styling to the table.
  drupal_add_css(drupal_get_path('module', 'commerce_price') . '/theme/commerce_price.theme.css');
  // Build table rows out of the components.
  $rows = array();
//  dpm($variables['components']);
  foreach ($variables['components'] as $name => $component) {
//    dpm($component);
    if($component)
    $rows[] = array(
      'data' => array(
        array(
          'data' => ($component['title'] == 'Shipping' && $line_item_title ) ? $line_item_title :  $component['title'],
          'class' => array('component-title'),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total'),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }
  return theme('table', array('rows' => $rows, 'attributes' => array('class' => array('commerce-price-formatted-components'))));
}

```

# Answer
> 0 votes
I think this is equivalent - not sure there's a better way than loading all the line items.

```
function HOOK_commerce_price_formatted_components_alter(&$components, $item, $entity) {
  foreach ($entity->commerce_line_items['und'] as $line) {
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line['line_item_id']);

    if ($line_item_wrapper->type->value() == "shipping") {
      $shipping_data = $line_item_wrapper->value()->data;
      $service_title = $shipping_data['shipping_service']['title'];
      break;
    }
  }

  if (isset($service_title)) {
    $components['shipping']['title'] = $service_title;
  }
}

```

(The title is coming from the price component type - *maybe* one could use `hook_commerce_shipping_service_info_alter()` to change the `price_component` to something per shipping service, and set the title in `hook_commerce_price_component_type_info()`, but that probably isn't any neater.)

---
Tags: theming, commerce
---


# Question
Title: How to disable links in taxonomy term node fields
I have a list of rendered taxonomy terms in a node sidebar, rendered as h2 tags, linked to the taxonomy page for that tid. I don't want that term to link anywhere, so I want to remove the link and just leave a plain rendered h2 tag.

Where is the best place to do this? It feels like a presentation change, so should I do it in a preprocess function? It also feels like a functional thing, so should I remove the link within a hook somewhere?

How is the best Drupal-appropriate way to do this?

# Answer
> 0 votes
I did this in the taxonomy-term.tpl.php file. The URL was wrapped in h2 and a tags, so I just removed the print statement in the a tag. That was the easiest.

# Answer
> 2 votes
If I understand your question correctly you can change it on the 'Manage Display' tab of your content type, make sure to select 'Teaser' at the top right

If you're using the build in article type it is at admin/structure/types/manage/article/display/teaser

# Answer
> 1 votes
In Drupal 7, go to Manage Display of that field and change format to "Plain Text"

---
Tags: 7, entities, taxonomy-terms, hooks, theming
---


# Question
Title: Copy contents from an field entity reference
I have 2 content type
1-**Parent Product**
Title
Fabric Type
Product Type
Product Description
2-**Child Product**
ParentProduct (Node Reference to Parent Product Content Type)
Title
Fabric Type
Product Type
Product Description
Product Code
Product Size
Product Color
**Here is the use case**.
1-I Create all my Parent Product
2-I Create a child
The first field I need to filled is ParentProduct (Node Reference)
By choosing the ParentProduct, I would like this parent act as the default value for Title, Fabric Type, Product Type and Product description of this child.
Is there any module that could help me for that?
Thanks a lot

# Answer
Using Entityreference prepopulate and Entityreference prepopulate token

Once installed, you will need to create a link for the Child on the Parent page's template that includes tokens for the fields you want prepopulated. The answer here shows how to string multiple values together.

If it needs use a Node Reference rather than an Entity Reference, then Node Reference URL Widget and Prepopluate will do approximately the same thing.
> 0 votes

---
Tags: nodes
---


# Question
Title: Can I attach a javascript function to a Drupal.behaviors javascript function?
I want to trigger another function any time Drupal.behaviors.MultiPage (found in field\_group/multipage) changes page.

It's part of this code:

```
Drupal.behaviors.MultiPage = {
  attach: function (context) {
    $('.multipage-panes', context).once('multipage', function () {

      var focusID = $(':hidden.multipage-active-control', this).val();
      var paneWithFocus;

      // Check if there are some wrappers that can be converted to multipages.
      var $panes = $('> div.field-group-multipage', this);
      var $form = $panes.parents('form');
      if ($panes.length == 0) {
        return;
      }

      // Create the next/previous controls.
      var $controls;

      // Transform each div.multipage-pane into a multipage with controls.
      $panes.each(function () {

        $controls = $('<div class="multipage-controls-list clearfix"></div>');
        $(this).append($controls);

        // Check if the submit button needs to move to the latest pane.
        if (Drupal.settings.field_group.multipage_move_submit && $('.form-actions').length) {
          $('.form-actions', $form).remove().appendTo($($controls, $panes.last()));
        }

        var multipageControl = new Drupal.multipageControl({
          title: $('> .multipage-pane-title', this).text(),
          wrapper: $(this),
          has_next: $(this).next().length,
          has_previous: $(this).prev().length
        });

        $controls.append(multipageControl.item);
        $(this)
          .addClass('multipage-pane')
          .data('multipageControl', multipageControl);

        if (this.id == focusID) {
          paneWithFocus = $(this);
        }

      });

      if (paneWithFocus === undefined) {
        // If the current URL has a fragment and one of the tabs contains an
        // element that matches the URL fragment, activate that tab.
        var hash = window.location.hash.replace(/[=%;,\/]/g, "");
        if (hash !== '#' && $(hash, this).length) {
          paneWithFocus = $(window.location.hash, this).closest('.multipage-pane');
        }
        else {
          paneWithFocus = $('multipage-open', this).length ? $('multipage-open', this) : $('> .multipage-pane:first', this);
        }
}
      if (paneWithFocus !== undefined) {
        paneWithFocus.data('multipageControl').focus();
      }
    });
  }
};

/**
 * The multipagePane object represents a single div as a page.
 *
 * @param settings
 *   An object with the following keys:
 *   - title: The name of the tab.
 *   - wrapper: The jQuery object of the <div> that is the tab pane.
 */
Drupal.multipageControl = function (settings) {
  var self = this;
  var controls = Drupal.theme('multipage', settings);
  $.extend(self, settings, controls);

  this.nextLink.click(function () {
    self.nextPage();
    return false;
  });

  this.previousLink.click(function () {
    self.previousPage();
    return false;
  });

```

What I want to do is track anytime the user clicks the "Next" or "Previous" buttons - the code that triggers this is at the bottom of the snippet.

Is there a way for me to bind an event handler to this function?

# Answer
> 1 votes
Yes you can. You can attach as many event handlers to any DOM element as you want.

So you have to write your own module that alters the output (is a form? some form\_alter function. Is a page? some ouptut alter function or theme function) adding your custom JavaScript.

In your custom JavaScript add the code using behaviors that attachs your event handlers for the click event.

The tricky part is how you locate the next and prev buttons. You can start from the code snippet you posted. It seems that prev and next buttons are located here:

```
 var multipageControl = new Drupal.multipageControl({
      title: $('> .multipage-pane-title', this).text(),
      wrapper: $(this),
      has_next: $(this).next().length,
      has_previous: $(this).prev().length
    });

```

See the *has\_next* and *has\_previous* entries.

Looking at the previous lines you can see:

```
// Transform each div.multipage-pane into a multipage with controls.

```

It seems that the `$(this)` code referes to a *div.multipage-pane*, so the buttons seem to be:

```
$prev_buttons = jQuery('div.multipage-pane').prev();
$next_buttons = jQuery('div.multipage-pane').next();

```

Disclaimer: I don't know that module so I am *shooting blindly* but I think this approach will work.

---
Tags: javascript, webforms
---


# Question
Title: redirect to another page on webform submit using [current-page:query:?] token
I am trying to configure a webform to redirect to another page after submission by including the redirect location in the url:

http://mysite/content/barb?destination=content/discus

According to webform there is a token `[current-page:query:?]` which I assume can extract the value of destination. I have including it in the webform redirect to custom URL of the form, but I cant get it to work.

I have tried:

* \[current-page:query:?\]
* \[current-page:query:?destination\]
* \[current-page:query:destination\]

But nothing seems to work. What is the correct way of using this token to get a variable from the URL?

# Answer
> 1 votes
I've found that no token is required for this...

You can select *Confirmation page* as the redirect location, then the `?destination=` parameter will just work. Not sure that this is a documented feature, though.

See also https://drupal.stackexchange.com/questions/120466/webform-redirect-to-referring-page-on-submit-not-showing-message which highlights a downside to this method.

# Answer
> 1 votes
I just tried the `[current-page:query:destination]` token in the *Custom URL* box, and that works too.

No problems with the confirmation message appearing, either!

---
Tags: webforms, tokens
---


# Question
Title: How to link to section in same static page?
How to create a menu link to the section that will display when I click on the link and hide when i again click on the link..

**link is**

```
    <a href="#contact" class="page-scroll"><span>contact me</span></a>

```

**the above link should open**

```
<section id="contact" class="cat-pages">
//some code
</section>

```

# Answer
> 0 votes
You need to use Jquery and a tiny bit of css.

**Javascript**

```
$('.page-scroll').click(function() {
    $('.cat-pages').toggle('slow');
});

```

**css**

```
.cat-pages { display: none; }

```

JS FIDDLE DEMO EXAMPLE

**edit:**

To use jquery in drupal you use

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

```

go to drupal/sites/all/themes/YourTheme/

look for your theme.info file and add this line in there

```
scripts[] = js/myscript.js

```

Then go drupal/sites/all/themes/YourTheme/js and create myscript.js file.

put this inside it

```
(function ($) {
    $('.cat-pages').hide();
    $('.page-scroll').click(function() {
        $('.cat-pages').toggle('slow');
    });
})(jQuery);

```

If the above doesn't work, try

```
(function ($) {
    $(document).ready(function () {
    $('.cat-pages').hide();
            $('.page-scroll').click(function() {
                $('.cat-pages').toggle('slow');
            });
    });
        })(jQuery);

```

**PS:**

Don't worry about `.cat-pages { display: none; }`css anymore, since I added the hide in the jquery `$('.cat-pages').hide();`

---
Tags: theming
---


title: Webform select list multiple selection

text:
# Question
Title: Webform select list multiple selection
I've added a webform component of type Select list. How do I configure the select list to let users select multiple options?

Thank for reply to let me know there is a check box call multiple, but I have no idea where is it.

# Answer
> 3 votes
On the edit screen for your select list component (`node/NODE_ID/webform/components/COMPONENT_ID`), there's a checkbox labeled "Multiple" whose description says "Check this option if the user should be allowed to choose multiple values."

With that checkbox checked, by default your component will be displayed as a set of checkboxes. To get it to display instead as a select element, look further down on the edit screen for the component, under the "Display" section. There's a checkbox labeled "Listbox" whose description says "Check this option if you want the select component to be displayed as a select list box instead of radio buttons or checkboxes."

EDIT: here's a screenshot of Webform's select component interface when used with the Bartik theme:

EDIT 2: After googling "drupal form builder select multiple", I found this issue which suggests that via form builder's UI you need to use the "checkboxes" component type in order to have a "select multiple" field. Per this question you could disable form builder's UI and then you'll get the stock webform UI where you'll find the checkbox.

# Answer
> 2 votes
You can use something like webform\_select\_options\_info, or The webform views sandbox, or you can modify the approach here in your own module Sample Request

This approach means writing a little custom module. Webform\_select\_options\_info() basically just takes an array of what ever you want them to be able to select multiple options of. the Approach in the second link uses a view for formatting, but you can spin off to your needs there.

# Answer
> 1 votes
There is a checkbox on the select list edit form that enables multiple selection.

---
Tags: webforms
---


title: Print field with an array

text:
# Question
Title: Print field with an array
I have a field name called 'field\_serial\_571' that contains an array. I've tried several ways to display it and it only display blank space. I ran a debugging script (printr) and this is what I found:

```
[field_serial_571] => Array ([und] => Array ([0] => Array ([value] => 1)))

```

Does anyone know how to display results from a field with an array?

# Answer
> 0 votes
Assuming this is an entity (it looks like it probably is), you might want to look into using entity metadata wrappers. It'll make your theming life much easier.

Otherwise, to immediately display your field, this would work (assuming a node):

echo $node-\>\[field\_serial\_571\]\[LANGUAGE\_NONE\]\[0\]\['value'\];

LANGUAGE\_NONE is a constant for an undefined language, in your example the 'und' part of the array. It's best practice to use that constant rather than using 'und'.

Read even more about entity metadata wrappers here: http://www.pixelite.co.nz/article/how-use-entity-metadata-wrappers-drupal-7/

---
Tags: entities
---


# Question
Title: Send newsletter with list of users with specific field value
Is there a module to send a newsletter with a list of users with the same interests?

# Answer
> 0 votes
There is the simplenews module which will do the newsletter sending part of your question but similar interests is up to you to define. Drupal can't predict what "similar interests" are!

If you already have a list of users with similar interests, simplenews will enable you to create individual groups/mailing lists which you could add your users to.

---
Tags: emails
---


# Question
Title: Prioritize Row within View based on Taxonomy Term
I am generating rows through a view and have specific requirement for listing on my page.

What I want is if there is one specific term value of my Filter Taxonomy, the row should show itself first.

For each result of this view, I have a term value of one taxonomy (Role).

Possible term values for this Taxonomy (Role) are:-

* Leader
* Manager
* Editor
* User

Now what I want is, that which ever row's Taxonomy value is `Leader`, the row should be shown first and then the `Manager`, then the `Editor` and at the end, of `User`.

Any help how I could achieve this in Views?

Thanks.

# Answer
On your view, for **Sort Criteria** remove whatever you're current using (post date is usually the default) and add Taxonomy term: Weight

Then go to admin/structure/taxonomy go to list terms and click on show row weight link (far right) and give them different weight numbers, or use the four arrows icon to drag them and arrearage them in the order you want them to show in.
> 0 votes

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


title: Outside Database

text:
# Question
Title: Outside Database
I have an outside database called "panels" that stores our company articles/blog posts/products etc... in it. Is there a good module to use, or I could write a custom module to hook into the outside database to display these content types? All changes would be done through our in house system, I am only looking to display them onto the drupal site we made for our store front.

# Answer
You may have some success with Migrate which will enable you to import data from an external source into a Drupal content type. You could set up a cron task to run the migration on a regular basis.
> 1 votes

# Answer
Maybe consider the Forena module? It is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports. Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

DBMSs that are supported are the Drupal DB itself (of course), but also MySQL, Oracle, MS SQL, Postgress, Sqite, anything PDO compliant.

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.
> 1 votes

---
Tags: views, database
---


title: Log in problem in maintenance mode

text:
# Question
Title: Log in problem in maintenance mode
I have a maintenance site problem. I can't go to the login page.

I tested in my localhost in maintenance and I could log in on /user.

I copied file system and database online but here I can't access the login page so I can not see the site to make changes and upload data.

This is the site: redlily.it/

I have displayed the $content variable in a div.content with display:none style. But in '?q=user' and in '/user' i have no loggin form.

Why am I not seeing the log in form under '?q=user' and '/user'?

# Answer
You can run below queries on database to get your site online:

```
UPDATE variable SET value = 's:1:"0";' WHERE name= 'site_offline';
DELETE FROM cache WHERE cid = 'variables';

```
> 1 votes

# Answer
in your DB find variable table and change site\_offline from 1 to 0
> 0 votes

# Answer
The problem was in the database setting.. wrong password -.-

Solved!!
> 0 votes

# Answer
I had a similar problem. Using Apache on Ubuntu. edited /etc/apache2/apache2.conf changing AllowOverride None to AllowOverride All for /var/www:

AllowOverride All

Drupal was installed in a sub-directory in /var/www .
> 0 votes

---
Tags: users, maintenance-mode
---


title: embedding a font in the code

text:
# Question
Title: embedding a font in the code
I know nothing but the admin functions of Drupal. The developer of my site used Roboto and other fonts when I asked for Arial. Now my website design gets completely screwed up in Chrome and Firefox browsers. The developer has since gone out of business. I was told that something could be added to the code to "embed' this roboto font so that when someone accesses my site that does not have roboto installed - which is just about everybody apparently - that roboto will automatically be installed in their computer? Someone at Go Daddy told me that the problem is that HTTPS should be inserted in the code instead of HTTP. That the developer does have the roboto code inserted but it should be HTTPS. I know I probably sound completely stupid but I cannot even find the code to even look at it or CSS style sheets. I have no idea where the code actually is for my site. If anyone can assist - I would greatly appreciate it. My site is nightvisionnv.com.

# Answer
> 3 votes
As for fixing this - see Shawn Conn's answer.

Some more background:

The "Roboto" font is *already* embedded in your site. If you look at he markup in your header, it has the following line:

```
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:700italic,400|Roboto:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

```

This should be:

```
<link href='//fonts.googleapis.com/css?family=Roboto+Condensed:700italic,400|Roboto:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

```

to make it work with both HTTP and HTTPS (as already pointed out by Shawn Conn).

Provided this is made to work, it means that if a user don't have Roboto installed, it will be downloaded from the googleapis CDN and cached upon first visit.

The line that inserts that link to the googleapis is *probably* in `html.tpl.php` in your site's theme (but I can't be sure - Drupal allows a site developer to insert such links in the header by other means).

Also, your style sheets uses the following every time a font is mentioned:

```
font-family: "Roboto",sans-serif;

```

This means: Use "Roboto" when available, otherwise fall back on the browser's default for "sans-serif". This should work OK in all browsers, including Firefox and Chrome - even if the HTTPS/HTTP mixup mentioned by Shawn Conn stops Roboto from being downloaded.

> Now my website design gets completely screwed up in Chrome and Firefox browsers.

I looked at your website in MSIE, Firefox, and Chrome. I don't see any obvious problems with it.

# Answer
> 3 votes
Google Web Fonts will have trouble loading over mixed protocols. Your site forces HTTPS but the URL is set to HTTP. It needs to set to a protocol agnostic URL:

```
<link href='//fonts.googleapis.com/css?family=Roboto+Condensed:700italic,400|Roboto:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

```

In order to find where the problem is trying doing a text search over your code base for "fonts.googleapis.com". It could be inside **html.tpl.php**, **template.php**, or some other location depending on how the dev built the theme.

---
Tags: theming
---


# Question
Title: Where to place JS code to be used by Admin?
I have a simple requirement that I want to implement JS on couple of fields. Through JS, I want to hide few fields by default and show them when a checkbox is clicked.

The problem is where to keep this JS for admin. Below is the JS which is working. Weirdly, when I paste in the console of Chrome, the JS then works.

## JS

```
jQuery('input#edit-field-mine-und').change(function() {
        if(jQuery(this).is(":checked")) {
            alert("Checked");
        }
        else {
            alert ("Not Checked");
        }
        //$('#textbox1').val($(this).is(':checked'));
});

```

Any help where I can place this JS so that it can be used in admin drupal pages?

# Answer
You have to put that either in an administrative theme or in a custom module.

It's a good idea generally to have a child theme based on the administrative theme you are already using.
This means that you can override most of the things (e.g. styles, labels, etc.) in the admin while still being able to update the parent theme.

Here's how you would do it if you are using Seven for example:

1. Create a new folder named `seven_custom`
2. Inside create a new file named `seven_custom.info` and copy all the regions from `seven.info` file
3. Copy the `screenshot.png` and `logo.png` from Seven
4. Create a new file named `custom.js` for example
5. Add that file under `scripts[]` in `seven_custom.info`, like so:

```
scripts[] = custom.js

```
6. Edit your JS file to extend Drupal behaviors and use `Drupal.t()` for making strings translatable:

```
(function ($) {
  Drupal.behaviors.UltimaTheme = {
    attach: function (context, settings) {
      $('input#edit-field-mine-und').change(function() {
        if($(this).is(':checked')) {
          alert(Drupal.t('Checked'));
        }
        else {
          alert(Drupal.t('Not Checked'));
        }
      });
    };
  };
})(jQuery);

```

I wrote this without testing, but should work fine. Let me know if it doesn't.
> 1 votes

---
Tags: javascript
---


# Question
Title: Are there Drupal modules that help process e-mails dynamically
I had the idea of implementing a workflow module for e-mail communications, something like this:

User role 1 can write e-mails (as nodes or custom entities) User role 2 can review and approve e-mails User role 3 can press send

I would then like the website to catch replies and enter them into the database with reference to the user entities that touched the e-mail entity, so that the workflow can also be applied to replies. The part that I'm not sure I can do here, is doing advanced e-mail processing based on which users touched the e-mail.

Are there any modules that can handle encoding these entity references into the reply-to or message of the e-mail so that the Drupal site can process the replies dynamically?

# Answer
Inmail is designed to be the low level framework to receive mails within Drupal. We proposed in D8 to also implement Mailhandler on top of Inmail and there's good chance this will happen to reduce complexity.

Inmail "works" and you can write plugins to handle the mails.

What you need is a system that supports dynamic mail addresses (through e.g. address expansion). They then need to be redirected / forwarded to the site. This is more a mail server (MTA) configuration than inmail on its own. Through this, every reply is sent to a unique mail address (defined when sending). You can then while handling the mail easily lookup the reference / know the origin.

We plan to add more support for common mail configuration to consider these dynamic situations through configuration only at some point.

Check the issue queue, open feature requests if you can't find a proper issue and start contributing to it! ;-)
> 3 votes

# Answer
For drupal 8 there is the module Inmail that sound promising:

> The purpose of Inmail is to process process incoming email and execute certain actions depending on the content of each message (…)

For drupal 7 there is a.f.a.i.k currently only Mailhandler that would offer functionalities which would allow similar workflows:

> Mailhandler uses Feeds to let you post nodes by email. It takes mail (usually from an IMAP mailbox) and imports it as whatever type of content you choose#

I must admit doubt that either of them is capable of what you call *'advanced e-mail processing'*. However – maybe something similar can be achieved when combining either of the above modules with Rules.
> 1 votes

---
Tags: emails
---


title: Amazon S3 for Stage / Production only?

text:
# Question
Title: Amazon S3 for Stage / Production only?
Is it possible to use the Amazon S3 module for stage / production only? The site I'm building, is using features. So when I export my fields for the content types, I either have the option to select Local File Storage, or the S3 File System.

I thought I had a solution, where on stage / prod, I would hide the local file system wrapper, but the issue turns out, that unless I select the S3 checkbox when editing a field in the content type, it doesn't default to S3.

I could go thru and select this option for all file fields, but then on the downside, dev will be broken.

My only other option, which I haven't tried, is setting a global variable via settings, and then using a if/else logic in the features for each file field, to pre-set the upload location for that field.

Ahhh, so messy.

Anyone come up with a clever solution in the pasts? That allows me to force files to be uploaded to S3 for stage/prod and local file system when running via local or dev?

Update:

Okay, so I noticed that features has the following hook:

hook\_field\_default\_field\_bases\_alter()

So, in my module, I'm using that hook, determining if the env should be serving the files via local storage, or s3. If it's s3, I then alter it from 'public' to 's3'

I went and just to be safe, re-exported all my features, and made sure that by default, it was set to public, an not s3. Now, all my env's are using the correct storage location. I'm still not sold that what I'm doing is the best solution, but it is working. Any thoughts?

```
$use_s3f3 = variable_get('image_save_s3f3', FALSE);

// Only on stage/uat/prod, do we want to use s3 as the file storage engine.
if ($use_s3f3 === TRUE) {
 foreach($fields as $key => $item) {
   if (isset($item['settings']['uri_scheme']) && $item['settings']['uri_scheme'] === 'public') {
     $fields[$key]['settings']['uri_scheme'] = 's3';
   }
 }
}

```

# Answer
I made a similar patch to the Amazon S3 module: "New variable to override file field URI scheme per environment" https://www.drupal.org/node/2422977#comment-9602981

This patch was adopted by the module, and is now the approved way of solving the OP's problem using the Drupal 7 Amazon S3 module. This is the issue I wrote on Drupal.org.

> ### Problem/Motivation
>
> When using Features (or `hook_field_default_field_bases()` directly) to export file field definitions, the Upload destination is included. This can already be handled in a custom module by implementing `hook_field_default_field_bases_alter()`, and checking `$conf` (set in env-specific settings files, etc). But it would be nice to include support directly in amazons3.module.
>
> ### Proposed resolution
>
> Implement `hook_field_default_field_bases_alter()`, and check for a namespaced variable `amazons3_file_uri_scheme_override`. This variable can be added to environment-specific `sites/*/settings*.php` files to allow certain environments to upload to S3 while other environments upload to whatever the defined/exported (public or private) URI scheme is.
>
> ### User interface changes
>
> The only change in the UI would be that the field settings reflect the URI scheme defined either by the exported field bases or the variable (on environments where that's present).
>
> ### API changes
>
> No API changes, but the patch documents usage of the variable.

Note the module's `README.md` also now contains this additional line:

> When using Features to export field definitions, the Upload destination is included. If you want to override this (for example, in a multi-environment workflow), use the 'amazons3\_file\_uri\_scheme\_override' variable. See amazons3\_field\_default\_field\_bases\_alter() for documentation.

Here is the relevant documentation of `amazons3_field_default_field_bases_alter` that README note is referring to:

```
* Allows a variable to override all exported field bases to use 'Amazon S3' as
* the Upload destination. For example this can be added to environment-specific
* Drupal settings files, to allow certain environments to upload to S3 while
* other environments upload to the exported (public or private) URI scheme:
* @code
* $conf['amazons3_file_uri_scheme_override'] = 's3';
* @endcode

```

Also note the variable is not deleted by `amazons3_uninstall()` because it's only valid use case is being defined in `$conf` (otherwise just change the field setting).
> 2 votes

# Answer
You could create a local config for s3 in your local settings.php ?

Instead of trying to change storage types for local dev, you could use s3 locally but on a temporary bucket.

We use a separate bucket for local development that we can trash or whatever, we override all the settings in the conf array;

```
$conf['s3fs_bucket'] = 'our-dev-bucket';
$conf['s3fs_region'] = 'ap-southeast-2';
$conf['s3fs_awssdk2_access_key'] = 'Access';
$conf['s3fs_awssdk2_secret_key'] = 'Secret';
$conf['s3fs_use_instance_profile'] = FALSE;

```

Will this work for you? It works in my small team (5 of us.)
> 1 votes

---
Tags: files, cdn
---


title: How can I delete my own node comments?

text:
# Question
Title: How can I delete my own node comments?
How can I delete my own node comments without installing modules?

Googling, I found the Comment Access module. I don't want to install it.

# Answer
> 1 votes
There is no permission in a default D7 configuration to only delete one's *own* comment. To get this you must install Comment Access (or another contributed module with a similar function).

If you add the permission "Administer comments and comment settings" (navigate to *Administration » People » Permissions*), to a role, that role get access to a "Delete" tab for comments, but that lets the user holding this permission delete *everbody's* comments - not only his/her own.

Installing a module is no big deal in Drupal. If you want this, I am afraid you need to install a module.

---
Tags: 7, comments
---


title: Hook_cron in drupal

text:
# Question
Title: Hook_cron in drupal
In my custom form module submit handler, I have written the following code:

```
function mymodule_form_submit($form, $form_state) {
db_insert('bds_user_expiry')->fields(array(
'uid' =>$user_id,
'active_user'=>strtotime("now"),
))->execute();
drupal_set_message(t('You have successfully set the expiry date'));
}
}

```

Here `bds_user_expiry` is my custom table name. When I click on submit button $user\_id and the current time will be stored in my table.Now I want to define this scenario in `hook_cron_queue_info()` so that whenever cron runs this snippet will also run. For this first I have to define `hook_cron()`, issue is how can I define the above function in `hook_cron`,

```
function mymodule_form_submit($form, $form_state) {
function my_module_cron(){
$result=db_insert('bds_user_expiry')->fields(array(
'uid' =>$user_id,
'active_user'=>strtotime("now"),
))->execute();
$result=db_query($query);
$queue=DrupalQueue::get("item");
foreach($result as $data){
$queue->createItem($data);
}
}
}

```

Is this right? Can I define hook\_cron in submit handler?

**UPDATED(To check if my snippet runs with cron or not)** Following code is written in my custom module file. when cron runs value of uid from `bds_user_expiry` will be inserted in `my_cron_table` just to check if my code is working with cron or not, but neither it gives me any error nor successful result.

```
function user_form_expiry_form_cron(){
$new=db_select('bds_user_expiry', 'b')
->fields('b',array('uid'))
->execute()->fetchassoc();
//print_r($new);
$result=db_query($new);
$queue=DrupalQueue::get("item");
foreach($result as $data){
$queue->createItem($data);
}
}
function user_form_expiry_cron_form_queue_info(){
$queues=array();
$queues['item']=array(
"worker callback"=>"myfunc",
);
return $queues;
}
function myfunc($data){
db_insert('my_cron_table')->fields(array(
'uid' =>$data,
))->execute();
}

```

# Answer
> 0 votes
If you want to execute the same snippet of code, you might refactor it into a separate function, and call it from both `mymodule_form_submit` and `mymodule_cron`. Something like the following:

```
function _mymodule_set_expiry_date() {
  db_insert('bds_user_expiry')->fields(array(
    'uid' =>$user_id,
    'active_user'=>strtotime("now"),
  ))->execute();
  drupal_set_message(t('You have successfully set the expiry date'));
}

```

And then, on your hooks:

```
function mymodule_form_submit($form, $form_state) {
  _mymodule_set_expiry_date();
  // ... rest of your code
}

function mymodule_cron() {
  _mymodule_set_expiry_date();
  // ... rest of your code
}

```

You can see the following question on Drupal Answers for a more detailed explanation about `hook_cron` and `hook_cron_queue_info`: how to use hook\_cron\_queue\_info in a custom module?

Hope that helps,

---
Tags: 7, cron
---


title: Drupal Sending tons of Spam email

text:
# Question
Title: Drupal Sending tons of Spam email
Apparently one of the modules installed on my drupal site has been sending SPAM emails from my server as in (name)\_(lastname)@(myservername).com , it managed to send 1000 email and queue 97,000 emails only in the first day..

At first, based on the email details, I figured it was being sent from a PHP page called diff.php under `/sites/all/modules/contrib/libraries/tests/libraries/diff.php`, so I deleted the whole tests folder, but now the emails are heading directly from my root site.. I have installed Hacked! to a development copy, and here's a copy of the results:

Does it seem like a module issue? should I re-install the changed modules?

# Answer
The version of core you're running - 7.30 - is *extremely* vulnerable. As long as you're running any version of core prior to 7.32, your site will *remain* vulnerable. The vulnerability will allow changing modules (which *can* be discovered with the **Hacked!** module), putting executable PHP in the database (which *can not* be discovered with **Hacked!**), and injecting malicious shell scripts (which *can not* be discovered with **Hacked!**).

**Simply replacing Drupal core and modules with non-hacked versions will not remove backdoors.**

Just going through the changed modules and reinstalling them will *not* do. At this point, even if you replace everything, the intruder have probably infected your database with exploits, as well as having installed several well-hidden backdoors to your site at shell level.

The best recourse is to delete your entire site an rebuild it from scratch on a clean vhost, then restore its contents from a backup made prior to Oct. 15, 2014.

Read this SA to understand the severity of this vulnerability: https://www.drupal.org/SA-CORE-2014-005. Also read:

If you're unable to delete the site and restore from backup, read this about recovering: Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?.

*After* you have cleaned up your site, to be alerted if this happens again, consider installing **File integrity check**. This module will monitor the integrity of almost all files on your site and send you an email if it detects that file integrity is breached.
> 7 votes

# Answer
yes - start in a new folder and install everything new. (you can try to copy the unchanged modules from your old installation - but i wouldn't suggest that)

take care of any customizations made to core or contributed modules (actually, this is bad practice ..) - so , first keep your code and check back there if something does not work.
> 0 votes

---
Tags: 7, advertising
---


title: Node delete performance issue

text:
# Question
Title: Node delete performance issue
I am using below code to delete all unregistered users node. But it takes very long time to execute node\_delete function.I have around 5000 records of users in node table. How can I improve the performance of node\_delete() function?

```
$query_node = db_query("SELECT n.nid FROM node n,status s WHERE s.entity_id = n.nid  AND type = 'employees' AND s.field_employee_status_value = '2' AND n.status = '1'");
$result_node = $query_node->fetchAll();

foreach($result_node as $node)
{
    $nid = $node->nid;
    // $node id , which you want to delete;
    node_delete($nid);
}

```

# Answer
Two appropriate options:

1. Use `node_delete_multiple` function instead of the `node_delete()`. I guess you need to do this only once, so this might be a faster solution if your server can execute the whole process at once (ie enough memory, not too many fields/modules, etc.).

```
$query_node = db_query("SELECT n.nid FROM node n,status s WHERE s.entity_id = n.nid  AND type = 'employees' AND s.field_employee_status_value = '2' AND n.status = '1'");
$result_node = $query_node->fetchAll();

$nids = array();
foreach($result_node as $node) {
  $nids[] = $node->nid;
}
// Delete everything at once.
node_delete_multiple($nids);

```
2. You can also use Administration Views with Views Bulk Operations. You can filter the nodes based on what you need and then perform operations on all rows. This will process the deletion as a batch process. Downside is that you might need to install 2 additional modules if you don't have them already.
> 3 votes

---
Tags: nodes
---


# Question
Title: Add to cart form AJAX not working when loading a product display via AJAX
I am trying to create "quick buy" functionality. I have a product listing and a customer is able to click on "quick buy" for that product and then I want to be able to load up a view mode for that product display in an overlay which has a few product display fields including the add to cart field.

I can get the loading of the product display via jQuery load (or ajax) no problem, the issue is that the add to cart button is not working via ajax and the customer is instead redirected to the callback (which is now the action in the add to cart form).

Javascript code to load product display node:

```
$('.quick-buy:not(.ajax-processed)').addClass('ajax-processed').click(function(e) {
  e.preventDefault();
  $.ajax({
    url: '/product/get/ajax/'+$(this).attr('rel')
  }).done(function(result){
    $('#quick-buy').html(result);
    Drupal.attachBehaviors();
  });
});

```

Module code:

```
function tweaks_menu() {
  $item['product/get/ajax/%'] = array(
    'page callback' => 'tweaks_get_product_ajax',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
  );
  return $items;
}

function tweaks_get_product_ajax($nid) {
  $node = node_load($nid, NULL, false);
  $node_view = node_view($node, 'product_quick_buy');
  $html = drupal_render($node_view);
  print $html;
}

```

I have also tried:

```
function tweaks_get_product_ajax($nid) {
  $node = node_load($nid, NULL, false);
  $node_view = node_view($node, 'product_quick_buy');
  $html = drupal_render($node_view);

  $settings = FALSE;
  $javascript = drupal_add_js(NULL, NULL);

  if (isset($javascript['settings'])) {
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data']));
    $settings .= ');
  }

  print $html . $settings;
}

```

...to no avail.

# Answer
The reason why it redirects after adding to cart is because the add to cart form doesn't use ajax by default. Wich causes it to redirect the user when submitted. If you want it to use ajax you'll have to alter the submit button via a HOOK\_form\_FORM\_ID\_alter.

For more info on the form ajax functionality
FAPI ajax

However by doing so you'll alter all the add to cart button forms on your entire website to use ajax.

So a better solution might be to create a custom add to cart form just for the `product_quick_buy` view-mode and display that instead of the standard form. This form can then use ajax to call it's submit handler.

Also I think your ajax link implementation for the hook\_menu doesn't follow the coding standards.

```
function tweaks_menu() {
  $item['product/get/ajax/%'] = array(
    // -- your code --
    'delivery callback' => 'ajax_deliver', // Tells drupal we'll be returning an ajax renderable array
  );
  return $items;
}

function tweaks_get_product_ajax($nid) {
  $node = node_load($nid, NULL, false);
  $node_view = node_view($node, 'product_quick_buy');
  $html = drupal_render($node_view);
  // Instead of printing we're generating an ajax renderable array and return that
  $commands[] = ajax_command_html('YOUR_JQUERY_SELECTOR_HERE', $html);
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

More info about ajax links Tutorial on ajax links
> 0 votes

# Answer
Ok, so there were a number of things I did to get it working, mainly with hints from:

load Ajax form in another page

Firstly, I forgot to mention that I have commerce\_ajax\_cart module installed which makes the add to cart buttons work with ajax.

Next, my ajax callback looks like this (super basic):

```
function tweaks_get_product_ajax($nid) {
    $node = node_load($nid, NULL, false);
    $nv = node_view($node), 'product_quick_buy');
    $html = drupal_render($nv);
    print $html;

}

```

Now I found that since there are other forms on the page I had to make sure the form didn't clash with any others so I have the following hook function:

```
function tweaks_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
    if (stristr($form['#action'], '/product/get/ajax') !== FALSE) {
        $form['#attributes']['id'] = 'quick-buy-form';
        $form['submit']['#attributes']['id'] = 'quick-buy-submit';
        $form['submit']['#ajax']['callback'] = 'tweaks_quick_buy_callback';

    }

}

```

Then I copied the the commerce\_ajax\_cart\_callback function and added in a call to my own javascript function:

```
function commerce_ajax_cart_callback($form, &$form_state){
    global $user;

    $form = drupal_rebuild_form($form['#form_id'], $form_state, $form);

    $commands = array();
    $commands[] = array('command' => 'commerce_ajax_cart_update') ;
    $commands[] = ajax_command_prepend('#block-system-main', theme('status_messages'));
    $commands[] = ajax_command_replace('.' . drupal_html_class($form['#form_id']), drupal_render($form));
    $commands[] = array(
            'command' => 'commerceAjaxCartFireTrigger',
            'data'    => $form['#form_id']

            );
    $commands[] = array(
            'command' => 'plQuickBuy',

            );

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

}

```

I also had to add in the following to my template.php to get the drupal ajax form libraries into the page:

```
function main_preprocess_html(&$variables) {
    drupal_add_library('system', 'drupal.ajax');
    drupal_add_library('system', 'drupal.form');
    drupal_add_library('system', 'jquery.form');
    drupal_add_library('system', 'druapl.progress');

}

```

Lastly here is my updated js code:

```
    $('.quick-buy:not(.ajax-processed)').addClass('ajax-processed').click(function(e)      {
      e.preventDefault();
      $.ajax({
        url: '/product/get/ajax/'+$(this).attr('rel')
      }).done(function(result){
        $('#quick-buy').html(result);
        Drupal.settings.ajax = {
          'quick-buy-submit': {
            callback: 'tweaks_quick_buy_callback',
            event: 'mousedown',
            keypress: true,
            prevent: 'key',
            submit: {
              _triggering_element_name: 'op',
              _triggering_element_value: 'Add to cart'

            },
            url: '/system/ajax'
          }
        };
        Drupal.attachBehaviors();
  });
});

Drupal.ajax.prototype.commands.plQuickBuy = function(ajax, response, status) {
    //do what you need to do to destroy overlay etc. here
}

```
> 0 votes

---
Tags: commerce, ajax
---


# Question
Title: In my checkboxes if i have a 0 value it select this checkbox
I have in my form a type 'checkboxes' form.

```
    // Form for the severity checkboxes.
    $kkkk_severity_levels = variable_get('kkkk_severity_levels', array());

    // Declare empty options array.
    $kkkk_severity_options = array();

    // Loop through each severity level and push to options array for form.
    foreach (watchdog_severity_levels() as $number_select => $severity) {
      $kkkk_severity_options[$number_select] = drupal_ucfirst(
        $severity);
    }

    // Checkboxes form.
    $form['kkkk_severity_levels'] = array(
      '#type'          => 'checkboxes',
      '#title'         => t('Type of log messages'),
      '#options'       => $kkkk_severity_options,
      '#default_value' => array_values($kkkk_severity_levels),
      '#required'      => TRUE,
    );

```

In these lines of code the watchdog\_emergency has a key 0 so when i select something from checkboxes i take selected also emergency always as it gets me out : e.g if i select 'info' with key 6 it gets me out:

```
6 (String, 1 characters ) 6
0 (Integer) 0
1 (Integer) 0
2 (Integer) 0
3 (Integer) 0
4 (Integer) 0
5 (Integer) 0

```

7 (Integer) 0 and so it selects also the 'emergency' with key as 0... How I can solve this problem?

# Answer
That's how the form API handles multiple selections for form elements.

You can easily solve it with standard language features:

```
$selected = array_filter($form_state['values']['kkkk_security_levels']);

```
> 3 votes

---
Tags: forms
---


title: Custom Markup to item in views

text:
# Question
Title: Custom Markup to item in views
I created a view that displays my user profile picture. I created a template for this view using *'views-view-fields--name.tpl.php.* This is the output I get.

```
<div class="view-content">
  <div class="views-row views-row-1 views-row-odd views-row-first views-row-last">
      <div class="field-content profile">
        <div class="user-picture">
          <img typeof="foaf:Image" src="/default_profile_picture.jpg" />
        </div>
      </div>
  </div>
</div>

```

What I want to do is add a link to my image, like so:

```
 ...<a href="#"><img></img></a>...

```

But it keeps adding that line to just before the **"user-picture"** div, and I want it after it. Is there any way to achieve this? Custom templates seems to not do the trick.

# Answer
You can do this in the views ui.

* Create a custom field
* Hide the display of the image field
* Use tokens provided to add image field output to your custom field

**Example:**

```
<a href="#">[image_field]</a>

```

**UPDATE**

Also ensure the style options are set to none on the image field so you don't get any div wrappers.
> 1 votes

---
Tags: views, theming
---


# Question
Title: EntityFieldQuery with pager and db_or using addTag
I'm having an issue that I hope some of you can help me with.

Drupal version: 7.36

I've created a list of all nodes of a certain content type using EntityFieldQuery. Since there are a lot of nodes with this content there's also pagination with 6 nodes pr page (not that it matters). Right above my list I have a little search field, where the user can search within this list of nodes with the specified content type. With this I'm using the addTag and db\_or method described here: Using hook\_query\_TAG\_alter to add 'OR' queries to EntityFieldQuery. With this the user searches both in the title and the content.

However. For some reason it doens't quite work while having `$query->pager()` or `$query->range()` and using the `$query->leftJoin()` function at the same time. If I outcomment the `$query->leftJoin()` and the connected `db_or->condition()` everything works fine. Or if I outcomment the `$query->pager(6)` everything works fine as well.

Here is all my code for getting the list of content types:

```
function node_load_by_type($type, $options = array()) {
    $settings = array(
        'limit' => array_key_exists('limit', $options) ? $options['limit'] : -1,
        'pager' => array_key_exists('pager', $options) ? true : false,
        'offset' => array_key_exists('offset', $options) ? $options['offset'] : 0,
        'orderDirection' => array_key_exists('orderDirection', $options) ? $options['orderDirection'] : 'DESC',
        'keywords' => array_key_exists('keywords', $options) ? $options['keywords'] : false,
    );

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', $type)
        ->propertyCondition('status' , 1)
        ->propertyCondition('nid', arg(1), '!=')
        ->propertyOrderBy('created', $settings['orderDirection']);

    if ($settings['limit'] !== -1 && $settings['pager']) {
        $query->pager($settings['limit']);
    } else if ($settings['limit'] !== -1) {
        $query->range($settings['offset'], $settings['limit']);
    }

    if ($settings['keywords']) {
        $query->addTag('search');
        $query->addMetaData('keywords', $settings['keywords']);
    }

    $results = $query->execute();

    if (is_array($results) && array_key_exists('node', $results)) {
        $results = node_load_multiple(array_keys($results['node']));

        if ($settings['limit'] !== -1 && $settings['pager']) {
            $results = theme('article_list', array('nodes' => $results, 'pager' => theme('pager', $query->pager)));
        }
    }

    return $results;
}

function THEME_query_search_alter(QueryAlterableInterface $query) {
    $keywords = $query->getMetaData('keywords');
    $words = "%" . $keywords . "%";

    $or = db_or()->condition('title', $words, 'LIKE');
    $query->leftJoin('field_data_body', 'n', 'node.nid = n.entity_id');
    $or->condition('n.body_value', $words, 'LIKE');
    $query->condition($or);
}

```

Has anyone experienced this before and found the solution? Or can simply see in my code somewhere that there's an error which is causing my problem. Ideas for doing it differently is also welcome.

Thanks in advance. :)

---

**UPDATE:**

More testing tells me that what triggers this is actually joining another database table into the `$query`. If I don't use pagination but still the `$query->leftJoin()`, `$query->join()` or any similar functions the search actually returns a *count* of a lot of results even though there might only be 1 result.

Using the global variable `$pager_total_items` I can see that when there's actually only 1 result, it tells me that there are 1917 results. Then the pagination goes mental and doesn't know what to do, so it creates a lot of pages with the 1 result on each page.

# Answer
> 1 votes
I found the answer to this issue.

Apparently the `THEME_query_search_alter` hook was triggered twice (also saw this happen when altering the standard Drupal user search query) and the new table was therefore joined into the final database query twice.

So when it tried to find results in the same table two times it kinda broke the search results, and returned these many many results instead of just a few.

The fix was then to check if the new table was already joined into the query, and this is how I did it (only changed the `THEME_query_search_alter` hook):

```
function hedeselskabet_query_search_alter(QueryAlterableInterface $query) {
    $keywords = $query->getMetaData('keywords');
    $words = "%" . $keywords . "%";

    if (!array_key_exists('n', $query->getTables())) {
        $or = db_or()->condition('title', $words, 'LIKE');
        $query->leftJoin('field_data_body', 'n', 'node.nid = n.entity_id');
        $or->condition('n.body_value', $words, 'LIKE');
        $query->condition($or);
    }
}

```

And now everything works. :)

---
Tags: paging, database
---


# Question
Title: Drupal put more values in #markup $form type
Is it possible to add more values into the #markup of a drupal form?

At the moment it is a link but I also want to add an image. When I add another #markup it only takes the last one, and when I add $image to the other #markup it doesn't work.

My code:

```
$image_options = array(
    'path' => 'img_url',
    'alt' => 'App logo',
    'title' => 'App logo',
    'width' => '56px',
    'height' => '56px',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
);

$image = theme('image', $image_options);

$form["link$key"] = array(
  '#type' => 'item',
  '#description' => t('Registered token(s): @total_tokens <br> Total sent push notifications: @push_notifications', array('@appname' => $record->app_name, '@total_tokens' => $total_tokens, '@push_notifications' => $sentMessages)),
  // '#href' => "admin/config/services/push_notifications/stats/". $record->app_id,
  '#markup' => l($record->app_name, 'admin/config/services/push_notifications/stats/' . $record->app_id),
);

```

So I want to be able to add $image to the current #markup..

# Answer
> 4 votes
The #markup property simply provides a string output.

Why dont you just concatenate your output into a variable.

```
$output = $image;
$output .= $link;

```

Then...

```
'#markup' => $output

```

Checkout the coding standards for Drupal around concatenation. https://www.drupal.org/coding-standards#concat

---
Tags: media, theming
---


# Question
Title: How to make the Views Slideshow controls actually work?
I installed the module Views Slideshow 7.x 3.1, including the dependent modules as well as the jquery.cycle.all.js (version 3.03) in sites/all/libraries/jquery.cycle.

I am able to create a slideshow with a numeric pager showing 1 2 3 for the 3 slides I have added.

However, the pager numbers aren't linked and the previous and next buttons look like links but nothing happens when I click them.

Have searched for a solution but found nothing.

Also, the slideshow doesn't cycle, just stays on the 1st slide.

# Answer
> 1 votes
Would it be possible to share the link?

It is also possible that there is a jquery conflict (ran into this issue a while ago). In my case it was superfish + flexslider, both with their own jquery source that were not interchangeable. This lead either the slider not working, or the menu not working.

I solved it by using jQuery.noConflict(); https://api.jquery.com/jQuery.noConflict/

# Answer
> 0 votes
Views Slideshow ver. 7.x-3.1 works as advertised.

However, to get any action, you need to enable not only **Views Slideshow**, but also something to cycle the slides (e.g. the **Views Slideshow: Cycle** sub-module). From your description of the symptoms, it sounds as if you've left the last step out.

Here is a link to a quite detailed tutorial about how to set the whole thing up.

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


# Question
Title: How to add the placeholder in view exposed filter
I am just created a block-view with exposed filter in view,, now i want to give the placeholder to auto-complete widget type same as label name , how can i do this ?

# Answer
You can simply add below code to form alter hook

```
$form['title']['#attributes']['placeholder'] = t('Keyword search');

```
> 3 votes

---
Tags: views
---


title: comment_admin_overview is missing

text:
# Question
Title: comment_admin_overview is missing
I am working on hook\_theme\_registry\_alter. I have tried to dpm($theme\_registry). But comment\_admin\_overview is missing, The version of drupal is 7. Any ideas??.

```
function hook_theme_registry_alter(&$theme_registry) {
  dpm($theme_registry);
  $theme_registry['comment_admin_overview']['function'] = 'theme_hook_comment_admin_overview';
}

```

# Answer
`comment_admin_overview()` is a form function in Drupal 7 (it was a theme function in 4, 5 & 6).

You can use `hook_form_alter()` to make your changes instead.
> 1 votes

---
Tags: theming
---


# Question
Title: Install a distro from an online repository core make file
I would like to use the hosting tool Aegir to install this distribution from a make file directly:

http://cgit.drupalcode.org/elmsmedia/plain/drupal-org.make

what is the "workaround" to be able to insert the above URL as a string in Aegir platform make file field here:

I have tried a lot of distributions but all failed.

thanks

# Answer
Unfortunately the Drush Make infra does not support this use-case well.

The quickest wordaround is to clone the project Git repository and provide a local path to the makefile in the Aegir UI.

For elmsmedia I guess the best makefile would be http://cgit.drupalcode.org/elmsmedia/tree/local.make.example

OpanAtrium has http://cgit.drupalcode.org/openatrium/tree/build-openatrium.make for this same purpose.
> 1 votes

---
Tags: distributions, version-control, drush, aegir
---


# Question
Title: Why does my site whitescreen with content?
I am creating a drupal 8 site. I have only installed two modules so far, Devel and Varnish.

However anytime I try to create an article and save it any page on the site that isn't an admin page is just White screen of Death.

I have no idea what could be causing this problem. Why would it cause the white screen?

# Answer
> 2 votes
Drupal 8 is still in beta so things are still going to be rough there.

WSOD's are usually a symptom of some PHP error being hidden by the web server (many default PHP setups don't advertise errors). The d.o. page on WSODs gives good advice on how revealing these errors and diagnosing the problem.

# Answer
> 2 votes
For dev enviroment you can follow the instructions of the sites/example.settings.local.php

> Local development override configuration feature.
>
> To activate this feature, copy and rename it such that its path plus filename is 'sites/example.com/settings.local.php', where example.com is the name of your site. Then, go to the bottom of 'sites/example.com/settings.php' and uncomment the commented lines that mention 'settings.local.php'.

With this you:

* Enable local development services.
* **Show all error messages, with backtrace information.**
* Disable CSS and JS aggregation.
* Disable the render cache (this includes the page cache).
* Allow test modules and themes to be installed.
* Enable access to rebuild.php.

---
Tags: 8, debugging, proxies, wsod
---


# Question
Title: Pass argument to view block within a minipanel
I am having a panel page, within the panel page there will be multiple minipanels in each row. The mini-panels have 2 views both which displays content based on the argument passed.

Basically the all the minipanels are same. The views within are also same. Only the argument passed change. But I am not getting how to pass argument.

See the below picture for detail.

In the end we'll have something like this. A repeated series of same panels and views with different contents.

I am not able to find out whats wrong.

# Answer
I just solved the exact same thing on my site, so writing it up here for future reference.

**Your views**:

* Create these as content panes
* Contextual filter = Content: thas taxonomy term id (in this case)
* Argument input (under "Pane settings" in the view) = "Input on pane config"

**Your mini panels**

* Context -\> Required context: taxonomy terms
* Content -\> (Your views) -\> Settings -\> "Term id" (probably named differently) = %taxonomy\_term:tid

**Your main panel**

* Context: Add taxo term id. You will have to add each term id you will want to use as a context here.
* Content -\> (Your mini panels) -\> Settings, select the term you would like to use on that instance of the mini panel:
> 1 votes

---
Tags: panels, views
---


title: How to edit breadcrumb in drupal 7?

text:
# Question
Title: How to edit breadcrumb in drupal 7?
How to edit breadcrumb info without install any drupal module?
Example: blog
Home \>\> blog \>\> admin's blog

I want to remove admin's blog

I cant find node--blog.tpl.php file.

I only can find node.tpl.php file.

Many Thank.

# Answer
> 1 votes
You can use this code in page.tpl.php replace with breadcrumb code.

```
$breadcrumb_array = drupal_get_breadcrumb();

```

print $breadcrumb\_array\[0\]

drupal\_get\_breadcrumb() gives the array.

You can use array as you want.

Please let me know code worked for you

# Answer
> 1 votes
Check the menu\_get\_active\_trail() and menu\_set\_active\_trail() functions. They should be of use for what you want (retreiving and changing your breadcrumb).

Try the following in your template.php in your theme :

```
/**
 * Implementing theme_preprocess_html
 */
function YOURTHEME_preprocess_html(&$vars) {
    $crumbs = menu_get_active_trail();
    $count = count($crumbs);
    // dpm($crumbs);
    unset($crumbs[$count - 1]);
    menu_set_active_trail($crumbs);
}

```

See how it goes.

# Answer
> 1 votes
you can override breadcrumbs theme in your template.php file

$variables : An array containing the breadcrumb links

```
/**
 * Implementing theme_breadcrumb
 */

function theme_breadcrumb($variables) {
  $breadcrumb = $variables ['breadcrumb'];

  if (!empty($breadcrumb)) {
    // edit $breadcrumbs here
    $output = '<div class="breadcrumb">' . implode(' » ', $breadcrumb) . '</div>';
    return $output;
  }
}

```

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_breadcrumb/7

---
Tags: 7, breadcrumbs
---


# Question
Title: Content type not responding to AJAX callback
I am using a ctools content type plugins to render a custom form that will have only one submit button.

The submitbutton will switch an eck entity field (boolean) from 0 to 1 and back (if pressed again, of course).

I have defined my ctools content type plugin, form (with ajax callback) and a submit handler

When i tested it with a hook\_menu path, all was fine and it worked.

Since i have put it in a ctools content type, no luck.

Any help would be very much appreciated!

Ps: What would be the best place to put my database logic? The submit handler?

Thanks a million!

```
$plugin = array(
  'single' => TRUE,
  'title' => t('Project isClient'),
  'description' => t('Project isClient AJAX plugin'),
  'category' => t('Project'),
  'render callback' => 'project_isclient_ajax',
  'defaults' => array(),
);

function project_isclient_ajax() {
  $pane = new stdClass();
  $pane->title = t('Project isClient');
  $pane->content = drupal_get_form('project_isclient_form');
  return $pane;
}

function project_isclient_form($form, &$form_state) {
  return array(
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Subscribe'),
      '#ajax' => array(
        'callback' => 'project_isclient_ajax_submit',
        'wrapper' => 'project-isclient-form',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    ),
  );
}

/**
 * Ajax callback function.
 */
function project_isclient_ajax_submit($form, $form_state) {
  // Dummy/dumb validation for demo purpose.
  return 'works!';
}

```

A little after posting this, i found AJAX calls in CTools Content Type Plugin? which states that ctools handles ajax forms differently. I checked using blocks, and this appears to be correct. In a block my callback works.

# Answer
> 0 votes
yes it seems like panles content type plugin handles the ajax calls differently. You could use the ajax commands listed in the ajax.inc file in core. There are functions for ajax\_command\_remove, ajax\_command\_append and more...

Here is my ajax callback that i call from my ajax form submit button example:

```
function my_form_ajax_callback($form, &$form_state) {
  $output = '<div id="newStuff">Clicked!</div>'
  $commands = array();
  $commands[] = ajax_command_remove('#id_to_remove');
  $commands[] = ajax_command_append('#id_of_wrapper_to_insert_in', $output, $settings = NULL);

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

```

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