# Question
Title: How to create a field which contains the entity created date
I need to create a field which contains the date an entity/node was created. I know some people achieve this by using a bit of code in their template, but I need this to be a real, accessible field I can use on the entity/node display, as well as in Views (sort, filter, etc). Additionally I would like a field for the last modified date.

How would I do this properly in Drupal?

We did create a bit of SQL that we ran in PHPMyAdmin (it was a one time script, we need to schedule it to be run daily), but I have a feeling I could be doing something in Drupal. Am I wrong?

# Answer
> 1 votes
You could use the Computed Field module to display the date on your page. Create a field and set the php code to display the date in readable format.

Call your field something like 'Date created' and enter code like the following under *Computed Code (PHP)*:

```
$entity_field[0]['value'] =date("Y/m/d",$entity->created);

```

Do not store the value in the database. You do not need to derive the value for views as the created date is available to views directly.

The last modified date is available as well as `$entity->changed`.

As an alternative, you might have a look at the Node Display Fields module, which has several widgets to display the type of information you are looking for.

# Answer
> 1 votes
The information is already in your database, so unless there is no other option, I wouldn't recommend to duplicate the data and store it again in another field.

Fortunately, there *is* another option, but it involves creating a custom module. If you're not a php coder, this may be over your head.

Drupal has a hook, hook\_field\_extra\_fields, which allows you to use data as a field even though it's not technically a field. Here is a tutorial how to use it: Adding fake Drupal 7 node fields with custom theme functions. It even uses your exact question as an example: taking the created date and rendering it as a field. With a bit of copy-paste and some adjustments, you should be able to do the same for the modified date. The tutorial also talks about theming, which is nice but not a necessity, so you can skip that part if you don't need it.

---
Tags: entities, datetime
---


# Question
Title: In Drupal Commerce, what is the difference from a product, product type, and product display?
I'm coming from ubercart and want to transition to drupal 7 commerce 1.x, but its very confusing on how this all relates to one another. First off I just want to clarify, what the difference from a product, product type, and product display?

I read a few online tutorials, but its not very clear on distinguishing how each one relates and how it is setup.

# Answer
Okay after reading a bit and messing around with the commerce module, its a bit more clear now. Don't even try to just read the documentation without clicking around and testing Drupal commerce as its very confusing if your not messing with the site. It's best to install just the Drupal Commerce module and not the Commerce Kickstart module so you can get a **CORE knowledge** of how it works from the ground up. Kickstart has too many other modules installed and will make it confusing of how thins are built.

Hopefully I can explain it a bit easier than the documentation. When starting out with Drupal Commerce and your coming from Ubercart, its good to know that there are no Options or Attributes as a configuration option as you have it in Ubercart. The idea of how Drupal Commerce was constructed was that **every** type of options within an attribute is its own product. (This is something I had to get my brain used to.)

Let's say I am selling T-shirts and I have SIZE and COLOR as an attribute. Now I have 5 difference sizes (X-Small, Small, Medium, Large, X-Large) and have 5 different COLORS (Red, Blue, White, Black, Green). YES, I know its a crap load of products to deal with compared to Ubercart which would have been only ONE and you just set attributes and options for it!

In Commerce, a product page is constructed in this way:

Product Type \> Product \> Product Display

**Product Type** You can think of Product Type as you creating a new Content Type under structure, but it just has its own section for it. Which is why this is called an Entity! Structure \> Content Type is a type of Entity. And Product Type is just another Entity. Hence the different page to set this up.

**Product** You create a product out of a product type. Same as if you create a new content type called "Basic Page", you would create a new page when you click on basic page under structre.

**Product Display** Now here's the tricky part to wrap your head around. When you create a product, there is no page where you can view it as its not a "DISPLAY". Its just a record in your site saying you have this product, but you cant view it. Now you create "PRODUCT DISPLAYS" via the regular structure menu as if you were creating a new content type. You can call it whatever. You know what, just use the default "Basic Page" and add a new field to it. That new field will have to be a type of **"Product Reference"**, which you select under the type option when you add new fields. Once you add a product reference option. Your BASIC PAGE is now considered a **"PRODUCT DISPLAY"**. When you first install commerce without anything else, you will have to make your own product display, so don't expect to see a product display option under structure. Once that is done, create a new BASIC PAGE and add a few products you already made and it will pop up with the add to cart forms and stuff.

I hope this was clear, if not let me know and I'll try to be a bit more precise.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Adding #ajax to checkboxes and getting selected values in callback
I've been trying to use #ajax callbacks on a form. I've got this working with radio buttons, so when I've debugged the form I get the value associated with the radio button as '#value' under 'triggering\_element' in $form\_state; what I'm struggling with is doing the same thing with a group of checkboxes. The first checkbox checked seems to work correctly, and I can see the correct value, but if I click a second checkbox, the value doesn't come through correctly (triggering element is the field that was returned in the previous #ajax callback for some reason??) and '#value' is a string and not an array as I would have expected. Also $form\_state\['#values'\] doesn't contain the previously selected checkbox or the current checkbox.

How do you correctly add #ajax to an element of type 'checkboxes' and how is it possible to get the value of all checked checkboxes when the ajax callback is fired?

# Answer
There is a module that can trigger an ajax callback on a form (content type) maybe that modules solves your issue http://drupal.org/project/conditional\_fields.
> -1 votes

# Answer
I hope this may help you. This example is from Drupal Example module which is creating checkboxes through ajax. Compare your code with it and hopefully will find the culprit.

Drupal Ajaxified Checkboxes example
> -1 votes

---
Tags: 7, ajax, forms
---


# Question
Title: How do I add the number of rows shown in a view to a menu link?
I want to add the number of rows shown in a view to a menu link, something as follows, for example.

> Companies(29) | Products(152) | Customers(522) | Orders(9888) ..

How can I achieve this?

# Answer
> 1 votes
You can do this with a view, assuming each item is a content type.

Create a new view of Content as an unformatted list of fields. Under 'Advanced' set Use Aggregation to Yes.

Under fields delete the title field, and add Content:Type and Content:NID.

Configure the Content:Type field as no label and "group by" under Aggregation Settings. Under 'Rewrite Results' check 'Output this field as a link', set it to replace spaces with dashes and to convert to lower case. In the path enter something like "list/\[type\]", depending on your desired target.

Configure the Content:NID field as no label, and add the prefic " (" and the suffix")". Set it to 'Count' under Aggregation Settings.

Use CSS to have both fields `float:left;` to line them up.

You can leave the view unsorted or sort by Content:NID-\>COUNT or by Content:Type. You should leave the filter for Published nodes, and you can add a filter to restrict the content types which will appear.

Then place the block where you want the menu to appear.

---
Tags: views, routes
---


# Question
Title: How to make a single query with multiple records
How do I make this as a single query?

```
$result = db_query("SELECT replace(source, 'node/', '') as source FROM {url_alias}  where source like 'node/%' limit 11");
foreach ($result as $record) {
$result2 = db_query("SELECT fci.* FROM {node} AS fci LEFT JOIN {node_access} AS fdfp ON fci.nid = fdfp.nid where fci.nid = :item_id AND fdfp.nid IS NULL", array(':item_id' => $record->source));
  foreach ($result2 as $record2) {
    echo '<pre>';
    print_r($record2);
  }
}

```

# Answer
> 0 votes
This works for me.

```
$result2 = db_query("SELECT fci.* FROM {node} AS fci LEFT JOIN {node_access} AS fdfp ON fci.nid = fdfp.nid where fci.nid IN(SELECT replace(source, 'node/', '') as source FROM {url_alias}  where source like 'node/%') AND fdfp.nid IS NULL");
foreach ($result2 as $record2) {
  echo '<pre>';
  print_r($record2);
}

```

# Answer
> 0 votes
Since you are not using any of the fields contained in the node\_access table, and you are making a `LEFT JOIN` with that table, you can avoid to join with that table. I would rather rewrite the query as follows, supposing that you want to get only the nodes with a path alias.

```
$result = db_query("SELECT n.* FROM {node} n INNER JOIN {url_alias} ua ON ua.source = CONCAT('node/', n.nid)");
foreach ($result as $record) {
  dpm($record->title);
}

```

If then you want to get all the nodes with a path alias to which the currently logged-in user has access, I would use the following code.

```
$query = db_select('node', 'n');
$query->fields('n');
$query->join('url_alias', 'ua', "ua.source = CONCAT('node/', n.nid)");
$query->addTag('node_access');
$result = $query->execute();
foreach ($result as $record) {
  dpm($record->title);
}

```

---
Tags: 7, database
---


# Question
Title: How do I set up PayPal parallel payments in Drupal 7 Commerce Express Checkout module?
After an exhaustive online search, I can't find an answer to my problem: where do I place the code snippets PayPal provides to implement PayPal parallel payments in Drupal 7's Express Checkout module? I went to this site to find the code snippets to paste into my site's code, but unfortunately, I can't figure out what file to paste the code snippets into in the Express Checkout module. I've read all of the instructions on PayPal, and being a relative beginner at Drupal (and a total beginner at PayPal), I can't figure out what to do next.

I am trying to allow users of my website to buy downloadable files provided by other users. When they do so, I want to take a small commission for posting their materials on my site. I understand that chained payments is also an option people use for this type of scenario, but considering my inexperience with PayPal, I think that parallel payments is the better of the two options.

In case it matters, I'm working in PayPal's sandbox mode. I've downloaded the paypalplatform.php file and I think I'm supposed to upload this to the main Express Checkout folder (but I'm not sure?), and I understand how to get my sandbox API credentials from PayPal, but I'm pretty much clueless from that point on.

The two specific snippets I'm having trouble with are these:

1.) The one in step 3a, where the instructions say "Insert this code snippet into the section of your code that initiates the preapproval flow on your website." What code initiates the preapproval flow? Is it contained in a file in the Express Checkout folder somewhere? In which file is it located, and specifically, where in the code should I paste the snippet provided by PayPal?

2.) The snippet provided in step 4c, where the instructions say "Insert this code snippet into the section of your code that initiates a PARALLEL PAYMENT on your website." Again, where is this code located? Is it in a file in the Express Checkout folder? In which file is it located, and specifically, where in the code should I paste the snippet?

Any help anyone can give me would be much appreciated. Thank you.

# Answer
The short answer is that there isn't just a place to "paste the snippet." That integration wizard is hopelessly simplistic. Support for a new payment method within Drupal Commerce would require more than simply adding code to a page, because presumably you'll want some sort of local record of any payment action taking place. For that to happen, you have to work with the Drupal / Drupal Commerce APIs as well.

In Drupal Commerce, these integrations are handled through payment method modules. We have documentation for writing them in the developer guide on DrupalCommerce.org. Additionally, if you're PayPal Express Checkout, you should switch to using the 2.x branch of the main PayPal project, http://drupal.org/project/commerce\_paypal, as it has a complete implementation of the Express Checkout payment method and has been verified by PayPal.
> 1 votes

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


# Question
Title: Display shipping subtotal including taxes
I'm settings up a shop with VAT and shipping. All works well except just one thing fails, when I include VAT in the shipping rate the price component displays the amount excluding taxes. But I want the full amount including taxes to be displayed. How can I achieve this?

# Answer
> 1 votes
This is happening because the "Order Total" process combines like price components together and then lists them out. As a result, the base shipping rate component is appearing unaltered and the VAT is being combined into any other product VAT (or shipping VAT) components. It's an unfortunate display side effect of the implementation of price components, but it's on the roadmap to be updated in Commerce 2.x.

In the meantime, your solution will involve implementing hook\_commerce\_price\_formatted\_components\_alter(), which you can find documented in commerce\_price.api.php. This is purely a display alteration, so all the necessary data will still be there unaltered - you can just fiddle with the display amounts of the price components so your VAT component gets added to your shipping component instead.

---
Tags: commerce
---


# Question
Title: Can I attach a jquery.ui.datepicker widget to a form element using the form api?
I have a generic form element:

```
$form['date'] = array(
    '#type' => 'textfield',
    '#title' => t( 'Date' ),
);

```

That I want to add the jquery ui datepicker to this element. Is there a way to do this through the form api, or do I have to add the following using drupal\_add\_js:

```
$('#edit-date').datepicker();

```

Or is there another, even better way?

# Answer
You can use after\_build in your form to call a function that contains drupal\_add\_js
> 4 votes

# Answer
The Date project contains a module (date\_popup.module) that implements a date\_popup form element. date\_popup.module for Drupal 6 defined the date\_popup\_load() function, but the function is not present in the version for Drupal 7 of the module, nor is it a Drupal core function.

What the function did was to include the necessary JavaScript files.

```
  $path = drupal_get_path('module', 'date_popup');
  if (module_exists('jquery_ui')) {
    jquery_ui_add('ui.datepicker');
    global $language;
    if ($language->language != 'en') {
      jquery_ui_add("i18n/ui.datepicker-{$language->language}");
    }
  }
  if (variable_get('date_popup_timepicker', 'default') == 'default') {
    drupal_add_js($path . '/lib/jquery.timeentry.pack.js');
  }

```

The equivalent function present in the Drupal 7 version of the module is date\_popup\_add(), which contains the following code.

```
drupal_add_library('system', 'ui.datepicker');
drupal_add_library('date_popup', 'timeentry');

// Add the wvega-timepicker library if it's available.
$wvega_path = date_popup_get_wvega_path();
if ($wvega_path) {
  drupal_add_js($wvega_path . '/jquery.timepicker.js');
  drupal_add_css($wvega_path . '/jquery.timepicker.css');
}

```

That function is called from date\_popup\_element\_process(), which is the #process function used from the date\_popup form field. You could write a #process function containing code similar to the one executed from that function, and attach it to the form field to which you want to add the date picker.
> 4 votes

# Answer
A much easier solution to this is to install the Date and Date Popup modules and use the following form api element to instantly get a date popup element. No extra js including needed.

```
$form['date'] = array(
  '#type' => 'date_popup',
  '#title' => t('Date'),
  '#date_format' => 'd/m/Y',
);

```

The #date\_format attribute accepts a PHP Date formatted string which is used as the input format for the date field.
> 4 votes

---
Tags: 7, forms, javascript
---


title: How do I get block content to show?

text:
# Question
Title: How do I get block content to show?
I have a custom module that I created. In it, I've implemented the `hook_block_view`:

```
function event_details_block_view($delta = '') {
$block = array();

switch($delta) {
    case 'event_details':
    $block['content'] = array(
    '#theme' => 'event_block_details',
    );
    break;
}

return $block;
}

```

I then have a file named `event-block-details.tpl.php` in my module folder. Right now, this is just some basic HTML to test whether or not the block is accepting the theme. When I go to my site however, I am able to see the block in the blocks tab and I can add it to a page, but none of the content displays.

Are there any suggestions as to what could be wrong? This is the first module I've written so I'm unsure where the errors can lie. I use Drupal 7.

# Answer
I think you should check this link for solving your problem : how-to-theme-a-custom-block-in-drupal-7. Actually you can search for that type of question around here.
> 1 votes

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


title: how to read csv file in drupal 6

text:
# Question
Title: how to read csv file in drupal 6
I want to read a simple csv file having 6 rows and 2 columns :

```
   **name   |  value**
    AJW097  |   1
    BDV763  |   1
    PVWC67  |   1
    WPC028  |   1
    TGI0227 |   1
    W5615C  |   1

```

I had saved this file here `sites/default/files/csvfile.csv`

here is the code i am using:

```
function my_module_form($form, &$form_state) {
$form = array();
  $form['browser'] = array(
    '#type' => 'fieldset',
    '#title' => t('Browser Upload'),
    '#collapsible' => TRUE,
    '#description' => t("Upload a CSV file."),
  );
  $file_size = t('Maximum file size: !size MB.', array('!size' => file_upload_max_size()));
  $form['browser']['upload_file'] = array(
    '#type' => 'file',
    '#title' => t('CSV File'),
    '#size' => 40,
    '#description' => t('Select the CSV file to be upload. ') . $file_size,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Upload CSV File'),
  );

  $form['#attributes']['enctype'] = "multipart/form-data";
  return $form;
}

function my_module_form_submit($form, &$form_state) {
  $filepath = $form_state['values']['upload_file']->filepath;
  $fp = fopen($filepath,'r') or die("can't open file");

print "<table>\n";

while($csv_line = fgetcsv($fp,1024)) {
    print '<tr>';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
        print '<td>'.$csv_line[$i].'</td>';
    }
    print "</tr>\n";
}
print '</table>';
fclose($fp) or die("can't close file");
}

```

The problem is it is not reading the file and every time i click on Upload CSV File button it dies and say: can't open file. where i am doing wrong?

# Answer
> 2 votes
try function form submit like:

```
function my_module_form_submit($form, &$form_state) {
  $line_max = variable_get('user_import_line_max', 1000);
  ini_set('auto_detect_line_endings', true);
  $filepath = $form_state['values']['file_upload']->filepath;
  $handle = @fopen($filepath, "r");
  // start count of imports for this upload
  $send_counter = 0;
  while ($row = fgetcsv($handle, $line_max, ',')) {
    // $row is an array of elements in each row
    // e.g. if the first column is the email address of the user, try something like
    $mail = $row[0];
  }
}

```

# Answer
> 2 votes
You can use different modules to read the data of .csv files into your database:

Feeds (Drupal 6 and 7) or Node Import (Drupal 6)

If you want to transform a .csv file into a table within a node you can use:

TableField (Drupal 6 and 7)

# Answer
> 1 votes
```
function my_module_form($form, $form_state) {

  #prepare the file upload form
  $form = array('#attributes' => array('enctype' => 'multipart/form-data'));

  #file selector element
  $form['csv'] = array(
      '#type' => 'file',
      '#title' => 'Upload users',
      '#description' => t('Pick a csv file to upload')
  );

  #submit button
  $form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Upload'
  );

   return $form;
}

#handle the form submission
function my_module_form_submit($form, &$form_state) {

  #this leads us to sites/mysite.example.com/files/
  $dir = file_directory_path();

  # unlike form submissions, multipart form submissions are not in
  # $form_state, but rather in $FILES, which requires more checking
  if(isset($_FILES) && !empty($_FILES) && $_FILES['files']['size']['csv'] != 0){

    #this structure is kind of wacky
    $name = $_FILES['files']['name']['csv'];

    $size = $_FILES['files']['size']['csv'];

    $type = $_FILES['files']['type']['csv'];

    #this is the actual place where we store the file
    $file = file_save_upload('csv', array() , $dir);
    if($file){
      drupal_set_message("You uploaded $name!");
      drupal_set_message("<pre>". print_r($name, true). "</pre>");
       drupal_set_message("<pre>". print_r($size, true). "</pre>");
        drupal_set_message("<pre>". print_r($type, true). "</pre>");
    }
    else{
        drupal_set_message("Something went wrong saving your file.");
    }
  }
  else {
    drupal_set_message("Your file doesn't appear to be here.");
  }
}

```

---
Tags: forms
---


# Question
Title: How do I programmatically change settings to simplify sharing of config changes?
I'm thinking specifically here of layout changes, such as:

* moving a block around, or
* when a new block is created and needs to be positioned, and shown or hidden on specific pages.

Currently, when somebody makes layout changes using the admin menus, we all have to go through the same process **by hand**. My issue with this is that it's time-consuming and error prone.

In an ideal world, I would love to have a system that is able to transfer someone's updated config changes to my local site.

Is this possible?

# Answer
At the risk of opening up a whole ugly can of worms on Drupal's current lack of config management, I am just going to point towards the D8 Configuration Management Initiative as the over-arching response to this.

To answer your more specific question about block/layout management, there are a few attempts at addressing this using Features/Features Extra:

Layout with Context or Panels or Display Suite

Better blocks with Boxes or Bean or Bricks
> 7 votes

# Answer
You can hardcode any variable (you know, from variable\_get()/-set()/-delete()) in your settings.php.

E.g, mentioned in that file, the "site name".

```
$conf['site_name'] = 'My Drupal site';

```

This only works for variables, so is of (very) limited use. As @nicoz mentions: a can of worms.

Places where I use this, though:

* A test.example.com/settings.php: $conf\['site\_name'\] = 'WARNING TEST ENVIRONMENT';
* Quick, custom modules. It saves you from developing settings-pages that will only be visited once while avoiding harcoded values inside that module.
* Different API-endpoints, keys, etc in various environments: You want to avoid hitting that production-payment-platform when developing on localhost. Or sending out 10.000 "W000t it works" mails to all your clients. :)

But for sharing with your co-workers this might be too limited.
> 2 votes

# Answer
I can recommend this session from DrupalCon London: Building and Maintaining a Distribution in Drupal 7 with Features.
> 1 votes

# Answer
This is an old question, so I'm posting an update: There's also a Drupal 7 version of the Configuration Management module.
> 1 votes

---
Tags: migrations, configuration
---


# Question
Title: Use mytheme_preprocess_block() to display HTML (icon fonts) in block titles
Unfortunately, HTML commands in block titles are not being rendered. I would like to be able to add icon font symbols to my block titles by adding comands like `<i class="icon-envelope"></i>` (this is Font Awesome syntax) to them WITHOUT installing yet another contrib module.

Is there a way to let HTML in block titles being rendered by adding a mytheme\_preprocess\_block() function to my template.php?

I came across a solution to let HTML commands in menu links being rendered by adding

```
function mytheme_link($variables) {
    $variables['options']['html'] = TRUE;
    return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}
```
to my template.php but haven't managed to modify the code for block titles.

# Answer
In preprocess\_block() function you can only define the title prefix and suffix for each title.

**For example:**

```
/**
 * Override or insert variables into the block template.
 */
function YOURTHEME_preprocess_block(&$variables) {

  $variables['title_prefix'] = array(
    '#type' => 'markup',
    '#markup' => '<i class="icon-envelope">',
  );
  $variables['title_suffix'] = array(
    '#type' => 'markup',
    '#markup' => '</i>',
  );

}

```
> 1 votes

# Answer
In some themes, such as Zen, The block title gets turned into the block "subject" (a variable that is ran through Drupal check\_plain() function) in the process function. You want to override the process function, and NOT the preprocess function.

```
function mytheme_process_block(&$variables, $hook) {
  $block = $variables['block'];
  if (isset($block->title) && strlen($block->title) > 0) {
    $variables['title'] = $block->title;
  }
}

```
> 0 votes

---
Tags: blocks, theming, input-formats
---


# Question
Title: Add a caption to an image field that allows multiple images
OK, the heading isn't the best example of english ever, but I hope you get what I mean...

I've run up against the bug in Drupal where it doesn;t check the length of the title value in an image field (http://drupal.org/node/916446) and I was using that field to store the caption for the image which I was displaying in a div underneath the image.

Is there a way to either allow the title field to hold more information, or even better (semantically especially), create an additional field to hold my caption information?

The reason I don't just create a separate field for caption is that I'm allowing multiple images on the image field and from a content management point of view, I wouldn't easily be able to match up the images to their captions.

I'm sure it's something simple like creating a version of the image.field.inc? Has anyone done it or know how to make this happen?

# Answer
> 2 votes
I believe what you are looking for is the Field Collection module. It allows you to group fields together and repeat the group many times. The following article gives a good description of what the module does: Create Multigroups in Drupal 7 using Field Collections

From the Field Collection project page:

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

# Answer
> 2 votes
The Image Field Caption module for Drupal 7 will add an extra text area on image fields that can be used to enter a caption of plain text or html for each image field's description.

The caption will be rendered below each image on the node display. If you need to customize the display, just take a copy of the image\_field\_caption.tpl.php file and place it in your theme's directory, then modify the html for your needs:

```
sites/all/themes/MY_THEME/image_field_caption.tpl.php

```

In the past I've used the awesome Field Collection module, but it may be a bit heavy when you just need a description/caption on an image field, and that's where the Image Field Caption module comes into play nicely.

# Answer
> 0 votes
Revisiting this question after it's been out here for a year, I believe the best possible solution is to not use an image field at all and to use a file field with the Media module instead.

This provides several benefits:

* Your images become entities - much easier to search, filter, find and use your images.
* You can add custom fields to your image entity such as a caption as in the original question, or even more specific things like copyright information, photographer credits, tagging and more.
* For those that don't like tinkering with templates and don't need to do anything too fancy, you also avoid having to create any custom templates because it's all configurable in the UI, just like a content type.

I'd also recommend persevering with Version 2 of the Media module too. It's got a lot going for it. The only exception being high traffic or rock-solid-stable sites. You should probably stick to the version 1 branch.

---
Tags: entities, media
---


# Question
Title: Migrate to data field with multiple values
I'm trying to use the migrate module to create products. My issue is that I need to map data to a field that contains multiple values.

This is the exact case.

Product A has 3 prices,

1. Stand Price
2. Price for x to y qty
3. Price for x yo -1 (unlimited)

Using the commerce price tables module this has created the field data table with 3 fields, price, min\_qty, max\_qty.

Is it possible to map data to a field that contains multiple columns(values) with the migrate module?

Also the data is coming from another database.

I have not had any success using the addFieldMapping() function in the migrate module.

Regards, Nathan.

# Answer
I've worked it out. Migrate can handle multiple values but due to the commerce price table having its own field type of 'commerce\_price\_table' I've needed to create a field handler for this field type.

Mapping is done like this in the migration class:(machine name for this field is field\_volume\_price)

```
$this->addFieldMapping('field_volume_price', volume_price);
$this->addFieldMapping('field_volume_price:currency_code',volume_price_min_qty);
$this->addFieldMapping('field_volume_price:min_qty',volume_price_max_qty);
$this->addFieldMapping('field_volume_price:max_qty',volume_price_currency_code');

```

Due to these fields holding arrays of data we need to create these in the prepareRow function in the migration class:

```
function prepareRow($row)  {
    foreach($row->product['volume_prices'] as $volume_price) {
        $row->volume_price[] = $volume_price['price'];
        $row->volume_price_currency_code[] = $row->product['currency'];
        $row->volume_price_min_qty[] = $volume_price['minimumQuantity'];
        $row->volume_price_max_qty[] = '';//this is unknown in our data, this is set in the handler
    }
}

```

If anyone is interested I've attached the handler. Also due to our set of data not containing the max qty value we had to work this out and set this in the arguments.(remove the loop if its set)

```
class ProductVolumePriceFieldHandler extends MigrateFieldHandler {
  public function __construct() {
    $this->registerTypes(array('commerce_price_table'));
  }

  public function fields($type) {
    // Declare our arguments to also be available as subfields.
    $fields = array(
      'currency_code'   => t('Subfield: Currency code for the field'),
      'min_qty'         => t('Subfield: Min Qty for the field'),
      'max_qty'         => t('Subfield: Max Qty for the field'),
    );
    return $fields;
  }

  public function prepare($entity, array $field_info, array $instance, array $values) {
    $migration = Migration::currentMigration();
    if (isset($values['arguments'])) {
      $arguments = $values['arguments'];
      unset($values['arguments']);
    }
    else {
      $arguments = array();
    }

    $language = $this->getFieldLanguage($entity, $field_info, $arguments);
    //we need to set the max value because the our data does not provide this
    if(isset($arguments['min_qty']) && !is_null($arguments['min_qty'])) {
        $minimumQuantity = $arguments['min_qty'];
        sort($minimumQuantity,SORT_NUMERIC);
        //create the max value of the ranges, eg:
        //min qty: 1,3,5,20
        //1-2,3-4,5-19,20--1

        //reconstruct the arguments array with qtys in order
        //$index becomes the new delta
        foreach($minimumQuantity as $index => $min){
            $args['currency_code'][$index]   = $arguments['currency_code'][array_search($min,$arguments['min_qty'])];
            $args['min_qty'][$index]         = $arguments['min_qty'][array_search($min,$arguments['min_qty'])];
            $args['max_qty'][$index]         = isset($minimumQuantity[$index+1])?$minimumQuantity[$index+1]-1:-1;
        }
        if(isset($args)){
            //set arguments array for new ording
            $arguments = $args;
        }
    }

    $delta = 0;
    foreach ($values as $value) {
        if(!is_null($value)) {
            $return[$language][$delta] = array('amount' => ($value * 100));
            if (isset($arguments['currency_code'])) {
                if (is_array($arguments['currency_code'])) {
                    $return[$language][$delta]['currency_code'] = $arguments['currency_code'][$delta];
                } else {
                    $return[$language][$delta]['currency_code'] = $arguments['currency_code'];
                }
            }
            if (isset($arguments['min_qty'])) {
                if (is_array($arguments['min_qty'])) {
                    $return[$language][$delta]['min_qty'] = $arguments['min_qty'][$delta];
                }else {
                    $return[$language][$delta]['min_qty'] = $arguments['min_qty'];
                }
            }
            if (isset($arguments['max_qty'])) {
                if (is_array($arguments['max_qty'])) {
                    $return[$language][$delta]['max_qty'] = $arguments['max_qty'][$delta];
                }else {
                    $return[$language][$delta]['max_qty'] = $arguments['max_qty'];
                }
            }
        }
        $delta++;
    }

    return isset($return) ? $return : NULL;

  }
}

```
> 2 votes

---
Tags: entities, migrations, commerce
---


# Question
Title: Translate Drupal's built-in English to another kind of English
I need to translate the American English Drupal core currently provides out of the box to a variation of English. I know I can use string overrides but there are too many that I need to override. Essentially I need to create my own custom language based off english. Suggestions?

# Answer
> 3 votes
You can do this with the Locale module, which is provided by core. Steps are for Drupal 7. This assumes you want to completely replace the built-in English with your own custom version of English (which will still show the strings for the built-in English unless you have translated/edited them).

1. Enable the locale module.
2. Go to languages admin (/admin/config/regional/language).
3. Click *edit* for the English (built-in) language. Add *en* as the **Path prefix** (this will allow you to add your own language without a path prefix.) Save.
4. Click "Add a language"
5. Choose "Custom language", set a language code, set both language names to *English*, leave **Path prefix** and **Language domain** blank, and choose *Left to right* for the **Direction**.
6. Go back to the language list (/admin/config/regional/language) and set your new English as the default language. Then uncheck *Enabled* for the built-in English.
7. Translate all the strings you want to modify on the translation screen (/admin/config/regional/translate/translate).

# Answer
> 2 votes
The Drupal core locale module is all you need to do this. Enable it if required, then navigate to `Home » Administration » Configuration » Regional and language`and notice the two tabs "Export" and "Import".

These allow you to export and import `.po` files with translations from the default (American English) into your default language. `.po`-fils are text files. The format is very simple and consists of pairs like these (the line starting with "#" is a comment):

```
#: src/colors.inc:36
msgid "color"
msgstr "colour"

```

So just export all the strings of your site, then translate those that needs translation, and import.

(You may want to create a custom language code for your custom english, just to be able to toggle between American english and custom english, instead of just overrwriting the American english.)

---
Tags: i18n-l10n
---


# Question
Title: I want to add user points whenever user like the page for Facebook. How can I do this?
After sharing or like a page on Facebook I want to add userpoints in Drupal 7, how can I do this?

# Answer
First, you need to have your users login to your site using Facebook API. There are many modules for it, two I know and seen used are:

That's the only real way to know "he" on Facebook is "he" on your site.

Then, Facebook will not push it's data to you. So you have 2 cases:

* Button "like this page on Facebook" on your page - you can detect it being clicked and make a rule for it, as Patrick Kenny told in his comment.
* Like clicked directly on Facebook - now that's hard. It was discussed on stackoverflow with some apparently good results, and there are tutorials avaliable.

Last but not least - you need to make sure you grant this bonus only once. If not, users could fabricate points by simply repeatedly liking-unliking your page.
> 1 votes

---
Tags: userpoints
---


# Question
Title: Disabling authoring information in Omega 3.x does not work from content type; how can I disable it?
I see no way of successfully disabling, through the user interface, the author information, wheb using an Omega 3.x sub-theme. The standard method of disabling it from the content type settings is not functional.

So is my only option to use a theme suggestion?

# Answer
Don't know how exactly it looks in your Omega theme, but in Zen you just remove/change the following snippet in templates/node.tpl.php (or templates/node--content\_type.tpl.php):

```
<?php if ($display_submitted): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```

In Bartik it's equivalent would be:

```
<?php if ($display_submitted): ?>
  <div class="meta submitted">
    <?php print $user_picture; ?>
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```
> 0 votes

# Answer
Well in omega you can still disable author and date in your content-type settings, but what if you only want to disable one portion of it? for example just the author name? go ahead and copy **node.tpl.php** from omega \> templates folder into your subtheme folder then find this part:

```
      <?php if ($display_submitted): ?>
       <footer class="submitted"><?php print $date; ?> -- <?php print $name; ?>   </footer>
      <?php endif; ?>

```

as you can see in omega unlike other themes it renders as two different variables: $date and $name . so you can delete `<?php print $name; ?>` or `<?php print $date; ?>`

make sure after copying **node.tpl.php** empty your cache.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: html5-respond.js not rendering CSS3 properties in IE7 and IE8
I am working on a drupal 7 website. I am using the zen theme as starter theme. But the html5-respond.js not functioning properly.

I have added border radius property for the boxes, but its not rendering in IE7,IE8. But the js is there and its calling properly.

Please advise me.

```
!DOCTYPE html>
<!--[if IEMobile 7]><html class="iem7"  lang="en" dir="ltr"><![endif]-->
<!--[if lte IE 6]><html class="lt-ie9 lt-ie8 lt-ie7"  lang="en" dir="ltr"><![endif]-->
<!--[if (IE 7)&(!IEMobile)]><html class="lt-ie9 lt-ie8"  lang="en" dir="ltr"><![endif]-->
<!--[if IE 8]><html class="lt-ie9"  lang="en" dir="ltr"><![endif]-->
<!--[if (gte IE 9)|(gt IEMobile 7)]><!--><html  lang="en" dir="ltr"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:dc="http://purl.org/dc/terms/"
  xmlns:foaf="http://xmlns.com/foaf/0.1/"
  xmlns:og="http://ogp.me/ns#"
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
  xmlns:sioc="http://rdfs.org/sioc/ns#"
  xmlns:sioct="http://rdfs.org/sioc/types#"
  xmlns:skos="http://www.w3.org/2004/02/skos/core#"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema#"><!--<![endif]-->

<head profile="http://www.w3.org/1999/xhtml/vocab">
  <meta charset="utf-8" />
<meta about="/files/clients/etihad/en/index" property="sioc:num_replies" content="0" datatype="xsd:integer" />

............

<!--[if lt IE 9]>
    <script src="html5-respond.js"></script>
    <![endif]-->

```

# Answer
> 1 votes
IE8 doesn't work on @import'ed stylesheets. but you can write query by this way

```
@ Media screen and (min-width: 980px)
{

  / * CSS Document * /

}

```

and also you must include css3-mediaqueries js

```
<! - Css3-mediaqueries.js for IE less than 9 ->
 <! - [If lt IE 9]>
 <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"> </ script>
 <! [Endif] ->

```

see this http://westilian.com/ie7-and-ie8-support-for-css3-media-query/

---
Tags: 7, theming
---


# Question
Title: How to write custom Form API elements for Drupal 7?
In context of this question I wanted to ask - how to provide custom controls to use with Form API? Especially ones that needs to be exploded into javascript and at least one additional hidden field to make their GUI work.

I can find manuals for Drupal 6 easily enough, but somehow I can't spot ones for 7. I know I need to start with hook\_element\_info(), but hook's description for Drupal 7 points to a manual for Drupal 6.

Could anyone provide step-by-step instruction how to make it work?

# Answer
Searching Google for "hook\_element\_info tutorial" brings up Create custom Form API elements with hook\_element\_info() in Drupal 7.

There is also the Examples for Developers project, which is included in the documentation at http://api.drupal.org. The Form API Example module implements hook\_element\_info() and contains a number of example elements in the form\_example\_elements.inc file.
> 3 votes

# Answer
Look at Examples project. Especially check form\_example module. I think this is the best source of knowledge about practical use Form API.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: call to undefined function fatal error - weird problem
I have a custom module which calls a custom function. I created this function longback working fine till yesterday. today it says call to undefined function fatal error. Does anyone know what the reason could be. I tried all the possibility to make it work, but it crashes! using drupal 7 , php 5.2

# Answer
> 2 votes
The reasons maybe:

1. Either the module is disabled.
2. Typo error in the function call.
3. The module has been removed.

---
Tags: routes
---


title: Views Custom Condition Error

text:
# Question
Title: Views Custom Condition Error
I got the error

> Fatal error: Class 'RulesEventSet' not found.

I got this error on installing the views\_custom\_conditions module module.

Please let me know the cause of this error as I Googled but didn't find the solution.

# Answer
Here is a patch that should fix your problem. Comment #10
> 0 votes

---
Tags: views
---


# Question
Title: SQL query the Drupal way, complex SELECT, conditional aggregate
I'm starting to invest time in learning custom Drupal entities like the ones explained here and I want to make sure that I am going to be able to do something in the future.

I am working with Drupal 7 with MySQL and have the entities API. Being tied to MySQL is okay.

Is it possible to perform a query like the one listed below in Drupal? If not, can I access a MySQL database view?

```
 select
        `listProducts`.`productId` AS `productId`,

        group_concat(if((`listProducts`.`className` = 'manufacturer'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `manufacturer`,

        group_concat(if((`listProducts`.`className` = 'model'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `model`,

        group_concat(if((`listProducts`.`className` = 'sub model'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `sub model`,

         group_concat(if((`listProducts`.`className` = 'year'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `year`
    from
        `hqr`.`listProducts`
    group by `listProducts`.`productId`

```

It's sort of an intense select statement. The data I'm working with is in the form

```
productId  className      optionValue
---------------------------------------
1          manufacturer   abcCompany
1          model          aModel
2          manufacturer   xyzCompany
2          year           2005

```

and should come out like

```
productId  manufacturer  model  sub model  year
-------------------------------------------------
1          abcCompany    aModel    -        -
2          xyzCompany      -       -       2005

```

Is doing this possible using the Drupal tools? If so, knowing how would be a big bonus too. Somewhere in my travels I saw a Drupal patch to enable group\_concat in Drupal views (if that changes anything).

# Answer
Drupal does not provide database transposition, unfortunately. It's database access system is pretty good at filtering, joining and reordering the data, but not at restructuring them.

There are many patches and hacks for specific task, but none was general enough and needed enough to be accepted into core or views so far.

Your safest bet is to define a view, and then access it just like any other table. Drupal sees no difference as long as you don't write (and if you want to play, you could make MySQL to accept writes, too).
> 1 votes

# Answer
Yes you can easily reproduce that query using Drupal's DB API. In fact you run pretty much any valid MySQL query through that API; the only type I've had problems with in the past is `LOAD DATA INFILE`.

The key is the `SelectQuery::addExpression()` method, which allows you to inject arbitrary expressions into the query. For example:

```
$query = db_select('listProducts')->groupBy('listProducts.productId');

foreach (array('manufacturer', 'model', 'sub model', 'year') as $field_name) {
  $sql = "group_concat(if((listProducts.className = '$field_name'), listProducts.optionValue, '') separator '')";
  $query->addExpression($sql, $field_name);
}

$results = $query->execute();

```

That produces:

```
SELECT
  group_concat(if((listProducts.className = 'manufacturer'), listProducts.optionValue, '') separator '') AS manufacturer,
  group_concat(if((listProducts.className = 'model'), listProducts.optionValue, '') separator '') AS model,
  group_concat(if((listProducts.className = 'sub model'), listProducts.optionValue, '') separator '') AS submodel,
  group_concat(if((listProducts.className = 'year'), listProducts.optionValue, '') separator '') AS year
FROM {listProducts} listProducts
GROUP BY listProducts.productId

```
> 0 votes

---
Tags: entities, database
---


# Question
Title: How to insert html inside form element div
I want to enhance the login form fields with icons from Font Awesome. For this I need to add some html inside the div of the name and pass fields (to be able to position accurately with css). The html part is for example something like

```
<i class="icon-lock icon-large"></i>

```

I tried using #suffix with hook\_form\_alter, but then the html is added after the div. I also tried with a user-login.tpl.php, but it seems you can only render individual form elements with drupal\_render, for example drupal\_render($form\['name'\]); But this also outputs the entire div.

What I want to end up with is something like this:

```
<div class="form-item form-type-password form-item-pass">
  <input id="edit-pass" class="form-text required" type="password" maxlength="128" size="60" name="pass" placeholder="Password">
  <i class="icon-lock icon-large"></i>
</div>

```

I'm using Drupal 7.

# Answer
> 11 votes
**Assuming you don't need the input wrapper. Just remove it:**

```
$form['pass'] = array(
        '#type'             => 'password',
        '#title_display'    => 'none',
        '#maxlength'        => 128,
        '#size'             => 60,
        '#required'         => TRUE,
        '#theme_wrappers'   => array(), // remove the wrapper
        '#prefix'           => '',
        '#suffix'           => '<i class="icon-lock icon-large"></i>',
        '#attributes'       => array(
                                'placeholder'   => t('Password')
                            ),
        );

```

the icon will be placed after the input:

```
<input type="password" maxlength="128" size="60" name="pass" id="edit-pass" placeholder="Password" class="inputbox form-text required">
<i class="icon-lock icon-large"></i>

```

**But if you need that div wrapper, you can just rearrange his position:**

```
$form['pass'] = array(
        '#type'             => 'password',
        '#title_display'    => 'none',
        '#maxlength'        => 128,
        '#size'             => 60,
        '#required'         => TRUE,
        '#theme_wrappers'   => array(), // remove the wrapper
        '#prefix'           => '<div class="form-item form-type-password form-item-pass">',
        '#suffix'           => '<i class="icon-lock icon-large"></i></div>',
        '#attributes'       => array(
                                'placeholder'   => t('Password')
                            ),
        );

```

Now the output will be exactly as you wrote:

```
<div class="form-item form-type-password form-item-pass">
    <input type="password" maxlength="128" size="60" name="pass" id="edit-pass" placeholder="Password" class="form-text required">
    <i class="icon-lock icon-large"></i>
</div>

```

---
Tags: 7, forms
---


# Question
Title: is there a safe way to convert a pressflow website to drupal 6?
I have a website that was built on Pressflow, and the client wants to upgrade it to Drupal 7.

Is there a way to convert Pressflow to Drupal 6?

# Answer
> 1 votes
Pressflow and Drupal are API compatible, so you can simply replace Pressflow with the equivalent version of Drupal core. The only snag may come if someone has used private Pressflow functions in their module code on the site - but this is highly unlikely.

To upgrade, you can follow the normal upgrade path, which is to go to the highest version of Pressflow first, then upgrade to Drupal 7 or Pressflow 7.

# Answer
> 0 votes
You can also give www.getpantheon.com a try, install a test Drupal 7 site and import your DB and code to safely test things out before going live with migration.

# Answer
> 0 votes
I unzipped D6 over Pressflow6 on our quite large site. Nothing bad happened. :)

---
Tags: 6
---


title: Tracking outbound Google Adsense clicks

text:
# Question
Title: Tracking outbound Google Adsense clicks
I would like to be able to track how many clicks are done on Google adsense ads from each node of my site. The purpose of doing so is to be able to do revenue sharing with the authors of each article that will be published.

This module may seem to be useful: http://drupal.org/project/adsense

Except that it says "Click Tracking: tries to track clicks on the displayed ads, **usually failing to do so.**"

Are there any alternatives?

Thanks in advance for your answers.

# Answer
> 2 votes
The problem is links are generated by Google. I assume Google tools does not suffice, and you can't generate report of enough quality using Google Analytics - if you could, you wouldn't ask here.

You cannot alter links. If what you display is not what Google provided, you are not getting any money. So the only sure way - generate link like http://example.org/count\_ad\_click/123dwe324), record click and redirect user - is closed for you.

You could cover ads with transparent link to your counting address, to avoid altering the real one. That counts as click hijacking and can hurt your reputation, badly. Browsers can start to display "possible malware" alerts, SEO position will drown and so on. Oh, and of course no money.

You still can use jQuery to append onclick to those links, and either push events to Analytics or to your own counting mechanism. Both are prone to manipulation, as they happen on a client side and user can fake those clicks all he wants, so you can get any number of false positives. On the other hand, if your reader will have javascript turned off, it will not count him at all, and some anty-hijacking plugins can prevent click count, too. Last but not least, that's the way AdSense module works now, anyway.

---
Tags: nodes, advertising
---


# Question
Title: Does View UI restrict fields based on filters, etc
In the Views UI, are the fields that you can add restricted by whats possible due to the filters, contextual filters, relationships etc? Eg if I set a filter to node type A, will the ui allow me to add fields that only exist in node type B?

# Answer
> 0 votes
In Views 3 in Drupal 6, the UI does not enforce any restriction of fields. (And it does tell you what content type(s) the field exists when you want to select one). About the only restriction I can think of is the initial View type, eg, a node View restricts you to nodes, taxonomy restricts you to terms, users to users, etc.

---
Tags: views
---


title: Access control in group based forums

text:
# Question
Title: Access control in group based forums
On my websites I have forums that mirror the structure of og-based groups. I am using advanced forums, OG Forum D7 and a decent amount of custom code.

My problem is to restrict access/visibility to forums based on the og role. While I know how to do it with forum topics which are stored as nodes, I have problems with forums which under a hood are taxonomy terms.

I am looking for a place where I can hook the code restricting visibility of a taxonomy term.

```
function mymodule_taxonomy_access($taxonomyterm, $op, $account) {
    if( $op == 'view' )
        $gid = get_grop_from_term($taxonomyterm);
        if( user_has_forum_access($gid, $account))
                return ACCESS_ALLOW;
        //else
        return ACCESS_DENY;
    }
}

```

I have no idea in which module I should look for the right hook: taxonomy, forum, forum\_access, core (I think that taxonomy terms are entities)?

Taxonomy Access Control while being very powerful, provides no connection with organic groups.

UPDATE I have found that TCL Lite is using the hook\_query\_TAG\_alter to hide taxonomy terms. The hook is editing all queries made to the database and is effectively filtering the taxonomy\_terms that any query can see. This looks like an awfully heavy solution.

Can anyone suggest a better approach?

# Answer
> 0 votes
After a small fight I managed to have it solved. There are few issues to have in mind like caching or preventing infinite recursion (you don't want to change the queries that you use inside the query altering function).

The code is based on TAC module.

```
function mymodule_query_term_access_alter($query) {
    static $mymodule_recursion_flag = FALSE;

    //prevent infinite recursion altering db_queries inside of this function
    if($mymodule_recursion_flag) return;

    // Take no action if there is no term table in the query.
    $alias = '';
    $tables =& $query->getTables();
    foreach ($tables as $i => $table) {
        if (strpos($table['table'], 'taxonomy_term_') === 0) {
            $alias = $table['alias'];
        }
    }
    if (empty($alias)) {
        return;
    }

    //store once obtained results
    static $mymodule_tids = null;
    if($mymodule_tids == null){
        //set the recursion flag
        $mymodule_recursion_flag = TRUE;
        // Fetch a list of all terms the user should not see
        $mymodule_tids = mymodule_get_taxonomy_black_list();
        //unset the recursion flag
        $mymodule_recursion_flag = FALSE;
    }
    // No restrictions - user can list all terms
    if (empty($mymodule_tids)) {
        return;
    }
    // Otherwise, filter the terms
    else {
        $query->condition($alias . ".tid", $mymodule_tids, "NOT IN");
    }
}

```

---
Tags: organic-groups, taxonomy-terms, nodes
---


title: Getting $head_title in my module

text:
# Question
Title: Getting $head_title in my module
I am building a module that requires me to get the $head\_title variable in the hook\_node\_view for some processing...I have found info about that variable in relation to themes and around core, but not getting it in a module...I have successfully used drupal\_get\_title(), and variable\_get() to get info, but I can not figure out how to get $head\_title...

Any help?

# Answer
`$head_title` is one of the variables passed to the html.tpl.php template file, and set from template\_preprocess\_html().

```
  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }
  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);

```

That variable would be available as `$variables['head_title']`, if your module implements `hook_preprocess_html()` or `hook_process_html()`. Otherwise, you just need to execute similar code to the one used by template\_preprocess\_html(). To adapt that code for a module, outside `hook_preprocess_html()` and `hook_process_html()`, I would rewrite it as follows.

```
  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }

  // Remove the following line if you just need the string.
  $head_title_array = $head_title;

  $head_title = implode(' | ', $head_title);

```
> 0 votes

---
Tags: hooks
---


# Question
Title: I would like to be able to trap when a particular message is sent via drupal_set_message
I would like to be able to trap when a particular message is sent via drupal\_set\_message like: "•Article john mitchell article800 **has been reverted back to the revision from** Tue, 05/28/2013 - 10:03." After the message is sent that matches my criteria then I would like to send an email. I know how to send emails within hooks/php but I need to know how to trap for a particular message so that I know to send this email. Are their any hooks that could use to trap for this occurrence?

# Answer
In Drupal 6, messages are themed for display via...

```
function theme_status_messages($display = NULL) {
  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "<div class=\"messages $type\">\n";
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>'. $message ."</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }
  return $output;
}

```

In Drupal 7, they are themed similarly via...

```
function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "<div class=\"messages $type\">\n";
    if (!empty($status_heading[$type])) {
      $output .= '<h2 class="element-invisible">' . $status_heading[$type] . "</h2>\n";
    }
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>' . $message . "</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }
  return $output;
}

```

so I'd imagine copying the appropriate function into your theme's template.php and naming it YOURTHEME\_status\_messages(...) along with some suitable regexing or strposing inside would do the trick pretty directly.
> 1 votes

---
Tags: hooks
---


# Question
Title: Drupal site moved from development to live - IE won't load stylesheets anymore
Before you ask ... I have looked everywhere for a solution, even drupal.org but nothing so far seems to work.

I developed a Drupal site (custom child theme for Zen) and on the development server everything looks fine in all browsers.

I did a test migration to another server before the launch. This move went well and everything looks fine in all browsers.

Then I moved the site to its live server where everything looks fine in all browsers except Internet Explorer which is not loading the stylesheets.

I know Drupal is known for generating many stylesheets and Internet Explorer will not load them if there are more than 31 (I believe) of them, but I did set the "Aggregate and compress CSS files" feature and clear the cache. This did not seem to help.

Could the answer be in one of the two following things?

1. The development site and backup site are both with one hosting provider. The live site is with a different hosting provider.
2. The development site and backup site are in subfolders of two different portfolio sites ... ie www.portfoliosite.com/Newsite. The live site is a subdomain of the parent site ... ie www.newsite.parentsite.com.

I have run out of ideas so if anyone has a possible solution or direction to look, please let me know. Thanks

# Answer
> 0 votes
I would start by checking two things:

1. Is there a difference in settings for caching and/or CSS aggregation on live vs. dev?
2. Have you tried clearing the cache via the button in the UI? Doing it from drush does not clear the CSS caches, and it also has some other behavior that's different from the UI button way.

---
Tags: theming
---


# Question
Title: Display content with Taxonomy on User and Content matching
I've got a specific content type. One field is a term reference field called "blog subject" in which a content author tags the node.

Ok. Moving on to the end user. I added the same term reference field to user account settings in which a user can select certain terms that they're interested in.

I would like to create a view in which the contextual filter is the user. By going to www.whatever.com/blogs/12, I can see content that matches the users selected interests.

Thoughts?

# Answer
Create a view showing users, and use a contextual filter on `User:UID`, and set 'Provide default value' the the 'Currently logged in user'.

You then should create two Relationships. The first on `User:blog_subject` will relate the user to the taxonomy terms. The second, using the first, will be on `Taxonomy Term: Content using Blog Subject` which will then relate the term to the content. Both relationships should be '*Required*'.

Once the relationships are in place, delete the '*User Name*' field that is a default for the type of view you created, and add the `Content:Title` field displayed as a link to content. Add filters like `Content:Published` to eliminate un-published content and a sort by, for example, `Content:Post Date (desc)`. All of these fields will be using the relationships. Make sure you delete all the `User:...` filters and sorts.

With multiple terms possible, this may create duplicate rows. There are two approaches you can use. The simplest is to go to *Advanced \> Other* and configure the *Query Settings* to '*Distinct*'. This might work. The other is to list the term and Set the view to Group By the term. That way you will get a list of pages that conform to each subject. If a page appears multiple times, it will do so under separate subject lists.

This should show a list of content matching the interests of the current user.
> 3 votes

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


# Question
Title: How do I unset hook_field_storage_load()?
I'm trying to unset `hook_field_storage_load()` and `hook_field_storage_write()` in `hook_module_implements_alter()` without success. Is there any other way to turn off those hooks?

# Answer
**TL;DR** `hook_module_implements_alter()` is not invoked when `mongodb_field_storage_field_storage_load()` is needed. You cannot achieve what you are trying.

The function that invokes `hook_field_storage_load()` is field\_attach\_load(), which contains the following code.

```
// Invoke hook_field_storage_load() on the relevant storage backends.
foreach ($storages as $storage => $fields) {
  $storage_info = field_info_storage_types($storage);
  module_invoke($storage_info['module'], 'field_storage_load', $entity_type, $queried_entities, $age, $fields, $options);
}

```

module\_invoke() calls module\_hook(), which contains the following code.

```
  $function = $module . '_' . $hook;
  if (function_exists($function)) {
    return TRUE;
  }
  // A
  // If the hook implementation does not exist, check whether it may live in an
  // optional include file registered via hook_hook_info().
  $hook_info = module_hook_info();
  if (isset($hook_info[$hook]['group'])) {
    module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
    if (function_exists($function)) {
      return TRUE;
    }
  }

```

Since mongodb\_field\_storage\_field\_storage\_load() is contained in mongodb\_field\_storage.module, your implementation of `hook_module_implements_alter()` will not be called. In fact `function_exists($function)` returns `TRUE` when `$function` is equal to `'mongodb_field_storage_field_storage_load'`, and the part of the code after the line marked with `// A` will not be executed.
> 2 votes

---
Tags: hooks
---


# Question
Title: How can I check if an image style for an image has been created already?
Is there a function I can use to check if a particular image style for a given image has been created already?

# Answer
I couldn't find one in the core files but fortunately it's pretty straightforward to implement:

```
function image_style_path_exists($style_name, $path) {
  $uri = image_style_path($style_name, $path);
  return file_exists($uri);
}

```

Assuming you have a file object you would call it like this:

```
$image_exists = image_style_path_exists('thumbnail', $file->uri);

```

If you only need to use it once in the site you could boil it down to:

```
$image_exists = file_exists(image_style_path('thumbnail', $file->uri));

```

but it's usually better to separate this sort of thing out into a function
> 4 votes

# Answer
I know that this question has been answered but it doesn't seem that the answer handles image styles that have yet to be generated.

The following function tries to load an image style, which is independent of file generation. Then it checks to see if the file has been created, if it hasn't then we kick off the generating the actual image style image.

This hasn't been fully tested but initial tests seem to work nicely.

```
// $style = image style name
// $src = file URI
function _helper_image_style_exists($style, $src) {
  $image_style = image_style_load($style, $src);

  if(empty($image_style)) {
    return false;
  }

  //Check if image style image has been created yet
  $dest = image_style_path($style, $src);
  if(!file_exists($dest)) {
    // Create image from image style
    image_style_create_derivative($image_style, $src, $dest);
  }

  return $dest;
}

```
> 3 votes

---
Tags: 7, media
---


# Question
Title: Apply grouping to custom views list template
I have a custom `views-view-list.tpl.php` template that uses

```
foreach ($view->style_plugin->rendered_fields as $delta => $item)

```

to manipulate the fields at this template level rather than using

```
foreach ($rows as $id => $row)

```

and relying on `views-view-fields.tpl.php` to render the HTML.

However, when using grouping in a view, the `views-view-list.tpl.php` is called once for each grouping, but the first method renders all items, rather than just the ones in the current grouping.

**How can I tell from `views-view-list.tpl.php` which items belong to the current grouping?**

# Answer
> 0 votes
Turns out the `$rows` object has indices that don't go from 0, counting up by 1. It keeps only indices of the items in the current group. That makes this code work:

```
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
    <?php if(isset($rows[$delta])) : ?>
         ... print out whatever necessary ...
    <?php endif; ?>
<?php endforeach; ?>

```

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


title: How to SAVE a webform in Simpletest?

text:
# Question
Title: How to SAVE a webform in Simpletest?
I am able to save a sample webform in Simpletest if I only use title and body:

```
  $edit = array();
  $edit['title'] = 'Sample webform';
  $edit["body[$langcode][0][value]"] = $this->randomName();
  $this->drupalPost('node/add/webform', $edit, t('Save'));

```

But when it comes to add the additional fields,

```
$edit['customfield_xxx'] = '0053416';

```

the test fails:

```
Failed to set field customfield_xxx to 0053416

```

Is any nesting necessary to make it work?

**UPDATE** It seems like after submitting the form as describe above I need to access the components page: $this-\>drupalGet('node/1/webform/components'); where I build an array with all components. However I have been able to fill in the specific component form with 1 single field.

# Answer
> 1 votes
You need to mimics the user's behaviour.

You need to submit individually each form in multiple steps.

You must write correctly the field names (look for input names in the DOM with Firebug or Developer Tools)

```
  $edit = array();
  $edit['title'] = 'Sample webform';
  $edit["body[$langcode][0][value]"] = $this->randomName();
  $this->drupalPost('node/add/webform', $edit, t('Save'));

```

then submit the fields individually:

```
  $edit = array();
  $edit['add[name]'] = 'Sample webform';
  $edit['add[type]'] = 'textfield';//or whatever, optional
  $this->drupalPost('node/webforms/components', $edit, t('Add'));

```

Rinse and repeat.

You can create a custom function to perform that.

---
Tags: testing
---


# Question
Title: How to create a taxonomy terms dropdrown with Views
I need to achieve a block containing a dropdown list of vocabulary terms (called topics). Each topic describe one or many of the content articles. Each topic which is assigned to no articles should not be displayed. When selecting the topic from a dropdown list a page with assigned articles should be displayed.

It seems like achieving a dropdown list of terms from within a view is harder than expected.

Here my steps: I created a View with display page and exposed form in block: Yes I selected the term ID and term Name fields; then I expose the filters as "Operator: Is one of," and I selected all. It seems like nothings happens.

# Answer
There are several approaches:

**A. Create a View out of Taxonomy Terms with a Page Display.**

For fields add: term id, term name For filters: Term name (with widgets) and expose the filter

Choose then:

* Dropdown,
* Vocabulary (of your choice)
* Expose this filter to visitors...,
* 'Is one of' then select all terms from the vocabulary
* Remove duplicates

In Views UI, on Advanced Tab

* Exposed form in block: Yes
* Exposed form style: Basic | Settings
* Adjust settings to have autosubmit

**B. Create a View out of Content and choose Taxonomy Terms among fields, similar to above.**

**C. Create a View with Block display from Taxonomy Terms and at Format Tab choose Jump Menu.** If you need to overwrite the Jump Menu path you need to add a custom text field and create your desire path out of Replacement Patterns.

Than select the created custom text field from Jump Menu path settings
> 2 votes

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


# Question
Title: Taxonomy dropdown to match the related content (in a views with exposed filters)
# Goal

Each time I select a term from the select all the related articles in the page will be listed. The correct link is terms/term-name (taxonomy term alias)

e.g terms/sports will display all sports articles

How do I alter the form submit link?

# Achieved so far

I created master display with 'exposed form in block: Yes' The block is shown up with all the terms I need in the select widget. Now when I select a term from the dropdown the url turns to terms?tid=54 displaying a page with the link to the terms/term-name. but I want to access directly.

All I need is to display at once from the select all the related content

# Answer
> 0 votes
Create a View with Block display from Taxonomy Terms and at Format Tab choose Jump Menu. If you need to overwrite the Jump Menu path you need to add a custom text field and create your desire path out of Replacement Patterns.

Than select the created custom text field from Jump Menu path settings

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


# Question
Title: Can we use Panels for Responsive web design?
I would like to make a new site using responsive design using the Omega theme. Are panels modules suitable for responsive design or should I use something else(like the Context module)? Thanks

# Answer
Two new ways of doing responsive design in Panels include Adaptivetheme 3.x and the Panoply distribution.
> 6 votes

# Answer
Yes! I just did it.

Assuming 2 col and variants - you might need more for other layouts:

1. In the lowest resolution @media query CSS I just set the '.panels-col-first' and '.panels-col-last' to `{ width: 99.9%; clear: both }`.
2. In higher resolution layouts, when you want it to go back to 2-col layout just undo the override `{ width: 49.9%; clear: none }`

Notes:

* the % widths should add up to LESS than 100% if you want to support IE 6 and 7 as they have rounding errors. You can always do this in your special ie.css if you have one and really need that 0.2% back!
* These classes should already be set to float left by the main Panels CSS, but you can override that too if needed.
> 5 votes

# Answer
I had the same issue. No need to code in css to resolve the problem. --\> Omega handle well panels in responsive design.

> "Omega comes with a handful of panels layouts by default. If you enable Panels on your site with the Omega theme also enabled, and you go to add a new panel you will see Omega: 12, ( or 16 or 24) Column Grid listed. Choose one of those, then choose a layout. I'm embarrassed about how easy it was, and I never even knew!"

I found the solution on this page, second comment http://www.kendallsdesign.com/blog/omega-theme-responsive-design-resources

By the way, there is really good materials.
> 1 votes

---
Tags: panels, theming
---


title: Authenticate against a Drupal Instance

text:
# Question
Title: Authenticate against a Drupal Instance
Is it possible for an application (e.g. a Java Web app) to authenticate against the Drupal users table? I know they use an SHA512 encryption, but I am wondering if there is any way to expose this service outside of Drupal

Perhaps use hook\_auth within Drupal, but expose that hook externally somehow?

# Answer
> 3 votes
`hook_auth()` has been gone since Drupal 5.

But it sounds like you're looking to implement something with `user_authenticate()`.

General outline of how to accomplish this (note that this will send passwords as plaintext - use SSL if that's a problem):

1. Create an API page using `hook_menu()` for your app to hit.
2. In that pages callback function, accept the username and password as POST requests (or however you want to build your app) and run them through `user_authenticate()`.
3. Return the results of `user_authenticate()` (either `FALSE`: *fail* or numeric: *pass*) as a json string (or whatever you want) and act accordingly within your external app.

---
Tags: security
---


title: Taxonomy and views exposed filter

text:
# Question
Title: Taxonomy and views exposed filter
I have a taxonomy reference link appearing on a content type. I have a view showing all nodes tagged with certain terms in that taxonomy vocabulary.

On the view page I configured an exposed filter (select box), with options to filter the view by taxonomy term.

When I use the exposed filter I get a url like in following example: ../viewpagepath?tid=5

When I manually type a different 'tid' as url parameter the active filter option in the exposed filter changes to the corresponding term name.

I used the Taxonomy display module to change the Taxonomy page to the same view. However, when I click on the taxonomy reference link on the content type, I can't get the url to look like this ../viewpagepath?tid=5 so that the right filter option is active.

How do I do this?

I see 2 options:

1. Changing the term reference link on the content type, so I get the same url pattern. (I can't use Pathauto because it doesn't accept a '?' in the pattern).
2. Changing the exposed filter url to match a pattern set in pathauto.

Wich one is best? Wich hooks or configuration do I use to get the right result?

# Answer
I've solved a similar problem with drupal\_get\_path\_alias() and hook\_form\_alter(). In my case I link from my content-type to the taxonomy page with the following:

```
<?php
// have a field with tags - in my content-type template I do
$terms = array();
foreach ($node->field_blog_post_tags['und'] as $key => $value) {
    $terms[] = '<a href="' . $base_url . '/' . drupal_get_path_alias('taxonomy/term/' . $value['tid']) . '">' . $value['taxonomy_term']->name . '</a>';
}
print implode(', ', $terms);
?>

```

And to set the exposed filter I use hook\_form\_alter() in a custom module:

```
/**
 * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ('views_exposed_form' == $form_id) {
    // term-id and vocabulary are part of arguments
    $args = func_get_args();
    // select your filter
    if (isset($args[0]->vocabulary_machine_name) && 'YOUR_VOCABULARY' == $args[0]->vocabulary_machine_name) {
      // set the exposed filter with name 'YOUR_FILTER'
      $form_state['input']['YOUR_FILTER'] = $args[0]->tid;
    }
  }
}

```

Maybe it's helpful for you.
> 1 votes

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


# Question
Title: problem merging views row-data into Drupal.settings
I have a custom view and a custom row template. For each row, the template defines a variable $rowdata. For example:

```
> row #0:  $rowdata = array(0=>array('a','b'), 1=>array('a','c'))
> row #1:  $rowdata = array(0=>array('a','b'), 1=>array('a','d'))
> row #2:  $rowdata = array(0=>array('x'), 1=>array('x'))

```

**What I Am Trying To Accomplish**

I want merge the rowdata from all the rows:

```
   $merged_rowdata = array(
      0=>array('a','b'),
      1=>array('a','c'),
      2=>array('a','b'),
      3=>array('a','d'),
      4=>array('x'),
      5=>array('x')
    )

```

and store the result in `Drupal.settings.mymodule.$viewID.merged_rowdata`:

```
Drupal.settings.mymodule.$viewID.merged_rowdata = array(
  0=>array('a','b'),
  1=>array('a','c'),
  2=>array('a','b'),
  3=>array('a','d'),
  4=>array('x'),
  5=>array('x')
)

```

(Note: All rows have the same value for $viewID)

**What I Tried**

I tried placing the following code in my row template:

```
drupal_add_js(array('mymodule' => array($viewID => array('merged_rowdata' => $rowdata))), 'setting');

```

But this does not merge the rowdata in the way that I want, as described above. Instead, it replaces $viewID with the row\_index:

```
Drupal.settings.mymodule = array(
  0 => array('merged_rowdata'=>array(0=>array('a','b'), 1=>array('a','c'))),
  1 => array('merged_rowdata'=>array(0=>array('a','b'), 1=>array('a','d'))),
  2 => array('merged_rowdata'=>array(0=>array('x'), 1=>array('x')))
)

```

I found that if I replace the variable $viewID with a string literal, eg 'myview':

```
drupal_add_js(array('mymodule' => array('myview' => array('merged_rowdata' => $rowdata))), 'setting');

```

then the rowdata gets merged in the way that I want:

```
Drupal.settings.mymodule.myview.merged_rowdata = array(
  0=>array('a','b'),
  1=>array('a','c'),
  2=>array('a','b'),
  3=>array('a','d'),
  4=>array('x'),
  5=>array('x')
)

```

Anyone know how I can get my desired result? Is there some way to "tell" drupal\_add\_js that the variable $viewID has the same value for all the rows?

**Background**

My style template loops through each row of the view output, and executes the row template on each row. Here is the code for my style template:

```
<?php foreach ($rows as $id => $row): ?>
  <div>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

# Answer
I was able to solve my problem by changing the datatype of $viewID from a number to a string.

This was the original setting of $viewID:

```
$viewID = $view->vid; // eg $viewID = 9

```

This is the new setting:

```
$viewID = 'vid' . $view->vid; // eg $viewID = 'vid9'

```

Now, when I place this code inside my row template:

```
drupal_add_js(array('mymodule' => array($viewID => array('merged_rowdata' => $rowdata))), 'setting');

```

I get the desired result

```
Drupal.settings.mymodule.$viewID.merged_rowdata = array(
  0=>array('a','b'),
  1=>array('a','c'),
  2=>array('a','b'),
  3=>array('a','d'),
  4=>array('x'),
  5=>array('x')
)

```

*Here is my interpretation of what is going on:*

drupal\_add\_js merges data differently depending on whether the keys in a particular subarray are numeric. If it sees all numeric keys, then it assumes the subarray is sequential (as opposed to associative), and resets the keys to make them sequential starting at 0.
> 0 votes

# Answer
If the string literal is giving you what you want, I'd try this:

```
drupal_add_js(array('o4mmgal' => array($view->name => array('merged_rowdata' => $rowdata))), 'setting');

```
> 1 votes

---
Tags: views, javascript
---


title: Narrower zones in Omega

text:
# Question
Title: Narrower zones in Omega
I am trying to make the Header and Footer zones a little narrower than the Content Zone in Omega3 & Delta. Here is an example of how it should look:

How can this be done with Omega3?

# Answer
> 0 votes
You cannot do this with Omega as its not part of the structure of the 960 grid system. Your best bet is to do it via CSS.

First you you would take the largest section, which would be the middle one. Say its 1000px, now the header and footer would also be 1000px. You would then modify the inner div in those regions to be 980px (10px on each side) to get the effect your looking for.

---
Tags: theming
---


# Question
Title: Which of the wysiwyg modules will get in to the core of Drupal 8?
I heard that there will be a wysiwyg editor in core for Drupal 8. Is there any decision made yet which one will make it? I heard about:

I have a decision to make which module I will add to my site and I need some deeper integration of the wysiwyg to the Drupal core. For example, that all external links are programmatically get stored in a link field an so on. So I am hoping to get some of those features in feature when I choose the right module backported to Drupal /.

# Answer
Dries answered this in From Aloha to Ckeditor on Jan 02, 2013:

> Therefore, we are going to switch from Aloha to CKEditor for Drupal 8 core. By making this switch, we will not only have a more mature WYSIWYG editor, but we also free up resources to work on other parts of Drupal's authoring experience. The CKEditor team has committed to fix the 8 functional gaps that we've identified in their two next upcoming releases.
> 6 votes

---
Tags: wysiwyg
---


# Question
Title: Automatically attaching/relating one view to another view based on same value in one field
My Drupal site draws data from a CRM system that stores info on contacts and companies. In the CRM, the contacts are related to the companies by a common ID. I have set up Drupal to automatically import the contacts and companies as separate content types and keep them up to date. Both the 'contact' and 'company' content types have an ID field, which is used to relate which contacts work for which companies.

I can create a view, with a page that shows an individual company. I am not sure how to attach a view of the contacts that work for the company. I know it would be possible to use node reference and EVA to relate the contacts with the companies manually. Unfortunately when new companies and contacts are added to the CRM the Drupal site needs to be able to create the relationship between the two automatically, probably based on the fact they both share a common value in the ID field.

It would be great to know how other people have managed to create relationships between two content types. I am not sure if there are any modules that can help with this, if I should create a theme template page for the company view page, and hand code some php that queries the database to return the related contacts, or if need to figure out how to build a module to do the above.

Thanks for your help, Paul

# Answer
You can do this by using Contextual Filters in Views. Contextual Filters allow you to filter Views results by "Context" (context usually means the currently displayed page or currently logged in user). Assuming you want to display Contacts on a Company page:

1. Create a new View (`admin/structure/views/add`) to show content of type *Contact*. Make sure the *Create a block* checkbox is checked. If you forget and skip that checkbox, you'll have to add a Block display on the next screen.
2. Fill out the View so that it looks as you want it to, with the appropriate fields, etc. displayed.
3. Under *Advanced*, click to add a *Contextual Filter*. You're going to be filtering Contacts to display only Contacts which match a certain value for the company ID field. Scroll through the list of fields in the popup window that appears until you find the company ID field. Check the checkbox next to that field and click the Add button.
4. You need to define the value of the contextual filter. Under **WHEN THE FILTER VALUE IS *NOT* AVAILABLE** choose *Provide default value*. Choose *PHP Code* for the dropdown *Type* and enter the following code in the PHP textarea:

```
$node = menu_get_object('node');
if (isset($node) && $node->type == 'COMPANY_CONTENT_TYPE') {
  $company_id = field_get_items('node', $node, 'COMPANY_ID_FIELD_NAME');
  if (!empty($company_id)) {
    return $company_id[0]['value'];
  }
}

```

Replace `COMPANY_CONTENT_TYPE` and `COMPANY_ID_FIELD_NAME` with the appropriate machine names for your company content type and the field name used to store the company ID.

This PHP loads the currently displayed node and loads the value of company ID field from that node. The value returned is used by the contextual filter to display only contacts which have a company ID field which matches this value.

You can preview the Contacts that will be displayed by manually entering a company ID in the *Preview with contextual filters:* input while editing the View. The preview should show only Contacts for which the company ID matches that entered value. On a live page view, this value is provided by the PHP above.
5. Save the View, and go to the Blocks admin page (`admin/structure/block`). Your new View should appear in the list of available blocks. Drag-drop the block you created into the Content region and save. Optionally configure the block and set it to only display when viewing Company nodes.

At this point you should be able to navigate to any Company node and see the list of contacts as a block, provided by Views. The PHP code entered loads the company ID from the Company node, and filters out all displayed Contacts which don't have a matching value for the company ID field of that Contact.

If you run into any issues or if I missed any steps, please comment below :-p For more information about using contextual filters, I recommend the Taming the Beast: Learn Views with NodeOne video series (parts 19-24 cover contextual filters).
> 0 votes

---
Tags: views
---


title: How to add a checkbox form to a panel?

text:
# Question
Title: How to add a checkbox form to a panel?
I have set up user comment email notification on my Drupal 7 site. When a comment is posted the author is notified by email. I did it using rules module as described here.

Now the user has the option to get notified or not. For this, I added a new boolean field checkbox on the user's account form page. So currently the user must go to his user account page to change this setting. I would like to make this setting available in a panel.

How can I add a checkbox to a panel in order to control that "notify me setting"? (The panel currently displays content type fields, comment forms etc).

# Answer
> 1 votes
One way is to define your own form and add it to a block in the panel.

After that, you save the value to the user account in the form submit handler.

**Background**:

Form generation summary

**Relevant hooks:**

**and some custom functions you'll need.**

* my\_module\_user\_notify\_form ( return form array )
* my\_module\_user\_notify\_form\_submit ( save to user )

If you use something like Profile2, you could also just embed the relevant user profile form in the block. It would then handle the form build and processing for you.

# Answer
> 1 votes
Ok, thanks to David's post, Panel now does let me choose my new block as content to add to the panel. I post the code below:

```
function mymodule_block_info() {
// This example comes from node.module.
$blocks['testblock'] = array(
                           'info' => t('Test'),
                           'cache' => DRUPAL_NO_CACHE,
                           );
return $blocks;
}

function mymodule_block_view($delta = '') {
// This example is adapted from node.module.
$block = array();

switch ($delta) {
               case 'testblock':
                 //  case 'recent':
                 $block['subject'] = t('Test');
                 $block['content'] =  drupal_get_form('mymodule_example_form');
                 //krumo($block);
                 break;
              }

//return $block['content'];
  return $block;
}

function mymodule_example_form($form, &$form_state) {

 $form['notify_me'] = array(
                         '#type' => 'checkbox',
                         '#title' => t('Notify me by email when I receive a new message'),
                         '#description' => t("Check this option to be notified by email when you receive a new message"),
                         );

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

function kl_example_form_validate($form, &$form_state) {
// Validation logic.
}

function kl_example_form_submit($form, &$form_state) {
// Submission logic.

```

}

---
Tags: panels, forms
---


# Question
Title: Add additional element to exposed view form?
I'm trying to modify an exposed view form by adding some additional markup. My current code looks like this:

```
  if ($form_id == 'views_exposed_form') {
    if ($form_state['view']->name == 'products_page') {
        // $element = array();
        $form['filter_by']['#type'] = 'item';
        $form['filter_by']['#markup'] = '<h2>Filter by:</h2>';
        $form['filter_by']['#weight'] = -10;
        // $form = array_merge($element, $form);
        $form['solution']['#options']['All'] = 'By Solution';
        $form['technology']['#options']['All'] = 'By Technology';
        $form['platform']['#options']['All'] = 'By Platform';
        $form['brand']['#options']['All'] = 'By Brand';
        $form['category']['#options']['All'] = 'By Solution';
    }

    dpm($form);
  }

```

Now I'm trying to move the `'filter_by'` element to appear first, before every other element, so I attached a weight value of -10 to it. However, the element is being added to the container that the submit button would normally be found.

I'm completely confused... any insight?

# Answer
Well then... apparently it's a weird lopsided solution that is necessary. See comment #10 here http://drupal.org/node/893392.
> 5 votes

---
Tags: views, forms
---


# Question
Title: adding rel attribute to image link in a node
I have a few images in a node that can be opened in a fancybox lightbox. I would like to link those images together to create a gallery. To do so I need to add a rel attribute to my image link. How can I do this?

I tried editing the field.tpl.php template, but without any luck.

Help would really be appreciated.

# Answer
> 1 votes
> I need to add a rel attribute to my image link. How can I do this?

You can add a data attribute to your link in l() function:

```
// your image
$image = array(
    'style_name' => 'the name of the image style',
    'path' => 'relative path to your image',
    'alt' => '',
    'title' => '',
    'attributes' => array('class' => array('some_class'))
);

// link elements
$text = theme('image_style', $image); // in your case it's an image
$path = 'link_url';
$options = array(
    'attributes' => array(
        'class' => array('some_link_class'),
        'rel' => 'some_relation'
    ),
    'html' => true
);

$link =  l($text, $path, $options);

```

**result:**

```
<a class="some_link_class" rel="some_relation" href="/your_site/link_url">
    <img src="path to your image style" class="some_class" typeof="foaf:Image">
</a>

```

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


# Question
Title: Best practices for protecting from injection on form fields
I am building a form in Drupal 7. I have a textarea field and would like to know if it is safe to get the field content ($form\['values'\]\['field\_name'\]) and save it to the database using something like db\_insert, db\_update or db\_merge. OR do I have to do some sort of filtering to avoid SQL injection attacks. Thank you

# Answer
> 2 votes
If you use the Drupal core database API functions, the content will be automatically escaped, preventing SQL injection.

You can run the content through filter\_xss prior to insert, otherwise you'll need to do that on display.

Drupal core stores the content unsanitized and sanitizes it on output.

User input should be validated on input and filtered on output.

More info on sanitization functions here: http://api.drupal.org/api/drupal/includes!common.inc/group/sanitization/7

See also http://drupal.org/writing-secure-code for information on writing secure code.

---
Tags: forms, security
---


# Question
Title: What are some quick ways to setup Product Displays in Drupal Commerce?
What is a fast way to create product displays in drupal commerce? Say I created 50 different unique products and now they are all over the place on the product list, how can I intuitively add these 50 products to a product display?

# Answer
> 0 votes
If you are adding product manually then you can use Auto Product Display module to set display of the product at the same time when you create product. But if you are using commerce feed along with feed then you will have to set two separate importer for each of them.

---
Tags: 7, commerce
---


# Question
Title: I'm having a problem getting Context to work properly
I'm having a kind of weird problem with the Context module in my Drupal 7 environment. I have the module installed and enabled, however, when I go to Structure --\> Context --\> Add, the Add Context Admin UI appears and under "Conditions" whenever I select one of the choices, the box to the right of it does not activate like it should, so I cannot put in a path or whatever. Nothing at all happens. It's the exact same for the "Reactions" as well.

It works fine in my development environment and the environment with the problem was migrated from the development environment, so I don't understand why it won't work.

I have tried completely uninstalling the module (including deleting the 'Context' folder from the server) and re-downloading and re-installing, flushing the caches, etc. Everything I can think of and I still get the problem.

Is this a problem anyone else has seen and how do I fix it?

Thanks

# Answer
> 0 votes
I had the same problem with the "blocks" section.

In the blocks section, you need to select the block(s) you want to add in a template region from the right panel where there is a list of all the blocks. Then click the + sign of the corresponding region.

As for the condition problem, that is weird have you tried in different browser?

---
Tags: 7
---