# Question
Title: How to limit access to certain users for those who have "administer users" permission
**EDIT:** I have found out how to solve the 'administer users permission needed' problem so I don't really need to know the answer for this. I will not delete the question however, since I would like to know the answer out of curiosity anyway.

~~Because of this I need to give the permission 'administer users' to everyone~~ while still being able to manage access to individual users (to their view and edit pages as well as to their cancellation).

Therefore I need to restrict users with 'administer users' permission to be able to edit just certain users (based on their id and the id of the user that is to be viewed or edited). (the access function itself is not the problem I already have that one)

I thought about doing something like 'Administer Users by Role' plugin but as it seems there are just too many potential security issues there (the 'administer users permission' is not used only in access to user edit/view but e.g in access to user fields settings page as well.

Any ideas?

# Answer
The `administer users` permission is a **VERY** powerful permission and you shouldn't give this permission anyone that you don't trust. Otherwise, the users with that permission can do all nasty things. For example:

* They can manage fields on user accounts at `admin/config/people/accounts/fields`
* They can manage permissions and grant/revoke users including themselves other permissions at `admin/people/permissions`
* They can add/cancel/edit users including admins!

Conclusion: Never, ever give this permission to ANYONE!

There are a few modules that let users granularly administer other users. One of them is the Administer Users by Role. Although, its latest version for Drupal 7 requires to give this mighty permission to the users, but there's a patch, which I also contributed, at this issue page. With this patch, you don't need to give 'administer users' permission to the users and still allow them to administer other users.

There are also other related modules, but I cannot tell anything about them since I don't use them:

Subuser

> This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.

Role Delegation

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
> 2 votes

---
Tags: users
---


title: Organic group membership request

text:
# Question
Title: Organic group membership request
I need help setting up a notification system for when a user requests to join a group.

At the moment, when the user types in their message and click the join button, the administrator receives no email notification of a users join request.

Can anyone help ?

# Answer
If I remember correctly this feature hasn't been implemented. I'm just hiding the field with CSS.
> 0 votes

# Answer
In OG 7.2 you need to enable Rules module then enable the two rules for "Pending" and "Active" memberships
> 2 votes

---
Tags: organic-groups, emails, notifications
---


# Question
Title: Display a thank you message instead of a page redirect after submitting a Webform in a block?
I am using the Webform module, and I've created a block containing a webform. When I submit the form, my browser goes to the main url for the webform.

How can I display a thank you message instead?

# Answer
> 3 votes
You can do it, from the webform configuration page: Use *Redirection location* or *Confirmation message*.

>

# Answer
> 0 votes
Use hook\_form\_alter in your custom module (better create a new custom module). Get the form id for the webform A using inspect element or firebug. Once done, you alter the submit handler for the webform.

The #redirect is what makes you to redirect to webform url, you might need to unset or change that. Use Drupal\_set\_message() in your custom submit handler to print the thank you message.

# Answer
> 0 votes
Reference of the link : Creating a hook\_form\_alter for webform

ou just need the id of the node and then use the id like in hook\_form\__alter()

the FORMID generated is webform\_client\_form\_

where NODEID is the id of the node

so if you have a module named mymodule and a node with id 44 which has a webform

```
function mymodule_form_webform_client_form_44_alter(&$form, &$form_state) {
$form['#redirect'] = 'your path';
}

```

# Answer
> 0 votes
You can follow the below step to redirect webform submission.

* Create a node using "Basic Page" content type or you can create any custom page or any panel page.
* Edit your Webform page. When you edit your webform node, you will find "view", "edit", "webform" links in your top of page.
* Click on "Webform" link in top of page and it will display the webform configuration for the node.
* Click on "Form settings" in webform configuration.
* In the "Redirection location" section, check radios button "Custom URL" and add the url of your page in textbox.

Kindly see that if you will create node content, then your url will be "node/\[nid\]" or if you create any custom page or panel page, then your url will be different.

---
Tags: 7, webforms
---


title: #states attribute of FORM API?

text:
# Question
Title: #states attribute of FORM API?
Currently I am using **states** attribute in my form to show/hide a drodown having days as its value on selecting a parent dropdown value. My working scenerio is that I want to show a dropdown having 31 days if january,march,may.... is selected and to show another dropdown having 30 days as its value when febraury,april,june .... is selected , can some one suggest me how its could be achieved because in usage of #states attribute only one value could be selected.

function sandbox\_ajax\_dropdown($form, &$form\_state) {

```
$options = array(1 => t('1 月'), 2 => t('2 月'), 3 => t('3 月'), 4 => t('4 月'), 5 => t('5 月'), 6 => t('6 月'), 7 => t('7 月'), 8 => t('8 月'), 9 => t('9 月'), 10 => t('10 月'), 11 => t('11 月'), 12 => t('12 月'),);

$form['state_list'] = array(
    '#type' => 'select',
    '#title' => 'Choose A Day First',
    '#options' => $options
);
$form['illinois_cities'] = array(
    '#type' => 'select',
    '#description' => t("Thirty-One Days."),
    '#states' => array(
        'visible' => array(
            ':input[name="state_list"]' => array('value' => '5'),
        ),
    ),
    '#options' => array(1 => t('1'), 2 => t('2'), 3 => t('3'), 4 => t('4'), 5 => t('5'), 6 => t('6'), 7 => t('7'), 8 => t('8'), 9 => t('9'), 10 => t('10'), 11 => t('11'), 12 => t('12'),
        13 => t('13'), 14 => t('14'), 15 => t('15'), 16 => t('16'), 17 => t('17'), 18 => t('18'), 19 => t('19'), 20 => t('20'), 21 => t('21'), 22 => t('22'), 23 => t('23'), 24 => t('24'),
        25 => t('25'), 26 => t('26'), 27 => t('27'), 28 => t('28'), 29 => t('29'), 30 => t('30'), 31 => t('31')),
);

$form['ohio_cities'] = array(
    '#type' => 'select',
    '#description' => t("Thirty Days."),
    '#states' => array(
        'visible' => array(
            ':input[name="state_list"]' => array('value' => '1', '2'),
        ),
    ),
    '#options' => array(1 => t('1'), 2 => t('2'), 3 => t('3'), 4 => t('4'), 5 => t('5'), 6 => t('6'), 7 => t('7'), 8 => t('8'), 9 => t('9'), 10 => t('10'), 11 => t('11'), 12 => t('12'),
        13 => t('13'), 14 => t('14'), 15 => t('15'), 16 => t('16'), 17 => t('17'), 18 => t('18'), 19 => t('19'), 20 => t('20'), 21 => t('21'), 22 => t('22'), 23 => t('23'), 24 => t('24'),
        25 => t('25'), 26 => t('26'), 27 => t('27'), 28 => t('28'), 29 => t('29'), 30 => t('30'))
);

return $form;

```

}

# Answer
Found it !!!!!!!! The solution is below highlighted.

function modulename\_form\_alter(&$form, &$form\_state, $form\_id) {

```
if ($form_id == 'webform_client_form_14209') {

    $form['submitted']['dob'] = array(
        '#type' => 'fieldset',
        '#title' => t('出生日期'),
        '#weight' => 4,
    );

    $form['submitted']['dob']['dob_month'] = array(
        '#type' => 'select',
        '#title' => t('月'),
        '#options' => array(
            1 => t('1 月'), 2 => t('2 月'), 3 => t('3 月'), 4 => t('4 月'), 5 => t('5 月'), 6 => t('6 月'), 7 => t('7 月'), 8 => t('8 月'), 9 => t('9 月'), 10 => t('10 月'), 11 => t('11 月'), 12 => t('12 月'),
        ),
        '#description' => t('Select month.'),
        '#required' => true,
    );

    /* for 31 days */
    $form['submitted']['dob']['dob_day_31'] = array(
        '#type' => 'select',
        '#title' => t('日'),
        '#options' => array(1 => t('1'), 2 => t('2'), 3 => t('3'), 4 => t('4'), 5 => t('5'), 6 => t('6'), 7 => t('7'), 8 => t('8'), 9 => t('9'), 10 => t('10'), 11 => t('11'), 12 => t('12'),
            13 => t('13'), 14 => t('14'), 15 => t('15'), 16 => t('16'), 17 => t('17'), 18 => t('18'), 19 => t('19'), 20 => t('20'), 21 => t('21'), 22 => t('22'), 23 => t('23'), 24 => t('24'),
            25 => t('25'), 26 => t('26'), 27 => t('27'), 28 => t('28'), 29 => t('29'), 30 => t('30'), 31 => t('31')),
        '#description' => t("Thirty-One Days."),
        '#required' => true,
        ***'#states' => array(
            'visible' => array(
                ':input[name="submitted[dob][dob_month]"]' => array(
                    array('value' => '1'),
                    array('value' => '3'),
                    array('value' => '5'),
                    array('value' => '7'),
                    array('value' => '8'),
                    array('value' => '10'),
                    array('value' => '12'),
                ),
            ),***
        ),
    );

    /* for 30 days */
    $form['submitted']['dob']['dob_day_30'] = array(
        '#type' => 'select',
        '#title' => t('日'),
        '#options' => array(1 => t('1'), 2 => t('2'), 3 => t('3'), 4 => t('4'), 5 => t('5'), 6 => t('6'), 7 => t('7'), 8 => t('8'), 9 => t('9'), 10 => t('10'), 11 => t('11'), 12 => t('12'),
            13 => t('13'), 14 => t('14'), 15 => t('15'), 16 => t('16'), 17 => t('17'), 18 => t('18'), 19 => t('19'), 20 => t('20'), 21 => t('21'), 22 => t('22'), 23 => t('23'), 24 => t('24'),
            25 => t('25'), 26 => t('26'), 27 => t('27'), 28 => t('28'), 29 => t('29'), 30 => t('30')),
        '#description' => t("Thirty Days."),
        '#required' => true,
        '#states' => array(
            'visible' => array(
                ':input[name="submitted[dob][dob_month]"]' => array(
                    array('value' => '2'),
                    array('value' => '4'),
                    array('value' => '6'),
                    array('value' => '9'),
                    array('value' => '11'),
                ),
            ),
        ),
    );

    $form['submitted']['dob']['dob_year'] = array(
        '#type' => 'select',
        '#title' => t('年'),
        '#options' => array(1 => t('2013'), 2 => t('2012'), 3 => t('2011'), 4 => t('2010'), 5 => t('2009'), 6 => t('2008'), 7 => t('2007'), 8 => t('2006'),
            9 => t('2005'), 10 => t('2004'), 11 => t('2003'), 12 => t('2002'), 13 => t('2001'), 14 => t('2000'), 15 => t('1999'), 16 => t('1998'), 17 => t('1997'),
            18 => t('1996'), 19 => t('1995'), 20 => t('1994'), 21 => t('1993'), 22 => t('1992'), 23 => t('1991'), 24 => t('1990'), 25 => t('1989'), 26 => t('1988'),
            27 => t('1987'), 28 => t('1986'), 29 => t('1985'), 30 => t('1984'), 31 => t('1983'),
        ),
        '#description' => t('Select year.'),
        '#required' => true,
    );
}
return $form;

```

}
> 0 votes

---
Tags: javascript
---


title: how separate Entity Reference in view?

text:
# Question
Title: how separate Entity Reference in view?
I have two content type, content type A and content type B , I used Entity Reference field in content type B to reference content type A.

I created view with field Entity Reference ,In Entity Reference there are more field included how can i separate this all field in view ?

# Answer
Add a "Relationship" to your view:

And then select "Entity Reference" in the "Filters" select list. You can choose whether is a content entity that is referenced, or referencing.
> 1 votes

---
Tags: views, entities
---


# Question
Title: Why is there quality loss on my image styles?
This is the original image (610x405)

This is the image after applying image style (scale and crop) to 290x190.

Both image have the same aspect ration, yet there is visible quality loss on downsizing. Am I applying the right image style? What should I be doing?

# Answer
> 15 votes
Under *admin/config/media/image-toolkit* there is an option to set the JPEG quality. By default this is 75%, so you should be able to up that to whatever you want.

# Answer
> 2 votes
You should use the following module : Image style Quality

> Set JPG quality per image style This module allows you to specify a custom quality on different image styles you create. After installing and enabling this module, you will have the option to add a new effect to your image styles, enabling you to change the quality.
>
> Uses and Application Having high quality images is great and improves the visual quality of your site. Problems can arise where you have dynamic content such as a page background images that users can upload. Having high image quality can lead to 2mb+ download sizes when using full 1920x1024 image styles. With this module, you can scale the quality of your large images down and leave your smaller thumbnails at your defined default.

---
Tags: 7, media
---


# Question
Title: how to add a serial number column in a view?
I created a view in drupal and needs some serial numbering as the first column which is not there in the content type on which I created the view. My question is how to add that serial number field in this view like this

```
cand_name | phone_num | email id

```

is my view

I want it like this..

```
sno | cand_name | phone_num | email id

```

hope I am clear, write comments if it needs still clear explanation.

Thanks in advance

# Answer
You should use **Global: view result counter** field defined in a view.

OR if you want a serial field for the content type you can use

the module serial field
> 7 votes

# Answer
Yon can follow below step to add serial number column.

* Administration -\> Structure -\> Views
* Edit your view.
* Add new fields in your view.
* Add "Global: View result counter" field from global section to your view.

> "Global: View result counter" field display the count number of rows in your view result.
> 5 votes

---
Tags: views, entities
---


# Question
Title: Is there a way to create a sort option for search results that works together with facets?
I'm using Drupal Commerce along with Search API and Facet API to create a search for my product dispays. Is there a way to create a facet that sorts products by price? I've tried using the exposed sort in views, but it doesn't work in unison with the facets. Any ideas? I'd prefer that the sort looks similar to the exposed sort criteria in views.

I'm using views to override a search provided by Search API. The view type is "Product display". I've added a "Search: Fulltext search" contextual filter to the view to override the search form. I'm also using Facet API to provide a faceted search to users made available using blocks on the search page. I've tried using the "SORT CRITERIA", which are available in views, to provide an option of sorting the search results by price and relevance. The problem I'm having with this is that the facets, which are provided by Facet API, don't work together with the sort criteria provided by the view.

*Additional Information*

If I select a sort criteria first, then apply a facet, the search results are narrowed down based on the applied facet and everything seems to work well.

If I apply the facet first, then select a sort criteria, the applied facet is reset and the search results that are shown revert back to how many there were before the facet was applied. For example, let's say that I sell 4 cars on my website, 2 red cars and 2 black cars. I search for "cars" and 4 items are shown in the results. I then apply a facet based on taxonomy terms for the color "red". There are only 2 red cars, so the search results are now only displaying 2 results. If I sort the results by "Price" the facet for the color "red" is removed. This causes the search results to revert back to the 4 items that were originally displayed for the search term "cars".

I want to be able to sort the results after a facet is applied and have the applied facet not reset itself.

# Answer
> 1 votes
Indexing the Price:

* Go to Administration -\> Configuration -\> Search and metadata
* Edit your `Search Index` and click on `Fields` tab.
* Select `Product->Price` from the `Add related fields` drop down in bottom of form and click on `Add fields` button. It will add fields for `Product -> price` in index.
* Enable check-box for the field `Product » Price » Amount (decimal)` and save the form.
* Now, you will find `Product » Price » Amount (decimal) (Min)` and `Product » Price » Amount (decimal) (Max)` field in your list. Enable these fields and save the form.
* Reindex your search.

Adding sorting in views:
* Go to Administration -\> Structure -\> Views
* Edit your view.
* Add field `Indexed Node: Product » Price » Amount (decimal) (Max)` or `Indexed Node: Product » Price » Amount (decimal) (Min)` to sort view and save the view.

---
Tags: views, search
---


# Question
Title: Create a user Programmatically in Drupal 6.22
i was trying to create a new user Programmatically in drupal 6.22 but i can't seem to get it working. I need to make a web service that can do a few things, one being create a new user. This webservice is going to be consumed by a mobile device. I was just trying to test the user\_save from outside drupal in just a simple php file and it doesn't seem to work. I just need to know what i'm doing wrong.

Here is my code

```
<?php
    require_once(includes/bootstrap.inc);
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    // Get an array of roles
    $roles = user_roles();
//Basic account information
$user = array(
    'name' => 'username',
    'pass' => 'Password',
    'mail' => 'email',
    'status' => 1,
   'init' => 'email',
    'roles' => array(array_search('authenticated user', $roles) => 1),
);
// See if the user exists by calling Drupal's user_load()
$existing_user = user_load(array('name' => $user['name']));
    if (!$existing_user->uid) {
    // Save the user
    $user = user_save(NULL, $user);
    }
?>

```

EDIT: Added the drupal\_bootstrap, still not working for me.

# Answer
Looks like you've included the bootstrap.inc but you haven't actually bootstrapped drupal.

Example:

```
require_once(includes/bootstrap.inc);
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```
> 1 votes

# Answer
I've tested your code, and it works if it is used inside a regular function that is part of a regular module on a regular Drupal 6 site. This suggests that it is not your code for creating a user is wrong, but that the outside Drupal environment you use for testing does not have enough of the Drupal "scaffolding" up and running, and the code fails because somewhere down the line, it attempts to call functions that does not exist in your test environment.

However, just to show an alternative approach, you can create a user by simulating the submission of the standard user creation form, like this:

```
function createuser_create() {
  $name = 'johndoe';
  $mail = 'johndoe@example.com';
  $password = 'Q1w2E3r4T5y';
  $form_state = array();
  $form_state['values']['name'] = $name;
  $form_state['values']['mail'] = $mail;
  $form_state['values']['status'] = 1; // Active user
  $form_state['values']['pass']['pass1'] = $password;
  $form_state['values']['pass']['pass2'] = $password;
  $form_state['values']['op'] = t('Create new account');
  drupal_execute('user_register', $form_state);
  $errors = form_get_errors();
  if (!empty($errors)) {
    drupal_set_message(t('User account creation failed.'), 'error');
  }
  else {
    drupal_set_message(t('User account created.'));
  }
}

```
> 0 votes

---
Tags: hooks, nodes, services
---


# Question
Title: Make taxonomy term only link to term page if multiple nodes have that term?
I have a free tagging taxonomy term field. How can I make it so on the node page the term only links to a term page if there are multiple nodes with the same term?

Otherwise this link and page are pointless, and are bad UX as the user will be expecting to see other similar nodes. So if there is only 1 node with a term then I would like the term to not be a link.

UPDATE ive tried creating a custom module called taxonomy\_link\_my.

In my taxonomy\_link\_my.info

```
name = Taxonomy link my
description = Stop taxonomy term being a link if no other nodes are tagged with the term.
core = 7.x

```

In my taxonomy\_link\_my.module (topic is the vocabulary name).

```
<?php

/**
 * Implements hook_node_view
 */
function taxonomy_link_my_node_view($node, $view_mode, $langcode) {
  if (isset($node->content['topic'])) {
    foreach ($node->content['topic']['#items'] as $delta => $item) {
       if (count(taxonomy_select_nodes($item['taxonomy_term']->tid)) < 2) {
         $title = $node->content['topic'][$delta]['#title'];
         $node->content['topic'][$delta] = array();
         $node->content['topic'][$delta]['#markup'] = $title;
       }
    }
  }
}

```

However it seems to have no effect.

# Answer
It can be achieved with the help of hook\_node\_view().

Assuming your taxonomy term field is "field\_tags":

```
/**
 * Implements hook_node_view
 */
function YOURMODULE_node_view($node, $view_mode, $langcode) {
  if (isset($node->content['field_tags'])) {
    foreach ($node->content['field_tags']['#items'] as $delta => $item) {
       if (count(taxonomy_select_nodes($item['taxonomy_term']->tid)) < 2) {
         $title = $node->content['field_tags'][$delta]['#title'];
         $node->content['field_tags'][$delta] = array();
         $node->content['field_tags'][$delta]['#markup'] = $title;
       }
    }
  }
}

```
> 0 votes

# Answer
Looks possible implementing hook\_entity\_info\_alter()

> Modules may implement this hook to alter the information that defines an entity. All properties that are available in hook\_entity\_info() can be altered here.

Here is some sample code

```
function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = 'mymodule_taxonomy_term_uri';
}

/**
* Entity uri callback for taxonomy terms. Add special exception to redirect users away
* from taxonomy term pages to the associated program node page.
*/
function mymodule_taxonomy_term_uri($term) {
  if (count(taxonomy_select_nodes($term->tid)) > 1) {
    return array(
      'path' => 'taxonomy/term/' . $term->tid,
    );
  }
  else {
    return array(
      'path' => '',
    );
  }
}

```

You need to make some tweaks to get term id by term name.I have not checked about returning the path if node count is 1.
> 1 votes

# Answer
I suppose it can be achieved with Views. You can can get node count which tagged with that term and if it is below 2 you can rewrite results and make a text without link. I am nearly sure those are possible with Views but to test, make sure and explain step by step can take several pages/hours. I suggest you to make searches about how to do. You may need additional Views modules and other things and hard code somethings with PHP.
> 0 votes

# Answer
I think the best way would be to create a custom formatter for the taxonomy field. Take a look at how the taxonomy module itself does it, in the function `taxonomy_field_formatter_view`. In there they have both the link formatter and the plain formatter.

In your custom formatter, you'll check whether there are other nodes that have each term (you'll use `taxonomy_select_nodes()` or something like this, depending on how your taxonomy field is set up). If there are no terms, you'll format it just as text, using the taxonomy module's plain formatter as an example. If it has nodes, you'll format it like the taxonomy module's link formatter.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to collect time periods, calculate the total, and present in ISO 8601 format?
I am trying to get few inputs of time periods from users (it can be by choosing in dropdown). let's say a user will be able to input in one field: "1 hour and 5 minutes" or 01:05; In second field the user will be able to input: "2 hours and 25 minutes" or 02:25;

Then, I want to calculate and add up the two time peirods for: "3 hours and 30 minutes" or 03:30;

It's important that all the date and time fields will be saved in ISO 8601 format, for google.

Someone can help, How can I do that?

Thanks!

# Answer
You're asking two completely unrelated questions here. To rephrase:

1. How can I provide Google with dates in a format that Google's scraper will recognize, as specified in Rich snippets - Reviews?
2. How can I accumulate time periods and present the result in a format suitable for humans?

Asking two unrelated question in one question is depreciated on SE, and will usually get your question closed, but I am going to answer them anyway.

**First question**: The ISO 8601 format requested by Google is `YYYY-MM-DD` with leading zeros if required, so July the 4th 2013 would be `2013-07-04`.

To format the ISO date you can use the PHP function `date` like this:

```
$isodate = date('Y-m-d', $timestamp);

```

where `$timestamp` is an integer with the number of seconds that has elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT).

Further, Google expects the `$isodate` string to be embedded in the page attached to the `dtreviewed` property using the syntax one of three metadata schemes (microdata, microformats, or RFDa). You do this in Drupal by overriding the template of page, node, etc. you want to embed the `dtreviewed` property in.

**Second question**: To accumulate time periods, you need to convert periods input by users (such as "1 hour and 5 minutes" or "01:05") to an integer format with seconds resolution. To convert to seconds you multiply the days with 86400, the hours with 3600 and the minutes with 60, so "1 hour and 5 minutes" becomes:

```
1 (hour) * 3600 + 5 (minutes) * 60 + 0 (seconds) = 3900 (seconds)

```

and "2 hours and 25 minutes" becomes:

```
2 (hour) * 3600 + 25 (minutes) * 60 + 0 (seconds) = 8700 (seconds)

```

To accumulate, you just add the seconds:

```
3900 + 8700 = 12600 (seconds)

```

To display in a suitable format, you can use `format_interval`.

```
$interval = 3900 + 8700;
$intervalstring = format_interval($interval, 2);

```

and `$intervalstring` will now be:

```
3 hours 30 minutes

```

(You will lose the "and" by using this standard function, if this "and" is important, you'll need to write your own.)

For avoidance of misunderstanding: Goggle is *not* interested in your time period data. A time period is typically an interval made up of **hours** and **minutes**, and not attached to a particular date. Google wants dates (as in **year**, **month** and **day of month**). Dates and time periods are different things, and there is no way you can format a *time period* as a *date*, or vice versa.
> 3 votes

---
Tags: datetime
---


# Question
Title: Is there a way to check if a custom form element exists in application
Suppose i am building a custom form element with

> hook\_element\_info()

Is there a way , in another module,to check this element's existence before inserting it to a form?

# Answer
> 2 votes
You can invoke the hook yourself to check for the existence of a specific element type:

```
if (in_array('some_element_key', array_keys(module_invoke_all('element_info')))) {
  // The element type exists.
}

```

---
Tags: 7, forms
---


# Question
Title: hook_schema is not creating database table
The following function is contained in process\_login.install as part of a custom module called process\_login. The module works if I manually created the database table, but naturally I would like the table created automatically on install.

The function itself does not generate a schema error on installing the module. But neither does it create the database table process\_login\_register in the Drupal 7 MySQL database.

There are no other errors I can see, or problems reported by Site Report.

I have removed it completely and reinstalled numerous times. I have searched the web extensively, and consulted two books I have on Drupal development. I can't see anything wrong with this function (listed below).

NOTE: I have also tried defining 'id' as serial but get the same result (i.e. no table created).

I have run out of ideas. Does anybody know why this function isn't working?

```
function process_login_schema(){
  $schema['process_login_register'] = array(
        'description' => 'Register a specific computer with the system.',
        'fields' => array(
                'id' => array(
                    'description' => 'Primary identifier.',
                    'type' => 'int',
                    'unsigned' => TRUE,
                    'size' => 'normal',
                    'not null' => TRUE,
                    'default' => 0,
                ),
                'ip' => array(
                        'description' => "The user's IP address at registration.",
                        'type' => 'varchar',
                        'length' => 32,
                        'not null' => TRUE,
                        'default' => '',
                ),
                'user_agent' => array(
                        'description' => "The user's browser user agent string at registration.",
                        'type' => 'varchar',
                        'length' => 255,
                        'not null' => TRUE,
                        'default' => '',
                ),
        ),
        'primary key' => array('id'),
  );
  return $schema;
}

```

# Answer
Use `drush dre -y [module]` which disables, uninstalls and then re-enables the module. The `-y` flag makes it even faster, avoiding you have to press *y* and enter three times.
> 22 votes

# Answer
Only if you uninstall a module, and subsequently re-install it, the database tables it uses and declares with `hook_schema()` are re-created.

To uninstall a module, you need to:

* Uncheck the checkbox shown for the module
* Click on *Save configuration*
* Click on the :Uninstall\_ tab
* Click on the check box to the left of the module name
* Click on the *Uninstall* button
* On the next page, confirm you want to uninstall that module by clicking on the *Uninstall* button

As alternative, if you have installed Drush, you can use the following commands.

```
drush pm-disable $module
drush pm-install $module
drush en $module

```

Replace `$module` with the short name of the module, between apices, and without the .module extension.

What you have done is disabling the module, and then re-enabling it. Even if you deleted the directory containing the module, for Drupal what you have done is just disabling, and then re-enabling it.
> 15 votes

---
Tags: 7, database
---


title: Views to show user referenced to node

text:
# Question
Title: Views to show user referenced to node
I'm trying to show user info in node where this user name is set in User reference field.

I have content type where is User reference field (field\_customer).

I have Views:

* **Show:** Users
* **Contextual filter:** (field\_customer) Content: Customer
* **Relationship:** User: Customer (field\_customer) - reverse

In Contextual Filter I have: When the filter value is NOT available = Provide default value User ID from URL
In Relationship I have: Require this relationship

And I have fields like User: Email, User: Name etc.

I created node and set one user to User reference field.

Views does not work as it should. It shows all users. I tryed to play with Views settings but just could not find proper settings.

What I am doing wrong here?

***EDIT***

I also created another Views.

* **Show:** Content
* **Contextual Filter:** Content: Customer
* **Relationships:** Content: Customer

In Contextual Filter I have: When the filter value is NOT available Hide view
In Relationships I have: Require this relationship

And it shows nothing on node page. Also tryed with different settings but no luck.

# Answer
It sounds like you need to reference the relationship you created down in the filter criteria. In the example below I have a views where I want to display all documents of the current logged in user.

1. I created the views showing all documents first. Get your view working the way you want it too first.
2. Create the relationship - I want documents that are related to who authored them
3. Filter your view by the author relationship. So in the example below my view is filtered by the current user - and it shows all documents in which the current user is the author.
4. Once your view is sorted you can work out the user reference part.

Hope this helps
> 1 votes

---
Tags: 7, views, users
---


# Question
Title: How to add conditional HTML meta tag using drupal_add_html_head to force only IE9 into compatibility mode?
Long story short: Some quite nice interative SVG map works fine on every major web browser thanks to svgweb. Except IE, of course. Every IE (8, 9, 10) needs a particular workaround. IE9 would only work when I force it into compatibility mode. Unfortunately I can't find a way to use `drupal_add_html_head` with `#tag' => meta` and `#prefix` and `#suffix` to only take effect in IE9. `drupal_add_html_head` works fine, but `#prefix` and `#suffix` discard it. So that doesn't work:

```
$meta_ie_render_engine = array(
  '#type' => 'html_tag',
  '#tag' => 'meta',
  '#attributes' => array(
    'http-equiv' => 'X-UA-Compatible',
    'content' =>  'IE=7',
  ),
  '#weight' => '-99999',
  '#prefix' => '<!--[if IE 9]>',
  '#suffix' => '<![endif]-->',
);
drupal_add_html_head($meta_ie_render_engine, 'meta_ie_render_engine');

```

Is there another way to use `drupal_add_html_head` with `tag => meta` conditionally? Or another drupal-like alternative?

# Answer
Had similar problem:

```
function detect_ie() {
    if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)) {
        return true;
    }
    else {
        return false;
    }
}

```

above will detect if IE in general. You will need to change 'MSIE' accordingly (something like 'MSIE9' but not sure if thats correct).

Then what i did was

```
if(detect_ie()) {
  $element = array(
  '#tag' => 'meta',
  '#attributes' => array(
  'http-equiv' => 'X-UA-Compatible',
    'content' =>  'IE=EmulateIE7',
     ),
  );
drupal_add_html_head($element, 'IE_cr_ap');
}

```
> 1 votes

---
Tags: 7, meta-tags
---


# Question
Title: how to hide particular comment programmatically
not sure why:

```
function MY_MODULE_comment_view_alter(&$build) {
    $build['#comment'] -> status = 0;
}

```

does not work. It displays comment on the red background, however comment is still visible for all users with 'view comments' rights. What I would like to achieve is simply hide comment so it's not visible.

# Answer
> 2 votes
You achieve this by adding a `comment_post_render` callback function to the build that outputs nothing:

```
function MY_MODULE_comment_view_alter(&$build) {
  $build['#post_render'][] = 'MY_MODULE_comment_post_render';
}

function MY_MODULE_comment_post_render() {
  // Nothing here.
}

```

# Answer
> 0 votes
I think you need this -

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    unset($implementations['comment']);
  }
}

```

Taken from the answer of a question here - Is there a way to stop comment\_node\_view from firing?

---
Tags: 7, hooks, comments
---


# Question
Title: alter the 26 (A-Z) parent links so that just the menu link text is displayed without its associated hyperlink
Within Drupal 7 I have created an A-Z menu which contains all the links on the site organized alphabetically. In addition to these links I have 26 additional parent menu links (A-Z) from which all the site links are organized as child links within these parent links.

I then use the sitemap module to display the contents of this menu within a page with a 3 column layout.

My questions what is the most efficient way to programatically alter the 26 (A-Z) parent links so that just the menu link text is displayed without its associated hyperlink which I had to do originally when creating these links which by default I made as the homepage for all 26 parent links.

# Answer
> 0 votes
special menu items:

Special menu items is a Drupal module that provides placeholder and separator menu items.

A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.

https://drupal.org/project/special\_menu\_items

---
Tags: routes
---


# Question
Title: Zen theme - recommended way to display 2 blocks next to each other in a region
I'm using a zen subtheme and I want to display 2 blocks next to each other.

I don't want to create 2 more regions in the info file because it will only be displayed on the home page. (Maybe even 3 blocks on another page)

Trying to move away from panels due to added markup and extra loading times during dev.

Would the correct way be to.

* Add blocks to content region
* Add css aka (width:50%) on the blocks to get the desired layout

or Is there another theme layer of some-kind I can use for layouts inside of zen?

# Answer
## Plain old CSS

Plain old css will work. Set your widths with those two blocks and float them.

## Zen Grids

If you create custom classes the zen grid sass extension can be used as well to set up layouts using sass

More on zen grids:

## Block class

Block Class is a good way of setting blocks up to line up accordingly next to each other:

> Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent element of a block. Hooray for more powerful block theming!
> 3 votes

# Answer
You can put both block in same region by setting it to show on front only, as per your requirement. Give 50-50 space to both of them by CSS.

If you need any more class/id to set their display right, you can use a module BLOCK CLASS to set unique ID/class for these or any particular block. Hope it helps :)
> 1 votes

---
Tags: theming
---


title: Using db_select with subqueries

text:
# Question
Title: Using db_select with subqueries
Here's an example raw query of what I am trying to achieve with database API:

```
SELECT * FROM (
    SELECT
      n.nid AS entity_id,
      n.uid,
      n.title,
      node_body.body_value,
      node_body.body_format,
      'node' AS entity_type
    FROM
      `node` n,
      `field_data_body` node_body
    WHERE
      n.status = 1 AND
      n.type = 'forum' AND
      n.nid = node_body.entity_id
  UNION ALL
    SELECT
      c.cid,
      c.uid,
      '-' AS subject,
      comment_body.comment_body_value,
      comment_body.comment_body_format,
      'comment' AS entity_type
    FROM
      `node` n,
      `comment` c,
      `field_data_comment_body` comment_body
    WHERE
      c.nid = n.nid AND
      n.status = 1 AND
      n.type = 'forum' AND
      c.cid = comment_body.entity_id
) AS results ORDER BY results.entity_id

```

I have to do this using `db_select()` because of the pager.

My question is: how can I use `db_select()` for selecting results that are *not* from a specific table, but from subqueries like the query above?

Thanks!

# Answer
> 1 votes
I posted a modified question on DBA site and the solution was to simply use a DB view instead.

Here is the code I ended up using:

`MYMODULE.install` file:

```
function MYMODULE_install() {
  db_query("CREATE VIEW {MYMODULE_view_sample}
              SELECT
                n.nid AS entity_id,
                n.uid,
                n.title,
                node_body.body_value,
                node_body.body_format,
                'node' AS entity_type
              FROM
                {node} n,
                {field_data_body} node_body
              WHERE
                n.status = 1 AND
                n.type = 'forum' AND
                n.nid = node_body.entity_id
            UNION ALL
              SELECT
                c.cid,
                c.uid,
                '-' AS subject,
                comment_body.comment_body_value,
                comment_body.comment_body_format,
                'comment' AS entity_type
              FROM
                {node} n,
                {comment} c,
                {field_data_comment_body} comment_body
              WHERE
                c.nid = n.nid AND
                n.status = 1 AND
                n.type = 'forum' AND
                c.cid = comment_body.entity_id");
}

function MYMODULE_uninstall() {
  // Remove the view once the module is uninstalled.
  db_query("DROP VIEW {MYMODULE_view_sample}");
}

```

And then simply browse it as if it was another table:

```
$query = db_select('MYMODULE_view_sample', 's');
$query = $query
  ->extend('PagerDefault')
  ->limit(10);
$query->fields('s');
$results = $query->execute();
foreach ($results as $result) {
  dpm($result);
}

```

Thanks to everyone posting here.

# Answer
> 3 votes
First of all, you can prepare a SelectQuery object using db\_select(), then use it in place of a table in another db\_select(). Example (off-the-cuff, not tested):

```
$inner_query = db_select('comment', 'c')
  ->fields('c');
$outer_query = db_select($inner_query, 'sub');

```

Second of all, you can UNION two prepared SelectQuery objects with the SelectQuery::union() method.

```
$some_query = db_select('comment_table', c)->fields('c');
$union_query = db_select('other_comment_table', o)->fields('o')->union($some_query, 'ALL');

```

So all the tools you need are there; it'll just take some trial and error to put them all together.

---
Tags: 7, database
---


# Question
Title: Altering the type of a menu item to local task (tab)
I've searched for hours but I can't find a good answer on how to alter the type of a menu item to local task (tab).

The private messages 7.x module (when aided by privatemsg\_filter) exposes the following tabs (local tasks):

* Inbox (/messages)
* Sent Messages (/messages/sent)
* All Messages (/messages/list)

There is a 4th menu item (/messages/new) which is currently a MENU\_LOCAL\_ITEM and I want to make it a local task as well. But how? And what is the best way?

# Answer
The following hack worked, to create a new local task item with definitions identical to the original menu item except it's a local task. But is it the optimal way?

```
<?
/**
 * Implements hook_menu().
 */
function MOMODULE_menu() {
  $items['messages/newmessage'] = array(
    'title'            => 'Write new message',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('privatemsg_new', 2, 3, NULL),
    // 'file'             => 'privatemsg.pages.inc',
    'access callback'  => 'privatemsg_user_access',
    'access arguments' => array('write privatemsg'),
    'type'             => MENU_LOCAL_TASK,
    'weight'           => 5,
    'menu_name'        => 'user-menu',
  );

  return $items;
}

```
> 0 votes

# Answer
Thanks @zenrol, here is a code example for the correct answer:

```
<?
function MYMODULE_menu_alter(&$items) {
  // Make the privatemsg new link a tab
  $items['messages/new']['type'] = MENU_LOCAL_TASK;
}
?>

```
> 0 votes

---
Tags: routes, privatemsg
---


# Question
Title: How to display a menu items for a node but not for it's parent
I have a page which I don't want to appear in a menu unless the user is already on that page or a child page underneath it.

For example on a shopping site, I would like to have a 'special offers' page positioned in the menu under the 'products' page, but it would only be visible if you're on the special offers page and not from the products page.

E.g. the standard menu

```
Home
    Products
    Contact us

```

When on the special offers page:

```
Home
    Products
         Special offers
    Contact us

```

Is there a way this effect can be achieved?

# Answer
> 0 votes
you could use Menu blocks and play a bit with the "Visibility settings"

---
Tags: routes
---


title: Form handler submit don't work

text:
# Question
Title: Form handler submit don't work
I have a submission handler for my custom form that doesn't work. I tried many solutions, but nothing works.

### My\_Custom.module

```
 [...]
function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => 'Créer une nouvelle équipe',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_newteam'),
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}
 [...]

```

### form\_tournament.inc

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

 [...]
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );
    $form['actions']['submit']['#submit'][] = 'form_newteam_submit';

    return $form;
}

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

function form_newteam_submit($form, &$form_state) {

    drupal_set_message("Bla bla submit !");

}

```

My validation function works.

I try all this code In `form_newteam()` function.

```
$form['actions']['submit']['#submit'][] = 'form_newteam_submit';
$form['#submit'][] = 'form_newteam_submit';
$form['#submit'] = array('form_newteam_submit');
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Créer',
 '#submit' => array('form_newteam_submit'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Créer',
  '#submit' => 'form_newteam_submit',
);

```

# Answer
Go back and scrutinize your validation function. The code you are showing here actually works, so the problem is something you did not include in your sample.

For the reference, the working implementation over here is:

```
function form_newteam ($form, &$form_state) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    drupal_set_message("valid");
}

function form_newteam_submit($form, &$form_state) {
    drupal_set_message("submit");
}

```

Please note that your function names do not conform to the drupal coding standards. Function names must be prefixed with the module name. Therefore you should name your functions like this: `tournament_newteam` or `tournament_newteam_form`. If those are administrative forms, stick them into `tournament.admin.inc` otherwise place them into `tournament.pages.inc`.
> 1 votes

# Answer
try

```
function form_newteam_submit(&$form, &$form_state, $form_id = 'form_id') {

    drupal_set_message(t('Bla bla submit !'), 'status');

}

```
> -1 votes

---
Tags: 7, forms
---


title: How to choose the alias used in a menu

text:
# Question
Title: How to choose the alias used in a menu
I'm having a bit of a problem when using multiple aliases regarding which alias appears on a menu.

For example, I have create a page `/node/1`, give it an alias `/page1` and add it into the navigation menu.

Browsing to the index page I can see the page in the navigation at `/page1`.

I also want the page to be available at another alias `/page2` so I add this through the URL aliases functionality. Unfortunately this updates my menu so the link in the menu now points to the URL `/page2` instead of `/page1`.

If I have multiple aliases to a node, how does Drupal decide which is used in a menu and how can I change this

# Answer
> 2 votes
When multiple aliases are available, Drupal uses the most recently created (as determined by the pid column in the url\_alias table).

I don't know an easy way to change this behavior. You could try manually altering the pid value in the database. Also consider if using a redirect is a better solution than aliasing.

# Answer
> 1 votes
When I faced the same problem, the only I solution I found was to use absolute (starting from `http://`) menu paths (i.e www.example.com/page-1), which are stored in Drupal's menu system as is, not as internal paths

# Answer
> 1 votes
To avoid these multiple aliases issue, you can directly give the node/\[nid\] path in menu items which will be static always.

# Answer
> 0 votes
You could use :Nodesymlinks. The answer of @Valery Lourie also is looking valid.

---
Tags: routes, uri, path-aliases
---


# Question
Title: Trying to install Drupal modules and themes: keep getting error "does not contain any .info.yml files."
I am new to Drupal. I am running Drupal 8. I have tried to install three different themes and modules, and keep getting this error:

> does not contain any .info.yml files

Including with the Beale Street module with a 8.x release.

Why am I seeing this error? Are .info.yml files a newish requirement that most themes don't have yet? Where can I get themes that include `.info.yml` files?

# Answer
> 6 votes
**TL;DR** you're trying to install a theme or module in Drupal 8, which doesn't contain the required files. You might be trying to install a Drupal 7 (or earlier) module by mistake, or it may not be a Drupal module at all.

The 8.x-dev branch of the Beale Street theme is most definitely not Drupal 8 compatible. It's a straight copy of the current 7.x-dev branch, so it hasn't been converted yet. The maintainer has said as much.

Converting a module/theme from 7.x to 8.x requires a lot more work than just adding a yaml file, and if you don't find one in a particular release you can safely assume it hasn't been converted yet.

There are lists of modules and themes on Drupal.org that are tagged with 8.x. As you've seen, not all of them are ready yet. Bear in mind quite a few will still be in -dev, so they're not expected to be useable.

---
Tags: 8
---


# Question
Title: Validate username field in user registration form, drupal 7
I need to compare the text in the username field with the text in email field of the registration form. If they are not equal i want to stop the registration. I think i should use a hook but i really don't know where to start from.

Any idea?

# Answer
You can do this by using `hook_form_FORM_ID_alter()` and adding an extra validation function to the user register form:

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MYMODULE_validate_register_form';
}

function MYMODULE_validate_register_form(&$form, &$form_state) {
  if ($form_state['values']['mail'] != $form_state['values']['name']) {
    form_set_error('name', t('Name and email must be the same.'));
  }
}

```

I'm not 100% positive those `$form_state['values']` keys are the right ones so you'll need to inspect the form to make sure; but the logic is the same either way.
> 6 votes

# Answer
Maybe the Email registration module is something for you: http://drupal.org/project/email\_registration

> Allow users to register and login using only an email address. Users can then log-in using their email address and password for authentication.
> 3 votes

# Answer
Clive's answer above is great, but if you prefer to work in the theme layer you can put this code into your theme's template.php file.

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'user_register_form'){
    $form['#validate'][] = 'MYTHEME_validate_register_form';
  }
}

function MYTHEME_validate_register_form(&$form, &$form_state) {
  if ($form_state['values']['mail'] != $form_state['values']['name']) {
    form_set_error('name', t('Name and email must be the same.'));
  }
}

```

You can obviously change the validation statement to do whatever you want, you just have to make sure to pass "form\_set\_error()" to invalidate the form and display a message to the end user.
> 2 votes

# Answer
You can also use the Login Toboggon module to do all kinds of neat login-y things.

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> * Allow users to login using either their username OR their e-mail address.
> * Allow users to login immediately.
> * Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
> * The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
> * Customize the registration form with two e-mail fields to ensure accuracy.
> * Optionally redirect the user to a specific page when using the 'immediate login' feature.
> * Optionally redirect the user to a specific page upon validation of their e-mail address.
> * Optionally display a user message indicating a successful login.
> * Optionally combine both the login and registration form on one page.
> * Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
> * Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)
> 1 votes

---
Tags: forms, hooks
---


# Question
Title: Ubercart 3: Skip review, single page checkout
I am using Drupal 7.12 and Ubercart 3.0. I created a custom module in order to enable a single page checkout by skipping the checkout review page.

## The Code

```
/**
 * Implementation of hook_form_submit().
 *
 * Change Ubercart review pages to instant order submissions.
 */
function uc_onepagecheckout_form_submit($form, &$form_state) {
    // check for order submit
    if(isset($form_state['storage']['order'])) {
        $order_id = $form_state['storage']['order']->order_id;
        $reviewRequested = $_SESSION['uc_checkout'][$order_id]['do_review'];
    }

    // If the normal submit handler set do_review then call the review
    // form submit function.
    if ($reviewRequested && $form_state['redirect'] == 'cart/checkout/review') {
        // Clear the previous redirect because we're going to override it anyway.
        unset($form_state['redirect']);

        // Cause the review form to be loaded because some modules may
        // do some of their processing here.
        uc_cart_checkout_review();

        $order = uc_order_load($_SESSION['cart_order']);
        if ($order->payment_method == 'paypal_wps') {
            $wps_form = uc_paypal_wps_form($form, $form_state, $order);
            $wps_url = $wps_form['#action'] . '?';
            foreach (element_children($wps_form) as $key) {
                $wps_url .= urlencode($key) . '=' . urlencode($wps_form[$key]['#value']) . '&';
            }
            $wps_url = trim($wps_url, '&');
            drupal_goto($wps_url);
        }
        else {
            // Now submit the form.  Obviously the $form_state isn't actually
            // correct... hopefully nothing will care.
            uc_cart_checkout_review_form_submit($form, $form_state);

            // And check for an error.
            if ($form_state['redirect'] == 'cart/checkout/review') {
                // There's an error, so pretend the user clicked back.
                uc_cart_checkout_review_form_back($form, $form_state);
            }
        }

        // Ultimately the $form_state changes made by functions above are used.
    }
    elseif ($form_state['redirect'] != 'cart/checkout') {
        // Log any unexpected URLs in 'redirect'.
        watchdog('uc_cart', 'Checkout returned unexpected destination url: %url',
            array('%url' => $form_state['redirect']), WATCHDOG_DEBUG);
    }
}

/**
 * Implementation of hook_form_alter().
 *
 * Changes text on review order button to submit order and adds our custom submit function.
 * Adds a "Skip checkout review" option to checkout settings form.
 */
function uc_onepagecheckout_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id) {
        case 'uc_cart_checkout_form':
            // Change the submit button label.
            $form['actions']['continue']['#value'] = variable_get('uc_checkout_submit_button', t('Submit order'));

            // Add our submit handler.
            $form['#submit'][] = 'uc_onepagecheckout_form_submit';
            // And add our JavaScript file to handle this submit button.
            drupal_add_js(drupal_get_path('module', 'uc_optional_checkout_review') .'/uc_onepagecheckout_checkout_form.js');
            // Add the uc_cart css, since it contains the throbber styles that we are using in the JavaScript.
            drupal_add_css(drupal_get_path('module', 'uc_cart') .'/uc_cart.css');

            break;
    }
}

```

This code is based on this module: Ubercart Optional Checkout Review

## The Problem

Submitted orders are getting stuck in the "in\_checkout" state instead of having the "pending" state. Also, no emails are sent to the customers. Probably, the invocation of `uc_cart_checkout_review_form_submit($form, $form_state)` does not work properly.

Can you help me to solve this issue?

# Answer
> 3 votes
I found it myself. The problem was a non-intended change in the ubercart core file uc\_cart.pages.inc, so that the function uc\_cart\_checkout\_complete() instantly returned without completing the order. This should not occur in normal cases, so that the code in my question should work.

# Answer
> 2 votes
You can easily remove review by installing uc\_optional\_checkout\_review module and set the check box of "Skip checkout review" at admin/store/settings/checkout menu.

# Answer
> 0 votes
Your solution works with products without attributes, but when you have attributes, you loose them i'm working on a solution but at the moment i don't have it.

---
Tags: 7, ubercart
---


# Question
Title: Create New User After Subscribing with Simplenews
I want new Subscribers to a single Newsletter using SimpleNews to automatically be set a Role so that they are already then registered on a site. I have already tried a custom Rules Set but the Role creation doesn't appear to happen and I'm wondering what I'm doing wrong in my approach to the Rule.

The frontend process is i) Anonymous user subscribes via the Simplenews Subs Block ii) send them they are now subscribed.

The backend is something like:

i) User Subscribes as an Anonymous user (i.e. not logged in)

ii) Subscribe to Newsletter type

iii) Set Role from initial 'Anonymous' to 'Subscriber' Role and assign to a Profile type.

Also, I'd like to reduce the 'confirm' email process which currently needs to be given by the end user to confirm a subscription.

I appreciate that some 'hacking' my be needed in the Simplenews core to reduce certain features and would appreciate any advice on this.

I'm sure this is easy to do and I'm merely missing something in my efforts, would someone like to share what I'm doing wrong in the above Rules structure?

Thanks.

# Answer
> 0 votes
I changed tact. The above probably has security issues, but I only needed a simple temporary solution for a new project launch. I dropped the use of a frontend 'Subscriber' option and instead reverted back to a standard registration page and commented out the $vars tabs option in the theme template.php page.

---
Tags: rules, users, emails
---


# Question
Title: How to insert a new tag with chosen module ?
I installed the chosen module and its library on my site drupal 7.

I created a custom field in a content type to enter tags (words) within the vocabulary (taxonomy).

Everything is working correctly for the selection of tag between those in vocabulary, but I can not insert new tags if they do not exist.

Any help ?

# Answer
> 2 votes
I believe the Autocomplete Deluxe module aims to solve that problem.

Autocomplete Deluxe is a replacement for Chosen module. It has a similar feel to the Chosen module, but allows you to add new tags/terms.

# Answer
> 1 votes
Problem is - both chosen and tag system override html tag with their own functionality. For now chosen does not support freehand writing in it. Unless you can rewrite that part of chosen library, you are stuck, sorry.

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


# Question
Title: How to collect Duration input, and let Google read it in "ISO 8601 duration format"?
I am building a Recipes site. As Google is demanding here: https://support.google.com/webmasters/answer/173379?hl=en I need to collect prepTime, cookTime and totalTime, in ISO 8601 duration format.

I think I found a way to do that:
I have installed the date module.
Then I have an option to choose field type: "Date (ISO format)".
For field widget I chose "select list".
Then, in the field settings "MORE SETTINGS AND VALUES" -\> "Custom format" -\> and writing "H:i".
For displaying the field I am choosing: "Date and Time" -\> Choose how users view dates and times: "Hours and Minutes (00:10)".
For me it looks fine, and it's collecting the data as I want, and displaying it properly.

Does my way is correct?
Will Google be able to read this data from the field correctly?

I am using the Microdata module and the Schema.org module. So, for example, in the field setting of the "Cook Time" field, I defined the relevant Property ("cookTime") in the microdata section and in the schema.org section. Is that enough? Does now Google will be able to read this data from the field correctly?

My site is still under development, using acquia DEV desktop. But, Here is a Sample text that I copied from the "view source":

```
<div class="panel-pane pane-entity-field pane-node-field-preptime" >

        <h2 class="pane-title">Prep Time</h2>

  <div class="field field-name-field-preptime field-type-date field-label-hidden"><div class="field-items" id="md9"><div class="field-item even" itemprop="prepTime"><span class="date-display-single" property="schema:prepTime" datatype="xsd:dateTime" content="0000-01-01T03:45:00+01:39">03:45</span></div></div></div>

  </div>

<div class="panel-pane pane-entity-field pane-node-field-cooktime" >

        <h2 class="pane-title">Cook Time</h2>

  <div class="field field-name-field-cooktime field-type-date field-label-hidden"><div class="field-items" id="md11"><div class="field-item even" itemprop="cookTime"><span class="date-display-single" property="schema:cookTime" datatype="xsd:dateTime" content="0000-01-01T01:15:00+01:39">01:15</span></div></div></div>

  </div>

```

**Update**:
I created the following field override template file called: "field--field\_preptime.tpl.php"

```
<?php
function time_to_iso8601_duration($time) {
    $units = array(
        "Y" => 365*24*3600,
        "D" =>     24*3600,
        "H" =>        3600,
        "M" =>          60,
        "S" =>           1,
    );

    $str = "P";
    $istime = false;

    foreach ($units as $unitName => &$unit) {
        $quot  = intval($time / $unit);
        $time -= $quot * $unit;
        $unit  = $quot;
        if ($unit > 0) {
            if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
                $str .= "T";
                $istime = true;
            }
            $str .= strval($unit) . $unitName;
        }
    }

    return $str;
}
 ?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
    <?php $time = strtotime(render($item), 0); ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>></div>
          <time datetime=<?php print time_to_iso8601_duration($time); ?> itemprop="prepTime"><?php print render($item); ?></time>
    <?php endforeach; ?>
  </div>
</div>

```

The Output, when I am viewing in the "view source" on the relevant page:

```
<div class="field field-name-field-preptime field-type-number-integer field-label-hidden">
    <div id="md11" class="field-items">
              <div itemprop="prepTime" class="field-item even"></div>
          <time datetime="PT3H45M" itemprop="prepTime">3 hours 45 min</time>
      </div>
</div>

```

As far as I can see, the input is fine, and the output is fine.
What do you think?
Does now everything is correct, and Google can read it now correctly?

# Answer
The page to you link to: Rich snippets - Recipes, tells you to use the ISO 8601 duration format attached to the properties `prepTime`, `cookTime`, and `totalTime` in one of three standard metadata formats (Microdata, Microformats, or RDFa).

What you're proposing do will *not* enable Google use these duration data for a *rich* snippet. However, Google may still index your site and use your data without using this special format - it then fall back on the human-readable data. Not having a your data packaged for a rich snippet is usually not a major problem vis a vis Google. You need to think about offering Google data prepared for a rich snippet is worth the work required to render these data.

As for using the Microdata and Schema.org modules to inject this metadata, it may or may not work. It depends on the capabilities of the modules, and on how you use these modules.

When looking at the output posted in your question, using MicroData, you output:

```
<div class="field-item even" itemprop="cookTime">
  <span class="date-display-single" property="schema:cookTime" datatype="xsd:dateTime"
    content="0000-01-01T01:15:00+01:39">01:15</span>
</div>

```

while Google expects this:

```
<time itemprop="cookTime" datetime="PT1H15M">01:15</time>

```

Hence, I doubt that the current output produced by the MicroData will be understood by Google. You've got the `itemprop="cookTime"` right, and the div-wrapper is probably also OK, but you're missing the `datetime` attribute in the MicroData tag and the formatting of the machine readable duration is wrong.

I think it would be simpler to use a template override to inject these metadata tags in the HTML, instead of struggling with these modules. So *if* you want to do this, here is how I would have done it:

The ISO 8601 duration format is not intened to be seen by humans. For instance, to indicate a duration of ten minutes the format is: "`PT10M`" and 3 hours 30 minutes is "`PT3H30M`". You can generate interval objects with the PHP `DateInterval` class. Example:

```
$interval = DateInterval::createFromDateString('3 hours 30 minutes');
$isointerval = sprintf('PT%dH%dM', $interval->h, $interval->i);

```

To get Google to pick up these, you need to embed them in the page HTML markup (they're not supposed to be visible to humans) attached to the properties `prepTime`, `cookTime`, and `totalTime` using the syntax one of three metadata schemes (microdata, microformats, or RDFa). You do this in Drupal by either overriding the template of page, node, etc. you want to embed the properties in, or by creating a custom field module that implements the cooking duration field complete with the markup specified by Google.
> 3 votes

# Answer
No, you will need to include additional information for ISO duration format.

http://en.wikipedia.org/wiki/ISO\_8601#Durations

You can use various metadata formats for Recipes to add the machine readable information for indexing, e.g microdata, microformat or RDFa

e.g, microdata for recipes.

```
<div itemscope itemtype="http://data-vocabulary.org/Recipe" >
  <!-- other content here -->
  Prep time: <time datetime="PT30M" itemprop="prepTime">30 min</time>
  Cook time: <time datetime="PT1H" itemprop="cookTime">1 hour</time>
  Total time: <time datetime="PT1H30M" itemprop="totalTime">1 hour 30 min</time>
  <!-- other content here -->
</div>

```

See the section at the bottom of this page: https://support.google.com/webmasters/answer/173379?hl=en for more information on metadata formats.

You'll probably need to use custom field templates or similar to add the additional metadata information there.
> 2 votes

---
Tags: entities, datetime
---


# Question
Title: How do I configure facet items to remain visible when they are selected?
I'm using Commerce Search API along with Search API and Facet API to provide a search for my products. For the server I'm using Search API Solr search.

I want to configure the facets for the search to remain visible when selected. As the facets are now, when I select one it disappears.

Although it seems that this should be an easy task to do, after searching around I couldn't find any information on how to successfully do this. If anyone has experience with this or an idea to make it work your help will be much appreciated.

# Answer
I figured it out. Go to "Configuration » Search and metadata » Search API" and click the facets tab. Next to the desired facets you will see "configure filters" with an arrow pointing down next to it. Click the arrow. In the drop down select "configure filters". Make sure that "Do not display active items" is NOT selected. This worked for me.
> 1 votes

---
Tags: theming, commerce, search
---


# Question
Title: Disable Node's Show summary in full view in D6
In https://drupal.org/node/514318 it talks about how to disable showing the summary/teaser in full view mode but only for D7 it seems.

In my D6 based site, I've filled in meta-description in the node teaser as required by Nodewords module.

The problem is that in full view mode it is clubbing this node teaser with the node's body text. Is there any option to avoid it adding with the body content?

In the picture from dsm($form) in hook\_form\_alter when editing node we can see there is teaser\_include array key with #default\_value = TRUE. I'm wondering where in the Admin interface we can specify this setting.

# Answer
I've written a form\_alter function for node edit form that has solved my problem:

```
function my_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'page_node_form') {
        $form['body_field']['teaser_include']['#default_value'] = FALSE;

        $prefix = $form['#node']->teaser;
        $str = $form['body_field']['body']['#default_value'];

        if (substr($str, 0, strlen($prefix)) == $prefix) {
            $form['body_field']['body']['#default_value'] = substr($str, strlen($prefix));
        }

    }
}

```

Also the teaser\_include as in the question is from the node edit form which is accessible from this checkbox:
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: where is the submit handler for the Drupal Commerce Review page?
I need to know how the drupal Commerce review page is being created and where the submit handler is which precedes that page. I have added a couple of fields which aren't being picked up in the panes, and I want to debug in the handler (or even a review page tpl file). Where can I find this? I have looking though the code and havn't found the answer.

# Answer
All checkout page forms are built using the checkout pane info David Thomas indicated through the function commerce\_checkout\_form() in commerce\_checkout.pages.inc. The validate handler does double duty for the checkout form, validating and actually submitting data on a pane by pane basis to capture valid data as soon as possible. This function is aptly named commerce\_checkout\_form\_validate(). Your best bet will be to log debug messages using watchdog instead of displaying them on the screen via drupal\_set\_message(), because we do some status message processing in there to put messages inline with the panes that generated them - that can make it hard to force a debug message to show when you expect it.
> 1 votes

# Answer
If you want to add checkout panes to the review process you can use

`hook_commerce_checkout_pane_info`

In particular:

> **review**: boolean indicating whether or not the pane should be included in the review checkout pane; defaults to TRUE

and also:

> **callbacks**: an array of callback function names for the various types of callback required for all the checkout pane operations, arguments per callback in parentheses: ....
> **review**($form, $form\_state, $checkout\_pane, $order): returns data used in the construction of the Review checkout pane

If you want to alter existing checkout panes, e.g the form or the content on the review page, you can use

`hook_commerce_checkout_pane_info_alter`

and adjust the `checkout_form` or `review` property there.
> 0 votes

---
Tags: commerce
---


title: views stripping html tags

text:
# Question
Title: views stripping html tags
I am using views to create a table in which I display blogs title and body. Blog is a content type in which body field can be any of plain text, HTML and full HTML. I want to display only two lines of the body for which I use trim option under Rewrite results tag, and set maximum length to 300 which serves the purpose for paragraphs. But if there is a line break then this doesn't work and the text appears in three lines. Please refer to snapshot below :

The output in row number 2 is desired one. How do I go about it?

# Answer
In the "Rewrite results" section, when you checked check-box "Trim this field to a maximum length", there is check-box "Field can contain HTML" in this section. If you check check-box ""Field can contain HTML", then Drupal will maintain your HTML with content.
> 4 votes

---
Tags: views
---


# Question
Title: How to get the URL for the re sized image
I have built a custom form in Drupal 7. The form has a file type field which allows the user to upload an image. I'm using the below code in the submit function to save and re size the image:

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

    $file = $form_state['storage']['file'];
    // We are done with the file, remove it from storage.
    unset($form_state['storage']['file']);
    // Make the storage of the file permanent
    $file->status = FILE_STATUS_PERMANENT;
    // Save file status.
    file_save($file);
    //get the url for the saved file
    $url = file_create_url($file->uri);
    echo $url;
    echo '<br>';

    $destination = 'public://ImageThumbnail';
    $img = image_load($file->uri);
    image_resize($img, 200, 200);
    $result = image_save($img,$destination);
    echo $result;

    exit;
  }

```

The image is re-sizing and saving correctly as the $result is printing 1. I need to know how to get the URL for the re sized image. Am I missing something?

Thanks for you help.

# Answer
> 1 votes
I wouldn't use your approach because as you can see by yourself now you have no reference to the resized image, what I would do is use image\_style\_path :

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

    $file = $form_state['storage']['file'];
    unset($form_state['storage']['file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    $url = file_create_url($file->uri);
    // this
    $derivative_uri = image_style_path($your_style, $file->uri);
    $url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);
}

```

This creates a folder in your files folder with your style name and stores the image there, then wherever in your code you want to get that image you just reutilize this code:

```
$derivative_uri = image_style_path($your_style, $file->uri);
$url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);

```

Drupal checks if an image is there and gives you back the `$url`, if it's not there it creates the image applying your style.

P.S. you need to register your style in configuration and once the style folder is created check it's permission settings.

---
Tags: forms, media, files
---


# Question
Title: Add meta tag description, page title and abstract programatically
I have created a custom page using a tpl.php file and I want to add meta tag page title, abstract and description that page. Can anyone show me how to add these meta tags programatically to custom page?

```
$description = array(
                 '#type' => 'html_tag',
                 '#tag' => 'meta',
                 '#attributes' => array(
                 'name' => 'description',
                 'content' => 'here all description goes',
               )
 );
drupal_add_html_head($description, 'description');

```

This is the code I am using to add description to my head. Thanks in advance.

# Answer
> 5 votes
In your theme's template.php file, you could add something like

```
/**
 * Implements hook_preprocess_html
 */
function THEME_NAME_preprocess_html(&$vars) {

  if (current_path() == 'my/custom/path') {
    $description = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'description',
        'content' => 'here all description goes',
      )
    );
    drupal_add_html_head($description, 'description');
  }

}

```

Clear cache to register new preprocess function.

---
Tags: theming, meta-tags, 7
---


# Question
Title: How to get the hard coded string as output in views_php module
I am using quiz module.

I am creating a view which has field which shows the status of the quiz. If the user score is greater than pass rate, the field should display "pass" else "fail". How to achieve this.

I used views php module to do this. But, I'm confused between **Value code** and **Output code**.

Can anybody provide some pointers?

# Answer
> 1 votes
**Value Code** : The value of the Field.

**Output Code** : The php code that you wish to execute for getting the output for that field.

---
Tags: 7, views
---


# Question
Title: How do I append something to a node when it's in detail page
I'm writing a module that appends content to a node. I'm doing this using `hook_process_node` :

```
function mymodule_preprocess_node(&$variables) {
  $variables['content']['body'][0]['#markup'] .= '<p>My content</p>';
}

```

How can I put a condition here to tell Drupal to only append content when the node is being displayed on a detail page, i.e. not in an index page?

# Answer
> 2 votes
If by "detail page" you mean the full node page, you can check the current view mode:

```
if ($variables['view_mode'] == 'full') {
  // ...
}

```

# Answer
> 0 votes
You should check `$variables['view_mode']`. You probably need to define a "Full content" view mode on your display settings of the node bundle. It will probably say "default" when "Full content" is not defined.

# Answer
> 0 votes
What is your detail page url?

if its **"domain/content/details"**, then use below condition inside your hook\_prepocess\_node.

First find your content type. for example, i'm assuming $variables\['type'\] = your\_content\_type.

```
if($variables['type'] == 'your_content_type' && arg(0) == 'content' && arg(1) != '') {
  // write your condition here.
}

```

---
Tags: 7
---


# Question
Title: Theme and Override Privatemsg messages/view/%thread
I've managed to embed all the other pages within Panels as per the D7 Panels/Privatemsg patch, and the only remaining page is the /messages/view/%thread pages. After scouring the Privatemsg API documentation and the internet, I still cannot figure out how to manually present this view or how to embed it in another location either with the API or with regular Drupal theme .tpl.php overrides.

I need to get a sidebar on the /messages/view/\* pages, preferably using panels.

1. Is there a function call to produce or print the entire thread list/reply form?
2. Do I have to break the reply form apart from the thread list?
3. After obtaining the thread list using \`privatemsg\_thread\_load()\`, is it possible to pass the data back into the overridden privatemsg-view.tpl.php file?

Any and all thoughts or hints are welcome... thanks guys.

# Answer
Take a look at privatemsg-view.tpl.php.

There is a preprocess hook where you may add theming variables to the privatemsg-view.tpl.php and execute any PHP code there. In my case it was:

```
<?
function MYTHEME_preprocess_privatemsg_view(&$vars) {
  $vars['author_uid'] = $vars['message']->author->uid;
  $vars['realname']= MYMODULE_get_realname($vars['message']->author);
}
?>

```

So here are some alternatives to populate the sidebar:

* Use this PHP code to trigger a drupal context which will show a block on the sidebar
* Programtically create other vars like the ones above. Those vars may contain sidebar data you can use when theming the TPL file which contains the sidebar.

Also, here is a full privatemsg theming guide.
> 1 votes

---
Tags: 7, views, theming, panels, privatemsg
---


# Question
Title: Can I use Plain PHP functions in tpl file?
I have a `tpl.php` page for login form in my drupal site in which have 4 images.

I need to display only one of these 4 images randomly on each page load.

I can easily do this in less than 10 lines of code using the php `rand()` function.

But is it advisable to directly use such functions in tpl files. Could this have some sort of security risk?

UPDATE:

The 4 images that I talked about. I have just uploaded them to `sites/default/files/images` folder and have included them in tpl file using following code:

```
<img src="http://mysite.com/sites/default/files/images/image.jpg"/>

```

I have a feeling that this is unsafe too. Please advise.

# Answer
For the first part of question:

You may output as form item the output of your custom function, where contain logic to get random image:

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['img_item'] = array(
          '#type' => 'markup',
          '#markup' => my_random_image_output(),
          '#weight' => -50
        );
    }
}

function my_random_image_output() {
    $output = '';

    // your custom logic to output one image $output = '<img src=".... />'

    return $output;
}

```
> 1 votes

---
Tags: theming, security
---


# Question
Title: Add styles to a custom sidebar region in Zen
I am using Zen as a theme.

I want to know how I can create a third sidebar and apply the styles in `responsive.css` to it.

I already know how to create a custom region and render it.

# Answer
> 0 votes
You create a sidebar region as same like other regions. And just edit the css and add the new region class there in existing sidebar css.

```
.sidebar1{
  background-color:yellow;
}
.sidebar1,
.sidebar_new{
  background-color:yellow;
}

```

---
Tags: 7, theming
---


# Question
Title: Create table while installing my custom module
My custom module name is "person" and its .install file has the following code.

```
<?php
/**
 * Implementation of hook_install().
 */
function person_install() {

  drupal_install_schema('person');
}

/**
 * Implementation of hook_schema.
 */
function person_schema() {

  // Static (meta) tables.

  $schema['person'] = array(
    'fields' => array(
      'pid'            => array('type' => 'int', 'length' => 11, 'not null' => TRUE, 'default' => ''),
      'name' => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
      'city'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
      'country'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE)
    ),
    'primary key' => array('pid'),
  );
return $schema;
}

```

But when I installed my module the table has not been created.Any thing wrong with this code?

# Answer
> 2 votes
In your schema your setting **pid** as primary key. You are setting '' value for primary key. Remove that default value for **pid** and try.

Then your code should be:

```
<?php
/**
 * Implementation of hook_install().
 */
function person_install() {

  drupal_install_schema('person');
}

/**
 * Implementation of hook_schema.
 */
function person_schema() {

// Static (meta) tables.

$schema['person'] = array(
  'fields' => array(
    'pid'            => array('type' => 'int', 'length' => 11, 'not null' => TRUE),
    'name' => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
    'city'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
    'country'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE)
  ),
  'primary key' => array('pid'),
  );
return $schema;
}

```

After edit the code don't disable and enable the module, hook\_install will only call at module install process, so you should first disable the module, unistall the module and then install the module again.

---
Tags: 6, database, installation
---


# Question
Title: How to send mails with mime module only for specific modules?
## **Fixed it, see answer below**

On my drupal installation there are some fancy webforms which send plain text emails, turning on the mime module messes them all up. But, I need the mime module to send html mails when using simplenews newsletters.

I did the following in the settings but it has no effect (html = plain): (http://abload.de/img/bildschirmfoto2013-11w1j7v.png)

What did I miss? How to use the mime mails only when simplenews is sending mails? I set HTML as format in newsletter settings.

Thanks!

# Answer
I installed the HTML Mail module and created a new setting with Mail \>\> Simplenews leaving the key blank, which works fine now!
> 0 votes

---
Tags: webforms, emails
---


# Question
Title: What file and directory permissions do I need in my Features directory?
I just tried to generate a feature on my test system and Drupal complained that the web server didn't have write permission for the Features directory. I changed the permissions from the normal 750 & 640 for modules directories to 770 and 660 and it worked fine.

I can't see any documentation that says you need to do this so I'm concerned something isn't set up correctly.

Should this work with the 'normal' permissions?

# Answer
> 1 votes
This is because Feature is doing something that's a little bit out of the ordinary ;-)

This is also one of the reasons I have my filesystem laid out as follows:

```
 sites/all/modules/
  - custom // Custom code.
  - contrib // The actual features.module is here.
  - features // This is for my Feature modules.

```

Because this means I can set the permissions on my Features differently to the contributed modules directory. Usually **760** I think. Then so long as the features directory is owned by a group that Apache is a member of, everything should work as expected. I do sometimes have to run a `chown -R` from my Drupal root, but that's because \*nix admin has never been a strong point of mine.

Obviously everything on my world facing servers (read: not my local machine) is more secure than this, as should yours be.

That said, on my local machine I always end up forgetting something and just chmodding everything to 775 because I'm in a hurry.

---
Tags: features, files
---


title: Add a 'GROUP BY' in Views?

text:
# Question
Title: Add a 'GROUP BY' in Views?
How do I add the equivalent of `GROUP BY` using drupal 6 and views 2?

# Answer
Views 3 supports grouping.

For views 2, aside of Views Group By, you can also write a custom module, implement hook\_views\_query\_alter(&$view, &$query) and do something like:

```
function MYMODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'view_name') {
    if ($view->current_display == 'page_XXXXXX') {
      // Tell the query constructor these fields must be used with the GROUP BY clause
      $query->add_groupby('field1');
      $query->add_groupby('field2');

      // hack to make the query constructor just ignore these fields (not adding them to the GROUP BY clause. It's needed to let it continue without problems
      $query->fields['fieldalias3']['aggregate'] = TRUE;
      $query->fields['fieldalias4']['aggregate'] = TRUE;
      // ... all but the grouped and aggregated fieldaliases must have this.

      // Configure the fields that perform the aggregation (SUM, AVG, etc)
      $query->fields['aggregatedfieldaliasA']['table'] = '';
      $query->fields['aggregatedfieldaliasA']['field'] = "SUM(fieldA)";
    }
  }
}

```

You now should be able to see the resulting query in the preview when editing the view and make sure it is correct. Field aliases in the code refer to "SELECT table.field1 as fieldalias1 ...", it's easy to get them just by checking the query shown in the preview.
> 2 votes

# Answer
There is a module, Views Group By that adds the `GROUP BY` functionality to Views
> 1 votes

# Answer
```
function xdas_target_audience_views_query_alter(&$view, &$query) {

    $controlled_views = variable_get('xdas_target_audience_views', array(
        'landing_products',
        'promotions',
        'landing_coupons',
        'landing_coupons_belvita',
        'landing_coupons_lulu',
        'related_coupon',
        'cuponazo',
        'banner',
        'brands',
    ));
    if (in_array($view->name, $controlled_views) && $view->base_table == 'node') {
        //add node_access to views so we can control access.
        $query->add_tag('node_access');
        $join = new views_join();
        $join->construct('xdas_target_audience_boost', 'node', 'nid', 'nid');
        $query->add_relationship('xdas_target_audience_boost', $join, 'node');
        $query->add_field('xdas_target_audience_boost', 'score', 'score' , array('function' => 'max'));
        $query->add_orderby(NULL, NULL, 'DESC', 'score');
        $query->add_groupby('nid');
    }
}

```
> 0 votes

---
Tags: 6, views
---


title: Performance -> Caching

text:
# Question
Title: Performance -> Caching
In Configuration \> Development \> Performance, in the Caching area, \[Cache pages for anonymous users\] and \[Cache blocks\] are unchecked. When I check them and save, the page reloads and both boxes are again unchecked. Is this wrong? Shouldn't they "remember" the state?

# Answer
In general, yes, the form should update with the values you set. However, there are few different ways you can override form settings.

The two in question are `cache` and `block_cache`. You need to search the files for lines that look like:

```
$conf['cache'] = FALSE;
$conf['block_cache'] = FALSE;

```

The integer `0` or the string `'0'` or `"0"` may be used instead. Checking the settings.php for the site, and any custom modules.
> 4 votes

---
Tags: caching, performance
---


# Question
Title: How to deactivate the automatic emails sent to administrator?
Is there any existing module to edit automatic emails sent to admin by Drupal 7? Something like Mail Editor to edit the mail templates but not only for those sent to users.

I need to deactivate the automatic email sent to administrator when an user have created an account. I have created a Rule to have details on this new account with tokens and now I do not need the automatic core email anymore.

Thanks for any help. I can not find any solution to this, except this custom module and I would prefer a newbie solution.

# Answer
> 3 votes
Enable and Install the Mailcontrol module and then go to `admin/config/people/accounts` turn off the checkbox.

> This small module extends original Drupal 7 account settings page with the ability to globally turn ON/OFF all standard mails.

By default Drupal 7 provides no option to globally disable the following mails:

* Welcome (new user created by administrator)
* Welcome (awaiting approval)
* Welcome (no approval required)
* Password recovery

---
Tags: users, emails
---


title: Sidebar formatting issues

text:
# Question
Title: Sidebar formatting issues
The Drupal 6 website I am working on is giving me some problems with the sidebars.

Here, my 'general info' sidebar is incorrectly showing 'home' sidebar info.

To the right is my 'divisions' sidebar which displays correctly \[except for the \>\> next to probate, can't seem to find a fix for that issue\]

I've tried to go through general info and compare the node hierarchy with that of divisions, making sure the settings are similar. I did not seem to find anything that would fix the issue for me.

Also if anyone could help me with why the "\>\>" 's show up seemingly randomly ( see 'Human Resources', 'Juvenile Delinquency Court', and 'Records management') These nodes do not have children.

First sidebar issue Second sidebar issue

# Answer
I checked your css file and it shows because of below css line, That arrow is activated for last li item, just delete or comment the lines.

```
#leftNav ul ul ul li.last a {
    background-color: rgb(190, 205, 222);
    background-image: url("img/blue/icon-leftnav.gif");
}

```

Probably you have to edit under themes folder or modules menu folder.

Go to your themes folder sites/all/themes/yourtheme/blue.css and search for **url("img/blue/icon-leftnav.gif")** or line 13 and comment the line and then clear the cache.
> 0 votes

---
Tags: 6, nodes, routes, navigation
---


# Question
Title: Difference between theme.info and drupal_add_js ( jquery-2.0.3 )
On a fairly new drupal (7.23) site I tried including the jquery-2.0.3.js file with the drupal\_add\_js function in one of my modules hook\_init function. All was working good and well when I was testing the login screen but then I went to some others pages, I got this error in firebug console:

```
TypeError: $(...).add(...).filter(...).once is not a function
http://XXX/sites/all/libraries/jquery/jquery-2.0.3.js?mw5wsb
Line 1670
```

(where XXX is my sitename)

So I noticed on one of my other sites the same library loaded fine when it was included in the theme.info file. So I tried it that way and sure enough jquery-2.0.3 loads fine when I do it that way. (ie.

```
scripts[] = js/vendor/jquery-2.0.3.js
```

Does anyone know why a jquery include would not work with drupal\_add\_js and why it would work with the theme.info file?

Many thanks.

d

# Answer
1. Generally speaking you should avoid adding third-party libraries directly from your module. If all modules would do that, your site would end up with multiple loads of jQuery/Modernizr/Backbone/etc.
First see if there is an existing module for that, and if not - use Libraries API to declare a dependency in your custom module and then load the script afterwards. This way if some other module depends on the same library and declares dependency through Libraries API, Drupal will load only one file automatically, avoiding conflicts.
2. For jQuery, check out jQuery Update module. Drupal itself uses jQuery for forms and other elements, so it is not enough that only your module or theme work on the latest jQuery. All core widgets, effects and AJAX calls need to be ported for specific version. That's why jQuery Update module exists - it upgrades the version of jQuery and loads updated Drupal scripts instead of the original ones, so the site does not break.
3. Regarding the differences between `drupal_add_js()` and adding a script filename in the `theme.info`, here's a summary:

* When you add a script to `theme.info` file, it will be automatically loaded for all pages displayed with *your theme*. This means that if you are using an administrative theme, such as Rubik, your script will not be loaded on pages where you use that theme.
    * With `drupal_add_js()` you can load a JS file only when you need it (e.g. only on certain pages, for certain roles etc.).
    * `drupal_add_js()` also provides you with additional functionality, such as inline JS for variables.

Hope this helps.
> 2 votes

---
Tags: javascript
---


# Question
Title: Can I take a list of Titles from a Content Type and turn them into a Taxonomy list?
I have a content type called Instructor Profiles. The title field is their name. Can I use a list of this Title field and make a Taxonomy list. Is there a way to keep a list synchronised?

# Answer
Yep, it looks like I can with Node Auto Term \[NAT\]

> Node Auto Term or NAT is a helper module used to facilitate node-node relationships through the use of the Taxonomy module; i.e. when a node is created, a taxonomy term is also created automatically using its title and body in any associated vocabularies. Other nodes can now be tagged with terms from these vocabularies thereby establishing node-node relationships.
> 2 votes

---
Tags: entities, taxonomy-terms
---