# Question
Title: How can I make db_query SELECT LIKE case insensitive?
I'm querying for an email address where I can't force the case of the search term or the data in the table. It's an API thing.

How can I convert this query to be case insensitive?

```
$results = db_query(
 'SELECT email_address
  FROM email_address_table
  WHERE (email_address LIKE :mail)',
  array(':mail' => '%' . db_like($mail) . '%')
)->fetchAll();

```

# Answer
The typical way to accomplish this is to compare a lower-case version of you search string against a the lower-cased variant in the table. See below for an example using strtolower() and LOWER():

```
$mail = strtolower($mail);

$results = db_query(
 'SELECT email_address
  FROM email_address_table
  WHERE (LOWER(email_address) LIKE :mail)',
  array(':mail' => '%' . db_like($mail) . '%')
)->fetchAll();

```
> 2 votes

---
Tags: database
---


# Question
Title: How to list profile fields in a tableselect?
I'm attempting to list out all the fields a user profile object would have into a tableselect. This will be displayed on the configuration screen of a module that I have been building. I have managed to make a tabelselect with checkboxes and dropdowns in it. That part I got down.

The part that I thought would be easy and ended up getting me stuck is getting an array of the fields a profile has. This would include any user made profile fields. Is there a simple way to get an array of the profile fields without needing to relate it to a user? The module would need this list on the front end for anonymous users so comparing it to the user would not work.

I don't need the values of any fields just the names and type of field maybe some settings like max and min. But will not need the value of any set user.

# Answer
> 1 votes
It sounds like you want field\_info\_instances():

```
$fields = field_info_instances('user', 'user');
$rows = array();

foreach ($fields as $field_name => $field) {
  $rows[] = array(
    $field_name,              // eg. 'field_my_field'
    $field['label'],          // eg. 'My Field'
    $field['description'],    // eg. 'A Description of my Field'
    $field['default_value']   // eg. 'default value'
  );
}

```

---
Tags: entities, users
---


# Question
Title: How to tell what is being loaded on a Rules Content is viewed event
Is there a way I can see what exactly is being executed on a Rules Event of '*Content is viewed*', followed by an action of page redirect to an external URL? Specifically if the content is actually being viewed, and then redirected.

I tried Devel viewing the query log and I didn't find anything. I also tried Devel's Display redirection page, but upon visiting the node, it just timed out.

Using rules event 'Content is viewed', then redirecting, I am still able to get a log message that says I visited that node, so I believe it is loading the node, then redirecting.

This concerns me because when I test other methods of node redirects to external URLs, I don't get a log message saying that I visited that node.

# Answer
> 0 votes
I struggled with a similar question ... The "clue" about what "Content is viewed" actually means, seems to be like so:

* The event ***Content is viewed*** is what it is: the user has (already) started viewing the content.
* The (system) event ***Drupal is initializing*** is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" **BEFORE** the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to How to specify a Rules event like "Content is 'going to be' viewed"?

**Be aware**: this applies to D7 ... and D6 is another story.

---
Tags: 7, rules, redirection
---


# Question
Title: Text comparison rules on node:body:value with input filters
My text comparison rule works like a charm if the user selects 'Plain text'. If they use 'Filtered HTML' it doesn't find a match even though the pattern does exist in the raw and filtered versions of the text.

The short question is how can a text comparison rule be run against filtered input?

The long version is what's the process by which rules and input filters interact and why is this an issue?

# Answer
In my case a custom input format was replacing youtube links with an iframe embedded video. Everything inside the iframe wasn't matching. My solution was to add the original youtube link outside of the iframe tag replacement pattern.

But why? Hypothesis is that one of the filters ends up running the body through htmlspecialchars.
> 0 votes

---
Tags: rules, input-formats
---


# Question
Title: How to add a Related Products View for Commerce Kickstart?
I am trying to show related products in the products display for Commerce Kickstart. I tried using the method outlined in this tutorial but ran into a couple of issues:

1. The "Target Type" in the entity reference field (the field used for the related product) does not show "Node" as an option.
2. The SQL error mentioned in the tutorial appeared when selecting "Aggregate" in the view.

The bottom line is I couldn't get this to work of Commerce Kickstart.

Has anyone had any success in getting this to work for Kickstart, or an alternative approach?

Thanks in advance for any insight into this.

# Answer
If you want to be able to reference nodes, your view must be taxonomy-based and utilise product categories. The category must be on the display node, not on the product and this is a good starting-point to understanding what's required. To see if this idea is relevant to your use-case, go here: http://www.bookfish.co.za/catalogue/gorongosa-joao-augusto-silva Bear in mind that I'm not using Commerce Kickstart but various Commerce modules on that site but it should work with CK.

To display my products, I added the following relationships & what I selected there to get it to work I have put in square brackets \[ \]:

1. Content: product \[required\]
2. (Products referenced by field\_product)Commerce Product: Referencing Content \[required\]
3. (Content referencing products from field\_product) Content: Taxonomy terms on node \[required, select the vocabulary you want, identifier: term\]
4. (term)Taxonomy term: Content using Category \[required, identifier: field\_category\]
5. (field\_category) Content: Category (field\_category) \[required, relationship: field\_category, identifier: term from field\_category\]
6. Content: product \[required, relationship: field\_category, products referenced by field\_product\]

for contextual filters:

1. (field\_category) Content: Nid \[Relationship: field\_category,

When the filter value is NOT available:

select "provide default value",

"type": Taxonomy term ID from URL

select "Load default filter from node page, that's good for related taxonomy blocks" and "Limit terms by vocabulary"

select your relevant category

"Multiple-value handling" select "Filter to items that share all terms" or whatever is relevant to your use case

under "More" select "Exclude"\]

Aggregation settings: \[Group results together\]

2. Content: Nid \[Relationship: do not use a relationship,

When the filter value is NOT available:

select "provide default value",

"type": Content ID from URL

When the filter value IS available or a default is provided:

select "Specify validation criteria"

Validator: "Content"

Content types: select the relevant product display

Filter value format: "Node ID"\]

Aggregation settings: \[Group results together\]

I then selected a view format of fields showing title, image, price and hidden fields of "add to cart form" and "stock" so that I could filter to relevant products that are in stock. For aggregation, I used "Group results together" and "entity ID"
> 0 votes

---
Tags: commerce
---


# Question
Title: Apache solr with rules module, on refresh, rule viewing node triggers it in search page
I'm building a site in free Acquia cloud env with apache solr running, I need to count when a node (for one content type) is being full displayed, that’s already working fine, but every time I refresh results page (viewing only teasers), it triggers not once, twice in all nodes within the content type, so my node full displayed count is not correct, Rules only option is 'when node is being viewed' and not 'node being displayed', I have to mention that this count field is to set solr sort results with a custom module (already working), any suggestions please?

# Answer
I struggled with a similar question ... The "clue" about what "Content is viewed" actually means, seems to be like so:

* The event ***Content is viewed*** is what it is: the user has (already) started viewing the content.
* The (system) event ***Drupal is initializing*** is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" **BEFORE** the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to How to specify a Rules event like "Content is 'going to be' viewed"?

So in your case, it'd be interesting to find out what result you'd get by using (system) event ***Drupal is initializing*** instead ... definitely worth a try I think ...

**Be aware**: this applies to D7 ... and D6 is another story.
> 0 votes

---
Tags: 7, rules, search
---


# Question
Title: Enabling XML under PHP in windows - import_html module not working
So I'm having a problem with import\_html. Basically, when I run the import from the sight, all of the content I wanted (except for xml files) get imported but I get these errors and warnings repeatedly:

```
Warning: DOMDocument::loadXML(): Opening and ending tag mismatch: link line 7 and head in Entity, line: 9 in parse_in_xml_string() (line 159 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\coders_php_library\xml-transform.inc).

User warning: Failed to cleanup namespaces and end up with a valid XML file in import_html_cleanup_namespaces() (line 1693 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

Notice: Trying to get property of non-object in import_html_process_html_page() (line 875 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

Warning: XSLTProcessor::transformToXml() expects parameter 1 to be object, boolean given in xmldoc_plus_xsldoc() (line 211 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\coders_php_library\xml-transform.inc).

User warning: Nothing useful extracted via XML from that content in import_html_process_html_page() (line 903 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

Notice: Undefined variable: tid in import_html_indexes_import_html() (line 27 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\extras\import_html_indexes\import_html_indexes.module).

Notice: Undefined property: stdClass::$title in node_import_html() (line 81 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\modules\core.inc).

Notice: Undefined property: stdClass::$import_html_create_menus in menu_import_html_after_save() (line 159 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\modules\core.inc).

Deprecated function: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in charset_decode_utf_8() (line 2051 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

```

When I run drush import-html,**nothing** gets imported and I get:

```
import_html found no XSL library support at all on this server! Need   [warning]
the PHP 'xsl' extension enabled in php.ini xml-transform.inc:31
Sorry, with no XML support there will be no content scanning AT ALL.     [error]
Aborting process. See the import_html_help.htm for info on enabling
XML under PHP. import_html_process.inc:724
WD Import HTML: Failed to process any node out of file                   [error]
'8ab24e480a68476f800648582eaabf43.html'
WD Import HTML:                                                          [error]
Failed to get any results from the attempted analysis of
8ab24e480a68476f800648582eaabf43.html.
The source file path was probably unavailable or not HTML.
WD Import HTML: No results! Failed to extract any new nodes            [warning]
Processing 1 files for import. Using default configuration settings.    [status]

```

Because I have a windows computer, I followed these directions for enabling xsl in php, and when I did so, I was able to get regular html files imported via the website import-html. But why am I getting these other errors?

# Answer
> 0 votes
The reason why drush was giving me the XSL library support error is because though I fixed the php.ini file in the drupal folder, drush uses a different php.ini file, so I had to modify that one in order to get the imports to work. Now, I get the exact same errors/warning when I import online as when I import via drush. i haven't been able to fix the warnings

---
Tags: drush
---


title: Printing fields from View using query

text:
# Question
Title: Printing fields from View using query
The query below is taken from the related View. How can I get the field value for 'field\_data\_field\_news\_link', 'field\_data\_field\_news\_source', and field\_data\_field\_news\_date' for each row (news content type that is published and featured)? I prefer to use what I already have, which probably means changes are needed to the JOIN statements? Right now, all that is printing are the node titles.

If there is a more straight forward approach, I'm open to that too.

```
<?php
    $query = "SELECT node.nid AS nid, node.title AS node_title, field_data_field_news_date.field_news_date_value AS field_data_field_news_date_field_news_date_value, 'node' AS field_data_field_news_date_node_entity_type, 'node' AS field_data_field_news_link_node_entity_type, 'node' AS field_data_field_news_source_node_entity_type
        FROM {node} node
        INNER JOIN {field_data_field_news_is_featured} field_data_field_news_is_featured ON node.nid = field_data_field_news_is_featured.entity_id AND (field_data_field_news_is_featured.entity_type = 'node' AND field_data_field_news_is_featured.deleted = '0')
        LEFT JOIN {field_data_field_news_date} field_data_field_news_date ON node.nid = field_data_field_news_date.entity_id AND (field_data_field_news_date.entity_type = 'node' AND field_data_field_news_date.deleted = '0')
        WHERE (( (node.type IN  ('news')) )AND(( (node.status = '1') AND (field_data_field_news_is_featured.field_news_is_featured_value = '1') )))
        ORDER BY field_data_field_news_date_field_news_date_value DESC
        LIMIT 5 OFFSET 0";

?>

<?php $results = db_query($query); ?>

<?php $i = 0; ?>
<?php foreach ($results as $row) : ?>
    <!-- Custom HTML here -->

<?php endforeach; ?>

```

Some background. I am upgrading a project that I inherited to Drupal 7. The Drupal 6 version has all hard coded templates (not my doing!). The specfic page I am working on is of Page content type. This is the News node. On this node, I need to render all News content types and the selected fields. I also need to render this into custom HTML. I prefer not to go the Rewrite results route. Changing anything in Manage Display would be changing the Page content type which I do not want to do. Additionally, it seems print render($content\['field\_news\_link'\]) would only render that field from one News content type? So if I already have a template file for the News node (of Page content type), what would be my approach? Would I create a template for the view and then just print the view in my existing News template?

# Answer
> 0 votes
This is not good approach for Drupal. Try to make the query in VIEWS UI, after that you have 2 options:

1. In the view add this option Show:Content | Teaser. Create tpl file for that specific node (node--news.tpl.php), add if statement for the DISPLAY(view) MODE of the content type (full or teaser). In the correct display mode you have all node fields that are enabled in the content "Manage display" tab (as admin structure-\>content type-\>news-\>manage display) and use " print render($content\['field\_news\_link'\]) ".
2. In the view add this option Show:Fields. Rewrite the option of the field "Rewrite results"-\>"Rewrite the output of this field" in the view and add there html + token of the field.

---
Tags: views, theming, database
---


# Question
Title: How to preprocess file before Feeds upload
I am using Feeds 7.x-2.0-beta1 . I am getting the data in a format that I need to change before inputting, since they are adding one item per row when some data has multiple values in one field . I want to modify the file to put all of those values in one field and one row before continuing with the feeds parser. Where can I put the php code to do this? what hooks are available? thanks

# Answer
The Feeds project page doesn't advertise it, but there is an API. If you look at **feeds.api.php** you can view all the hooks it makes available. A few of them take action before a feed item is processed or saved.
> 2 votes

---
Tags: feeds
---


title: Different price for role

text:
# Question
Title: Different price for role
My question is similar to others, but not exactly the same. All the other answers have a specific discount (%) amount for Members, but my client needs to be able to set a totally different, specific price for each of their art classes for members, that is, there is no specific rule that applies to all classes equally. So, I created a Member Price field to hold each unique reduced price, but I'm not sure which action in the dropdown would switch out the base price for the price in that field.

# Answer
> 1 votes
It was a strange flow of events, but the question was relevant to Ubercart, which I was wrong not to mention in the original post. It took doing research for a Drupal Commerce install to find the path to the answer for Ubercart!

The answer was the Price per Role module. Part of the project requirements were that the "member" viewer should be able to see the original price. As a workaround, we actually had to set up a special fields so that both prices could show! Yes, this could have been done with coding, but the client doesn't have a budget for coding.

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


# Question
Title: How to show a different product variation other than the default one on page load ( ajax trigger )
I have a node display for more than one product variation. Normally the user has to select one of the variation options by selecting them from the drop-down list which rebuilds the node display via AJAX.
Now say for instance that I want to link one of the product variations from else where. If I simply link www.example.com/node/10 the default product variation will be displayed which might not be the one I would like to present to the user.

So I probably have to send a query parameter in the URL, for example www.example.com/node/10?product\_id=15, and trigger the AJAX event programmatically in my custom module.

# Answer
Please see Implement unique URLs for particular products on product displays. It is an open feature request for Commerce, and it also links to a working sandbox with the implementation: http://drupal.org/sandbox/maciej.zgadzaj/1845182
> 3 votes

# Answer
Sure here you go, you'd have to modify for you own implementation.

```
/**
 * Implements hook_commerce_product_reference_default_delta_alter().
 */
function location_variant_flag_commerce_product_reference_default_delta_alter(&$delta, $products){
    $lang = LANGUAGE_NONE;

    //load the node
    $node = node_load(arg(1));
    //only execute if the hide location variant field is set to 1
    if(count($node->hide_location_variant) > 0 && $node->hide_location_variant[$lang][0]['value'] == 1){
        //get the default product based on the users location
        $default_product = location_variant_flag_get_default_product_for_user_location($products);

        if($default_product){
            //DC doesn't always return the delta consistently, sometimes it is the product id and
            //sometimes it is the array key so check if array key 0 exists, if so return the array key
            //otherwise return the product ID
            if(isset($products[0])){
                foreach($products as $key=>$product){
                    if($product->product_id == $default_product->product_id){
                        $delta = $key;
                        break;
                    }
                }
            }
            else{
                $delta = $default_product->product_id;
            }
        }
    }
}

```
> 2 votes

# Answer
```
<?php
/**
 * Implementation of hook_form_alter()
 */
 function MYMODULE_form_alter(&$form, $form_state, $form_id) {
   if (strpos($form_id,'commerce_cart_add_to_cart_form_') !== FALSE) {
    $product_id = $form['product_id']['#default_value'];

    foreach(drupal_get_query_parameters() as $paramenter => $argument) {
      if ($paramenter == 'product_id') {
        $product_id = $argument;
      }
    }

    $form['product_id']['#default_value'] = $product_id;

    if (!isset($form_state['triggering_element'])) {
      $form['product_id']['#ajax']['event'] = 'MYMODULE_commerce_variation_trigger';
      drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/MYMODULE.js',  'file');
    }
  }
}
?>

MYMODULE.js
(function ($) {
  $(document).ready(function() {
    $('#edit-product-id').trigger('MYMODULE_commerce_variation_trigger');
  });
} (jQuery));

```
> 0 votes

# Answer
You can quite easily do this in a custom module using hook\_commerce\_product\_reference\_default\_delta\_alter()
> 0 votes

# Answer
Just because I've come across this twice, if you have a custom module for your custom functionality here is a quick and easy example of sending in a product id or sku as a query parameter using `hook_commerce_product_reference_default_delta_alter`:

```
function myModule_commerce_product_reference_default_delta_alter(&$delta, $products){
    if(isset($_GET['pid']) || isset($_GET['sku'])){

        //if a "pid" or "sku" parameter exists loop through the products that are attached to the node
        foreach($products as $key=>$product){

            //if the product id or sku matches the current productm set the delta to the key
            if($product->product_id==$_GET['pid'] || $product->sku==$_GET['sku']) $delta=$key;
        }
    }
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Generate PDF from custom fields, and link from Views page
I have a list of records that are presented to end-users in a View. That works fine. What I want to do is generate a printable PDF from custom fields so that users can print out a nicely formatted profile page and hand the printout to someone else. Does anyone know if this is possible?

# Answer
I know there is a module called Views PDF. I did have it working on a test CiviCRM 4.2 site, but formatting the PDF was somewhat tedious and I have never used it on a live site.
> 1 votes

# Answer
We have made use of https://www.drupal.org/project/print multiple times for providing PDF option on a civicrm Views display.
> 1 votes

---
Tags: views, files
---


title: Views and Fields help

text:
# Question
Title: Views and Fields help
I have product images that I want to appear in a view. Easy enough. At the same time I have 6 different product types. So what I'm trying to do is create a view that is 6 columns across. Each column is a different product type. Then each product will fall into 1 of 6 categories. Some columns will have 4 items, some 7. I cannot seem to do this with the "Grid" layout. Which seems the best way to do this. Any suggestions?

# Answer
What I would do is add a taxonomy with 6 "product-types" terms, then add a term reference field in contentype, make "6 content pane views" displaying your contentype and filtering on term reference, and with panels module (or display suite) do a 6 column display with all fields that you require, each view will have it's own column, and you are done.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to populate a select list in my custom module with the content types of the site?
I am making my first custom module, and I want to have a select list in the module settings that has all the content types in the site, so that the admin can select which content types to have associated with the module.

here is the code I have so far:

```
$form['MODULE_select_content_types'] = array(
  '#type'          => 'select',
  '#title' => t('Select Content Types'),
  '#description' => t('Select the Content Types that users can subscribe to'),
  '#default_value' => variable_get('MODULE_unlisted_content_types', array()),
  '#options'       => $select,
  '#multiple'      => TRUE,
);

```

How do I populate the $select variable with a list of all the content types in the site?

# Answer
> 0 votes
I found some code in another module that did the same thing. That module had this code before that form option in the form function

```
$select = array();
$select[0] = '<' . t('none') . '>';
$nodetypes = node_type_get_types();
foreach ($nodetypes as $ntype => $nname) {
  $select[$ntype] = $nname->name;
}

```

---
Tags: 7
---


# Question
Title: How to make submenus appear on hover regardless of what page you are on?
I am using CorporateClean theme for this site and I want the submenus dropping down from the main menu tab "gallery" to appear on hover no matter which page you are on. How to achieve this?

# Answer
> 1 votes
Edit your Menu Link and make sure **Show as expanded** is checked.

> If selected and this menu link has children, the menu will always appear expanded.

---
Tags: theming
---


# Question
Title: Is there a module that lets one person do a bulk publish/update?
On my site I need the ability to let multiple people edit and add content, but I need that content to be only able to be published at one time by one person.

Is there a module out there that lets a user of a certain role publish all of the new and updated content at the same time?

# Answer
> 1 votes
This should be possible using the Views Bulk Operations module (=VBO) ... Quote from its project page:

> ... augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

So create a view that lists all "content waiting to be published", whereas you might want to limit the access to such view to only that "one person" (the content approver?).

Then have the content approver use VBO to select "all" content to then apply "bulk operation" = "publish".

Should you want to do so, you could further enhance/refine this content approval process with modules Flag and Rules modules also. Refer to these questions to get an idea of the possibilities:

---
Tags: 7, nodes
---


title: Adding a view to a panel

text:
# Question
Title: Adding a view to a panel
Running Drupal 7, Views 3 and panels 3

Been searching for an answer for this for a few hours now and I can't seem to find one. I am creating a custom user profile page in panels. I created a view to display certain fields from profile2 if that user is of that role. When I test the view at the bottom of the views page by passing it an id it works fine. here are the settings:

```
Contextual filters:
Node:Nid

Relationships:
Content:Author
(author) User: Profile

```

Now in panels when I add this view I have the heading Content: Nid with a drop down list in the options. I select the information I want to display and save. Then when I go to the profile page, nothing shows up. I don't think it is passing the nodeid to the view, but I am not sure what I haven't done.

# Answer
If you create the view as a content pane (panel pane), you are able to select options used in panels on how to receive the context params, (Like from a Panel context of type Node). When adding the content pane in Panels you also get to select which variables should be sent to the view. This is probably what you are missing.
> 8 votes

# Answer
In Module list: look out for Chaos Tools → then ativate the submodule: Views Content Panes (Allows Views content to be used in Panels).

Practically you'll find this new feature while on the Views UI when add a new Display (you'll notice Content Pane display)

Checkout this tutorial: http://dev.nodeone.se/node/555
> 6 votes

# Answer
Here's what I did to get it to work:

* goto: admin/structure/panels/settings/panel-page
* click on Allowed View panes content
* Check the box of the view you want to add in panels

Note: It might be necessary to create a "Content pane" view using the views module of the view you want to add.
> 0 votes

---
Tags: panels
---


# Question
Title: When adding a node, the site images do not show
I have some image links that are inside standard `<a href>` tags, that link to some external sites. Example: ``

The images display no problem, until I go to add a node of my custom content type "Front Page Announcement". Then, the images do not display - i.e. the path to the image cannot be found.

I URL I get is: `http://localhost/bedsastro_new/node/add/front-page-announcement` And the images are in `assets/site-images/`

When I look at at where the browser is expecting the image to be, it's : `http://localhost/bedsastro_new/node/add/front-page-annoucement/assets/site-images/pic.jpg`

How do I ensure that Drupal is looking at right location for the images (i.e. `http://localhost/bedsastro_new/assets/site-images/pic.jpg`) ?

Thanks! Daz

# Answer
> 0 votes
It seems that the root of your Drupal site is `http://localhost/bedsastro_new/` .

To reference an image with filename `pic.jpg` (using an `img` tag) which is located in the site's subfolder named `assets/site-images`, you should specify `/assets/site-images/pic.jpg` as the value of the `src` attribute within the `img` tag.

With that, Drupal will try to find that image at `http://localhost/bedsastro_new/assets/site-images/pic.jpg`, which is where your image is actually located, so that should work.

# Answer
> 0 votes
OK, I found the solution - or at least A solution!

I updated the paths for the images to use `<?php print base_path(); >/asset/site-images/image.jpg`

And this worked :)

---
Tags: 7, nodes, media
---


# Question
Title: Which hook will load after node page load and file download
I need to run `db_insert` and `db_update` once after a node is loaded. Its only for particular node content type. Which hook can i use for it?. Can i add that hook in template.php instead of adding it in a `.module` file?.

I need another hook which will run once after a file gets downloaded.

# Answer
> 2 votes
It's not really clear what you need re node hooks, since your title says "after node page load" and the body of your question says "after a node is loaded". Those are very much two different things. If you're looking for a hook that fires after the page has been displayed on the front end, there isn't one (though you could theoretically implement your own using AJAX).

Your best bet would be to consult the list of Node API Hooks and select the one that best suits your exact use case.

To get notified of file downloads through the private file system you can implement hook\_file\_download(). There's nothing similar for public file downloads, as Drupal's default behaviour is to pass straight through to existing files, without bootstrapping (hence no hook could ever be fired).

---
Tags: nodes, files
---


# Question
Title: getting key of submitted entity list field
I'm having troubles with the following: I created a form with entityforms and now i want to send a confirmation email with mimemail. Getting that to work is no problem.

But i need to perform a small check with the php evaluation function of mimemail.

The form is for customers to place an order, but they have to specify 1 of 2 printing techniques available, 'fdm' or 'polyjet'. This is a 'list' field in the entityform with the two options. And in the confirmation email i need to check what technique has been chosen so i can display some lines of text depending on the technique.

For my php evaluation i would like to get the key (machine readable name) of the submitted value.

So i can do something like this:

```
switch ($chosenkey){
    case "pol":
        echo "lines of text for polyjet";
        break;
    case "fdm":
        echo "lines of text for fdm";
        break;
    default:
        echo "error";
}

```

So basically i just need to know how i can create a variable ($chosenkey) that contains the submitted key of the chosen printing technique.

anyone any idea how i can accomplish this? I have googled around but can't find any relevant answer.

# Answer
I'm not familiar with entityform so forgive me if none of this makes sense, but I imagine it works much like webform in that it sends the e-mail to the addresses you set up upon a successful form submit with no need for any custom code. So adding another validator or submit function to send the e-mail would result in two e-mails.

What you can do is use hook\_mail\_alter in a custom module and see what variables entityform passes to its drupal\_mail call. With any luck, all the form values from $form\_state will be included and you can do the check there and then change the $message\['body'\] array accordingly.

In the hook\_mail\_alter you can do a switch statement for the $message\['key'\] or $message\['id'\] to make sure you're not running your check for every mail your drupal site sends but only for the entityform in question.

I would also include a custom token of sorts in the template you, presumably, entered when settings up the entityform so you can easily change the e-mail body once you've run the check. I don't know if you could do it with Drupal's Token system, but even just entering 'my\_module\_custom\_token' in the template and then using str\_replace on 'my\_module\_custom\_token' with the correct sentence in the mail\_alter is better than nothing.

If none of this applies, then naturally disregard this answer entirely.
> 0 votes

# Answer
Thank you for helping.

Problem is that the check i wan't to do is very simple and i'm not looking to write an extra custom module for it. It looked to me that MimeMail has build in PHP evaluation for simple tasks. And the thing i wanted to accomplish looked simple to me.

After a lot of trial and error (my PHP knowledge is very basic) i have found a solution to my problem.

Getting the key of a submitted value works like this:

```
<?
    $values = field_get_items('entityform', $entity, 'your_field_name');
    $value = $values[0]['value'];
    ?>

```

This code gets me the key that i need to perform a simple check like this:

```
<? if($value == "key1"){ ?>line of text for key 1<? }else{ ?>line of text for key 2<? } ?>

```

Everything works fine now and in my case my problem got solved :)

Thanks again!
> 0 votes

---
Tags: 7, entities, emails
---


# Question
Title: How to format database fields in a report created with Forena?
How can I choose how to display the fields from the database returned by the data block (using the Forena module)? Such as a field just returns a number, but each number of that field represents something else that I'd like to display. For example:

```
 if (id=5) { $text = "see website"; } else { $text = "free"; }

```

If this is not possible, how in general can I change how the fields are displayed?

# Answer
> 2 votes
When you're "developing" a report (= Specifying the various report options), you have a choice to do so using either of the following features:

* Use the WYSIWYG Report Writer, something *novice* Forena users typically do, or *end users* that are granted permissions to "develop" their own reports (and which get saved in Forena's typical '.frx' files).

In this case, you should look at Fields (within the WYSIWYG tutorial), located also at `/reports/help.reportingwysiwyg#fields` in your own site.
* "Code" your own reports in the XHTML language used in Forena (saved in '.frx' files), which is called "FRX Report Writing". This is what the real power users will want to do, since it gives them the full XHTML power to build any report.

In this case, you should look at Fields (within the FRX tutorial), located at `/reports/help.reportingwysiwyg#fields` in your own site.

Be prepared: there are quite some options to pick from ...

---
Tags: 7, log-messages, forena
---


# Question
Title: How does resizing of images work with lighttpd?
I switched the Webserver from Apache to Lighttpd. Since then, resizing images according to the defined sytles (/admin/config/media/image-styles) does not work anymore.

Anybody knows what may be missing?

**Edit:** Added excerpt from phpinfo():

*gd*

```
GD Support: enabled
GD Version: 2.0
FreeType Support: enabled
FreeType Linkage: with freetype
FreeType Version: 2.4.8
T1Lib Support: enabled
GIF Read Support: enabled
GIF Create Support: enabled
JPEG Support: enabled
libJPEG Version: unknown
PNG Support:    enabled
libPNG Version: 1.2.46
WBMP Support: enabled

```

*imagick*

```
imagick module: enabled
imagick module version: 3.1.0RC1
imagick classes: Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
ImageMagick version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
ImageMagick copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
ImageMagick release date: 2012-08-17
ImageMagick number of supported formats: 206
ImageMagick supported formats: [.....Many!!]

```

# Answer
Change your lighttpd rewrite rule to this :

```
url.rewrite-final = (
"^/system/test/(.*)$" => "/index.php?q=system/test/$1",
"^/([^.?]*)\?(.*)$" => "/index.php?q=$1&$2",
"^/([^.?]*)$" => "/index.php?q=$1",
"^/rss.xml" => "/index.php?q=rss.xml",
"^/(.+/files/styles/.+\.+.+)\?(.*)$" => "/index.php?q=$1&$2"
)

```

That must work. if not disable the clean ulrs to see if the problem is solved or not .
> 2 votes

---
Tags: 7, media
---


title: Change / Increase the node title length

text:
# Question
Title: Change / Increase the node title length
I want to increase the node title length on Drupal 7, and as I guess I need to do just two things (theoretically).

1. Change the title column in the node table to acept more than 255 characters.
2. Alter the node creating/editing form to let the title field accept more than 255 characters.

I've done, #2 and trying to get #1 using this code:

```
/**
 * Implements hook_schema_alter().
 */
function my_module_schema_alter(&$schema){
    if(isset($schema['node'])){
        dsm($schema['node']);
        $schema['node']['fields']['title'] = array(
            'type' => 'varchar',
            'length' => 555,
            'not null' => TRUE,
            'default' => '',
        );
        dsm($schema['node']);
    }
}

```

If I check dsm() before and after, I can see a change, but I don't see the title column in the node table affected. Am I missing something or using the bad hook?

I also use this code to change the form on creating/editing nodes (this works well):

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id){
    if($form['#id'] == 'norma-node-form'){
        $form['title']['#type'] = 'textarea';
        $form['title']['#maxlength'] = 555;
    }
}

```

# Answer
> 0 votes
as I mention it on a comment before, and just because this question must be marked as answered, I then copy it again:

I've decided to create a new field and "migrate" the stored information with Views Bulk Operations using the "PHP option". The code was:

```
$entity->field_new_title['und'][0]['value'] = $entity->title; node_save($entity);

```

And then hide the title node generating a new one with auto\_nodetitles module.

# Answer
> 2 votes
When you are implementing `hook_schema_alter()`, the table's schema is not changed.
You are informing the modules calling drupal\_get\_schema() (which is then called by functions such as drupal\_write\_record()) what the actual schema is. If you altered a database table without implementing `hook_schema_alter()`, the functions/modules using `drupal_get_schema()` would get the schema implemented by the module using that database table, which is not anymore the one describing the database table.

You need to first alter the existing database table using db\_change\_field(), taking in consideration the following note:

> **IMPORTANT NOTE**: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.

# Answer
> 2 votes
There's a module for that: Node Title Length:

> This module increases maximum length of node titles to 8000 characters.

# Answer
> 0 votes
The simplest solution is...

Create a new field (field\_full\_title) and set the maximum length to whatever value you want, use that to store the full title, optionally truncate this value to store in the original title field.

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


# Question
Title: How to add a link to the CSV download to my module page, for a report created with Forena?
How do I add a link to the CSV download created by the Forena module to my module page?

Do I just copy the link in 'inspect element' and put that in my `$output` variable that I return on the recommendations page?

# Answer
For any report that you create (using Forena), just add `.csv` as an extention to the report (output) URL. That contains the CSV equivalent of that report.

As a sample, consider the sample report located at `/reports/sample.states` (in your own site, one of the samples shipped with Forena). Change the URL to `/reports/sample.states.csv` (= just add `.csv` to it) to get the same report in `.csv` format.

If you'd adding such `.csv` to the URL of the Simple Table of States in the demo site, the result is like so ...

Same technique applies for other supported extensions (export formats), such as adding `.html`, `.xls` (MS Excell), `.pdf` or `.doc` (MS Word).

By the way, all *data blocks* are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:
> 3 votes

---
Tags: 7, importing-exporting, log-messages, forena
---


title: Other modules functions

text:
# Question
Title: Other modules functions
Is it possible to have a function call within one module which calls a function of a different module even if that function has not been defined as a hook?

# Answer
Yes. You can call all function is write in file .module. If function don't write in file .module. You need use function module\_load\_include and you can call it.
> 0 votes

# Answer
Yes, you can. In your .module file, first load the module name in which your function exists, then, the name of that file. For example:

module\_load\_include('your\_file\_extension','your\_module\_name','your\_file\_path'); for better undersatnding:

```
module_load_include('inc','module_name','includes/file');

```

and there should exist a folder name include and in this folder put your "file.inc"

and call this function inside hook\_init.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: How can I dynamically load options into a select list?
I'm creating form using `drupal_get_form` and I'm using the following code for creating a select list:

```
$form['select-user-group'] = array(
  '#type' => 'select',
  '#title' => t('Select a group'),
  '#options' => array(
    '' => t('-- Select a user group --'),
  ),
  '#ajax' => array(
  'event' => 'load',
  'callback' => 'selectuser_ajax_callback',
  'method' => 'replace',
);

```

and then I'm trying to define a function like following to dynamically add options to the select list:

```
function selectuser_ajax_callback() {

  db_set_active('drupal');

  $result = db_query("select * from {content_type_usergroup}");
  $record = db_fetch_object($result);

  $str = '<select>';
  while ($obj = db_fetch_object($result)) {
    $str .= '<option value=' + $obj->vid + '>' + $obj->field_p_group_name_value + '</option>';
  }
  $str .= '</select>';

  echo $str;
}

```

But it's not working. How to make this function work properly to populate the select list `'#options`?

# Answer
For just populating select list options, you don't need to go through an Ajax approach! Simply write a separate function and write your database query inside it and then just call that function in `'#options'` of your `$form['select-user-group']`.

For example for displaying all node types in a select list you can use the following function:

```
function get_node_type_info() {

  $wizard_plugins = node_type_get_types();

  $options = array();

  foreach ($wizard_plugins as $key => $wizard) {
    // Don't forget the $ before wizard
    $options[$key] = $wizard->name;
  }

  return $options;
}

```

And then use this function to populate the `'#options'` like so:

```
$form['display_options'] = array(
  '#type' => 'select',
  '#title' => t('Component Type'),
  '#options' => get_node_type_info(),
);

```
> 4 votes

---
Tags: forms, 6
---


# Question
Title: How can I add more than one pointer to a map?
I want to create a block which has search functionality for looking up locations. I want to be able to add a pointer to the map at the searched for location.

It should be able to add more than one pointer to the map based on what is searched for.

An example of pretty much exactly what I'm looking for the input of locations can be seen here: http://www.mapcustomizer.com/

Does anybody know how to do this?

Thanks

# Answer
You can use Get Location module for this functionality. It will create multiple location markers on a single map, with a popup bubble info and it comes up with inbuilt views. You just need to enable a block after installing it. Some more details about this module (from its project page):

> ... will provide Google maps API version 3 enabled maps on which to display markers of locations found in location-enabled content-types.
>
> These can be displayed per node, eg "/getlocations/node/xxx" will display all the locations associated with that node. They can also be displayed per content-type, so if your content-type has a machine name 'venue' you can show them all with "/getlocations/type/venue" and it also supports paths like "/getlocations/user/xxx" and "/getlocations/users" for location-enabled users. These links have their own access permissions so control can be exercised on a per role basis.

If looking for custom thing, specify your complete requirement.
> 1 votes

---
Tags: location, google-maps, javascript
---


title: Not able to update module via drush

text:
# Question
Title: Not able to update module via drush
I am trying to update a module via drush. Referring this link

```
[root@localhost d7]# drush update
The drush command 'update' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have    [error]
installed new extensions.

```

But it is giving error that 'update' command could not be found. Can anybody help me with this?

# Answer
> 3 votes
Update all update available modules other than locked modules.

drush pm-update

or

Update specified module only.

drush up 'module-name'

# Answer
> 1 votes
You can update your module following this procedure too:

> * make sure db is backed up
> * put site in maint mode
> * disable the module
> * remove the old module's directory in /sites/all/modules/
> * put in the new module's directory in /sites/all/modules/
> * re-enable the module
> * run update.php
> * take site out of maint mode

and if "**update**" command is not found, may be your drush is not installed properly, try inreinstalling it.

---
Tags: 7, drush
---


# Question
Title: How to create a link to a file in a module?
In Drupal 7 I have a custom module that create a file in `public://company/my.csv` but in my module admin interface I want to create link to this file in a status message :

```
drupal_set_message('download your ' . l('file', $url));

```

To link the file I tried

```
$url = file_create_url('public://company/my.csv');
$url = drupal_get_path('file', 'my.csv');

```

I tried also to make myself the link to sites/default/files etc but it doesn't run. Sometimes I get 404 not found and sometimes "You cannot access to this directory".

(I have already checked that the file is well created in the good folder)

Any help is appreciated.

# Answer
> 2 votes
file\_create\_url() is right choice. Check the url it generates and try to open it directly in browser. If it fails do one of these:

* Check if file is exists in right folder
* If yes, check if it readable (filesystem permissions). Also check permissions for files/ directory.
* If file exists and is readable, check your server setup. It should allow to view files from files/ directory. Probably you have wrong mod\_rewrite config (apache) or wrong nginx config.

---
Tags: 7, files
---


# Question
Title: How to theme Profile 2 fields for anonymous?
I bring this question because I am not able to find the answer in anywhere, my apologies if it is a repeated one.

I have a Profile 2 type "curriculum\_vitae", that I use to gather jobseekers CV.

I have all the Jobseeker's CVs available for anonymous users which is working fine. My question how to theme the jobseeker's CV page "The page that will display to anonymous user once they click at the jobseeker profile".

I have a page named "profile2--curriculum\_vitae.tpl.php" located at "\templates\profile2--curriculum\_vitae.tpl.php".

I want to theme every single field of curriculum\_vitae profile.

For example :

```
<div class="container">
<div class="row">
<table class="table table-user-information">
<tbody>
<tr>
<td><strong>Email:</strong></td>
<td>Here I want to print jobseeker's email in here, the filed machine name is "field_cv_email_address"</td>
</tr>
</tbody>
</table>
</div>
</div>

```

# Answer
Your template needs to be:

```
<div class="container">
  <div class="row">
    <table class="table table-user-information">
    <tbody>
    <tr>
      <td><strong>Email:</strong></td>
      <td><?php print render($content['field_cv_email_address']); ?></td>
    </tr>
    </tbody>
    </table>
  </div>
</div>

```
> 1 votes

# Answer
You can create a View of *page* display of type `Profile types`

Then in this View add `curriculum_vitae` as *Relationships*, It causes the fields of `curriculum_vitae` profile be added to the *Fields*.

Now create a *Contextual Filter* of any field you want (it might be name, ID, ...).

So you can easily theme this View to display the information of the selected user. If the View name be *profile*, Then using `views-view-fields--profile--page.tpl.php` you can theme the output.
> 2 votes

# Answer
Same Colin Shipton's answer and more for your question. Code in file profile2.tpl.php

```
<?php
$share = field_get_items('profile2', $profile2, 'field_cv_share_my_personal_info');
//dpm($share);
$email = $share[0]['value'] == 'YourValue'
  ? $content['field_cv_email_address']
  : t('Sorry not accessible to public"');
?>
<div class="container">
  <div class="row">
    <table class="table table-user-information">
      <tbody>
      <tr>
        <td><strong>Email:</strong></td>
        <td><?php print $email; ?></td>
      </tr>
      </tbody>
    </table>
  </div>
</div>

```
> 1 votes

---
Tags: 7, theming, users
---


# Question
Title: How to show only child terms of a taxonomy on a table
I want to display only child terms of a taxonomy on a tableselect ? Example :

Term A has : terms {B,C,D} term E has : term {F}

I want to display only {B,C,D,F} on a table (in order to make some stuff with checkbox etc)

# Answer
Solved by joining two tables : taxonomy\_term\_data and taxonomy\_term\_hierarchy, the second one contains the field : parent ( 0 for parents, tid of the parent if it's a child term)
> 0 votes

---
Tags: taxonomy-terms, forms
---


# Question
Title: How can I add a custom content pane to a feature?
I have a custom content pane that I'm using in a panel that I would like to include in a feature. In the features UI, I don't see any options to add it to the feature; however, on the custom content panes page there is an export option, so it seems like there must be some way to do this.

How can I add a custom content pane to a feature?

# Answer
> 1 votes
Using the recent Features, UUID Features, Panels and CTools, you can export custom content panes without any problems as the mentioned issue has been fixed.

# Answer
> 1 votes
Unfortunately, as per this issue, a bug in features prevents custom content panes from being exported.

---
Tags: 7, panels, features
---


title: Cronmonitor with import-html

text:
# Question
Title: Cronmonitor with import-html
So I'm trying to get the import-html module to import files every time there is a cron run. However, I was hoping someone could help me understand what the format of file\_list, profile\_id, and source\_siteroot is supposed to be. Below is my interpretation of file\_list and source\_siteroot

```
function cronmonitor_cron() {
  if(variable_get('cronmonitor_enable',0)){
    $file_list = ".";
    $context = array();
    $context['profile_id'] = drush_get_option(array('profile-id'), import_html_current_profile_id());
    $context['source_siteroot'] = "sites/default/files/old-sites/.";
    import_html_import_files($file_list, $context);
  }
}

```

but whenever I run cron, I get

```
invalid argument supplied for foreach() import_html_process.inc:52

```

This in turn is the line

```
foreach ($file_list as $list_index => $rel_path) {

```

Which definitely means there is something from with $file\_list, right? What should its structure be? The site says it is
"an array of simple file paths, probably selected from the file\_list form. * Relative to the import context settings."
But it'd help if someone gave me an actual example as the words go over my head right now.

# Answer
> 0 votes
I changed $file\_list to an actual list, \["."\] and source\_siteroot to "sites/default/files/old-sites/" and that gave me a valid path. Also profile\_id to import\_html\_current\_profile\_id();

Thanks!

---
Tags: theming, importing-exporting, cron
---


# Question
Title: How to make a specific template according number of nodes in a content type?
I have a content type article and I need a specific template for showing articles according the number of nodes. If I have 2 nodes (content type article) I need to make a template, if I have 3 nodes (content type article) I need to make another template. How do you suggest to make that?

# Answer
> 0 votes
I don't know how to swap template files with panels I only know how to modify the layout based on condition, sorry. here's a small little snippet i quickly wrote to display a different template based on the number of nodes inside of the content type. This should really be done with a custom module but I don't have time.

1. Make sure templates are in template folder under your theme and named correctly.
2. Copy paste snippet below into your `template.php` file.

```
function YOURTHEME_preprocess_node(&$vars) {

if($vars['type'] == 'article'){
     // set content type
     $content_type = 'article';

     // Count number of articles in article
     $query = "SELECT COUNT(*) amount
               FROM {node} n ".
              "WHERE n.type = :type";
     $result = db_query($query, array(':type' => $content_type))->fetch();

     // get number of articles
     $articleCount = $result->amount;

     //specify template based on number of articles
     // one - is equal to _ and two -- is equal to __ for template file
     // No need to add `.tpl.php`
     if($articleCount == 1){
         $vars['theme_hook_suggestion'] = 'page__template1';
     }
     if($articleCount == 2){
         $vars['theme_hook_suggestion'] = 'page__template2';
     }
     if($articleCount == 3){
         $vars['theme_hook_suggestion'] = 'page__template3';
     }
     // ect.... you should make a dynamic loop here this is just basic logic.
   }
}

```
3. Modify code to your liking
4. Clear Cache

# Answer
> 0 votes
`count(node_load_multiple(array(), array('type' => 'The_Content_Type')))` will give you the number of nodes of type `The_Content_Type`.

The @DMAC solution is right but since you need to do this in Panels module so I give you this solution. In Panels select *Selection rules* and *PHP Code*

Now use this code

```
$nodes = node_load_multiple(array(), array('type' => 'The_Content_Type'));
 if(count($nodes) == 2)
     return TRUE;
 else
     return False;

```

You can clone this *variant* and replace `2` with `3` and modify the theme.

---
Tags: theming, panels
---


# Question
Title: How to do Domain site name translation (DA module)
I just want to translate site name to different language - so when users browse a domain in english they see **English site name**, and when they browse in polish for example, they see **Polska nazwa strony**.

I got all modules (Domain Access, i18n, Variable) and I had enabled two languages, checked variable (site name) in admin/config/regional/i18n/variable - but I can't translate the site name.

I try to translate it on admin/config/system/site-information page - different name for en patch and different for pl - no results, and on admin/structure/domain/view/X/config - also without any results.

Any idea how to menage to translate site name? Am I doing something wrong?

I have tried the Domain Variable module also already (as suggested in one of the answers), with no avail. I have read this nice article by Jose, but it just doesn't work on my site (Drupal 7.38, Domain Access 3.11 and latest version of the Variable module). I did set everything step by step, but I can't figure out what is going on and why this doesn't work.

# Answer
The project page of the "Domain Access" module says:

> If you use the contributed i18n module suite, you should use the Domain Variable module instead of the provided Domain Configuration and Domain Settings modules.

Therefore, I think you should try the Domain Variable module, to check if it fixes you issue.
> 0 votes

---
Tags: i18n-l10n, domain-access
---


# Question
Title: In which step in the checkout process is an user account is created?
I'm using Commerce Kickstart (Drupal 7.23, Kickstart 7.x-2.9). New commerce orders are linked to user accounts. If an account with the same email address does not exist yet, a new account is created. This is the normal flow.

I would like to know in which part of the checkout process, that account is created or linked to, because I've found some cases where the commerce order is linked to anonymous user with no reason.

# Answer
> 0 votes
This happens in Commerce Checkout through Rules.

1. Rule *commerce\_checkout\_order\_convert* will check the order's given mail against existing users and automatically assign it.
2. Rule *commerce\_checkout\_new\_account* creates a new account if the mail given doesn't match a user.

See the rule "Create a new account for an anonymous order". It creates a new user based off of the mail provided by the anonymous user during checkout.

---
Tags: rules, commerce
---


title: Display a block even if it is empty

text:
# Question
Title: Display a block even if it is empty
I am using a menu\_block block that displays sub-menus depending on what page the user is. on some pages, there are no sub-menus, so my menu-block is automatically hidden by drupal. how do i force drupal to display my block even if it is empty?

thanks.

# Answer
> 1 votes
I agree with '2-Stroker'. Do this:

```
function HOOK_block_view_alter(&$data, $block) {
  if ($block->module == 'menu_block' && $block->delta == 'DELTA_OF_THE_BLOCK') {
    $data = array('subject' => 'TITLE OF BLOCK', 'content' => ' ');
  }
}

```

# Answer
> 0 votes
I don't know of a way to explicitly force a block (title) to render if the block content is empty.

I would have hidden the block title from the block itself, and the put the title in an appropriate template.

# Answer
> 0 votes
One way would be to actually put something in it... but hide it via CSS. I actually had to do that to accomplish a quick hack to lobotomize some bad legacy code.

# Answer
> 0 votes
You could create a second block that simply contained the title and then toggle the block visibility based on whether or not the other block exists. You can achieve this by either turning on the PHP filter module and writing some custom PHP to detect if the first block is present or not, or you can write a custom module to do this if you don't want PHP filter on as noted here: Is there a way to set block visibility programmatically without using the PHP Filter module?

# Answer
> 0 votes
I found a work around for my project was to simply make a switch case for the block creation, either "Create Block with content" or "Create block with message"

Example:

```
function ms_server_status_block_view($block_name = '') {
  $block = array( 'subject' => t('TITLE'), 'content' => $content, );
  //OR THIS: $block = array( 'subject' => t('TITLE'), 'content' => 'DEFAULT COMMENT', );
}

```

---
Tags: blocks
---


title: Broken image using custom View template

text:
# Question
Title: Broken image using custom View template
I am trying to print each row with custom HTML. I need to display the image field wrapped inside the image link. I have this in the tow style output template:

```
<div class="myRow">
    <div class="myImg">
        <a href="<?php print $fields['field_news_link']->content; ?>" target="_blank"><img src="<?php print $fields['field_news_image']->content; ?>" /></a>
    </div>
    <a href="<?php print $fields['field_news_link']->content; ?>"><?php print $fields['field_news_source']->content; ?> /></a>
</div>

```

The link part is working, but the image does not display. In the HTML I get:

```
<img src="<img src=" http:="" localhost:8888="" test="" sites="" default="" files="" styles="" featured_image="" public="" 10.27.14%20cnbc.png?itok="MGeDqtuK"" width="200" height="150" alt="my alt tag">

```

On the front end, I see the broken image square and '/\> directly after. What am I doing wrong?

# Answer
You need to print image src like this:

```
<?php print file_create_url($uri); ?>

```

Just change `$uri` with uri of your image (`$fields['field_news_image']`...)

Take a look on function file\_create\_url as well.
> 0 votes

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


# Question
Title: How to add a permission : reorder Taxonomy terms
I need some roles to be able to edit and add terms of specific vocabularies, **but not to reorder them**. How can I add the permission **reorder *foo* vocabulary terms, reorder *bar* vocabulary terms...** with a module or programmatically ?

AFAIK edit terms permissions immediately give you the permissions to reorder terms also.

I already tried these modules below but none implements such permission.

Vocabulary Permissions Per Role

> Allows adding to/editing terms of/removing terms from vocabularies per role... adding terms to a vocabulary but not to another, **reordering**/editing terms of a vocabulary but not another's, etc.

Says so, but reordering /editing come together.

Taxonomy access fix

> * adds 1 permission per vocabulary: "add terms in X"
> * changes the way vocabulary specific permissions are handled
> * changes the Taxonomy admin pages' access checks
> * alters the vocabularies overview table to show only what you have access to edit or delete
>
> The module does what native Taxonomy lacks: more specific Taxonomy permissions (and checking them correctly).

Thank you.

# Answer
After digging a bit more into permission implementation, this is how I solved this issue, in combination with Taxonomy access fix.

```
/**
 * Implements hook_permission();
 */
function MYMODULE_permission() {
  return array(
    'reorder_taxonomy_terms' => array(
      'title' => t('Reorder taxonomy terms'),
      'description' => t('Allows users to reorder taxonomy terms.'),
    ),
  );
}

/**
 * Implements hook_js_alter().
 */
function MYMODULE_js_alter(&$javascript) {
  if (!user_access('reorder_taxonomy_terms')) {
    unset($javascript['misc/tabledrag.js']);
  }
}

/**
 * Implements hook_form_FORM_ID_alter();
 */
function MYMODULE_form_taxonomy_overview_terms_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (!user_access('reorder_taxonomy_terms')) {
    foreach($form as $k=>$v){
      if(substr($k, 0, 3) == 'tid'){
        unset($form[$k]['weight']);
      }
    }
    unset($form['actions']['reset_alphabetical']);
    drupal_add_css(drupal_get_path('module','vts_taxonomy_permissions').'/MYMODULE.css');

  }
}

/**
 * Implements hook_FORM_ID_alter();
 */
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (!user_access('reorder_taxonomy_terms')){
    unset($form['relations']['weight']);
  }
}

```

In MYMODULE.css

```
/* Hide reorder help text */
#block-system-help {
  display: none;
}

```
> 0 votes

# Answer
You need to implement hook\_form\_alter and remove the `Sort alphabetically` button based on the role.

Edit: Something like this (tested)

```
function mymod_form_alter(&$form, &$form_state, $form_id) {
  if (in_array('userrole', $user->roles) && ($form_id == 'taxonomy_overview_terms') {
    unset($form['actions']['reset_alphabetical']);
    drupal_add_css(drupal_get_path('module','mymod').'/css/mymod.css');
  }
}

```

and in `css/mymod.css`, do

```
.handle,.tabledrag-toggle-weight {display:none;}

```

This hides the `Reset to alphabetical` button, drag handles, and `Show row weights` link.
> 1 votes

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


# Question
Title: Different domain names to site languages
I have a Multilingual Drupal 7 site. The site is in 3 languages Dutch (default), English and German. The multilingual setup is done based on the i18n module. All is setup and works great!

Dutch site: litebook.eu German site: litebook.eu/de English site: litebook.eu/en

But now i have 2 more Domain names i have to use: *litebook.de* and *litebook.co.uk*

I want: \- *litebook.de* to go to litebook.eu/de \- *litebook.co.uk* to go to litebook.eu/en

What is the best way to set this ups and what do i have to do exactly?

Thanks a lot!

# Answer
the simple way will be to use .htaccess

```
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^litebook.de$ [OR]
  RewriteCond %{HTTP_HOST} ^www.litebook.de$
  RewriteRule (.*)$ http://litebook.de/de/$1 [R=301,L]
  RewriteCond %{HTTP_HOST} ^litebook.co.uk$ [OR]
  RewriteCond %{HTTP_HOST} ^www.litebook.co.uk$
  RewriteRule (.*)$ http://litebook.eu/en/$1 [R=301,L]
</IfModule>

```
> 0 votes

# Answer
Here is an attempt to complete the previous answer, specific to the extra comment by OPer added to it, which is "***What is Domain Access module different then using redirect method***" ...

* "using redirect method" is like instructing the browser with something like so: "*If somebody enters an URL like, then do not display the content located at that URL; And instead, display the content of the redirected URL*".
* The Domain Access module is used (as mentioned on its project page) for:

> running a group of affiliated sites from one Drupal installation and a **single shared database**. The module allows you to share users, content, and configurations across a group of sites.

Obviously, the redirect method has nothing to do with such "sharing" ... The redirect method doesn't know anything about such sharing of databases. Maybe one could say also "doesn't even care why the content of some other URL is to be shown as a replacement of the redirected URL".
> 0 votes

---
Tags: 7, i18n-l10n, domain-access
---


# Question
Title: How to prevent installation to run from UI?
I have an installation profile that will be installed purely via Drush/CLI. So I need to prevent anyone to run the installation from web interface.

What would be the best approach?

# Answer
> 1 votes
Just specify hidden: true in the info yml file

---
Tags: drush, 8, installation, installation-profiles
---


title: how to add a content creation in a view

text:
# Question
Title: how to add a content creation in a view
I've created a view where it displays all created articles by the current login user. named as "my Articles".

Now, I need to add a `node/add/articles` (which let me add a new article) together with the "my Articles"(view). where the "node/add/articles" is above of "my articles".

I don't have any idea how could I add an `node/add/articles` inside a view.

I need two solutions.

One is by not using a module and the other is using a module.

# Answer
> 0 votes
this could be done two ways that come to mind:

1) Create the view as a block, then under the block configuration set it to show at the top of the content region and only on `node/add/article` page

2) Create the view as a page, and then using Advanced Form Block create a block for the node/add/article form to show in the content region above the View, only on the page url for the view

> Welcome to Advanced Form Block Module. With this module you can do the following:
>
> 1) Create any number of blocks with a particular node edit form.
>
> 2) create any number of blocks with a particular node add form of a content type.
>
> 3) Create as many blocks as you like of each kind.
>
> 4) From the content type choose which fields to display on a per block basis.However required fields will be automatically displayed.
>
> 5) All forms will be saved through ajax. So multiple node forms can be independently placed on a single page and worked with simultaneously.

---
Tags: nodes
---


# Question
Title: If theme folder contains no html.tpl.php file, which html.tpl.php would Drupal default to using?
I’ve taken over a site wherein the theme folder does not contain any html.tpl.php. In this case, which html.tpl.php would get used?

# Answer
> 1 votes
I found it, it's in

mysite/modules/system/html.tpl.php

---
Tags: theming
---


title: Encoding and decoding in Views

text:
# Question
Title: Encoding and decoding in Views
I have a view that accepts a contexual filter.When I pass a value through contextual filter like view/sometext ,it is passed directly without encoding.I need to encode it in the url and decode it before processing it in the view.How can I achieve this?

# Answer
In the view's contextual filter, you would need to select 'PHP Code' in the 'Provide a default value'. Then in code you can specify something like:

```
// get current path
$path = explode('/', current_path());
// make sure the path component exists (replace 1)
if (empty($path[1])) return;
// decode the component (use any function you fancy; replace 1)
return base64_decode($path[1]);

```

The encoding would happen wherever the link exists. If it is a view, you might need to use a module such as Views PHP in order to rewrite your link.
> 0 votes

# Answer
If it is related to a query string, you probably want this views patch: https://www.drupal.org/node/1652568#comment-10121478
> 0 votes

---
Tags: views
---


# Question
Title: How to show selected options only if item is selected in select?
I have created a select option for Province which has values of #1, #2, #3

and I have created a second select for Municipality with values #4,#5,#6,#7,#8,#9,#10,#11,#12

If I select #1 in Province I want to show #4,#5,#6 in Municipality select only.

Can this be achieved? If so how?

# Answer
You may use Reference field option limit module to accomplish this task

> This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.
> 0 votes

---
Tags: forms
---


# Question
Title: How do I capture an audit trail of changes made to a view?
What would be the best way for me to log any administrative changes that might have been made on a view? E.g. a new filter added or a field removed. The audit entry should include a user stamp and a time stamp and the change that was made. Doesn't look like any of the conventional options seem to capture this information.

# Answer
You may use Features module to save your view in code and add version control system (Git, SVN) to your project. Every time when you will change the view you will need to update feature with this view and commit your changes into version control system. Then you will have a history of changes
> 1 votes

---
Tags: 7, views
---


# Question
Title: Adding custom designed product to cart in drupal commerce
Hi I am developing a site for T-shirt designing. I have a custom UI where all the T-shirt products in my site are loaded. customer can design the T-shirt according to their needs like changing color,adding text/image etc using my UI. At the end of UI I have a buy button where user can buy the custom product. How can I add this product to my Drupal cart when user clicks buy button? I have the product id and price loaded in my hand and am using Drupal commerce module in my site.

This is my button form

```
<button type="submit" class="btn btn-primary"  name="button">
                                Buy Now! </button>

```

# Answer
I think you can done it using commerce\_cart\_product\_add(). Pass product id and line item as parameters. For details please check here.Hope this will help you..
> 0 votes

---
Tags: commerce
---


title: How to show rating along with comments?

text:
# Question
Title: How to show rating along with comments?
could anyone tell me how to display rating along with comments? Am working on an ecommerce site and am using five star module for rating. i have configured the five star module where we can rate when posting comments. But after the comments have been submitted the rating does not show up along with respective comments. How to bring rating along with comments?

# Answer
* Goto: `admin/structure/types/manage/theme-display/comment/fields`. In Add existing field select **Fivestar Rating** and save

I have added screenshot
> 0 votes

---
Tags: rating
---


title: wysiwyg in rules text field

text:
# Question
Title: wysiwyg in rules text field
I've got some rules sending email messages to users. The content of the email is defined in a field in a 'send mail' action and I were wondering if it's possible to use wysiwyg there?

# Answer
> 1 votes
Yup. You can use `hook_FORM_ID_alter()` to change any field into text area into a WYSIWYG field:

```
function MYMODULE_form_rules_ui_edit_element_alter(&$form, &$form_state, $form_id) {

  //Set the type to text format
  $form['parameter']['message']['settings']['message']['#type'] = 'text_format';

  //Replace 'full_html' with 'filtered_html' or any other input format that has a WYSIWYG profile
  $form['parameter']['message']['settings']['message']['#format'] = 'full_html';
}

```

---
Tags: rules, wysiwyg
---


# Question
Title: Using views, how to render a block of father terms with a brief shortlist of child terms?
I've a list of taxonomy terms with related subs as follows:

**Father 1**

* child 1.1
* child 1.2
* child 1.n

**Father 2**

* child 2.1
* child 2.2
* child 2.n

**Father 3**

* child 3.1
* child 3.2
* child 3.n

and so on.

I need to put a list of the father followed by the first 5 child elements in a block and put it into homepage.

Now the point is, that after lots of trying, I didn't find a solution about how I can do this.

The only thing that I managed was the selective display of the fathers, but I didn't reach the child in any way. I don't reach the father through a node, or his own term page, because I only need the taxonomy tree iterated in a block containing a list of unformatted columns.

I have already themed all but I'm still not capable of displaying the childs under the father term.

For short, here is a representation of what I'm looking for:

I'm going out of my head because of this, so any help will be greatly appreciated!

# Answer
> 1 votes
If you didn't find better solution you may create one view that will display parent term name and parent tid and second view that will display four children with a contextual filter by parent tid. And using template\_preprocess\_views\_view\_field insert view with terms children in the view with parents.

```
/**
 * Implements hook_preprocess_views_view_field().
 */
 function mymodule_preprocess_views_view_field(&$vars) {
   switch ($vars['view']->name) {
     case 'terms_parents':
       if ($vars['field']->options['id'] == 'tid') {
         $vars['output'] = views_embed_view('children_view', 'display', array($vars['output']));
       }
       break;
   }
}

```

# Answer
> 0 votes
Consider adding appropriate "relationships" to your view (think of a "join" in SQL).

If that doesn't help, consider enhancing your question by adding a screebprint of your current view setup (wher eyou can see fields, relatationships, etc).

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


title: Non existing pages does not return 404

text:
# Question
Title: Non existing pages does not return 404
I have a strange problem when i visit some page like this

> example.com/node/386 "onmouseover=prompt(9999) "

**from Drupal perspective that page doesn't exists right ?**

getting something like this

# Answer
I was alterting the body class array for some reason with a non safe code.

```
$variables['classes_array'][] = 'mysite-'.arg(0);

```

Now, changed to

```
$variables['classes_array'][] = 'mysite-'.check_plain(arg(0));

```

As you can see javascript gets executed as added it to dom `body`

check\_plain

> Encodes special characters in a plain-text string for display as HTML.

PHP strip\_tags will work too.

> (PHP 4, PHP 5) strip\_tags — Strip HTML and PHP tags from a string

Hope someone finds it helpful.
> 2 votes

---
Tags: 7, debugging
---


# Question
Title: How to order multiple values in a field collection
I have an Content type which includes a field of type Field collection, of which there can be an unlimited number of values. I can't work out how to order the rows of data that are displayed by this field.

# Answer
> 1 votes
You can order the Items when you are creating it using the widget that is next to the field. I mean this (It is a field collection that contains multiple fields)

and if you need to sort the items after adding the content, you can use Field Collection views module. This module creates a view of type field collection and by some configurations you can get what you want.

---
Tags: nodes, entities
---


title: How to rewrite field with php in views?

text:
# Question
Title: How to rewrite field with php in views?
I need to do a string replacment with php on a title field in views 3 / drupal 6.So i would to know the best way because after research i found these:

* use Views PHP module
* use Computed fields module
* use PHP in the views template
* use a template file like field.tpl.php (only for D7 ?)

Thanks for tips.

# Answer
> 1 votes
I'm afraid you should never use PHP in Views. As the linked page mentions, you should write your own handler or plugin.

---
Tags: 6, views
---


# Question
Title: How to create a directory during a module install?
I need to create a directory in `public://` when the module is installed via `file_prepare_directory()`. I used this code in function `mymodule_install()`:

```
$mydir = 'public://mydir';
file_prepare_directory($mydir, FILE_CREATE_DIRECTORY);`

```

Upon uninstalling, clear the cache, and installing the module it does not create **mydir**.

# Answer
> 0 votes
Are you sure the directory where you are creating `directory` is writable?

`file_prepare_directory` checks that the directory exists and is writable. You can try drupal\_mkdir statement to create directory in `hook_install`

---
Tags: 7, files
---


# Question
Title: Hook to get details of taxonomy term page
I wrote a module to store taxonomy page details to DB. My requirement is to store `tid`, `term name`, `vid` and UNIX `timestamp` to DB table on every load of taxonomy term page. Here is my code:

```
function reporting_api_taxonomy_term_load($terms) {
  $tid = $terms[arg(2)]->tid;
  $vid = $terms[arg(2)]->vid;
  $term = taxonomy_term_load($tid);
  $name = $term->name;
  db_insert('reporting_api')
    ->fields(array(
      'tid' => $tid,
      'name' => $name,
      'vid' => $vid,
      'timestamp' => REQUEST_TIME,
    ))
    ->execute();
}

```

But it creates unwanted rows with timestamp only. Can any one help to fix this. Is `hook_taxonomy_term_load` is the correct hook.

# Answer
> 2 votes
Taxonomy terms can also be loaded when you're not on a taxonomy page, so `arg(2)` will be empty, hence empty records.

To fix:

```
$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  db_insert('reporting_api')
    ->fields(array(
      'tid' => $term->tid,
      'name' => $term->name,
      'vid' => $term->vid,
      'timestamp' => REQUEST_TIME,
    ))
    ->execute();
}

```

---
Tags: taxonomy-terms
---


# Question
Title: Unable to sort by term weight within multiple term reference
I have two taxonomies, Menu and Menu Category. Menu has a term reference to Menu Category, allowing multiple selections.

I have a view that displays a Menu, and in this view I'm displaying the related Menu Categories - in the Multiple Field Settings for Menu Categories, I have the "Display all values in the same row" option unchecked.

The Menu Categories are sorted by weight, but in the view they are not being output in this order (I can't honestly say what order they are appearing in, perhaps by the order they were added as term references, but certainly not alphabetically or by id).

I've added a Menu Category to the sort criteria, but that doesn't have the desired effect (presumably because it's not looking within the Menu Categories).

I also tried adding a relationship to Menu Category from this view, but this doesn't seem to work either - although there are 3 options and I'm not sure which (if any) are correct:

* Taxonomy term: Content using Menu Category
> Relate each Content with a Menu Category set to the term.
* Taxonomy term: Menu Category (field\_menu\_categories)
> Appears in: taxonomy\_term:menu.
* Taxonomy term: Taxonomy term using Menu Categoies
> Relate each Taxonomy term with a Menu Categories set to the term.

**Update:** As requested, to clarify my view output, I'm expecting the Menu details including the list of Menu Categories, with this taxonomy sorted by the weight assigned to it.

# Answer
> 1 votes
On further looking at this issue, I decided to approach it from a different angle. Without any modifications to my view, which has no sort order defined, I installed and enabled the Taxonomy Term Reference module (https://www.drupal.org/project/term\_reference\_sortable).

Using the above module and setting my Menu Categories term reference to use this widget, I found the order I selected is reflected in my view.

---
Tags: views
---


title: Return webform in a node

text:
# Question
Title: Return webform in a node
I have a custom filter added for a content type 'sample'. On selecting the custom filter for the node body, it checks for webform tokens like \[webform:1234\], by exploding it checks whether it is a webform or not. If it is a webform, it loads that node and render the same to the node body. Here is my code please have a check.

```
function landing_page_filter($text, $filter, $format, $langcode, $cache, $cache_id) {
  preg_match_all('/\\[([a-zA-z0-9_]+:[a-zA-z0-9_]+)+\\]/m', $text, $match);
  $matches = $match[0];
  foreach ($matches as $token) { dpm($token);
    $token_name = str_replace(array( '[', ']' ), '', $token);
    $type = explode(':', $token_name);
    if ($type[0] == 'webform') {
      $nid = $type[1];
      $node = node_load($nid);
     $form = drupal_render($node);
    }
  }
  return $form;
}

```

# Answer
Rather than loading a page based on nid and then returning the loaded output as an HTML , use drupal\_goto function like below :

```
drupal_goto('node'/.$nid);

```
> 0 votes

---
Tags: webforms, input-formats, theming
---


# Question
Title: HTML mail - how to properly format message
I am trying to implement html mail notifications using htmlmail module. I am not certain if message should be formatted as array in `$message["body][]` before the template or passed as a string in `$message['body']`.

The reason I am asking is that I first expected the email to be sent in as a string but then saw the `HTMLMAILSystem::format` function that flattens the body array:

```
  public function format(array $message) {
    $eol = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    // @todo Remove this when issue #209672 gets resolved.
    $default_from = variable_get('site_mail', ini_get('sendmail_from'));
    if ( !empty($message['headers']['From'])
      && $message['headers']['From'] == $default_from
      && valid_email_address($default_from)
    ) {
      $message['headers']['From'] = '"'
      . str_replace('"', '', variable_get('site_name', 'Drupal'))
      . '" <' . $default_from . '>';
    }
    // Collapse the message body array.
    if (module_exists('mailmime')) {
      $body = $this->formatMailMIME($message);
      $plain = $message['MailMIME']->getTXTBody();
    }
    else {
      if (is_array($message['body'])) {
        $message['body'] = implode("<br />$eol<br />$eol", $message['body']);
      }
      $body = theme('htmlmail', $message);
      if ($message['body'] && !$body) {
        watchdog(
          'htmlmail',
          'The %theme function did not return any text.  Please check your template file for errors.',
          array('%theme' => "theme('htmlmail', \$message)"),
          WATCHDOG_WARNING
        );
        $body = $message['body'];
      }

```

So if I understood correctly, message must be preformatted with correct html in `$message["body"][]` , but I am not 100% sure there are lots of code-bits involved for email sendouts. I also need to validate if this will allow me to send mail as plaintext?

# Answer
In Drupal 7, it's the implementation of `MailSystemInterface::format()` that formats the message body and changes it to a string; before that, `$message['body']` is supposed to be an array.
In Drupal 6, `drupal_mail()` receives an array for `$message['body']`, and changes it in a string.

```
// drupal_mail() in Drupal 6

// Build the e-mail (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use module_invoke() as
  // we need to have $message by reference in hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

  // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  drupal_alter('mail', $message);

  // Concatenate and wrap the e-mail body.
  $message['body'] = is_array($message['body']) ? drupal_wrap_mail(implode("\n\n", $message['body'])) : drupal_wrap_mail($message['body']);

```

Compare the code you are showing with the code used by the Drupal 7 implementation (`DefaultMailSystem::format()`).

```
public function format(array $message) {
  // Join the body array into one string.
  $message['body'] = implode("\n\n", $message['body']);
  // Convert any HTML to plain-text.
  $message['body'] = drupal_html_to_text($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = drupal_wrap_mail($message['body']);
  return $message;
}

```

Drupal requiring `$message['body']` to be an array of strings is made clear in `hook_mail_alter()`, which describes it as follows:

* 'body': An array of strings containing the message text. The message body is created by concatenating the individual array strings into a single text string using "\n\n" as a separator.

Since `hook_mail_alter()` is invoked right before the `format()` method, that method is supposed to get an array, not a string.

```
 // drupal_mail() in Drupal 7

 // Bundle up the variables into a structured array for altering.
  $message = array(
    'id' => $module . '_' . $key,
    'module' => $module,
    'key' => $key,
    'to' => $to,
    'from' => isset($from) ? $from : $default_from,
    'language' => $language,
    'params' => $params,
    'send' => TRUE,
    'subject' => '',
    'body' => array(),
  );

  //  …

  // Build the e-mail (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use module_invoke() as
  // we need to have $message by reference in hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

  // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  drupal_alter('mail', $message);

  // Retrieve the responsible implementation for this message.
  $system = drupal_mail_system($module, $key);

  // Format the message body.
  $message = $system->format($message);

```

The only reason I could see to check if `$message['body']` is a string is to protect the code against modules not correctly updated in the passage from Drupal 5 to Drupal 6. In fact, Drupal 5 passed a string for body, as evident in the example for `hook_mail_alter()` shown in the documentation.

```
function hook_mail_alter(&$mailkey, &$to, &$subject, &$body, &$from, &$headers) {
  $body .= "\n\n--\nMail sent out from " . variable_get('sitename', t('Drupal'));
}

```
> 1 votes

---
Tags: hooks
---


title: Check for WebForm Errors

text:
# Question
Title: Check for WebForm Errors
Some of my website visitors are stating that they are filling out the webform (ver 7.x-4.2) and we are not getting the email. They have not provided any detail (error messages, etc...) and when I login and review the Results tab I do not see their emails. I've tested the webform and I get the emails. My questions are as follows:

1) Is there anyway to look for webform errors in a log file? Where would I look? 2) If a webform is not successfully sent, it won't show in the Results tab correct? When does the submission get recorded?

Regards,

John

# Answer
The email may not have been sent without any error at the Drupal end. I recently experienced this problem, and found that the mail server was rejecting emails sent "from" someone claiming to be the same host as itself.

In short, Drupal could successfully send the email without knowing that it wasn't received.

We solved the problem by installing the modules "mailsystem" and "mandrilL" and signing up for a free Mandrill account.
> 1 votes

# Answer
Some of the reports that can be found within the admin section of a Drupal site:

* **Status report**, located at */admin/reports/status*.
* **Recent log messages**, located at */admin/reports/dblog*

(requires core module `dblog` to be enabled).
> 0 votes

---
Tags: webforms
---


# Question
Title: How do I include coffeescript and sass compilation steps into managing Aegir platforms?
By providing a drush make file, Aegir will create a new platfrom but sites cannot be created or migrated to it until coffeescript and sass files have been compiled.
Generated javascript and css are not suited to being kept under version control as they cause unnecessary conflicts etc.

How to augment Aegir to include these extra steps?

# Answer
We do our own automation of the drush provision and drush hosting commands that Aegir does, plus we add a couple of extra steps to do the sass and coffeescript compilations before migrating a site to a new platform automatically.

So we still have the benefits of the Aegir front end but also augment the power of the drush backend with our required extra steps. Plus, by tying it in with Git tags we make generating new Aegir platforms an integral part of the site-development workflow.

It was quite a big step to augment our reliance upon Aegir with automating the running of drush provision steps from our own Fabric tasks. However, at the cost of one or two limitations, our solution is giving us much more flexibility in the resulting automated workflow.

These are the components:

* A Git post-receive hook that triggers a Jenkins job
* A Jenkins job that runs the Fabric tasks
* Fabric tasks that drive drush provision and drush hostmaster steps
* A YAML configuration file.
* A drush .make template file

The solution took quite a bit of effort initially but should be straightforward to copy.
It is a bit lengthy to describe in detail here but a detailed description can be seen here which should give you enough information to tailor our solution to your similar needs using the Fabric program here on GitHub
> 0 votes

---
Tags: drush, aegir, theming
---


# Question
Title: Struggling with Feeds Importer to custom content type
I am struggling to get to grips with the Feeds Importer, getting it to create nodes of my custom content type.

I have created the Feed Importer :

```
$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'feed_new_horizons';
$feeds_importer->config = array(
  'name' => 'New Horizons',
  'description' => 'NASA New Horizons News Feed',
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => FALSE,
      'use_pubsubhubbub' => FALSE,
      'designated_hub' => '',
      'request_timeout' => NULL,
      'auto_scheme' => 'http',
      'accept_invalid_cert' => FALSE,
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsSyndicationParser',
    'config' => array(),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '2592000',
      'author' => '63',
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'title',
          'target' => 'title',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'description',
          'target' => 'body',
          'unique' => FALSE,
        ),
        2 => array(
          'source' => 'url',
          'target' => 'field_feed_source',
          'unique' => FALSE,
        ),
        3 => array(
          'source' => 'author_name',
          'target' => 'field_feed_author',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'delete',
      'input_format' => 'full_html',
      'skip_hash_check' => 0,
      'bundle' => 'feed_news_item',
    ),
  ),
  'content_type' => 'feed',
  'update' => 0,
  'import_period' => '1800',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

```

And although it runs and imports the articles, it does not create the nodes as my custom content 'Feed News Item' - it always creates them as the default 'Feed Item'

I don't see (or understand) how the Feed links to the Importer - I can't see an obvious link between the two, so it's possible I have missed something!

# Answer
So I gave up with Feeds Importer. Despite a clean install, I could not get the feed description to go into any other target field other than description.

Despite setting the text format as Full HTML, it defaulted back to Filtered HTML and would not show the image in the feed. I had to edit each node, change the text format and then it would display.

So, I reverted back to the core aggregator and after some head scratching with CSS, got it to do what I wanted..

You can see the initial result at http://bedsastro.org.uk \- this will be revised and updated shortly, but at least I got it working!
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: how to avoid fieldset in drupal date field
I have a date field in registration form, I am using template for that. When I using its outputs the html with fieldset. How can I remove that I wanna style likebleow fields.

Please see the image

**Its drupal 7**

# Answer
Use the latest full release or the 7.x-2.x-dev version of the Date module.

There is an new option `Render as a regular field` available there:

The option was added at the Make it possible to disable fieldset for date field issue.
> 7 votes

# Answer
You can simply add this to your `template.php` file

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

```

Here '`MYTHEME`' should be you theme name defined in you `.info` file placed inside your theme directory.

Source: http://codekarate.com/blog/removing-fieldset-drupal-7-date-field
> 6 votes

# Answer
It's easiest to do so with CSS.

```
#fieldset-wrapper-id {
  margin: 0;
  padding: 0;
  border: 0 none;
}
#fieldset-wrapper-id legend {
  display: none;
}

```
> 4 votes

---
Tags: 7, theming, datetime
---


title: Node access control

text:
# Question
Title: Node access control
I have 2 content types:

* **Project**.
* **Proposal**.

The Proposal content type has a field reference to the Project content type.

I want to give view access to "Proposal"s only for the user who created the "Project" which the "Proposal" is referenced to.

Any suggestions to help me resolving this problem?

# Answer
> 1 votes
I think you will have to write a custom module to do this. I would suggest implementing the hook `hook_node_access`

```
function <mymodule>_node_access($node, $op, $account) {
   if ($node->type == 'proposal' && op == 'view') {
       $project_node = node_load($node->fields-><project reference>['und'][0]['value']);
       // If the project node is created by the current user, then grant access
       if ($project_node->uid == $account->uid) {
           return NODE_ACCESS_IGNORE;
       } else {
           return NODE_ACCESS_DENY;
       }
   }
}

```

---
Tags: nodes
---