# Question
Title: What file contains the queries of customized views?
I am trying to understand a previous theme in a website and one view shows different results from expected. Then, I want to check whether the query is being generated wrongly or not.

Are there a file in the Views module that contains the queries for my customized views?

# Answer
Views settings can be exported through the Features module as custom module code. So, if the site is using Features, and the view has been previously exported, then you will find the code inside one of the module files.

In that case, you can use a command line tool like Grep to find the file which contains the view. I would search recursively for the machine name of the view inside your www folder.

If the Features module is not in use, then you can see the view code if you go to the view edit page, then click "export view" in the upper right hand drop down.
> 0 votes

---
Tags: views
---


# Question
Title: How to read input username to drush script?
I need to complete a script which gets a username from terminal to a php script and then deletes the user's comments.

So I am wondering how the username should be read by the php script, the same way that one can read a value in a bash script.

Thanks

# Answer
> 4 votes
In your Drush command you need to call `drush_get_option('myoption');` to get the value of an input parameter.

To call your Drush command you need to specify your input option as below:

`drush mycommand --myoption=myvalue`

# Answer
> 1 votes
there is an example command in the drush directory : http://drupalcode.org/project/drush.git/blob/refs/heads/7.x-4.x:/examples/sandwich.drush.inc

in the command hook you define your arguments and those are then passed to the function that implements the command

# Answer
> 0 votes
If you implement a drush command, you can call that via the command line and define arguments and switches.

You can easily then hook into drupal. as your function can run from a bootstrapped drupal instance.

# Answer
> 0 votes
***In answer to the question by "alfish"***

I think the ultimate answer to this "old" question is to use PHP to control stdin.

```
function ask_user_name() {
  print("Please input your name: ");

  $handle = fopen ("php://stdin","r");
  $line = fgets($handle);

  drush_print("Your name is $line");
}

```

Basically there was no need to establish an interface mechanism in drush since it already exists in php... but Drush does provide four commands anyway.

* drush\_choice
* drush\_choice\_multiple
* drush\_confirm
* drush\_prompt

So in using drush\_prompt you would do something like this.

```
function ask_user_name() {
  $result = drush_prompt("Please input your name",NULL,TRUE);
  drush_print("Your name is $result");
}

```

I hope this helps.

---
Tags: drush
---


# Question
Title: PDOException: SQLSTATE[42000] Implicit conversion from data type nvarchar to varbinary(max) is not allowed
I got this problem with my drupal 7.24, Windows server 2012, IIS8 and the sql server 2012.

I'm using the last dev version of sqlsrv which is suppose to fix a similar bug, but I still have this one.

> PDOException: SQLSTATE\[42000\]: \[Microsoft\]\[SQL Server Native Client 11.0\]\[SQL Server\]Implicit conversion from data type `nvarchar` to `varbinary(max)` is not allowed. Use the `CONVERT` function to run this query. in `dblog_watchdog()` (line 160 of D:\inetpub\website\modules\dblog\dblog.module).

I've migrated my DB from a mysql to the sql server through the migration tool and using the drivers 5 and 3.51 to convert the schema. (got the same error in both case) BTW I have hexadecimal data sometime instead of normal data.

```
function dblog_watchdog(array $log_entry) {
  Database::getConnection('default', 'default')->insert('watchdog')
    ->fields(array(
      'uid' => $log_entry['uid'],
      'type' => substr($log_entry['type'], 0, 64),
      'message' => $log_entry['message'],
      'variables' => serialize($log_entry['variables']),
      'severity' => $log_entry['severity'],
      'link' => substr($log_entry['link'], 0, 255),
      'location' => $log_entry['request_uri'],
      'referer' => $log_entry['referer'],
      'hostname' => substr($log_entry['ip'], 0, 128),
      'timestamp' => $log_entry['timestamp'],
    ))
    ->execute();
}

```

On the dbo.watchdog I have a column call variables which is a varbinary(max) (used to be a LONGBLOB on mysql) and got hex data now. I think the problem is coming from here. When I comment those lines (insert query), it works, but with a lot of warning like:

> Warning: `array_flip()`: Can only flip `STRING` and `INTEGER` values! in `DrupalDefaultEntityController->load()` (line 173 of D:\inetpub\website\includes\entity.inc).
>
> Warning: Cannot modify header information - headers already sent by (output started at D:\inetpub\wendy\includes\common.inc:2700) in `drupal_send_headers()` (line 1216 of D:\inetpub\website\includes\bootstrap.inc)
>
> PDOException: SQLSTATE\[42000\]: \[Microsoft\]\[SQL Server Native Client 11.0\]\[SQL Server\]Implicit conversion from data type `nvarchar` to `varbinary(max)` is not allowed. Use the `CONVERT` function to run this query. in `variable_set()` (line 975 of D:\inetpub\website\includes\bootstrap.inc).

Anyone got an idea how to fix that?

# Answer
> 1 votes
I've figured out the main problem, when I was using the SQL migration tool to migrate, it was creating a database, so I devided to create mine to check. The one created by the tool was Latin1\_general\_CL\_AS and mine was SQL\_Latin1\_General\_CP1\_CI\_AS instead. That seems to have fixed the problem

---
Tags: 7, database, migrations
---


# Question
Title: Drupal Commerce custom Coupon Type not discounting
I'm trying to create my own coupon type so that I can give it a name that will appear in the checkout and add features such as expiry date and product reference. I have been able to add the features to the "percentage amount" coupon type and if I only had one coupon type I'd just change the display name of that, but there will be many coupon types in my shop. Each is a one-time use coupon that a major client can give to their members so there would be types such as Ford-employee-discount and Toyota-employee-discount with individual coupons trackable to individual staff. So even the coupon code wouldn't be good enough to display because it will be something like "F\_Emp-JH6d98"

So now that I have a new coupon type I have duplicated all the fields from percentage coupon type but when I get such a coupon added to a bill the "Granted amount" is blank. No discount is applied but the coupon is there on screen and listed as used by the database.

I'd prefer to be able to add a display name field to the coupon type and set it for each coupon I issue (which are made in batches by the Coupon Batch module), but without modifying the Coupon module I can't see how to display the value of that field in the right places.

# Answer
> 1 votes
You may need to implement

`hook_commerce_coupon_granted_amount_alter`

to add your granted amount to the display there.

e.g:

```
/**
 * Implements hook_commerce_coupon_granted_amount_alter
 */
function MYMODULE_commerce_coupon_granted_amount_alter(&$amount, $coupon, $values) {

  if ($coupon->type == 'my_coupon_type') {
    $order = commerce_order_load($values->order_id);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon);

    // Do stuff to get amount from coupon...
    // ...
    // ...
    $amount = 1000; // example
    $currency_code = "USD";
    $amount = commerce_currency_format($amount, $currency_code, $coupon);
  }
}

```

---
Tags: 7, commerce
---


# Question
Title: Email a Whole Node (Including template contents)
I have created my own custom node.tpl.php file. I now want to email the entire node, each time the user creates a new node of that content type (I have made sure that all the HTML in my node.tpl.php file is email friendly).

How can I do this? Ideally I would like the email to go to a specific email address automatically when the node is saved.

I have found that a combination of Rules and HTML Mail can achieve what I want. Except... When creating a rule action, there isn't the option to email the entire node (including the node.tpl.php theming). Rules only gives the option to email out specific node fields (without theming).

Any suggestions would be most appreciated!

# Answer
> 20 votes
Here's another approach. (The code is available in this sandbox.)

### nodemail.info

```
name = Nodemail
description = Sends node e-mails.
core = 7.x

```

### nodemail.install'

```
<?php
function nodemail_enable() {
  $current = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  $addition = array('nodemail' => 'NodemailMailSystem');
  variable_set('mail_system', array_merge($current, $addition));
}

function nodemail_disable() {
  $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  unset($mail_system['nodemail']);
  variable_set('mail_system', $mail_system);
}

```

### nodemail.module

```
<?php
class NodemailMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

function nodemail_mail($key, &$message, $params) {
  switch ($key) {
    case 'node_mail':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      break;
  }
}

function nodemail_node_insert($node) {
  if ($node->type == 'mycontenttype') {
    $params['subject'] = 'Node "' . $node->title . '" was created';
    $params['body'] = render(node_view($node));
    $to = variable_get('site_mail', '');
    $from = 'noreply@example.com';
    $lang = language_default();
    drupal_mail('nodemail', 'node_mail', $to, $lang, $params, $from);
  }
}

```

The install file contents and NodemailMailSystem class are used to allow this module to send html e-mails. The 2 other functions are implementations of hook\_mail() and hook\_node\_insert() that deal with sending the e-mails when a node of `mycontenttype` is created. One thing you'll have to note is that Drupal will use the node template file of the theme that is being used for node creation pages (or the core node.tpl.php if the theme doesn't have it) for the node view. You may also want to check out the node\_view() and drupal\_mail() functions that are used here. This whole thing should work with Drupal 7 core functionality (no contributed modules are needed).

# Answer
> 6 votes
You could create a token that was the rendered node, or create a custom Rules action that will send the rendered node.

You want to look at

```
$build = node_view($node);
$html = render($build);

```

**Updated with code**

This code shows how to add a property to all nodes which can can be made accessible in rules. I've created this a module called `googletorp`

```
/**
 * Implements hook_entity_property_info_alter().
 */
function googletorp_entity_property_info_alter(&$info) {
  // Add the current user's shopping cart to the site information.
  $info['node']['properties']['rendered_node'] = array(
    'label' => t("Rendered_node"),
    'description' => t('The full rendered node.'),
    'getter callback' => 'googletorp_render_node',
  );
}

/**
 * Return a rendered node as HTML.
 */
function googletorp_render_node($node) {
  return render(node_view($node));
}

```

The first function is a hook that adds the property to the node, where in a callback is defined to provide the data. The second function is the actual callback that returns the rendered node.

In order for this to work, you need to install the entity tokens module which is a part of the entity API module, but this is required by rules anyways.

# Answer
> 1 votes
Another option would be use my module Entity2Text(DRupal 7).

Right now it give a "textexport" token for every View Mode of an entity. This works well for a lot field types but has some problem more complex ones like Address Field.

I am also going to add "htmlexport". If you want to try that out checkout out this branch: http://drupalcode.org/project/entity2text.git/shortlog/refs/heads/7.x-1-htmlexport

You would still have to use Rules and MimeMail(or probably htmlmail mentioned above).

---
Tags: rules, emails
---


# Question
Title: Overriding a View table layout in module
I'm trying to override a view table from within my module. I can't locate what the arguments are suppose to be and in what order (for my hook\_theme func). I copied the theme file from views/themes and did no modifications. Does anyone know what is going wrong, and what should the arguments value be below?

My theme configuration is currently:

```
'views_view_table__opportunities_mentions' => array(
  'arguments' => array(
    'view' => NULL,
    'title' => NULL,
    'header' => NULL,
    'fields' => null,
    'class' => null,
    'row_classes' => null,
    'rows' => null
  ),
  'template' => 'views-view-table--opportunities-mentions',
  'original hook' => 'views_view_table',
  'path' => drupal_get_path('module', 'smd') . '/theme',
),

```

# Answer
> 3 votes
The easiest way to theme views is to edit the particular view in question and scroll down to find the link 'theme information'. This screen will tell you exactly what views theming templates that it is currently using and what templates you can make in your theme to override this output.

That essentially all views theming is - overriding the default markup with something to suit you designs.

@see http://www.group42.ca/theming\_views\_2\_the\_basics for an excellent tutorial on views theming

**EDIT**

If you want full control over the markup produced, *and* for this to be portable across themes, the only option you have is to create a custom module. This custom module could also have themeable components, and could even use a view to perform any heavy SQL (or you could just hand-write the SQL)

Take a look at a similiar module to get you started, and have a read through hook\_theme

# Answer
> 0 votes
The theme function you want to override, is a templated theme function. This means that a preprocess function is called, and them the variables are passed to the template. Preprocess functions are a bit different, in that only a single variable is passed to it: an array containing all variables, so the order of the variables are irrelevant.

See:

# Answer
> 0 votes
It's way better to preprocess the view.

If you want to override just a particular display, you need to be specific. You must first create a tpl.php file for the view. You can figure out which one you want by looking at the theme information for your particular view. Here is an example:

You then want to find the template suggestions of row style, which is currently 'Table':

*views-view-table.tpl.php* will override **every** view that has a table style. If you want to be specific to just this view, you're going to want (in this case) *views-view-table--frontpage.tpl.php* \- replace 'frontpage' with whatever suggestions your view is giving you.

You actually need to create this file in your theme directory. But what do you put in this file? Well, just click that 'Style output' link, and you will be presented with code that you can simply copy and paste right into that file.

After saving this file, open up your template.php and create a preprocessor for it. Note that preprocessors *do not work* without the file being present in D6. Here is some stub code, keeping with our example:

```
function [theme-name]_preprocess_views_view_table__frontpage(&$vars) {
  // manipulate the $vars here
  ...
}

```

$vars is passed by reference so you only have to manipulate the appropriate keys to do what you want.

# Answer
> 0 votes
It actually looks mostly correct to me, I used the same code in my module. I wanted to package my template file with my view in the module. As the site uses the regular bartik theme for admin and I didn't want to edit that theme to add my CSS.

What I believe is wrong is the following:

```
'views_view_table__opportunities_mentions' => array(
  'arguments' => array(
  'view' => NULL,
  'title' => NULL,
  'header' => NULL,
  'fields' => null,
  'class' => null,
  'row_classes' => null,
  'rows' => null
),
'template' => 'views-view-table--opportunities-mentions',
'base hook' => 'views_view_table',
'path' => drupal_get_path('module', 'smd') . '/theme',
),

```

Note that instead of `original hook`, it should be `base hook`. This is required that view has own preprocess functions to be correctly wired to your tpl. If you don't set that correctly it will pick up your custom tpl anyway, but you'll get all kinds of errors about missing or null variables in the tpl because the preprocess function didn't set any of the variables that the tpl uses.

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


title: How to add a Location field in drupal 7

text:
# Question
Title: How to add a Location field in drupal 7
I have my location module enabled but I cannot see a **location field** while creating a new form.How can I add location field to a content type.

# Answer
> 1 votes
You might have missed installing the location\_cck sub module it provides location field type to add on any content type out of the box.

# Answer
> 1 votes
You need to have the Geofield module installed instead. You can then add location information e.g Longitude/Latitude.

---
Tags: 7, location
---


# Question
Title: How do I display a block on an edit form for particular content types?
It's fairly simple to display a block on the node add form for a particular content type. Simply restrict visibility to a URL path like *node/add/article* and you're good to go.

I would like to know how to display a block on the edit form for a particular content type. For instance, when editing an article, the URL path is *node/NID/edit*.

Is there an easy way to display a block for edits of a given content type?

# Answer
> 2 votes
You need to add `php code` in the `block Visibility settings` in admin section of block. You can follow below code.

```
$node = menu_get_object();

   if (isset($node) && $node->type == 'article' && arg(2) == 'edit') {

     return TRUE;
   }

   return FALSE

```

Another example:

```
$nid = arg(1);

   $node = node_load($nid);

   if (isset($node) && $node->type == 'article' && arg(2) == 'edit') {

     return TRUE;
   }

   return FALSE

```

# Answer
> 1 votes
Here's how to display a block on an add and edit form for a particular content type via PHP code in the block configuration.

```
<?php
    $show_block = false;
    $content_type = 'article';
    $types = array($content_type);

    if (arg(0) == 'node' && is_numeric(arg(1))) {
        $nid = arg(1);
        $node = node_load($nid);
        $type = $node->type;
        $show_block |= in_array($type, $types);
    } else if (arg(0) == 'node' && arg(2) == $content_type) {
        $show_block = true;
    }
    return $show_block;
?>

```

---
Tags: 7, blocks, nodes
---


# Question
Title: How to hide a field (cck) based on a date field?
I am looking for a way to hide a content field based on the nodes date field.

Example:

**Event Name:** Some Name Here

**Event Date:** 12/12/2012

**Event Location:** Somewhere

**Buy Tickets:** ticket.com

If the date has passed I would like the Buy Tickets field to not show ... any help would be appreciated.

# Answer
The solution is very simple. In template.php file implement `MY_THEME_preprocess_node()`. Example:

```
function MY_THEME_preprocess_node(&$variables) {
  //  dpm($variables);
  if($variables['type'] == 'MY_CONTENT_TYPE') {
    $date_field_value = $variables['content']['field_DATE_FIEL_NAME'][0]['value']; // find the correct value of your field

    $converted_date = strtotime($date_field_value);

    if(time() > $converted_date) {
      hide($variables['content']['field_DATE_FIEL_NAME']);
    }
  }
}

```

you can also use `hook_node_view`:

```
function MY_MODULE_node_view($node, $view_mode, $langcode) {
  if($node->type == 'MY_CONTENT_TYPE') {
    $date_field_value = $node->content['field_DATE_FIEL_NAME'][0]['value'];

    $converted_date = strtotime($date_field_value);

    if(time() > $converted_date) {
      hide($node->content['field_DATE_FIEL_NAME']);
    }
  }
}

```
> 2 votes

# Answer
A good starting point is Field formatter conditions module. Easy to implement what you are looking for but will work well where the date is fixed. However since the dates for each event are bound to be different you are most likely not going to find it feasible for the task since the formatter is not implemented per node.

In that case I would go for a custom module (you can correct me on this one) that implements `hook_node_view_alter()`

I am answering this in a bit of a hurry. Will be back with a code sample but for now have a look at the hook on api.drupal.org and at another question answered on Stackexchange to get an idea.

Hoping I am of help.
> 1 votes

---
Tags: views, theming, datetime, entities
---


title: Ubercart payment

text:
# Question
Title: Ubercart payment
How can I configure payment for ubercart?

I want default checkout to be worked or credit card option to get money to my paypal account. How it can be done?

# Answer
Check the following abstract from the link for ubercart payment using paypal:

PP Account Settings:

Signup for a PayPal account. Before you can use WPS you need to sign up for a PP account. We recommend using this link to tell PayPal you registered through Ubercart. They in turn support the continued development of our project.

Open a business account (optional). Although this step is optional, it is recommended for you to keep your personal and business PayPal accounts separate. Opening a business account is preferable because it allows you to use a business name on the PayPal checkout pages and in theory allows you to keep your private name separate. Presenting a business name to customers will help build customer confidence.

Go through the approval process to verify your account. This will require a bank account and correct contact information, possibly more. You can always contact their customer service if you get stumped here. Configure PayPal account settings. Login to your PayPal account and go to the profile page/tab. There are many options here but only a few are required to get WPS working with UC.

Setting up WPS:

Click on "Website Payment Preferences" under the "Selling Preferences" section. Enable "Auto Return".

Set the "Return URL" to http://www.yourdomain.com/cart/checkout/complete

Enable "Paypal Account Optional" (optional). This will make it so customers are not forced to create a PayPal account during checkout.

Save your settings.

Setting up IPN:

Click on "Instant Payment Notification Preferences" under the "Selling Preferences" section.

Make sure that "Instant Payment Notification (IPN)" is not checked. Make sure that no IPN URL is set. UC provides this automatically. * Note: When you login to PayPal, you may get taken to a "Getting Started Steps" page. Steps 1 and 2 are required and involve opening your business account and getting verified. However, step 3 is not required. You do not have to create any buttons or links as UC handles redirecting users to PayPal automatically.

Ubercart PayPal Settings

Enable uc\_payment and uc\_paypal modules at "admin/build/modules".

Configure PayPal WPS settings at admin/store/settings/payment/edit/methods:

Click the "Enable" checkbox for WPS.

Expand the "PayPal Website Payments Standard settings" fieldset and make the following changes:

Enter your PayPal account e-mail address in the appropriate field.

Set the "PayPal server" to "Live" (versus Sandbox) when you're ready to process orders.

The other fields are self-explanatory and based upon your requirements. Be sure to set them per your needs.

Configure your Checkout Settings at admin/store/settings/checkout. You probably want to make sure you've enabled the following two options:

New customers receive an e-mail with their account details.

Anonymous checkout.

Enable Automatic order update in WorkFlow-NG module by going to "admin/build/workflow-ng"

Click "Edit" for the Update order status on full payment Tick "Active" checkbox.

Click "Submit"

For using Report module first you have to enable the Statistics module by going to "admin/build/modules"

Now enable Report feature by going to "admin/store/settings/reports" Choose "Payment Received" under "Report Statuses"
> 1 votes

---
Tags: 7, ubercart, payment-gateways
---


title: Module for comment validation

text:
# Question
Title: Module for comment validation
I'm learning how to create a new module for the first time, so please bare with me. I'm trying to add a validation on the comment form from scratch; it's just not validating at all, meaning that my form successfully submits when I intentionally don't fill out the subject field.
Here is my code:

```
/*
 *  Implementation of hook_form_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == "comment_form") {
    $form['#validate'][] =  'my_module_comment_validate';
  }
}

/**
  * Validate routine to prevent keywords from being used within comments.
  */
function my_module_comment_validate($form, &$form_state){

if ($form_state['values']['subject'] == '') {
 form_set_error('', t('Error!'));
 }
}

```

# Answer
In your `form_set_error()` call, you haven't set a specific field name on which to set an error. It's possible that without a `form_set_error()` call identifying a real form element no error is happening.

```
form_set_error('subject', t('Error!'));

```

Also, check to make sure your validation function is being called with a `drupal_set_message()`
> 1 votes

# Answer
change your form id...that should be

```
function MYMODULE_form_comment_form_alter(&$form, &$form_state, &$form_id){
}

```

and clear your cache..it should work for you
> 0 votes

---
Tags: 7, forms, hooks
---


# Question
Title: Does commerce send an order notification email to site admin (site email) out of the box?
Does commerce send an order notification email to site admin (site email) out of the box?

If not how do I do this?

# Answer
It doesn't look like it does, no. There is, however, a rule set up to send the order notification to the user. It's called "Send an order notification e-mail".

You can easily clone this rule, but instead of sending the email to the owner of the order, send it to the admin's email address.

The admin user isn't available as a data selector for this rule, so you'll either have to expose it yourself somehow (not sure exactly how you'd do that without custom coding off the top of my head), or simply switch to 'direct input mode' and put the email address in manually.
> 6 votes

# Answer
If you want to include line items in the email to site admin, I'd recommend using https://drupal.org/project/commerce\_email

Although the project page doesn't mention it, there are also dependencies on these modules: variable variable\_email htmlmail
> 1 votes

# Answer
You could "Clone" It's called "Send an order notification e-mail" and edit Data selector to site:mail (or switch to the direct mode to fill your e-mail address).
> -1 votes

---
Tags: 7, commerce
---


# Question
Title: How to create 10 extra nodes when a node of a specific content type is created?
I have some business logic in my application where i need to create 10 extra nodes of a content type, when a node of a specific content type is created from Drupal Content Creation page. I know how to programmatically create a node, and I can achieve it via menu hooks, but cant get them done via `hook_node_insert()` which takes my application into some sort of a loop(maybe because of `node_save()`). My menu code is an under but I want it to be run from node insert hook.

```
function nodecreator_menu() {
    $items['admin/create/nodes'] = array(
      'page callback' => 'nc',
     'access arguments' => array('access content'),

    );
    return $items;
  }
function nc(){
      $node2 = new stdClass(); // We create a new node object
  $node2->language = LANGUAGE_NONE;
  $node2->field_vote_year[$node2->language][0]['value']="2009-01-01 00:00:00";
  //$node2->field_select_base_vote[$node2->language][0]['target_id']=$node->nid;
  $node2->field_select_base_vote[$node2->language][0]['target_id']=8;
  $node2->type = "vote"; // Or any other content type you want
  $node->title="Test";
   $node2->title = $node->title.$node2->field_vote_year[$node2->language][0]['value'];

  node_object_prepare($node2); // Set some default values.
  $node2->uid = 1; // Or any id you wish
  $node2 = node_submit($node2); // Prepare node for a submit
  node_save($node2);

}

```

# Answer
You might experience an infinite loop here since every time you save the node (auto-generated or not), hook\_node\_insert() gets invoked. To prevent this infinite loop, you can use an extra pseudo-property in your hook\_node\_insert() to dictate if whether or not nodes should be automatically created.

Below is an example of how your hook\_node\_insert() might look like:

```
// If the node is an auto-generated node, don't create additional nodes.
if (!isset($node->auto_generated)) {
  // Auto-generate 10 nodes.
  for ($i = 0; $i < 10; $i++) {
    // Create a new node object and populate its fields.
    $node2 = new stdClass();
    $node2->language = LANGUAGE_NONE;
    $node2->type = "test";
    $node2->title = "Auto-generated (" . $node->nid . "-" . $i .")";

    $node2->created = REQUEST_TIME;
    $node2->uid = $node->uid;

    // A flag to let hook_nodeapi() implementations know that this is an automatically
    // generated node.
    $node2->auto_generated = TRUE;

    // Finally, save the node.
    node_save($node2);

    watchdog('test', "Auto-created node: <pre>@node</pre>", array(
      '@node' => print_r($node2, TRUE),
    ));
  }
}

```
> 2 votes

---
Tags: nodes, hooks
---


# Question
Title: Drush contrib modules not available if executed externally
Using Drush 5.8 contrib modules are not available if executed externally.

E.g. Drush Entity is not available if executed on a Django view via a check\_output:

```
check_output("drush -l example.com -r /var/www/my/example/site/ entity-read node", shell=True)

```

Any command regarding Drush Entity return an error specifying that the command "could not be found. Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions."

The same command is available if executed via an interactive python shell or via ssh.

I've installed Drush Entity in this way:

```
drush dl drush_entity

```

This command on my system put drush\_entity into /home/admin/.drush directory. This directory seems to be ignored, since site-alias too are ignored if i put them inside that directory.

# Answer
> 1 votes
The solution is to pass the environment variable $HOME to check\_output, in this case /home/admin:

```
check_output("drush -l example.com -r /var/www/my/example/site/ entity-read node", shell=True, env={'HOME': "/home/admin"})

```

This force the /home/admin/.drush directory to be read. If everything is fine this command:

```
drush ev 'print(drush_server_home());'

```

should return /home/admin. If drush\_server\_home() returns an empty string, contrib modules installed inside .drush on home directory will not be available.

Ensure to install contrib modules with the same user controlling the /home/admin directory.

Read the documentation of the language you're using to pass the $HOME variable on command execution.

---
Tags: drush
---


# Question
Title: Showing content on pages without taxonomy
I have setup a drupal site so that a block is showing specific content on pages with the same taxonomy term as the block.

Now I am trying to get some sort of default content for pages without taxonomy terms. I want the block to show all the content without taxonomy terms attached on pages without any terms attached (such as the front page and some sub pages the client makes himself).

The block in question is a slider and it would be silly if the client would see the slider disappear on pages he creates due to taxonomy.

How can I achieve this?

# Answer
> 2 votes
This should be fairly straight forward

1. Create a new view that displays all the content without a taxonomy term,
2. In the existing block view look under the advanced settings for no results behaviour and click add. In here you can add a view to display if there are no results so simple select your view that you created in step 1.

---
Tags: taxonomy-terms
---


title: Language AND region selector

text:
# Question
Title: Language AND region selector
I'm asked to build a website which allows visitors to select both a language **and** a region, together, so it's a set of combined choices (eg. one choice would be "Switzerland French", another would be "Switzerland German", and so on). (Right now it's a combination of two countries and two languages, but it may be extended to other countries or languages in the future.)

This choice then accompany the visitor everywhere on the site, until of course she decides to change it. (The selector will be visible on all pages.)

Based on this choice:

* a **language** is set (the site will be localized),
* some contents (based on Views) will be **ordered** differently, and some will be filtered out,
* some contents (blocks or pages) will be made visible or not,
* the rest of the contents remain accessible and basically unchanged (but localized).

I'm not completely new to Drupal, but I'm no Drupal guru either. And I have no idea on how to implement that.

Can you advise me on how to approach this?

# Answer
In the absence of any other answer, I've decided to try using the Organic Group module to solve this case.
I made this choice after reading this article which is the closest I've found to my needs.

However, I'm still not entirely sure that this is the only or even the best solution, so any other suggestion is still welcome.
> 0 votes

---
Tags: 7, views, i18n-l10n
---


# Question
Title: Drupal 7 localhost is shortening css strings
My local copy of a Drupal 7.19 site has been cutting the css strings and I cannot figure it out. I have checked my .info file, settings file and tried disabling modules, all to no avail. It continues to render css like this:

```
<link type="text/css" rel="stylesheet" href="http://localhost/rwr/" media="all">

```

Where is should be

```
<link type="text/css" rel="stylesheet" href="http://localhost/rwr/sites/all/[themename]/css/global.base.css" media="all">

```

My remote site is generating @import calls to the css, but my localhost is not.

Feel free to link me to an existing solution for this. I have been googling and reading for hours, but I cannot find a solution. Thank you!

# Answer
> 0 votes
same issue, to me helps:

visit: admin/config/development/performance

turn on "CACHING" for: Cache pages for anonymous users

turn off all "BANDWIDTH OPTIMIZATION" Compress cached pages. Aggregate and compress CSS files. Aggregate JavaScript files.

Then Clear all cahces

That fix my issue with css ;)

---
Tags: 7, theming
---


# Question
Title: Is there a way to integrate revisioning with Panels + CTools content types?
I'm using CTools content types to make highly customized Panels panes. The panes together form a Panels Node (I'm using the Panels default module for this).

The Panels node itself can be revisioned, but these revisions do not include changes to the content that lives in the panes. It seems that *the content of the panes themselves* cannot be revisioned.

Is there a way to use revisions/workflow/workbench/anything to control the publishing flow of the panes?

# Answer
> 1 votes
Unfortunately, I can't think of any simple way to do what you want.

I would probably have solved it by having the content type pull it's content from the entity they are displayed on instead.

It's possible that fieldable panel panes could be useful to you.

In the end, if you *really* need revisioning on the the content type settings form, you're gonna have to implement it yourself. Since the form is a standard Drupal form, I would try doing it with a node type as backend, instead of doing the whole thing from scratch. You should be able to just load up the edit form for a node, and re-use most of the functionality.

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


# Question
Title: Insert bank detail in email if the user choose to pay with bank transfer
I want to add a to order checkout emails the bank account details managed by commerce\_bank\_transfer module. I create a rule for the order with the bank transfer payment method but I'm not undertanding how to add in the mail my site's bank account infos.

I tryed to add this code to the email

```
<?php
   $payment_method = commerce_payment_method_load('bank_transfer');
   echo commerce_bank_transfer_bank_details($commerce_order->order_id, $payment_method);
?>

```

I did some test and in the mail there is nothing where I was expecting my bank info.

Reading commerce\_bank\_transfer module I saw that commerce\_bank\_transfer\_bank\_details function request a 'setting' key in the $payment\_method array but if I retry the payment method by

```
commerce_payment_method_load('bank_transfer');

```

I have no 'setting' key.

How can I retry the setting from a payment method?

# Answer
I solve with this code:

```
<?php
$payment_method = commerce_payment_method_instance_load($commerce_order->data['payment_method']);
echo commerce_bank_transfer_bank_details($commerce_order->order_id, $payment_method);
?>

```

commerce\_payment\_method\_instance\_load() function need in input a string like

'bank\_transfer|commerce\_payment\_bank\_transfer'

and it returns a paymente method with all data \[ setting included \]
> 2 votes

---
Tags: rules, emails, commerce
---


# Question
Title: Administration Structure to list menu items fails to display
When I access admin/structure/menu/manage/main-menu this should show a list of all of the menu items and enable re-ordering, enabling, etc. This has stopped working and will only display the top level menu (without styles) and sometime just a blank page.

I think it is related to the number of menu items I have. Checking the database for menu\_links shows almost 500 entries. Is there a way around this?

Possibly I need to think differently. I am not actually displaying all of the items on the user menu just the top two levels. But by adding node and hiding them I get the breadcrumbs for 'free'. Is there a better way to handle the breadcrumbs that would enable me to remove excess items from the menus?

Thanks in advance Andrew W.

# Answer
If you want to modify only `breadcrumb`, then you can use one of below module.

custom breadcrumbs:

> Allows administrators to set up parametrized breadcrumb trails for any **node type, Views, Panels, Taxonomy vocabularies and terms, paths** . This allows node types to have "**Home \> User Blog \> 2005 \> January**" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.

path breadcrumbs

> Path Breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!
> 0 votes

---
Tags: routes, breadcrumbs
---


# Question
Title: How can I add field information to an standard image?
How can I automate this. I am having some sort op coupon like website. But I want the coupon code to be placed into an image. With the nessecary information from the rest of the fields, like date and other conditions, company name, etc.

How can I accomplish this?

# Answer
> 2 votes
I assume you already have image installed and a content type set up that you have an image field attached to.

1. You will need to install the following modules image cache actions and token also the following will need to be enabled "Image Effects Text" (this is part of image cahce actions)
2. Add an image style by going to example.com/admin/config/media/image-styles and clicking add style.
3. Using the select list under Effect select text and then click add
4. You will now be in a page where you can set all the txt setting including the actual text to overlay the image with. You can select the type of text using the select list labelled "text source" if you have token installed you can select token and browse tokens for your replacement text.

---
Tags: views, entities
---


title: Calender System module and webform

text:
# Question
Title: Calender System module and webform
Does "Calender System" only works with "content types " ? The date popup options does not show while adding a "date" type field in to a webform node .

Date Field properties in a content type . Date field properties in a webform node .

Any clue ? thanks :)

# Answer
The module info page at https://drupal.org/project/calendar\_systems claims it has webforms support. 4th last item. So I suppose it does not only work for content types.
> 0 votes

---
Tags: webforms, datetime
---


# Question
Title: How to show a map within a node using gmap and location modules
I'm trying to save a location together with the node of a certain content type and when the node is shown I want the location to show up on a map within the node content. I use the Gmap and Location Modules, and I manage to save locations to the database, but the map doesn't show up. Any suggestions?

# Answer
> 0 votes
In the display settings of your content type, you should be able to change the value to "Map only" or "Adress with Map".

Then it should display it as a GMap.

I use:

* GMAP
* GMAP Location
* Node Locations
* Location CCK

I think you're missing Location CCK, in order to get the Map stored as a field in the content type.

Otherwise, if you use the content Location, I think the map is available as a block (not sure about this one).

---
Tags: 7, location, google-maps
---


# Question
Title: Hierarchical Select with taxonomy in Views
I have a generic content which can be differencied by a taxonomy term. Then i've created to views filtered by a taxonomy. I want to enable a second filter, exposed , based on the taxonomy, depending on the first filter also bases on the taxonomy but not exposed.

For example: I have the following taxonomy: Type :

1. News
    1. First
    2. Second
2. Publication

1. Third
    2. Fourth

My content is 'Article' and the Type is 'News \> First' In my View 'News', I can only see the content News ( First or Second), this part is easy. What I need is an exposed filter where i can only choose First or Second from News depending on the fact that I'v already done a previous filter based on the first level of this taxonomy.

How can I do that?

Thanks

# Answer
> 3 votes
You can achieve this by combining Simple Hierarchal Select and Views Dependent Filters. So you use SHS for selecting the taxonomy term, and then set a dependency that if a term is selected on the first taxonomy, show the second taxonomy.

1. Add your first/primary taxonomy that you will be using to determine the secondary options. Don't select any terms, expose filter.
2. Add your secondary taxonomy, expose filter.
3. Add a **Global: Dependent Filter** to your list of filters.
4. Your **Controller Filter** is the first taxonomy that will be deciding which second field/taxonomy will showing up.
5. The *Controller Values* are the values from the taxonomy selected for the *Controller Filter*. Pick the term which when selected will show the dependent taxonomy. The dependent filter is the secondary taxonomy that you want to show up.

There does need to be some specific ordering going on, like the dependent taxonomy needs to be above the Dependent Filter, but I can't remember exactly. I'm sure you can figure it out from there.

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


# Question
Title: Where does Drupal store information after creating a rule?
I'm wondering where Drupal stores information in the database when one creates a rule with an event *A node has been flagged* and an action *Grant user points to a user*.

Can you help me?

# Answer
Rules are stored in the rules\_rules table in D7. The table contains the rows of name (a machine readable name) and data (a data blob).

---

^ this is from D6, D7 has rules stored in rules\_config, with rules\_trigger holding the triggers and the ID of the rule and the trigger matching to each other.
> 2 votes

---
Tags: 7, database
---


title: Users Export module hook

text:
# Question
Title: Users Export module hook
I'm using Users Export that provides a hook with no extra information.
I need somehow to explore the `$info` parameters in order to this extra fields

my code:

```
function display_my_users_loft_data_grids_info_alter(&$info) {
    var_dump($info);
}

```

But in that case the `var_dump` doesn't work.

Does someone know any example or documentation or help me to debug that?

# Answer
> 1 votes
Get the Devel module installed and use the `dpm()` function, e.g.

```
function display_my_users_loft_data_grids_info_alter(&$info) {
    dpm($info);
}

```

Then perform whatever action it would take to invoke that hook, and you'll see the `$info` variable exported to the messages area for easy browsing.

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


title: How to use CKEditor on the front-end?

text:
# Question
Title: How to use CKEditor on the front-end?
CKEditor do not work on one specific theme, it works fine in the back-end and also when I switch the theme.

When I look the sources, I get the JS & CSS, `ckeditor` class on textarea but not the injected code that CKE add under each textbox with `id="cke_edit-body"`.

What can be the sources of the problem?

I know it's not jQuery, I found similar issues but they were provoked by a custom jQuery update, I use 1.3.2

# Answer
> 0 votes
On Input filter option (admin/settings/filters) you can check the user permission for each type of input filter you have on the site.

Then if you are using the WYSIWYG module, at admin/settings/wysiwyg you can check which type of editor is using each input filter.

If the WYSIWYG editor is working for anonymous user on one theme but not on the other, you could also check (with Firebug or Chrome DevTools) if there are Javascript errors. If that is the case, please, update this post with the error message.

---
Tags: 6, wysiwyg
---


# Question
Title: Drupal files on NFS, performance degredation
Many people use NFS to keep the sites/default/files directory outside of the normal webroot of a Drupal install.

However, I'm running the entire Drupal install over NFS.

When the site has not been accessed in some time, there's a solid 15-20 seconds of delay before a page loads. After that everything is fine. I have Drupal's page caching turned off for these tests to provide consistent results.

Initially I found that PHP's `realpath_cache` needed to be adjusted, because the default of 16k is not enough to handle all of paths Drupal loads when bootstrapping. I have this raised to 128k, and I see now that the utilized cache size goes up to around 40-50kb (after browsing around the site all over to "trigger" more file loads).

However, that does not seem to affect performance at all. Those cache entries expire anyway and will eventually PHP will need to hit the FS again.

I also have the built in "poor mans cron" disabled, so it's not related to Drupal running a bunch of cron tasks on that page load.

I suspect it may be related to NFS.

Is anyone else running a Drupal install completely over NFS, or have you in the past and come to any conclusions that may help?

# Answer
Assuming APC is installed; inside php.ini

```
; http://www.php.net/manual/en/ini.core.php#ini.sect.performance
realpath_cache_size=1M ; 1MB
realpath_cache_ttl=3600 ; 1 hour

; APC
; http://www.php.net/manual/en/apc.configuration.php
apc.ttl=2419200 ; 4 weeks
apc.localcache = 1
apc.localcache.size = 1024
apc.num_files_hint = 2048
apc.user_entries_hint = 128

apc.file_update_protection = 10
apc.stat = 0
apc.stat_ctime = 0
apc.file_md5 = 1

; OPcache
; http://www.php.net/manual/en/opcache.configuration.php
opcache.enable_file_override = 1
opcache.validate_timestamps = 0

```

Then when your code changes you need to restart Apache or run

```
apc_clear_cache('opcode');
opcache_reset();

```

And for Drupal install the following modules as these are designed to help with the drupal files dir when used on a NFS filesystem
https://drupal.org/project/imageinfo\_cache
https://drupal.org/project/advagg
https://drupal.org/project/httprl (will speed up the above 2 modules)
> 2 votes

---
Tags: performance
---


title: Include files used by multiple modules

text:
# Question
Title: Include files used by multiple modules
I have some include files (.inc) that have classes in them that are used by multiple modules. Where should these be stored so that they are accessible to files\[\] in a modules .info file? Preferably without having to store copies of the files in each modules directory.

# Answer
> 2 votes
Probably the sanest way to do this would be to create a new module which has little to no functionality, but includes the .inc files; then make your other modules dependent on that module. As you develop the other modules and find other functionality you want to share between them, just implement it in the "parent" module, and away you go.

If adding another module is objectionable for some reason, you could implement it as a "library" and use the Libraries API module - but that's intended for Drupal-external third-party PHP libraries like TinyMCE, not things you've built yourself.

---
Tags: 7, .info
---


title: Access Node in html.tpl.php in Drupal 7

text:
# Question
Title: Access Node in html.tpl.php in Drupal 7
I am trying to access the current $node variables in the html.tpl.php within Drupal 7. The problem is that I am running a Analytics software in the backend for which I've to record each page's analytics from html.tpl.php.

If there's a normal page, I have to record generic attributes but if it's a node, I need the following things in the `html.tpl.php`:-

* Title of the Content (Node)
* Content Type of the Content

I can do this in `node.tpl.php` through `$node->type;`, but unfortunately I need it in html.tpl.php.

Many Thanks.

# Answer
> 6 votes
You can get the current menu object with `menu_get_object()`. From there you can determine if that object is a node or not. Since it defaults to "node" it will be empty if you're not on a node page and will have all the normal node object stuff available if you are.

```
$node = menu_get_object()

```

---
Tags: theming, nodes, users
---


# Question
Title: Protect site from flooding when user login is attacked by brute force
I've been experiencing issues with bots trying to force their way into the website I manage. It seems to be a daily occurrence the the flood system is being triggered (I'm on D7).

I'm happy the the flood system is doing it's job and stopping the attacks, but the problem is the bots are using private IPs, so when the flood is triggered it just locks everyone out.

I would like to find out if there is a way to limit the amount of bots that are getting through to the actual login verification. I tried throwing hidden captcha on to the login form, which does an ok job of it, but even when it suspects a bot, it doesn't't stop the login verification, so the flood system still gets triggered. Does anyone know of anything I can put in front of that process to limit the amount of bots getting though? The less intrusive, obviously the better.

# Answer
> 2 votes
In case anyone else comes across a similar issue, I didn't realize that the two IP addresses were coming from my varnish servers. I was able to use secure login to redirect user login attempts to https (which I should have been doing anyway) and that ended up bypassing vanish, thus allowing me to capture the actual IPs. That allowed to flood table to function as it was intended.

# Answer
> 5 votes
The type malicious bots you describe can connect through open proxies all over the world (typically without permission), each having different IP addresses. They can also use trojans and viruses on hijacked client computers/servers to do their work. In other words, Drupal's built-in flood control system, that uses IP-addresses for blocking, is no good for dealing with this type of attack. If the flood system causes problems for you ("locks everyone out"), you need to reconfigure it or turn it off.

You can do this by adding one or both of the following pair of configuration settings to your site's `settings.php` file:

```
// Set per-IP failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_ip_limit'] = PHP_INT_MAX;
$conf['user_failed_login_ip_window'] = 5;

// Set per-user failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_user_limit'] = PHP_INT_MAX;
$conf['user_failed_login_user_window'] = 5;

```

In that way, no-one will be locked out.

Instead of using the built-in flood control in Drupal, try using Apache ModSecurity to limit bots access to your server, filtering on content (*POST* requests), instead of IP-address.

From its documentation on HTTP Traffic Logging:

> Web servers are typically well-equipped to log traffic in a form useful for marketing analyses, but fall short logging traffic to web applications. In particular, most are not capable of logging the request bodies. Your adversaries know this, and that is why most attacks are now carried out via *POST* requests, rendering your systems blind. ModSecurity makes full HTTP transaction logging possible, allowing complete requests and responses to be logged. Its logging facilities also allow fine-grained decisions to be made about exactly what is logged and when, ensuring only the relevant data is recorded.

First discover the pattern in the *POST* requests the bots make, and use Apache to block them.

---
Tags: security, advertising, 7
---


# Question
Title: Execute product pricing rule for the order owner
I have a custom product pricing rule set up in Drupal Commerce which gives users of role *Trade* a different price by using a different commerce\_price field on the product which works fine.

But I need to export the values later on in to a XML file. The original product price is being returned as the rule is set up to use the *Current user* role, not that of the original user who made the transaction.

Is there anyway to have the rule act on the line item owner or for me to overwrite this in my XML output when calling `rules_invoke_event('commerce_product_calculate_sell_price', $line_item);`

# Answer
In any product pricing situation, you should always make your user related conditions check against the commerce-order:owner token, not the site:current-user. That sounds like exactly what you need.
> 0 votes

---
Tags: 7, commerce, rules
---


title: Which test cases/tests should I run?

text:
# Question
Title: Which test cases/tests should I run?
I'm a bit confused about best practices for testing in Drupal 7.

When I'm going to deploy, should I run the entire test suite—including all Drupal core tests—every time? This seems like a bit of overkill, especially given how long each test takes to run.

At the same time, it seems logical that I should run all tests every time, since code changes I make in my custom modules could break something in core (via hooks, etc.). The problem is, each test runs in a sandbox with only its dependencies enabled, so core tests won't even be aware of my custom modules and thus won't fail even if they should.

I'm accustomed to testing in Rails, in which tests are run against the entire application as a cohesive unit, with all "modules" (gems) being enabled at test runtime. It seems that in Drupal, only certain pieces are tested at a time, which prevents an accurate assessment of whether the site will work in production.

So I guess my question is twofold: A) Should I run the entire Drupal test suite (including core tests) every time I deploy? B) How do I check whether my custom code causes core tests to fail, given that core tests don't take custom modules into account?

# Answer
No, running Drupal core test suite is wrong. You can assume that your code won't messed up drupal core and if you so - you'll get exception for that and then the fun will start :).

If you came from the ruby world then you probably familiar with the Behat solution and if not you should check this - very easy to use QA platform and a lot of posts were written in order to test your site with behat. But there is also selenium that can help you.

And i'll give a you a tip on how to start the testing suite for your site: For now you probably have a running site. You need to take a pen and paper or a google doc and start what features you create for your site: what happens when the use login, what happens when he create node. After you wrote your tests you can start to write them in test - behat, selenium simple test... what ever! As long as those tests testing your features.

Another tip is: when ever you have a bug and you fixed this, you write a test that verity that the bug can't be reproduced. This the way all of the big projects i know works: OG, Message stack, Open scholar,
> 1 votes

---
Tags: testing
---


# Question
Title: entity_load() not listing custom fields.
I created the custom field for existing entity, I can see those fields listed on '`field_info_instances()`' . And I also have data in those fields, but I can't see those fields listed on the entity object returned by `entity_load()`.

This is how I am installing the fields

```
/**
 * Implements hook_update_N()
 */
function dashboard_update_7002() {

        field_create_field( array(
            'field_name' => "dashboard_url",
            'type' => 'text',
            'cardinality' => 1,
            'entity_types' => array('manufacturer'),
            'translatable' => TRUE,
            'locked' => true,
        ));

        field_create_instance(array(
            'field_name' => "dashboard_url",
            'entity_type' => 'manufacturer',
            'bundle' => 'manufacturer',
            'label' => "Dasboard URL",
            'required' => FALSE,
            'widget' => array(
                'type' => 'text_textfield',
            )
        ));

    }
}

```

# Answer
After banging my head for a while, I found the solution. On the module where that entity was defined '`hook_entity_info()`', '`fieldable`' property was missing which is set to `FALSE` by default. Therefore none of the fields were being attached to that entity.
> 2 votes

---
Tags: entities
---


# Question
Title: Is there a way to dynamically apply a CSS to a menu that includes the taxonomy term of the current page
For example, if I have page nodes with a vocabulary called "issues", which has terms, such as "budget", "education" and "foreign policies", and there's a menu titled "Information", I want to be able to add a class to that menu link for each page, such as "budget-info", "education-info" and "foreign-policies-info", dynamically. I assume I can throw in a JS behavior, but if there's a module that does this so the user can manage the class names assigned to each menu, especially that handles tokens and/or PHP so you can throw in part of the current url, that would be better. Note that I don't want to create a menu from taxonomy terms, but a standard item in the main menu with a custom class name applied which is comprised of a combination of a manually supplied name, and a taxonomy term that comes from current node.

Thanks!!

# Answer
> 0 votes
You could probably use Field Formatter CSS Class in some form or fashion, that can add a class to the node based on a taxonomy term, etc.

---
Tags: 7, taxonomy-terms, routes, javascript, theming
---


title: Taxonomy and menu links

text:
# Question
Title: Taxonomy and menu links
I have an example content type "Cars" and two vocabularies: "Country" with some terms of countries and "Brand" with some terms of brands.

The content type will have three more field that will be term references: Country, Brand and Type of cars.

I'm using a view page with path /cars that displays all the contents from that content type. The "Country" and "Brand" I'm using them as a exposed filters.

So my goal is to create a menu links from the left sidebar with type of cars like Hatchbacks, sports cars, city cars... etc. and will display the number how many cars are hatchbacks, how many sports cars....

When a user click on some of the menu links from left like for an example "Hatchbacks" it will display all the hatchbacks. And after that the filters Country and Brand will stay so a user can filter them.

My question is how can I create such menu links and will display the numbers of the nodes?

I'm using Drupal 7.

# Answer
> 0 votes
I used the taxonomy menu module on my latest project for this purpose, works like a champ!

Here is a quote about it (from the module's project page):

> Transforms your taxonomy vocabularies into menus with ease!
>
> Features:
>
> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules

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


title: How do I hide field in node.tpl.php?

text:
# Question
Title: How do I hide field in node.tpl.php?
I would like to hide this field if it is empty. No clue where to start with my limited PHP/Drupal knowledge. The Else would be "Nothing to see here."

```
<?php

  $my_field_value = $content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'];

echo "<input type=\"button\" value=\"Danh's Cart\" id=\"Adding PDC course\" onclick=\"setCookie('class','$my_field_value" . "r_000000000000');document.cartform.submit();\" style=\"float:none;\" /><input type=\"hidden\" name=\"id\" value=\"$my_field_value\" />";

```

?\>

# Answer
Here you go:

```
    if(isset($content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'])){
     $my_field_value =  $content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'];
} else {
        $my_field_value = '';
}

```
> 0 votes

---
Tags: entities
---


title: Push Items to Array using drupal_add_js

text:
# Question
Title: Push Items to Array using drupal_add_js
I'm using this code in a for loop to push items to an array but it doesn't add to the array, just overwrites it each time I think:

```
drupal_add_js(array('THINGS' => array('ONE' => array('VAR' => $var_one), 'TWO' => array('VAR' => $var_two), 'THREE' => array( 'VAR' => $var_three))), 'setting');

```

So this is what I end up with:

```
"THINGS":{"ONE":{"VAR":"blah blah blah"},"TWO":{"VAR":"blah blah blah two"},"THREE":{"VAR":"blah blah blah three"}}

```

When what I want is this:

```
"THINGS":{"ONE":{"VAR":"blah blah blah", "VAR":"blah blah blah one"},"TWO":{"VAR":"blah blah blah two","VAR":"blah blah blah two two"},"THREE":{"VAR":"blah blah blah three","VAR":"blah blah blah three three"}}

```

So I guess my question is, how do I print objects within objects using this method, or would it be easier to just push the variables with javascript within a script tag?

Any ideas? Am I doing this right?

# Answer
The problem seems to be the key of the nested array, where you are using 'VAR', you are repeating this key and that makes PHP to override the value on the array (or on the object on Js).

I think you would have to use the 'VAR' key on a slightly different way:

```
drupal_add_js(array('THINGS' => array(
    'ONE' => array(
      'VAR' => 'blah blah blah',
      'VAR_ONE' => 'blah blah blah one'
    ),
    'TWO' => array(
      'VAR' => 'blah blah blah two',
      'VAR_ONE' => 'blah blah blah two'
    ),
    'THREE' => array(
      'VAR' => 'blah blah blah three',
      'VAR_ONE' => 'blah blah blah three three'
    )
  )
));

```

to get what you are looking:

```
"THINGS":{"ONE":{"VAR":"blah blah blah", "VAR":"blah blah blah one"},"TWO":{"VAR":"blah blah blah two","VAR":"blah blah blah two two"},"THREE":{"VAR":"blah blah blah three","VAR":"blah blah blah three three"}}

```
> 2 votes

---
Tags: javascript
---


title: jQuery effects with exposed filters

text:
# Question
Title: jQuery effects with exposed filters
I am trying to produce a view with exposed filters, where:

1. The options are listed as text links, like a menu
2. The page automatically updates when a link is clicked
3. jQuery effects appear to seamlessly 'reorder' and remove items smoothly

eg: http://thisiseyeweb.co.uk/our-work#filter=.e-commerce

I have solved 1 & 2 by using Better Exposed Filters and settings in Views. So I can produce the list of links that make up the menu, and the ajax action to change what is displayed. But I can't make items that should no longer display 'fade out' or remove themselves in a prettier fashion, like the link above.

Many thanks.

# Answer
> 2 votes
You may want to look at this https://drupal.org/project/views\_quicksand

It integrates this plugin http://razorjack.net/quicksand/ with views.

Hope it helps.

# Answer
> 1 votes
Looks like a Job for Isotopes http://isotope.metafizzy.co/

Here is a module for Drupal implimentation https://drupal.org/project/isotope

This one is for Views

https://drupal.org/project/views\_isotope

# Answer
> 0 votes
Hum, I guess you can't do it with the normal behaviour of view exposed filter... My guess would be to do it all by yourself in JS.

1. Display all your items, like no filtered
2. Somehow add a class to the row, identifying the data to be filtered on
3. List your filter items, on a view attachment or in a block
4. Somehow add a class to these items, identifying the data that they'll display
5. Add JS to fetch identifier in item's class, and fade on click all rows which don't have the identifier

Though, I hope somebody has a more views-friendly answer :)

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


# Question
Title: Automatically create hyperlink based on span class
Does anyone have any idea how I can do this? I want my content writer to be able to add span classes to certain numerical amounts that then automatically hyperlink to a pre-defined URL. Example:

> And the price at John's hardware shop is`<span class="john-shop">`$2.35`</span>`

I am fully aware there is a module called Word Link Which does a fantastic job of hyperlinking specific keywords but as numerical amounts are not specific to anything this is a tad more challenging. What I mean by this is in Word Link you can say:

"coca cola" - link automatically to www.cocacola.com "Nike" - link automatically to www.nike.com

"$5.67" is just a number so a span class would be approriate.

Grateful for any help.

# Answer
You could do this in your field-template file.

```
<?php foreach($class in $classes)): ?>
  <?php if ($class == 'johns' ): ?>
    // do something
  <?php endif; ?>
  <?php if ($class == 'sarahs' ): ?>
    // do something
  <?php endif; ?>
<?php endforeach; ?>

```

Downside this way is you need to maintain a list in the templatefile.
> 0 votes

# Answer
You can approach this via hook\_node\_view\_alter().

**Via hook\_node\_view\_alter()**

```
/**
 * Implements hook_node_view_alter().
 */
function test_node_view_alter(&$build) {
  $node = $build['#node'];

  $pattern = '/<span class="[A-Za-z\-_ ]*">\$[0-9\.,]+<\/span>/';

  // Get the link from a field in the node.
  // This assumes field_url is a text field that contains the URL
  // (e.g. http://http://drupal.stackexchange.com).
  $replacement_link = $node->field_url[LANGUAGE_NONE][0]['value'];

  // Get the subject.
  // This assumes that the text you want to replace is in the 'body' field.
  $string = $build['body'][0]['#markup'];
  $build['body'][0]['#markup'] = preg_replace($pattern, "<a href='".$replacement_link."'>$0</a>", $string);
}

```

There are downsides to this approach:

1. You have to make sure that the author adheres to the pattern (`<span class="<SOME-CLASS>">$<NUMERICAL-VALUE></span>`). Any deviation from the pattern may result to text not being replaced.
2. This will replace all instances that matches the pattern.
3. The preferred way to manipulate DOM via PHP is by using HTML DOM Parsers.
> 0 votes

---
Tags: navigation
---


title: Zurb Foundation 4 jquery conflict

text:
# Question
Title: Zurb Foundation 4 jquery conflict
I am working on a Drupal 6 theme which uses the **Zurb Foundation 4 framework**. The problem I have is ideally Foundation 4 requires **jQuery version 1.10.2**.

Drupal 6 only supports up to **jQuery version 1.3.2** using the jQuery Update module. Upgrading site to Drupal 7, unfortunately isn't an option.

I have search through forums and tried a number of the suggested solutions but I can't seem to get both versions of jQuery to function without either breaking **Core or Zurb Foundation** functionality.

# Answer
> 1 votes
You can use jQuery Multi module which provide functionality to load multiple jquery in `Drupal` site.

> **jQuery Multi** allows you to load an extra version of the **`jQuery`** library in parallel to **`Drupal's`** version, without conflicting with **`Drupal's`** version. You can then choose any JavaScript library or files to use the new version of **`jQuery`**. No need to alter packaged jQuery plugins!
>
> * run a newer version of jQuery in parallel to Drupal's without interfering with things that use the default jQuery version, using
> jQuery's built in noConflict mode
> * use the newer version of jQuery in custom scripts using the provided alias
> * configure specific libraries to use the newer jQuery
> * configure any JS file in the system to load using the newer jQuery

---
Tags: 6, theming, javascript
---


title: Execute Sql Query in drupal

text:
# Question
Title: Execute Sql Query in drupal
I have SQL Query and I want to execute it in Drupal. My SQL Query is like this.

```
select cat.tid as cat_tid, cat.name as cat_name, cat_parent.parent as cat_parent_tid,
count(deals.nid) as no_of_deals
from
taxonomy_term_data as cat

left outer join taxonomy_term_hierarchy as cat_parent on cat_parent.tid=cat.tid

left outer join field_revision_field_categories as store_categories on
store_categories.field_categories_tid=cat.tid

left outer join field_revision_field_store as deal_stores on field_store_nid=store_categories.entity_id

left outer join (select * from node where type='deal' and status=1) as deals on nid=deal_stores.entity_id

where cat.vid=5

group by cat.tid, cat.name, cat_parent.parent

```

I converted this query with the help of this module https://drupal.org/project/query\_coder

and got the resulted query as

```
$query = db_select('taxonomy_term_data', 'cat');

$query->addExpression('count(deals.nid)', 'no_of_deals');

$query->fields('cat', array('tid', 'name'));

$query->fields('cat_parent', array('parent'));

$query->leftJoin('taxonomy_term_hierarchy', 'cat_parent', 'cat_parent.tid = cat.tid');

$query->leftJoin('field_revision_field_categories', 'store_categories', 'store_categories.field_categories_tid = cat.tid');

$query->leftJoin('field_revision_field_store', 'deal_stores', 'field_store_nid = store_categories.entity_id');

$query->leftJoin('', 'deals', 'nid = deal_stores.entity_id');

$query->condition('cat.vid', 5);

$query->groupBy('cat.tid');

$query->groupBy('cat.name');

$query->groupBy('cat_parent.parent');

$result = $query->execute();

```

Now how can I execute this query in drupal, I tried to import this query in views 3 but got some unexpected error, Also I tried to add this query into the block but again getting the same error. I also created a custom block in a custom module that too did not worked. Please help me how can I execute this query. Answer will be greatly appreciated.

# Answer
You should better start debugging the query.Things that might be help you debugging the query.

1. Install devel module. Having logged in as admin visit "yoursitename.com/devel/php" here you can execute any php code.
2. Put your query there and add this `dpm($result);` single line of code in the last of query. Execute the query, see what you get as result.
3. If the query execution is throwing error visit "yoursitename/admin/reports/dblog" and try to figure out the reason for the error.

You can also cross check if the query returned with drupal wrapper functions is same as your original query by stringyfying the query object, to do that add

```
`dpm((string) $query);`

```

just before $result = $query-\>execute(); and also remember to comment $result = $query-\>execute(); as execution of query may cause error in your case.
> 0 votes

# Answer
I think you have to iterate loop the data which is coming from this query "select * from node where type='deal' and status=1".

Inside the loop you need to pass the data to the above db\_select query you got. That will fix your problem I hope!!!!
> 0 votes

# Answer
I executed the successful query in my module, I am returning the result as a block by implementing hook\_block\_info().

Please check the module code below `t('category block'),`

`);

}

function custom_category_block_view($delta='') {

$block = array();
 switch ($delta) {
 case 'my-links':
 $nodes = db_query("select cat.tid as cat_tid, cat.name as cat_name, cat_parent.parent as cat_parent_tid,
 count(deals.nid) as no_of_deals
 from
 taxonomy_term_data as cat
 left outer join taxonomy_term_hierarchy as cat_parent on cat_parent.tid=cat.tid
 left outer join field_revision_field_categories as store_categories on store_categories.field_categories_tid=cat.tid
 left outer join field_revision_field_store as deal_stores on field_store_nid=store_categories.entity_id
 left outer join (select * from node where type='deal' and status=1) as deals on nid=deal_stores.entity_id
 where cat.vid=5
 group by cat.tid, cat.name, cat_parent.parent");

```
$list = array(
    '#theme' => 'links',
    '#links' => array(),
    '#prefix' => '<div class="my-links"><h2>Related Links</h2>',
    '#suffix' => '</div>',
  );

```

foreach ($nodes as $record) {

$list['#links'][] = array('title' => $record-> cat_name .' ('. $record->no_of_deals . ')' );

```
  }

````

`$block['subject'] = t('category block');
 $block['content'] = $list;
 break;
 }
 return $block;
}`

Just Create a custom module and add this to your module file and you are done.
> 0 votes

---
Tags: views, blocks
---


# Question
Title: How do I dynamically include ouput from an external file?
How do I dynamically include output from another web page?

This is the result of a CGI link along the lines of: http://www.example.com/name.cgi?Arg=argument I would like to include everything within the html tags that it generates as HTML on my page.

(I own both web pages!)

# Answer
There are a couple of modules that can help with this:

Web widgets (http://drupal.org/project/web\_widgets): Embed any other web site content in a widget with a simple widget API.

Iframe\_filter (http://drupal.org/project/iframe\_filter): you just need to add this filter to an input format and the content you create using that format will be displayed inside an iframe created dynamically.

And other iframe projects: http://drupal.org/project/insertFrame, http://drupal.org/project/iframe\_page (only dev version available right now for d7).
> 1 votes

---
Tags: theming
---


# Question
Title: How renderable array for an image with style should look like?
I have a custom module that outputs some images. Now, I would like to render them properly.

Currently, I use `theme()` function, kinda similarly to the way shown here1 and here1:

```
echo theme('image_style', array(
  'path' => $image['uri'],
  'style_name' => 'product_page_thumbnail',
  'attributes' => array(
    'alt' => $image['ImageAlt'],
    'title' => $image['ImageTitle'],
  )
));

```

Now, the `theme()` docs says:

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

So how would I do that?

I know renderable array for links, it's as simple as:

```
$link = array(
  '#type'    => 'link',
  '#title'   => $title,
  '#href'    => 'http://example.com',
  '#options' => array('html' => TRUE, 'title' => 'link'),
);

```

So I want the same, but for images. Somehow I can't find any documented example of it.

---

1Internal Stack Exchange links, just for reference.

# Answer
There's nothing specific for images, but there is for *any* theme function. Your old code using `theme()` would be equivalent to:

```
$build = array(
  '#theme' => 'image_style',
  '#path' => $image['uri'],
  '#style_name' => 'product_page_thumbnail',
  '#alt' => $image['ImageAlt'],
  '#title' => $image['ImageTitle'],
);

```

Basically you pass the named variables for the theme function as `#`-prefixed properties, and the render system will do the rest.
> 14 votes

---
Tags: media, theming
---


# Question
Title: Loading fully themed node with Ajax - Drupal 7
I am loading node content to a specific div with Ajax. Is it possible to load a fully themed and rendered node (themed via page--node--1.tpl.php) with Ajax?

I have a custom module controlling my Ajax functions. From what I understand, the code below should be returning a fully themed node - but it is not doing so:

```
function ajax_reader_init() {
    drupal_add_js('misc/jquery.form.js');
    drupal_add_library('system','drupal.ajax');
}

/**
 * Implements hook_menu()
 */
function ajax_reader_menu() {
    $items['ajax-reader'] = array (
        'page callback' => 'ajax_link_response',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}

function ajax_link_response($type = 'ajax', $nid = 0) {
    $output = _ajax_reader_load_noder($nid);
    if ($type == 'ajax'){
        $commands = array();
        $commands[] = ajax_command_replace('.main', '<div class="main">'.$output.'</div>');
        $page = array(
            '#type' => 'ajax',
            '#commands' => $commands
        );
        ajax_deliver($page);
    } else {
        $output = '<div class="main">'.$output.'</div>';
        return $output;
    }
}

function _ajax_reader_load_noder($nid = 0) {
    $node = node_load($nid);
    if($node) {
        $vnode = node_view($nid);
        return theme("node", $vnode);
    }
}

```

# Answer
> 3 votes
There is a contributed module **Ajaxify Drupal with JQuery Ajax** available for this. You can load any pages, nodes or anything to a div by using ajax without loosing css and ajax behaviour of loading content.

> Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.

---
Tags: nodes, ajax
---


# Question
Title: Search has disappeared on Drupal Commerce Kickstart site
When I first installed Drupal Commerce Kickstart it had a search enabled in the 'User Bar First' region. Now for some reason it has disappeared and I can't find it anywhere. I have tried searching the blocks and checking the search settings. What has happened to it?

# Answer
> 1 votes
The block that you need is actually called **'Exposed form: display\_products-page'**. Since it isn't immediately obvious what this is for I must have changed the block position to 'none'. Since it doesn't have search in the block name I didn't realize it was connected to search. Simply looking at the blocks on a new Kickstart Commerce install made it obvious what I was needed. Just change the position of the 'Exposed form: display\_products-page' block to 'User Bar First'.

---
Tags: 7, search, commerce
---


title: dependent dropdowns in ajax

text:
# Question
Title: dependent dropdowns in ajax
Searching for cascading ajax dropdown in this forum only gives me two discussions here and the other here

I have an almost similar issue only that the form select element I'm about to create cascades down in the 'taxonomy tree'. So each dropdown that was ajaxed will again be used to trigger another dropdown--in ajax...

Here is my sample module (trimmed down to relevant parts only):

```

function mainswitchboard($form,&$form_state){
    $form = array('#prefix'=>'', '#suffix'=>'');
    $form['maincategory'] = array(
        '#title'=>'Firs Select',
        '#type'=>'select',
        '#options'=>_populate_dropdowns(),
        '#ajax'=>array(
            'callback'=>'maincategory_callback',
            'wrapper'=>'wrapper-div',
            'method'=>'replaceWith'
        )
    );
    return $form;
}

```

```

function maincategory_callback($form,$form_state){

   $from_element_name = $form_state['triggering_element']['#name'];

    $triggerer = $from_element_name;
    $value = $form_state['values'][$triggerer];

    drupal_set_message(time(). ' ' .$triggerer);

    $commands = array(); $arguments = array();
    if(count(_populate_dropdowns($value))) {
        $form['subcat_for_'.$value] = array(
            '#title'=>'Subcat for '.$value,
            '#type'=>'select',
            '#options'=>_populate_dropdowns($value),
            '#attributes'=>array('id'=>'subcat_for_'.$value,'name'=>'subcat_for_'.$value),

        );

         $arguments['ajax'] = array(
            'subcat_for_'.$value=>array(
                    'event'=>'change',
                    'callback'=>'maincategory_callback',
                    'wrapper'=>'wrapper-div',
                    'method'=>'replaceWith',
                    'url'=>'/drupal7/system/ajax',

            )
        );

        $commands[] = ajax_command_settings($arguments,TRUE);

    }

    $commands[] = ajax_command_insert(NULL, drupal_render($form));
    $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
    return array('#type'=>'ajax','#commands'=>$commands);

}
```

The above code seems to work the only problem is you the second dropdown no longer produce results (although a throbber is showing when you click the second dropdown..) The second dropdown does not seem to honor the arguments variable, hence, it does not seem to call the function in its callback...

I'm stuck new drupaler...

Thanks!

# Answer
> 2 votes
You cannot change your $form in your ajax callback. Instead try to add a validate function with hook\_form\_alter on your form (or if in custom form just there) where your add a variable to your $form\_state and don't forget $form\_state\['rebuild'\] = TRUE. This will cause your form to rebuild (so form build function is called anew) In your form build function you can check this variable in $form\_state and malipulate the form. In your ajax callback you need to replace the form element (ajax\_command\_replace)

So workflow will be: form build function - ajax trigger - form build function - form validation (set variable & rebuild) - form build function - ajax callback

# Answer
> 0 votes
Following URL helped me to fix this issue.

Issue was rebuilding second select list.

Dependent drop down list

---
Tags: 7, ajax
---


# Question
Title: Why Views Data relationship between custom entity type and node doesn't work?
Fields names are equal in both tables.

Inside hook\_views\_data:

```
  $data['stream']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

 $data['stream']['nid'] = array(
    'title' => t('Related node'),
    'help' => t('Node related to stream item.'),
    // Define a relationship to the {node} table, so example_table views can
    // add a relationship to nodes. If you want to define a relationship the
    // other direction, use hook_views_data_alter(), or use the 'implicit' join
    // method described above.
    'relationship' => array(
      'base' => 'node', // The name of the table to join with.
      'base field' => 'nid', // The name of the field on the joined table.
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
    ),
  );

```

(similar to example from api page)

but there isn't above relation in Add relationships box. Could some one give me any hint?

# Answer
> 1 votes
I solved it by this way:

```
$data['stream']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'field' => 'nid',
    'handler' => 'views_join', // this is actually optional
    'left_table' => 'node'
  ),
);

$data['stream']['nid'] = array(
    'title' => t('Related node'),
    'help' => t('Node related to stream item.'),

    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),

    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
      'allow empty' => TRUE,
      'help' => 'Filter on a related node nid.',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric',
      'numeric' => TRUE,
      'validate type' => 'nid',
      'help' => 'Argument on related node nid.',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
      'help' => 'Sort on related node nid field.',
    ),
    'relationship' => array(
      'title' => t('Stream node'),
      'help' => t('Relation to node related to current stream item'),
      'label' => t('Stream node'),
      'base' => 'node',
      'base field' => 'nid',
    ),
  );

```

---
Tags: 7, views, nodes
---


title: Run query after page load

text:
# Question
Title: Run query after page load
I have a table of reservations which is built using Views module.

I want to highlight new reservations only 1 time. So I want to run a database update query (function `db_update`) after a page load. I tried to run it in `hook_page_alter()` or in `hook_process()`, but I didn't succeed, because query runs before showing a table. What hook should I use in my case?

# Answer
> 2 votes
hope this will help

```
/**
 * Post process any rendered data.
 *
 * This can be valuable to be able to cache a view and still have some level of
 * dynamic output. In an ideal world, the actual output will include HTML
 * comment based tokens, and then the post process can replace those tokens.
 *
 * Example usage. If it is known that the view is a node view and that the
 * primary field will be a nid, you can do something like this:
 *
 * <!--post-FIELD-NID-->
 *
 * And then in the post render, create an array with the text that should
 * go there:
 *
 * strtr($output, array('<!--post-FIELD-1-->' => 'output for FIELD of nid 1');
 *
 * All of the cached result data will be available in $view->result, as well,
 * so all ids used in the query should be discoverable.
 *
 * This hook can be utilized by themes.
 * @param $view
 *   The view object about to be processed.
 * @param $output
 *   A flat string with the rendered output of the view.
 * @param $cache
 *   The cache settings.
 */
hook_views_post_render(&$view, &$output, &$cache)
    {
if ($view->name == 'your_view_name')
    {
   //do your logic
   }}

```

---
Tags: views, database, 7
---


# Question
Title: Add referencing entities into this entities renderable array
Lets say I have a taxonomy called bands, and a taxonomy called band\_members.

Band\_members have an entity reference field relating each band member to a band.

When I view the bands taxonomy term page the band\_members will not be listed.

I can modify the taxonomy term template and manually add them in there, however the bands need to be shown in popups, and the content for each popup is returned via AJAX using drupal\_render(taxonomy\_term\_view($term)). This means any template changes won't show up. What I need to do is use a hook like hook\_taxonomy\_term\_view\_alter to add the band\_members for that band into the renderable array.

However that will be quite a lot of work, and I though it seems like a fairly standard task to need to displayed referencing entities, so is there an easier way to do this?

In this example I've used taxonomies as an example, however this could apply to nodes, users or any other entities that reference each other.

# Answer
Seems custom code was the easiest thing here after a bit of research...

```
function HOOK_taxonomy_term_view_alter(&$build) {
    if($build['#term']->vocabulary_machine_name=='bands') {
        $units = load_bands_members($build['#term']->tid);
        $build['units'] = array(
            '#markup' => theme('bands_members', array('members' => $members))
        );

    }
}

```

The function load\_band\_members returns an array of taxonomy terms and looks like this:

```
function load_band_members($tid) {
    $tids = db_query("SELECT tid
        FROM taxonomy_term_data td
        INNER JOIN field_data_field_band b ON b.entity_id = td.tid
        WHERE td.vid = 6 AND b.field_band_tid = :tid", array(':tid'=>$tid))->fetchCol();
    return $tids ? taxonomy_term_load_multiple($tids) : false;
}

```

I'm sure it would somehow be possible to get Drupal to render my band members for me, like it does on their own taxonomy term page, as opposed to me having to call my own custom render function but that will do for now...
> 0 votes

---
Tags: entities, theming
---


title: How can I set Dkim in phpmailer?

text:
# Question
Title: How can I set Dkim in phpmailer?
I have installed phpmailer module and it works fine. https://drupal.org/project/phpmailer

But it doesn't seem to have the option for DKIM. How can I set DKIM for the mails sent by phpmailer?

# Answer
Support for this it was requested over 2 years ago, and was moved to 7.x-3.x-dev branch, so it will not be possible in phpmailer for Drupal 6. The reason is that Drupal 6 will reach the end of its life soon, when Drupal 8 stable will be released. Thus, it will never be possible to set it in phpmailer for Drupal 6.

Anyway, enabling it at PHP level is a costly procedure. PHP is not really the best language for cryptography. As you can read here, configuring DKIM support at the MTA level makes all your server generated email for a given domain signed by default, and also off-loads the calculation burden to the system that's supposed to be optimized for it.

To make sure there is your MTA involved, you can use SMTP Authentication Support module. As you can see in it's issue queue it does not enable you to force DKIM from Drupal, but at least it ensures your mail server is sending mails, and does not interfere with mailserver's DKIM settings either.
> 2 votes

---
Tags: 6, emails
---


title: Captcha missing

text:
# Question
Title: Captcha missing
I installed captcha module in Drupal 7 and works with all forms except Contact form. This is the main one I would like it to work with. I am new to this and it's my first try with Drupal, I have one site running Zencart properly and now would like a blog site. Drupal site as it is now " http://jamair.x10.mx/drupal/ "

# Answer
> 2 votes
Have you enabled it for that form?

Go to yoursite/admin/config/people/captcha and check to make sure the captcha is enabled on the site contact form. It looks like it's functioning fine on that site (as it's showing up ok on the login block) so my first guess would be it's just not turned on for that form.

---
Tags: forms
---


# Question
Title: 500 error on Migrate class after preImport function runs on Migration
I have a migration class that creates nodes from tables in an SQL database. A second migration class uses MigrateSourceList with MigrateListXML and MigrateItemXML (grabs IDs from list xml, ID is the name of each item xml, same as wine example with MigrateSourceList). I want the second migration to write to the same nodes from the first migration.

The issue is I am getting a 500 response right after the preImport successfully runs on the second migration.

Here is my migration class:

```
class ArticlesXML extends XMLMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Articles: XML Content');

    $dependencies = array(
      'ArticlesStubs'
    );

    $this->dependencies = $dependencies;

    $fields = array(
      'Title' => t('Title'),
      'Intro' => t('Intro'),
      'BodyContent' => t('Body Content'),

    );

    $xml_folder = 'public://Articles/';
    $list_url = $xml_folder . 'Articles.xml';
    $item_url = $xml_folder . ':id.xml';

    $this->source = new MigrateSourceList(new MyListXML($list_url), new MigrateItemXML($item_url), $fields);

    $this->destination = new MigrateDestinationNode('article');

    $source_key = array(
      'ID' => array(
        'type' => 'varchar',
        'length' => 20,
      )
    );

    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationNode::getKeySchema());

    $this->addFieldMapping('nid', 'ID')
         ->sourceMigration('ArticlesStubs');
    $this->addFieldMapping('title', 'Title')
         ->xpath('wcm:element[@name="Title"]');
    $this->addFieldMapping('field_introduction', 'Intro')
         ->xpath('wcm:element[@name="Intro"]');
    $this->addFieldMapping('body', 'BodyContent')
         ->xpath('wcm:element[@name="BodyContent"]');

  }

  public function preImport() {
    parent::preImport();
    $data = array();
    $query = db_select('migrate_files_info', 'm');
    $query->join('migrate_files_data', 'i', 'm.ID = i.ID');
    $query->isNotNull('m.Description');
    $or = db_or()->condition('m.ArticleType', '1', '=')->condition('m.ArticleType', '2', '=')->condition('m.ArticleType', '4', '=')->condition('m.ArticleType', '5', '=')->condition('m.ArticleType', '6', '=')->condition('m.ArticleType', '8', '=');
    $query->condition($or);
    $query->fields('i', array('URL', 'ID'));
    $query->range(0,20);
    $result = $query->execute();
    while($record = $result->fetchAssoc()) {
      $data[] = $record;
    }
    $xml_data = new SimpleXMLElement("<?xml version=\"1.0\"?><articles></articles>");
    my_module_migrate_array_to_xml($data, $xml_data);
    $xml_data->asXML('public://Articles/Articles.xml');
    $url_prefix = 'http://mysite.com';
    $caught = array();
    foreach($data as $record) {
      foreach($record as $key=>$value) {
        if($key = 'URL') {
          if ($wrapper = file_stream_wrapper_get_instance_by_uri('public://')) {
            $realpath = $wrapper->realpath();
          }
          $xml_file = $url_prefix . $record['URL'];
          $file_headers = @get_headers($xml_file);
          if($file_headers[0] == 'HTTP/1.1 404 Not Found' || $file_headers[0] =='HTTP/1.1 404 Not Found') {
            continue;
          } else if ($file_headers[0] == 'HTTP/1.1 302 Found' && $file_headers[7] == 'HTTP/1.0 404 Not Found') {
              continue;
          } else if(file_exists($realpath . '/Articles/' . $record['ID'] . 'xml')){
              continue;
          } else {
            try {
              file_put_contents('public://Articles/' . $record['ID'] . '.xml', file_get_contents($xml_file));
            } catch (Exception $e) {
              $caught[] = $xml_file;
              echo $e->getMessage;
            }
          }
        }
      }
    }
    foreach($caught as $xml_file) {
      if ($wrapper = file_stream_wrapper_get_instance_by_uri('public://')) {
        $realpath = $wrapper->realpath();
      }
      $file_headers = @get_headers($xml_file);
      if($file_headers[0] == 'HTTP/1.1 404 Not Found' || $file_headers[0] =='HTTP/1.1 404 Not Found') {
        continue;
      } else if ($file_headers[0] == 'HTTP/1.1 302 Found' && $file_headers[7] == 'HTTP/1.0 404 Not Found') {
          continue;
      } else if(file_exists($realpath . '/Articles/' . $record['ID'] . 'xml')){
          continue;
      } else {
        file_put_contents('public://Articles/' . $record['ID'] . '.xml', file_get_contents($xml_file));
      }
    }
  }

  public function postImport() {
    $data = simplexml_load_file('public://Articles/Articles.xml');
    usnet($data->articles);
    file_put_contents('public://Articles/Articles.xml', $data->saveXML());
    $files = glob('public://Articles/*');
    foreach($files as $file) {
      if(is_file($file) && $file != 'Articles.xml') {
        unlink($file);
      }
    }
  }

}

```

This is another class I created because the default MigrateListXML will not properly parse my ID list XML file (this is the same file as ArticlesXML class):

```
class MyListXML extends MigrateListXML {

  protected function getIDsFromXML(SimpleXMLElement $xml) {
    $ids = array();
    foreach ($xml as $article) {
      $step = 1;
      foreach($article as $element) {
        if ($step == 0) {
          $ids[] = (string)$element;
        } else {
          $step--;
        }
      }
    }
    return array_unique($ids);
  }

}

```

This is my XML with the list of IDs:

```
<?xml version="1.0"?>
<articles><article><URL>/path/to/file.xml</URL><ID>1233</ID></article><article><URL>/path/to/file2.xml</URL><ID>1234</ID></article></articles>

```

Here is an example of an individual XML file that is supposed to be imported:

```
<?xml version="1.0" encoding="UTF-8"?>
<wcm:root xmlns:wcm="http://www.stellent.com/wcm-data/ns/8.0.0" version="8.0.0.0">
<wcm:element name="Title">SomeTitle</wcm:element>
  <wcm:element name="Intro">introintrointro</wcm:element>
  <wcm:element name="BodyContent">contentcontentcontent</wcm:element>
<wcm:list name="TestB"/>
</wcm:root>

```

This is the error I get:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=756&op=do StatusText: Internal Server Error ResponseText:

Unfortunately there are no other clues as to what the issue is.

# Answer
The issue was with the migrate module source file xml.inc. I had previously applied a patch that added the ability to define namespaces on IDs for XML sources, however the patch was incomplete and called a function that was never defined. Removing that call allowed for the migration to run successfully.
> 0 votes

---
Tags: migrations
---


# Question
Title: Creating custom field with Display Suite and Profile 2
I am trying to use Display Suite (newest version) to format the profile page for users. I am using the Profile2 module and the default main-profile type. I have the user's full name (not username) split into the fields for first, middle, and last. I am trying to create a custom field to combine these three fields as the full name.

I am trying to create a code field but I don't know what variable or replacement pattern to use. There is nothing in the list of available tokens. I have tried php using $content and $entity and get undefined variable errors.

How can I create a custom field in Display Suite to combine these three fields from a Profile2 entity?

# Answer
Enough trial and error and I finally figured it out. I ended up using Display Suite Code as the text format, but writing php code in the field code box.

And to grab the first name the code was: `$entity->field_first_name['und'][0]['safe_value']`.
> 0 votes

---
Tags: 7, entities, users, display-suite
---