# Question
Title: Entity Metadata Wrapper: Setting User Reference
**Problem**

How do I set a user reference value from the reference module using an entity metadata wrapper?

**So Far**

I have a form submit. It's creating an node with a user reference field. I can't work out what structure will submit the value.

First I tried submitting a user account (object), however this throws an awful error.

```
global $user;
$ewrapper->field_user_permission->set($user);

```

I then tried submitting uid, however it said it was expecting an array not a string.

```
$ewrapper->field_user_permission->set($user->uid);

```

I then tried creating a custom array based on printing out the array of a field that was already set.

```
$user_perm = array (
  'uid'    => $account->uid,
  'access' => TRUE,
);

 $ewrapper->field_user_permission->set($user_perm);

```

But that printed out another horrible error. What should I be using to submit the user reference?

```
 PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'uid' for column 'delta' at row 1: INSERT INTO {field_data_field_user_permission} (entity_type, entity_id, revision_id, bundle, delta, language, field_user_permission_uid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6), (:db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 246 [:db_insert_placeholder_2] => 246      [:db_insert_placeholder_3] => contact_details [:db_insert_placeholder_4] => uid [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 182 [:db_insert_placeholder_7] => node [:db_insert_placeholder_8] => 246 [:db_insert_placeholder_9] => 246 [:db_insert_placeholder_10] => contact_details [:db_insert_placeholder_11] => access [:db_insert_placeholder_12] => und [:db_insert_placeholder_13] => 1 ) in field_sql_storage_field_storage_write() (line 451 of C:\XAMPP\htdocs\drupal\modules\field\modules\field_sql_storage\field_sql_storage.module).

```

EDIT

New error for creating a new level:

```
$user_perm[] = array (
  'uid'    => $account->uid,
  'access' => TRUE,
);

$ewrapper->field_user_permission->set($user_perm);

PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1: INSERT INTO {field_data_field_user_permission} (entity_type, entity_id, revision_id, bundle, delta, language, field_user_permission_uid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6_uid, :db_insert_placeholder_6_access); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 253 [:db_insert_placeholder_2] => 253 [:db_insert_placeholder_3] => contact_details [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6_uid] => 190 [:db_insert_placeholder_6_access] => 1 ) in field_sql_storage_field_storage_write() (line 451 of C:\XAMPP\htdocs\drupal\modules\field\modules\field_sql_storage\field_sql_storage.module).

```

# Answer
> 0 votes
I managed to get it working manually without the ewrapper. Using the old school method.

```
$entity->field_user_permission['und']['0']['uid'] = $account->uid;
$entity->field_user_permission['und']['0']['access'] = TRUE;

```

# Answer
> 0 votes
Looks like Drupal is trying to set the delta column to the string "uid", which suggests you need another level in your array:

```
$user_perm[] = array (
  'uid'    => $account->uid,
  'access' => TRUE,
);

$ewrapper->field_user_permission->set($user_perm);

```

# Answer
> 0 votes
To set the initial value or additional values:

```
$ewrapper->field_user_permission[] = $user->uid;
$ewrapper->save();

```

This method also works with wrapped multi value Entity Reference fields.

---
Tags: 7, users, entities
---


# Question
Title: Notice: Array to string conversion in token_replace() (line 102 of /var/www/html/includes/token.inc)
I am getting this notice when adding a content type in Drupal 7.24.

> Notice: Array to string conversion in token\_replace() (line 102 of /var/www/html/includes/token.inc)

What does it mean? Could I reinstall the modules to fix it?

# Answer
> 0 votes
Check Notice: Array to string conversion in token\_replace() (line 102 of /.../includes/token.inc).

> This is a dirty fix that excludes wrong values passed into the token\_replace(). Use it only as a last resort, this does not solve the issue but only disables the message !
>
> Open token.inc and change the content of `token_replace()`
>
> ```
> return str_replace($tokens, $values, $text);
>
> ```
>
> Change to:
>
> ```
>  foreach ($replacements as $value => $replacement) {
>    if ((!is_array($value)) && (!is_array($replacement))&& (!is_array($text))) {
>      $text = str_replace($value, $replacement, $text);
>    }
>  }
>  return $text;
>
> ```

---
Tags: tokens
---


# Question
Title: Differentiate between same nodes in Drupal Autocomplete Search
I have implemented Autocomplete Search functionality. Autocomplete suggestion will be available based on characters typed in textbox. When user selects a suggestion then user will be navigated to the page.

Now I want to know that if any website contain same name then how to distinguish between these two.

Example - Website contain 4 Names of Person:- Sandy, Siren, Anita, Sandy. When user type S in text field then 3 suggestion appear i.e - Sandy,Siren,Sandy.

How to distinguish between two "**Sandy**" using Drupal default Autocomplete feature.

# Answer
> 1 votes
Few Possibilities:

* You can add a content-type name along with the node title when autocomplete shows the result to describe the user in which relation it goes. For e.g., "**Sandy -- Content Type Name**"
* You can add a Nid along with the node title when autocomplete shows the result to describe the user in which relation it goes. For e.g., "**Sandy -- Nid**" Nid I don't think is a good idea. But you can also set some relative name while getting result for user to know which "**Sandy**" should be chosen.

Hope it will take you on the right path.

---
Tags: 7, search, ajax
---


# Question
Title: Do we require a token module for token_replace() to work?
I am creating a custom token using token\_replace() and then adding hook\_tokens\_info() and hook\_tokens in .tokens.inc file. Will this function work without token module ? I mean do we need token module for this function

# Answer
> 2 votes
You don't need the Token module to use the functions you mentioned in your question. They are defined in Drupal core.

References:

# Answer
> 2 votes
Since `token_replace()` is a Drupal 7 function, there is no need to install the Token module to get the tokens a third-party module, or one you developed, make available. The only reason to install the Token module is getting more tokens available, and some bug fixes for some of the tokens Drupal core implements.

```
// @todo Remove when http://drupal.org/node/1173706 is fixed.
$date_format_types = system_get_date_types();
foreach ($tokens as $name => $original) {
  if (isset($date_format_types[$name]) && _token_module('date', $name) == 'token') {
    $replacements[$original] = format_date($date, $name, '', NULL, $language_code);
  }
}

```

```
// Current date tokens.
// @todo Remove when http://drupal.org/node/943028 is fixed.
if ($type == 'current-date') {
  $replacements += token_generate('date', $tokens, array('date' => REQUEST_TIME), $options);
}

```

---
Tags: 7, tokens
---


# Question
Title: HIde node in view when field message is equal
Can I hide a node in a view when they have a specific message? Like, if the message: "Please don't show this node" is equal with specific field content then hide him in the view, else show him?

Is there an option for this?

# Answer
> 1 votes
Just an idea if you can try...

As per my point of view you may try to use flags with the timer? whenever the countdown is ended invoke a flag and you can use this flag in views.If the flag is invoked do not show the content else it will be visible.

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


title: Kickstart installed nothing?

text:
# Question
Title: Kickstart installed nothing?
I followed the install directions by deleting all but the /sites folder, copied the files into the drupal dir, deleted the cache but nothing changed except and notice that drupal core needed updating to 7.24, which i did. What am i missing here?

# Answer
> 0 votes
By considering that you have gone through pre-installation checklist of Commerce Kickstart, following are the steps to install commerce kickstart :

1. Download Commerce Kickstart.
2. Extract the Files into root directory.
3. Installation Screen, welcome.
4. Requirements Problem Screen.
5. Setting up the database configuration.
6. Installation running through.
7. Site Configuration.
8. Configure Store Content.
9. Importing Products.

---
Tags: installation, commerce
---


# Question
Title: How to hide webform Results tab in webform?
On my Drupal 7 how hide webform Results tab?

# Answer
You can hide webform Results tab by restricting user's permission access e.g. uncheck the following checkboxes in permission section :

```
1. view all webform results.
2. view own webform results.

```
> 1 votes

# Answer
You can use tab tamer module to hide the tab from webform.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
>
> Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when javascript is disabled.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How can I display a Browser Prompt for Confirmation before executing ajax callback for a button element?
I have a `button` type element in a form. It has an ajax callback to some function that performs a delete operation. Everything works perfect.

I want to add a browser prompt when user clicks on the delete button. The prompt should ask user to confirm the delete action and only after the confirmation should the callback function be executed (using ajax of course).

How can I do this?

Following is the code for `button` element:

```
$form['delete'] = array(
  '#type' => 'button',
  '#value' => t("Delete"),
  '#element_validate' => NULL,
  '#ajax' => array(
    'callback' => 'delete_something',
    'wrapper' => 'delete-message',
  ),
  '#limit_validation_errors' => array(),
);

function delete_something(){
  //Some Code
}

```

# Answer
This one should help you the same way you want to achieve the functionality. Instead of ajax callback I have created a ctools modal which will return the delete and cancel button..

`"delete/nojs/1"` where 1 will be the Item which you want to delete.

use this in your form.

```
$form['delete'] = array(
  '#markup' => ctools_modal_text_button(t('Delete'),"delete/nojs/1", t('Delete'), 'ctools-modal-modal-popup-small'),
);

```

create a menu item.

```
function custom_module_menu() {
  $items = array();
  $items['delete/%ctools_js/%'] = array(
    'type' => MENU_CALLBACK,
    'title' => t('Delete'),
    'page callback' => 'delete_something',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
  );
  return $items;
}

```

and call this function.

```
function delete_something($js = NULL) {
  if (!$js) {
    return drupal_get_form('delete_form');
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('Delete'),
    'ajax' => TRUE,
  );
  $output = ctools_modal_form_wrapper('delete_form', $form_state);
  if (empty($output)) {
    $output[] = ctools_ajax_command_reload();
  }
  print ajax_render($output);
  drupal_exit();
}

function delete_form($form_state = NULL){
  $form['message'] = array(
    '#prefix' => '<div class="delete_message">',
    '#value' => t('Are you sure want to delete?'),
    '#suffix' => '</div>',
  );
  $form['submit']['delete'] = array(
    '#prefix' => "<div id = 'delete_button'>",
    '#suffix' => "</div>",
    '#value' => t('Delete'),
    '#type' => 'submit',
    '#submit' => array('delete_form_submit'),
  );
  $form['submit']['cancel'] = array(
    '#prefix' => "<div id = 'cancel_button'>",
    '#suffix' => "</span></div>",
    '#value' => t('Cancel'),
    '#type' => 'submit',
  );
  return $form;
}

function delete_form_submit($form, &$form_state) {
 //some code to delete
}

```
> 3 votes

---
Tags: forms, ajax
---


# Question
Title: dynamic taging node with keywords(terms) is body
I have some vocabulary and I want to tag the content automatically with keywords types in body of content. Example my body is : `"Drupal is lovely content management system that provide good api to developer"`

and
`Drupal`,`content management system` are in vocabulary1
`api`,`developer` are in vocabulary2

How can I extract my vocabulary tags auto from body of contents?

# Answer
After some searching and pay time I found the great module rule autotag,it is great,of course it is not completely which I want but extract tag from body very good with good performance
> 0 votes

# Answer
You can do this by writing a custom module that analyzes the node content in a hook\_node\_presave hook and check if the terms from a particular vocabulary is present in the node.

I created a small custom module that just works if you enter the correct parameters. https://github.com/Ayesh/drupal-node-auto-tag

Download a tarball or clone it, and set the node type, field names and vocabulary ID in top of the .module and enable the module.

Good luck!
> 1 votes

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


# Question
Title: How to make a custom translatable string?
For example, i've a array contains string for each elements

$description\[\] = $discount-\>short\_description;

foreach ($description as $value) { $line.= $value." "; }

the $line will be used in

```
  $output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'hidden',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(1),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => t($line)),
  );

```

how can i make this $line will appear in admin/config/regional/translate/translate, so i can translate it?

# Answer
Clear caches. Then, go to http://example.com/admin/config/regional/translate/i18n\_string and hit "Refresh strings" button. This should do it.

Also, t() is known to cause problems if used on variables, not strings directly. But most of these problems affect tools that tries to extract strings into .po files, so there is a fair chance it will work for you. But think twice if you really need a variable there.

If it happens to you that your string aren't recognized by panel, you can use one more method. Write your own .po file. Structure is as follows:

```
white-space
#  translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgid previous-untranslated-string
msgid untranslated_string
msgstr translated_string

```

Repeat this (in one file) for all strings. Create one file per language you want to translate to. Then go to http://example.com/admin/config/regional/translate/import and import your files. From now on, strings will be available for translation in interface.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Why does form ID get displayed to drupal_set_message?
I'm upgrading from 6 to 7 (thankless task!) and Ive noticed that in the admin section the name of any form that is on the page seems to get output to drupal\_set\_message (it appears in the green box) I thought this to be unusual but possibly deliberate on the part of the module author. However, in my custom module I have a form and when ever I go to the page the name of the form appears in the green status box.

Can anyone shed any light onto why this may be happening?

# Answer
> 3 votes
You may be having hook\_form\_alter(&$form,&$form\_state,$form\_id) in your code possible code in your custom code will be

```
function hook_form_alter(&$form,&$form_state,$form_id) {
//just remove the below line to disable the message
drupal_set_message($form_id);

}

```

---
Tags: 7, forms
---


# Question
Title: add Global PHP code field to Views on condition
I want to add PHP field to View based on condition that certain logic field in content item is checked. How can I check that it is checked in PHP code?

More concisely: how can I check if some product's field is checked in Views?

The View is just showing list of contents

# Answer
> 1 votes
I think you have not followed a correct way, these are the steps to create a custom field on the basis of value of an existing text field are :

1. Add a field in any content type on basis of whose value you want to display a custom field.
2. Add contents of that content type filling value of newly created field say its a checkbox having 0 or 1 as its value.
3. Create a view of that content type.
4. Add fields and a custom field having some value, say ;

```
<?php
echo 'Astha Chauhan';
?>

```

in output code field.

1. Then add a filter of type Global:PHP and add a filter code accordingly:

    ```
      <?php
          if ( $row->field_test_field == '2') {
           return $row->php;
          }
          else {
           return 'null';
          }
       ?>

    ```

# Answer
> 0 votes
I guess you are using a product's field in your view based on whose value you want to add a custom field. Rite ???

* If yes then add a field whose value you want to check in your view.
* Then add a Global PHP field (note that the field whose value you want to check should be arranged prior to Glbal PHP field)
* Add php logic there by using available tokens of previous field.

---
Tags: 7, views
---


# Question
Title: New scheduled rule knocks out existing scheduled rule
I have a rule set with an active rule to send mail to a user. This is triggered by a workflow being marked done.

This seems to work just fine until more than one, completely seperate, workflow is marked done.

When I view the scheduling rule set page that shows what's in queue for scheduling I can see the mail that is about to go out from the workflow I marked as done. Now when I go ahead and mark another workflow as done it seems to replace the email that was about to go out to another user from the previous workflow being marked done with the most recent one.

Any ideas as to why I cannot have more than one scheduled rule set in queue at a time?

D6, rules module up to date at v1.5

# Answer
> 2 votes
Make sure the Identifier for the scheduled task is unique. Adding the node ID of the node that completed the workflow could work to ensure the Identifier field is unique.

A new task will replace an existing task with the same Identifier. This happens because the Identifier value is the key each task is stored with in cron.

Check out this free video Introducing Rules Scheduler for more tips.

---
Tags: rules
---


# Question
Title: I deleted /devel_themer folder now my website reports an error
`devel_themer` folder of my website that was in `public_html` had about 500MB size so I deleted this folder. now when I log in to administrative account it reports this error :

`Fatal error: Maximum execution time of 30 seconds exceeded in /home/my_web_site/public_html/sites/all/modules/devel_themer/devel_themer.module on line 342`

now what shall I do ?

# Answer
I know its answered in comment, but for others who land here.

Increasing the execution time in php.ini can solve this. An ideal value would be `120`.

If it doesn't solve the problem we might need to disable and uninstall the module and fix the problem. Ofcourse you can install it back after things are fixed.

**If you can access the admin page:**

1. Disable the module.
2. Uninstall the module from the uninstall tab in modules page and delete the module folder.
3. Clear the site cache if required.

**If you can't access the admin page:**

1. Delete the module folder.
2. Run update.php

If you were not logged in at the time of the error you will have problem accessing the update.php, then you will have to either use drush the command `drush updatedb` or temporarily enable access to update.php by changing settings.php file.

If you had drush, you an also consider disabling the module with it.

Line to change:

```
$update_free_access = FALSE;

```
> 1 votes

---
Tags: debugging
---


# Question
Title: in drupal 7, how to add user pic and name to the user menu when logged in?
In drupal 7, there are default blocks such as user menu block and login block, the user menu block are especially working for the logged in user while login block are working for non logged in user.

the user menu block contains the static user menu with account, profile, logout menu item, however what I want to do is when the user logged in, the user menu can have additional menu item showing the user pic and name.

I know this could be done by making a new block with php code, but I just want to know if I want to use the existing user menu block, what and how I should change it?

# Answer
> 1 votes
In Drupal 7, you can implement hook\_block\_view\_alter() to alter the content of a block defined from another module. For example, menu\_block\_view\_alter() is an implementation of that hook done by the Menu module.

```
function menu_block_view_alter(&$data, $block) {
  // Add contextual links for system menu blocks.
  if ($block->module == 'system' && !empty($data['content'])) {
    $system_menus = menu_list_system_menus();
    if (isset($system_menus[$block->delta])) {
      $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($block->delta));
    }
  }
}

```

`$data` is the array defined from the implementation of hook\_block\_view(), and it contains two array indexes:

* "subject": the default localized title of the block
* "content": the content of the block's body

In Drupal 7, `$data['content']` could be either a string containing HTML code, or an array as accepted from drupal\_render().

`$block` is an object containing all the data about the block loaded from the database. You can at least count on two elements:

* "module": the name of the module implementing the block
* "delta": the identifier for the block used from the module implementing it

If you just need to alter one single block, you can consider implementing hook\_block\_view\_MODULE\_DELTA\_alter(), which is the equivalent of `hook_form_FORM_ID_alter()` of `hook_form_alter()`. Replace *MODULE* with the module name, and *DELTA* with the identifier for the block.
The hook gets the same parameters as `hook_block_view_alter()`.

# Answer
> 1 votes
You can add any tokens to the menu item if you use the menu\_token + menu\_html modules:

1. Go to the user account settings at example.com/admin/config/people/accounts
2. Select the user's image style to an image style with the desired dimensions.
3. Set the default avatr URL to an image with the same dimensions as your selected image style.
4. Install the menu\_token module. This will allow you to add tokens like \[current-user:picture\] to the menu item title.
5. Install the menu\_html module. This will tell drupal to keep the html in the token.
6. Edit the menu item, enable tokens and HTML, and set the menu item title to someting like \[current-user:name\] \[current-user:picture\].
7. Optionally, add tokens in your module (with hook\_token\_info + hook\_tokens) to allow to put non-default image styles onto your menu item.

---
Tags: routes, blocks, users
---


# Question
Title: Sending an email using phpmailer drupal 6
How do I use the phpmailer module. I have it installed and my test email sends. However the php mailer tutorials show examples for using the module outside of Drupal. I want to place some code within a node to quickly fire off an email to myself when x happens.

or is it better to use the durpal mail function, I am using drupal 6, however this is not part of a module but instead will be placed in a node.

# Answer
You should consider using drupal\_mail for sending email from Drupal. That will make sure Drupal can control your mails. For example say, you are using some module like Re-Route Email or maillog.

```
  $params = array(
    'subject' => t('Client Requests Quote'),
    'body' => t("Body of the email goes here"),
  );

  drupal_mail("samplemail", "samplemail_html_mail", "me@site.com", language_default(), $params, "admin@site.com");

/*setting up our mail format, etc in hook mail*/
function hook_mail($key, &$message, $params)
{
    case 'samplemail_html_mail':
          /*
           * Emails with this key will be HTML emails,
           * we therefore cannot use drupal default headers, but set our own headers
           */
          /*
           * $vars required even if not used to get $language in there since t takes in: t($string, $args = array(), $langcode = NULL) */
          $message['subject'] = t($params['subject'], $var, $language->language);
          /* the email body is here, inside the $message array */
          $body = "<html><body>
              <h2>HTML Email with Drupal</h2>
              <hr /><br /><br />
              {$params['body']}
              </body></html>";
          $message['body'][] = $body;
          $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
          break;
}

```

You would invoke this in your code somewhere. Or else you can use the rules module to send email as per some events or actions in the site.

If you still want to use PHP Mailer, you have module to do that here.

you can see a screencast on using rules to send email here.
> 0 votes

# Answer
I wrote this code to send email using drupal\_mail() function, if it may help you.

```
            <?php

                            function astha_menu() {
                                $items['custom-astha'] = array(
                                    'title' => t('Sending Mail!'),
                                    'page callback' => 'custom_astha',
                                    'access callback' => 'user_access',
                                    'access arguments' => array('Send Mail'),
                                );
                                return $items;
                            }

                            function custom_astha() {

                                $form['custom_form'] = drupal_get_form('custom_astha_form');
                                $output = drupal_render($form);
                                return $output;
                            }

                            function custom_astha_form() {
                                $form['email'] = array(
                                    '#type' => 'textfield',
                                    '#title' => 'UnRegister User Email',
                                    '#size' => 20,
                                    '#required' => TRUE,
                                );

                                $form['file'] = array(
                                    '#type' => 'file',
                                    '#name' => 'file',
                                    '#title' => 'Attach any file!!',
                                );

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

                                return $form;
                            }

                            // to send mail

                            function astha_send_mail($to, $from, $subject, $body, $file) {

                                // move_uploaded_file($_FILES["file"]["tmp_name"], 'upload/'. $_FILES["file"]["name"]);
                                $params = array(
                                    'subject' => $subject,
                                    'body' => array(token_replace($body, array('callback' => 'user_mail_tokens', 'sanitize' => FALSE)),),
                                    'attachment' => array(
                                        'filecontent' => file_get_contents($_FILES['file']['name']),
                                        'filename' => $_FILES['file']['tmp_name'])
                                );
                                drupal_mail('custom', 'information', $to, language_default(), $params, $from);
                            }

                            function custom_astha_form_submit($form, &$form_state) {
                                $ind_user = $form_state['values']['email'];
                                $to = (string) $ind_user; // to e-mail address
                                $from = (string) variable_get('site_mail', 'asifiqbal929@gmail.com'); // from e-mail address
                                $subject = "abc"; // subject of e-mail
                                $body = "xyz </br>Faithfully yours,<br/> [site:name] team";
                                $file = $_FILES['file']['tmp_name'];
                                // here we call our mailing function
                                astha_send_mail($to, $from, $subject, $body, $file);

                                drupal_set_message('Mail to ' . $ind_user . ' has been sent.');
                            }

                            function custom_astha_form_validate($form, &$form_state) {
                                $mail = $form_state['values']['email'];
                                if (!valid_email_address($mail)) {
                                    form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
                                }
                            }

                            function custom_mail($key, &$message, $params) {
                                switch ($key) {
                                    case 'information':
                                        $message['subject'] = $params['subject'];
                                        $message['body'] = $params['body'];
                                        $message['params']['attachments'][] = $params['attachment'];
                                        break;
                                }
                            }

        ?>

```
> 0 votes

---
Tags: 6, emails
---


# Question
Title: dev-test-prod staging workflow for drupal with transport of database changes
Hi I am looking for a best practice staging workflow for a four level staging environement for drupal:

dev-\>test-\>pre-prod-\>prod

I found this quite informative thread already Applying Updates to Multiple Drupal Sites

As the Teams will change especially on the test upwards it has to be pretty straight forward.

1. I guess we will move everting as far as posible through git or would rsync be better choice?
2. Is there some way to maintain some kind of central stage configuration where you just maintain the server adresses e.g. in on central place
3. How to move database changes without conflicting with productive content

Would be great if someone could share hints to some documentation of such a workflow.

Thanks in advance

# Answer
in the meantime we do have a quite robust workflow and toolset for deploying Drupal through a multistage environment.

We use: -Features, Strongarm and Drush on the Drupal side -Jenkins, Git, Rsync for the Deployment

If you are interessted in further details just send me a PM
> 0 votes

# Answer
Regarding #2, I would recommend using drush site aliases. See also the sync\_enable example in Drush, which demonstrates how you can get Drush to automatically adjust your database settings when you move your db from prod towards dev. For moving configuration from dev to production, many folks use features; you might also want to look at ctools export bonus, which is built on much of the same technology.
> 1 votes

---
Tags: importing-exporting, workflows, staging
---


# Question
Title: Prevent site from being indexed by search engines?
I have two requirements for my site

1. I don't want my site to be indexed by search engines
2. Anonymous users should not be able to see any content of the site

I would have been satisfied with ip restriction in the .htaccess file but I cannot use that because this site is part of a multisite setup and as far as I know one cannot use .htaccess files in sites/mysite1/.htaccess and I don't want to go down the symlink route at the moment.

Right now I am using:

* Shield (for Apache authentication and to prevent non content elements from being previewed)
* Metatag `(<meta name="robots" content="noarchive, nofollow, noindex, noodp, nosnippet" />`

but thinking about it some more I thought that perhaps just using the **Shield** module wil prevent my site being indexed. Or even just disabling the **View published content** permissions?

So my questions are:

1. Will the Shield module prevent my site from being indexed?
2. Will disabling the View published content permissions prevent my site from being indexed? (with the downside that part of the site can be previewed)

# Answer
> 5 votes
Question 1: Shield will deny access to anyone that doesn't know the credentials, including robots. Using this module should be suffiscient for the use case you describe.

As long as you use Shield, metatags doesn't matter. If you do not use Shield, the metatag you list will prevent your site to be indexed by *polite* search engines (such as Google - read about Google's policy here). It will have no effect on some other (impolite) search engines (such as Baidu).

Question 2: Disabling "View published content" for the anonymous user role will prevent any *content* on the site from being indexed. Your site itself, and the placeholder string that is shown to the anonymous user when viewing published content is disabled ("No content has been created yet.") is still visible and may be indexed by search engines.

---
Tags: security, 7
---


# Question
Title: how to use EntityFieldQuery by language?
```
global $language;

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'events')
->propertyCondition('language', $language->language)
->propertyCondition('tnid', $output)
->execute();

```

I tried using this code and it is showing me empty page, any help on using EntityFieldQuery?

# Answer
$language variable is better to be in the function as:

```
 function getListNode(){
   global $language;
   $query = new EntityFieldQuery();
   $query->entityCondition('entity_type', 'node', '=')
         ->entityCondition('bundle', 'content_type', '=')
         ->propertyCondition('language', $language->language, '=');
   $nids = $query->execute();
   return entity_load('node', array_keys($nids['node']));
 }

```

it works for me good luck
> 6 votes

# Answer
Since you're not actually querying any field values, I'm not really sure why you need to use an `EntityFieldQuery` for this. It would be much easier (and far more efficient) to use a straight query to load the node id(s):

```
$nids = db_select('node', 'n')
  ->condition('type', 'events')
  ->condition('language', $language->language)
  ->condition('tnid', $output)
  ->execute()
  ->fetchCol();

$matching_nodes = node_load_multiple($nids);

```
> 3 votes

# Answer
Your code seems correct. Make sure you actually display the results

```
if (!empty($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);
  $output = node_view_multiple($nodes);
  drupal_render($output);
}

```
> 0 votes

# Answer
The `propertyCondition` method needs a 3 parameter for the matching to work

```
propertyCondition('language', $language->language, '=')

```
> -3 votes

---
Tags: database
---


# Question
Title: How can I hide and print a field in my tpl.php?
I'm using kickstart 2. I have product variation types and a content type for each product. field\_desc under the content type manage fields, I have managed to hide and print render successfully in my node--product--type.tpl.php.

However, I have another field called field\_spec which is a variation type field rather than a content type field. when I use the following codes in my tpl.php to hide and print the field\_spec, this field is not hidden or printed where I want.

I use the following codes to hide and print both field\_spec and field\_desc however field\_spec isn't hiding whereas field\_desc is:

```
  <?php
    hide($content['field_desc']);
  ?>

 <?php
 print render($content['field_desc']);
 ?>

```

I have checked that field\_spec is spelled correctly, I have cleared caches etc. however I cannot hide and print field\_spec.

Is this something to do with the fact field\_desc is a content type field whereas field\_spec is a variation type field?

Thank you

# Answer
I think you need to use `$content['product:field_NAME']` for this

See this answer for more info: Print out a Drupal Commerce field only if it has a value
> 1 votes

---
Tags: theming, commerce
---


# Question
Title: add content page doesnot work for other users
I created a few users that are responsible for adding content to the website. they are just allowed to add/remove content (defined by role). the problem is the add content link (`mywebsite/node/add`) does not display the add page, it just displays MY `page.tpl.php` . I guess `add` page is overridden by my `page.tpl.php` , how can I have admin add page for other users ?

# Answer
> 1 votes
you should include `print render($page['content']);` in your page.tpl.php file otherwise, it will not display content for the page.

`content` is default block which Drupal use to render content of a page.

If you do not want to use `content` region in your `theme`, then you can set `View the administration theme` permission for your user role.

Setting permission:

* Go to `Administration -> People -> Permissions`
* Checked check-box of `View the administration theme` for your user role and save form.

# Answer
> 1 votes
If you are using Drupal 7 just print the following line in your page.tpl.php :

```
         <?php print $content; ?>

```

If still it does not display the content type section , then check which template file is getting called there? Track the file and print the above line.

# Answer
> 0 votes
Node creation page URL should contain content type name at last. This means that mywebsite/node/add is wrong. If you want to create a page content then the URL should be mywebsite/node/add/page.

Generally speaking, the node creation page URL for the *nameofyourcontenttype* content type is http://yourwebsite.com/node/add/nameofyourcontenttype.

The page at node/add will only display the list of the content types for which the users can create a node.

---
Tags: 7, theming
---


title: How can you add a field value to css?

text:
# Question
Title: How can you add a field value to css?
I know this is possible in views -\> style settings of a field, but what if you can't customize the fields?

I would like to add css to the mini calendar from the calendar-module depending on the value of a field called 'field\_location'.

**So `class="fri mini future has-events "` becomes `class="fri mini future has-events field_location"`**

I copied the calendar-mini.tpl.php and on line 49 I changed

```
< td id=" < ?php print $cell['id']; ? >" class="< ?php print $cell['class']; ? >">

```

into:

```
< td id=" < ?php print $cell['id']; ? >" class="< ?php print $cell['class'] ' ' . $node->field_location['und'][0]['value']; ? >">

```

If I use `$node = node_load(736);` it works, but it adds the 'field\_location' of that node to all classes. I need to place the right 'field\_location' in the right class.

# Answer
Copying out the relevant portion of the template:

```
<tbody>
  <?php foreach ((array) $rows as $row): ?>
    <tr>
      <?php foreach ($row as $cell): ?>
        <td id="<?php print $cell['id']; ?>" class="<?php print $cell['class']; ?>">
          <?php print $cell['data']; ?>
        </td>
      <?php endforeach; ?>
    </tr>
  <?php endforeach; ?>
</tbody>

```

If you want the `<td>` wrapping your cell to have an additional class based upon what is inside that cell, you will need to do something like this:

```
<tbody>
  <?php foreach ((array) $rows as $row): ?>
    <tr>
      <?php foreach ($row as $cell): ?>
        <?php
          $new_class= // grab information out of $cell['data']
        ?>
        <td id="<?php print $cell['id']; ?>" class="<?php print $cell['class'] . ' ' .  $new_class; ?>">
          <?php print $cell['data']; ?>
        </td>
      <?php endforeach; ?>
    </tr>
  <?php endforeach; ?>
</tbody>

```

If it's not easy to do, `$cell['data']` is probably HTML since it is just being printed, you do have the entire `$view` object to work with, and there, you can grab stuff out of `$view->result` and correlate that to these cells.
> 0 votes

---
Tags: entities, theming
---


title: swiftmailer - html and email templates

text:
# Question
Title: swiftmailer - html and email templates
I need to create a HTML email, and someone suggested Swiftmailer. I installed that module, but it's not clear to me how to create HTML.

I enabled SwiftMailer as the sitewide default in the Mail System module, and I added a message like this:

```
$string = "This is a defined message: You have been send a message - \n" .$params['message'] . '\n <a href="http://wwww.google.com">click here</a><button type="button">Click me</button>';

```

But the HTML isn't picked up. The `a` tag is a link, but the button is not a button. I also can't apply inline styles.

Additionally, I will need to know how to create **multiple email templates**, which apply to different email types (I only saw online how to create one, `swiftmailer.tpl.php`)

# Answer
Swiftmailer just sends emails ... it doesn't let you create HTML / plaintext content for emails.

For ease of setting this all up you likely want to use a module that supports the Mime Mail module and then at least use something like Previewable Email Templates (PET) module. Quote from the PET module page:

> The Previewable Email Template (PET) module lets you create email templates, with token substitution, which can be previewed by the user before sending. The emails can be sent to one or many email addresses in a flexible way, and the recipients may or may not be Drupal account holders (users).
>
> PET stores templates in a db table, not the variables table, so there is none of the memory usage which goes with the latter.
>
> PET templates are in one place for easy management by site administrators. Emails can be sent one of three ways:
>
> * interactively, from a link.
> * programmatically, in response to any situation.
> * via a Rules action (D7 only).
> 3 votes

# Answer
You should use MIME mail (it requires mailsystem module)

> This is a Mime Mail component module (for use by other modules).
>
> It permits users to receive HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it. If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment. Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative. Allows you to theme messages with a specific mailkey. Converts CSS styles into inline style attributes. Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.
> 1 votes

---
Tags: emails
---


title: why #submit not apply in form

text:
# Question
Title: why #submit not apply in form
I create a menu and in callback of it call this function

```
function floristdev_own_price_choice(){
  module_load_include('inc', 'node', 'node.pages');
  $form = node_add('customflower');
  $form['#submit'][]='floristdev_own_price_choice_sub';
      //      unset($form['#action']);
  dsm($form);
  return drupal_render($form);

}
function floristdev_own_price_choice_sub($form,$form_state){
    drupal_set_message('I called');
    dsm('blah blah');
}

```

but the `floristdev_own_price_choice_sub` never call ( I put die and drupal\_set\_message to test is it call ) where the problem, I am using drupal 7.

# Answer
> 3 votes
This is probably what's happening...

* `node_add()` calls `drupal_get_form()` internally, which finalises the form and commits submit/validate handler data to the cache.
* You're modifying the data in the form array *after* it's been saved to cache.
* When the form submits, the page reloads and the API grabs the cached submit handlers from the store. As your submit function was never saved alongside that data, the API doesn't know about it.

You should use `hook_form_alter()` as already noted by Jimmajamma in the comments, then you won't have this problem at all.

# Answer
> 0 votes
You need to change your hook\_menu to have `drupal_get_form` as callback and the form id as the argument:

```
function floristdev_menu() {
  $items['whatever/path'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('customflower_node_form'),
    ........ etc
  );
}

```

And do a hook\_form\_alter:

```
function floristdev_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'customflower_node_form') {
    $form['#submit'][]='floristdev_own_price_choice_sub';
  }
}

```

Now this should run:

```
function floristdev_own_price_choice_sub($form,$form_state){
  drupal_set_message('I called');
  dsm('blah blah');
}

```

---
Tags: 7, forms
---


# Question
Title: How should I structure a node migration that has three locations?
I have a situation where I need to migrate a D6 node that has three location fields. The example code shown in the drupal module documentation ( https://drupal.org/node/2018113 ) isn't working. I either get no addresses or four copies of the node.

# Answer
> 0 votes
I used the following code to join to the location tables for each lid field in the d6 content. Whee!

```
$address_arguments = array(
        'administrative_area' => array('source_field' => 'hq_province'),
        'locality' => array('source_field' => 'hq_city'),
        'thoroughfare' => array('source_field' => 'hq_street'),
        'premise' => array('source_field' => 'hq_additional'),
        'postal_code' => array('source_field' => 'hq_postal_code'),
);
$this->addFieldMapping('field_company_address','hq_country')
->arguments($address_arguments);

$address_arguments = array(
        'administrative_area' => array('source_field' => 'leg_province'),
        'locality' => array('source_field' => 'leg_city'),
        'thoroughfare' => array('source_field' => 'leg_street'),
        'premise' => array('source_field' => 'leg_additional'),
        'postal_code' => array('source_field' => 'leg_postal_code'),
);
$this->addFieldMapping('field_company_legal_contact','leg_country')
->arguments($address_arguments);

$address_arguments = array(
        'administrative_area' => array('source_field' => 'inc_province'),
        'locality' => array('source_field' => 'inc_city'),
        'thoroughfare' => array('source_field' => 'inc_street'),
        'premise' => array('source_field' => 'inc_additional'),
        'postal_code' => array('source_field' => 'inc_postal_code'),
);
$this->addFieldMapping('field_company_inc_state','inc_country')
->arguments($address_arguments);

$this->addUnmigratedSources(array('field_company_twitter:title','field_company_twitter:attributes','field_company_linkedin:title','field_company_linkedin:attributes','field_website:title','field_website:attributes'));

}
protected function query() {
$query = parent::query();
$query->leftJoin('location_instance', 'hq_i', 'hq_i.lid = f.field_hqaddress_lid AND hq_i.vid = n.vid');
$query->leftJoin('location', 'hq_l', 'hq_l.lid = hq_i.lid');
$query->addField('hq_l','street','hq_street');
$query->addField('hq_l','additional', 'hq_additional');
$query->addField('hq_l','city', 'hq_city');
$query->addField('hq_l','province' ,'hq_province');
$query->addField('hq_l','postal_code', 'hq_postal_code');
$query->addField('hq_l','country' ,'hq_country');

$query->leftJoin('location_instance', 'leg_i', 'leg_i.lid = f.field_legal_contact_address_lid AND leg_i.vid = n.vid');
$query->leftJoin('location', 'leg_l', 'leg_l.lid = leg_i.lid');
$query->addField('leg_l','street','leg_street');
$query->addField('leg_l','additional', 'leg_additional');
$query->addField('leg_l','city', 'leg_city');
$query->addField('leg_l','province' ,'leg_province');
$query->addField('leg_l','postal_code', 'leg_postal_code');
$query->addField('leg_l','country' ,'leg_country');

$query->leftJoin('location_instance', 'inc_i', 'inc_i.lid = f.field_incorporation_state_lid AND inc_i.vid = n.vid');
$query->leftJoin('location', 'inc_l', 'inc_l.lid = inc_i.lid');
$query->addField('inc_l','street','inc_street');
$query->addField('inc_l','additional', 'inc_additional');
$query->addField('inc_l','city', 'inc_city');
$query->addField('inc_l','province' ,'inc_province');
$query->addField('inc_l','postal_code', 'inc_postal_code');
$query->addField('inc_l','country' ,'inc_country');

return $query;
}

```

---
Tags: location, entities, migrations
---


# Question
Title: Ajaxy entity reference views filter by entity reference view
I have two content types that share a taxonomy (Size).

On content type A, I have an "entity reference" to content type B in the form of a checkbox widget.

What I want: On the node creation form, when I change the size (without saving), the entity reference filter gets updated appropriately.

What I currently have: The entity reference filter only changes when I save the node.

How I got there:

I'm using an Entity Selection views filter by entity reference view

In my entity reference view, the only thing I could come up with is to set a contextual filter of "content has taxonomy term ID"

Then use "provide default value" -\> "taxonomy term ID from URL" and "load default filter from node page"

So, If I create a new node of type "A" and set "Size" to "Size X" and SAVE the node, the entity reference gets filtered properly.

What I want to happen is that on the node creation form, when I change the size it dynamically filters the entity reference without having to save the node.

There is no ajax option on an entityreference views display, and I"m not seeing any other modules that seem to solve this.

Can anyone point me in the right direction here?

# Answer
I'm not sure this question has a good, Drupalish answer. I've got a crazy idea, though, that you might try.

Instead of letting your users go straight to `node/add/typeA`, send them first to a custom page where they choose their size. That link will then send them to the node add screen with a TID tacked onto the end, like `/node/add/typeA/34`.

On the node creation page, your custom module will automatically select the right Size term based on the URL path, and disable the widget so the user can't change it.

In your Entity Reference view, when you provide a default value to your contextual filter, instead of "Taxonomy term ID from URL", simply choose "Raw value from URL" and set the Path component to 4. With any luck, the Entity Reference view will get the TID from your modified URL and show the right list.

When they try to edit that node after creation it gets a bit tricky. You could just forcibly redirect the path to `node/[nid]/edit/34` and do the same thing, but now you've made it so the user can never change the category after they select it the first time, which is bad. Maybe you can hijack `node/[nid]/edit` and send them to your custom page again? I've never seen that done before.

This whole idea kind of craps up the usability of the site, but it's the best idea I can think of, short of writing your own custom AJAX stuff to provide your argument to the ER view manually, rebuild the form, etc.
> 0 votes

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


# Question
Title: Why responsive panels are not one beside another by default?
I am using the adaptive theme with panels, mini panels, panels everywhere, and AT Panels Everywhere. My site default template is of at panels everywhere.

I built a 5 column mini panel for the footer. I assigned for each column only one thing: menu, or a logo, or "powered by drupal".

When I am using the builder layout for the mini panel, and build 5 column - every thing works fine, and I have 5 column one beside another, in only one row. (although, I am trying to avoid the builder and use only AT layouts).

But, If I am using the "AT responsive panel - 4,5,6 column" for the mini panel layout, the result is that my footer has two rows: top row is with 2 panels and bottom row is with 3 panels. it looks like the blocks or something are too big, and the AT layout is just being responsive.

I tried to solve that and make it one row, and add to each panel a class, and made them very narrow. but that didn't work, and I still have 2 rows, even though the panels are very narrow and can feat perfectly in one row (5 columns).

How can I make sure that every panel will use 20% of it's layout (when possible), and all will be presented in one row, 5 columns side by side?

Here is the problem:

Here is the footer code:

The footer is still in two rows, and looks like that:

What causing the AT mini panel to think it has no room, and need to change the layout?

# Answer
> 0 votes
I finally found the solution. AT is printing the following css code :

```
.five-5x20 > .panel-row {
    clear: none;
}

```

so, I adjust all the code to be:

```
#panel-footer .five-5x20 > .panel-row {
    float: left ;
    display: block;
    width: auto;
    clear: none;
}

```

the clear: none fix the proble, and now the float: left is working.

@Marcel Thanks for all the help

# Answer
> 0 votes
This can be done CSS only:

Apply a width and float to all panels in the footer:

```
#footer .region {
  float:left;
  width:20%;
}

```

Or make them a little smaller so you can apply margins to 'm.

---
Tags: panels, theming
---


# Question
Title: How can the items in a field collection view be restricted to those of its containing entity?
I have an entity type with a field collection that I want to display as table within the main entity display. I have created the view as a block view and added it as a block field using Display Suite.

However items that don't belong the containing entity appear in the display. In effect the embedded view displays all the field collections items, instead of those added to the containing entity.

The Contextual filters and the Relationships in Views UI don't display a means of linking the collection items to the host node.

Is there a way of filtering the view by the node?

# Answer
> 1 votes
It is rather counterintuitive because the way the settings that need to be changed are labeled. The idea is to filter the view by the Node Id for the containing entity, but that doesn't show up immediately in any of the places you expect to see it..

The first step is to add a `Relationships`. When you click the Add button you get the option for applying to `Add Displays` or `This block (override)`. In my case I am doing it for only that view so I chose `This block (override)`.

The relationship I choose is `Field collection item (Entity with the`Config Type (field\_system\_config\_type)`.`Config Type`and`field\_system\_config\_type\` are the friendly and machine names of the field collection.

The select list for choosing which category to filter on is redundant because `Field collection item` is the only one there.

The next stage is to choose the `Contextual filter`. This order has to be followed because unless the `Relationship` is chosen first, the right elements to select for the `Contextual filter` don't show up.

The element to select here is the node id for host entity - `Content: Nid`. It is easier to type it exactly as there are quite a number to choose from.

You then select it and click `Apply (this display)`. After that there is a message `This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'.` You click on `Provide default` and in the '`Fixed value` select `Content Id from URL` and click on `Apply (this display)`

This returns you back to the main Views UI screen and you can save it now.

If you know the node ids of some of the content types, you can test it by typing them in the `Update preview` box and see the list of field collections they match.

---
Tags: views, entities
---


# Question
Title: Open a Make Meeting field inside colorbox
I am using the Make Meeting Scheduler for my site, which is a Doodle-like scheduler module. This module makes it possible to insert a field (only field, not available as block) into a node. However, I need to open this field inside Colorbox.

I know a possible workaround would be to create separate nodes with only the Make Meeting field and then connect them to the original nodes where I need them, but this is definitely not an elegant solution.

I'm really not good with Drupal templates and that is why I haven't come up with a better solution. I suppose I should edit the template, print a link with the class "colorbox-load" and have that link point to the Make Meeting div. Problem is, I am currently clueless as to how to do that.

# Answer
The easiest way to do this is through views. You can configure a view with an "Contextual Filter" of the node id to show and then configure it to show your makemeeting field here. Here's a screenshot of a view that worked for me (note the important parts are marked with arrows.

Then when I go to */meeting-popup/6* (where 6 is the id of a node with a meeting field) i see the following.

Then you can add a link to /meeting-popup/ on the nodes page using the lightbox-load class so it will showup in a popup.

Lastly you can theme the meeting-popup pages so that they only show the content and don't show any regions/sidebars, etc.

Alternatively you can have views make it into a "block" if you know of a good way to do it that way.
> 0 votes

---
Tags: 7, entities, theming, javascript
---


# Question
Title: load files to the public files dir via admin panel?
I was wondering if I could get some advice on best practice on loading images directly to the public files DIR - without FTP access?

My site lives on cloud hosting, and I have no FTP access, my code pushes go through git, but my files dir is not included in the git repo. I have to load a couple images that are not part of any content type to the public files dir, and don't know if there is a module for that, or what other best practices may be. I *can* put a support ticket in if I have to, but I'd like to see if I can get around that if it's possible

Thanks!

# Answer
Since my user case was only one image, I ended up putting the file in the theme folder. for future and larger number file loads I'll be using the media module
> 1 votes

---
Tags: 7, files
---


# Question
Title: 2 separate Profile2 Views (one faculty, one staff)
I've been able to create a view with the profile2 module (with custom forms)that renders all users on a view. How can I create a separate category of users, say 'faculty' and 'students' and have a view for each? So the faculty view would only show users labeled as faculty.

Thanks!

# Answer
> 0 votes
You could add a field "user type" to the current profile and then add a views filter or views "contextual filter" to only show one type at a time. You may need to add a "relationship" on the profile2.

Alternatively, profile2 lets you specify different types of profiles. So you could make a 'faculty' profile and a 'students' profile.

It really depends on what would work best in your setup.

---
Tags: views, users
---


# Question
Title: How do I set, and return, a value in Views PHP?
I'm not going to use the real scenario here, just a very simple one that I think should be working.

I have a View. This view does access some Solr stuff.

I've added a new field to the view. It's a Global PHP field. My end goal of this is that I'd like to make this field sortable when you click the table heading.

In the "Value code":

```
return "asdfasdf";

```

In the "Output code"

```
<?php
  print $value;
?>

```

This returns... nothing. No errors, no output. This is the simplest example I could think of. Am I missing something here?

"Output code" does display other things, even complex things if I ask it to. It just seems like "Value code" is being completely ignored.

# Answer
It works for me. I put the information you said in a PHP field and it printed out as expected. I imagine it's a caching issue or something else about your site that is causing the issue.
> 2 votes

---
Tags: views
---


title: Drupal Home page permission

text:
# Question
Title: Drupal Home page permission
I forbid content access to all user that are not connected. The problem is that Drupal prevent also the access of the main page (And I want that an anonymous user will be able to see it..). How can I separate the main page access to the other content of the site ?

Thank you

# Answer
This question was asked on the Drupal forums here.

If your frontpage is a node you can control access using the Content Access module.

If your frontpage is being generated by a custom module then you can do it by modifying the hook\_menu implementation in your module. You can change the access\_callback to the value TRUE so that everyone can access that page. See this related question

> "access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user\_access() unless a value is inherited from the parent menu item; only MENU\_DEFAULT\_LOCAL\_TASK items can inherit access callbacks. To use the user\_access() default callback, you must specify the permission to check as 'access arguments' (see below).

See the full documentation here.
> 2 votes

# Answer
Another route is to use Panels (1) in combination with views (2), which allows you to create a different frontpage lay-out depending on the role, so also for the role anonymous (not logged in users).

(1) https://drupal.org/project/panels (2) https://drupal.org/project/views
> 0 votes

---
Tags: 7, entities, users
---


# Question
Title: using DrupalWebTestCase - any trick to prevent it from running from scratch each time?
It makes sense to run each test in a completely clean environment. However, before tests can be run, they have to be developed, during this process it is so frustrating to have to wait 3 or 4 minutes each time to see the result of any change/correction in the test.

Is there any trick to somehow resume the test in the environment where is finished or broke last time, without recreating the whole Drupal database? At this point, I am not interested in the tests to be 100% reliable, but rather in getting rid of more or less obvious errors in tests themselves.

For example, in my WebTestCase, I wrote $myfunction instead of $myfunction() and the test failed. The test so far created a content type, so in order to re-run it in the same environment, I would just delete that content type if exists, etc. It would be quicker.

# Answer
> 1 votes
No, there isn't. Simpletest doesn't know if your last test run was successful, or maybe broke something within the test environment, or if you changed it. That alone would be problematic, beside technical reasons. Also, the really slow part isn't your custom setUp() code but setting up a complete Drupal installation every time.

There are some tricks to improve the speed, however.

* Use the testing profile by adding a `protected $profile = 'testing';` to your test class. Maybe you need to define a few additional dependencies though, because that only installs the absolutely required modules. This improves test speed ~50%.
* Have a single public test\*() method, which calls a number of functions. Then you only need a single set-up for the whole test class. However, you need to be aware that your test methods aren't run in a separate environment anymore.
* "Hacking" core by changing the default engine from InnoDB to MyISAM. That makes create TABLE statements much faster.
* Improve your MySQL configuration, here's my configuration as an example: http://techblog.md-systems.ch/blog/improve-mysql-performance
* When actively working on a single test method and the class has multiple ones, disable the others by replacing `function test...` with `function dtest..`. Don't forget to revert that before committing.

A single test method takes ~10 seconds on my laptop. That's not too bad.

# Answer
> 0 votes
I realize that this is an old, long-since-answered question, but anyone else who finds this via google (like I just did), will probably appreciate this.

There's a contrib module called SimpleTest Clone, which supplies a replacement for the the DrupalWebTestCase class, called SimpleTestCloneTestCase. If you derive your test class from this new class, it will clone the active database for each test (instead of rebuilding your site from scratch). On a small testing site, this takes maybe 10-15 seconds: far faster than the complete rebuild process.

It's also useful if you need to run your tests against live site data.

---
Tags: 7, testing
---


# Question
Title: How do I show the "Your Cart" link in my Rules message
I have a created a rule in drupal commerce. I want to include a link to the users cart in that message, just like the link that appears when you add a product to the cart. When I use the url token, the message displays like this: This item has been removed from `http://dcomm/user/3/orders/6.`

I want it to be --This item has been removed from your cart. and you click on the "your cart" and be taken to your cart view.

How do I do this?

# Answer
> 0 votes
Just add a link to

```
<a href="/cart">your cart</a>

```

It will show the user's shopping cart.

---
Tags: commerce, rules
---


# Question
Title: Run PHP when node and/or profile is updated?
I wanted to run an external script when a user profile(2) is updated, and/or when a node is updated. I've added the code to the themes template.php, but no go.

What have I missed?

```
<?php

$api_script_url = "http://www.aaa.com/test/test.php";
$msg = "File updated.";

// WHen a node is updated, be it new or old, update file.
function theme_node_update($node) {
    include($api_script_url."?q=".$node->nid);
    drupal_set_message($msg, 'status');
}

// WHen user profile2 profile is updated, be it new or old, file.
function theme_profile2_update($profile) {
    include($api_script_url."?q=".$profile->uid);
    drupal_set_message($msg, 'status');
}

?>

```

# Answer
Theming functions are the wrong place for something like that. To run some PHP code after an node or profile (thus entity) is updated you should use the Rules module or use the following hooks, hook\_entity\_insert, hook\_entity\_update
> 2 votes

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


# Question
Title: Adding fields via ajax in form does not show in arrays in form_submit
I have am trying to add fields to a form in drupal via ajax. I am able to have my fields show up on the form without issue but the problem is seeing values of those fields when the form is submitted. I have read many tutorials on this tonight and I am very confused why my input fields are not even showing up in $\_POST. Here is an example of what I am trying to do:

```
function add_product($form, &$form_state) {
    //Several other fields but the main one around this issue is below.
    $form['img_mng'] = array(
        'label' => array(
            '#type'     =>  'markup',
            '#markup'   =>  '<h3>Upload Images</h3>',
        ),
        'file1' => array(
            '#type'     => 'file',
            '#size'     => 22,
        ),
        'addMore'   =>  array(
            '#type' =>  'button',
            '#value'    => t('Add More Images'),
            '#ajax' => array(
                'callback'  =>  'add_img_upload',
                'method'    =>  'append',
                'wrapper'   =>  'kc_img_uploads',
                'keypress'  =>  'true',

            ),
            '#prefix'               =>  '<div id="kc_img_uploads"> </div>',
        ),
    );

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

function add_product_validate($form,&$form_state) {
    //Appropriate Validation
    dpm($_POST); //$_POST does not show the fields, not sure how that is even possible since the new fields are added to the form.
    dpm(get_defined_vars()); //None of the variables show the new fields.
}

function add_product_submit($form,&$form_state) {
    // Appropriate database actions....
    dpm($form_state); //No values for new fields.
    dpm($_POST);  //New fields do not even show in the $_POST.
}

function add_img_upload($form,&$form_state) {
    dpm($form_state);  //Does not show the added field below if the button is clicked more than once.
    $num_of_files = 1;
    foreach ( $form['img_mng'] as $key => $value ) {
        if ( preg_match('/^file[0-9]+$/',$key) )
            $num_of_files++;
    }
    $form['img_mng'][sprintf('file%d',$num_of_files)] = array(
        '#type'     => 'file',
        '#size'     => 22,
        '#id'       => sprintf('edit_file%d',$num_of_files),
        '#name'     => sprintf('files[file%d]',$num_of_files),
        '#parents'  => sprintf('file%d',$num_of_files),
        '#array_parents'    => sprintf('file%d',$num_of_files),
    );
    $form_state['values'][sprintf('file%d',$num_of_files)] = '';
    $form_state['file2'] = NULL;
    return $form['img_mng'][sprintf('file%d',$num_of_files)];  //The fields are added to the form every time the button is clicked.  However, the id and name of the elements are only incremented once.  ie file1 becomes file2 but never makes it to file3+.  So I will have one file1 and 1 to many file2's.
}

```

I originally tried this with managed\_file type but I see several people have run into the issue of it returning an empty string. I was actually able to get it to return the field details but found clicking the upload button on any of the new fields submitted the form? Any advice on how to correct this issue with managed\_file type is highly desired but will settle for file type. Thanks again.

# Answer
> 1 votes
The form builder function is what Drupal refers to whenever it needs to rebuild the form. Parts of the form should not be built in the ajax callback. Instead, you can return them using something like

```
function add_img_upload($form,&$form_state) {
  return $form['img_mng'];
}

```

Your form builder has access to form state information, which allows you to build the form conditionally depending on the state of the form.

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


title: Query takes nearly 6 secs. Is it ok?

text:
# Question
Title: Query takes nearly 6 secs. Is it ok?
I switched on Devel logging on site (shop on Drupal Commerce), went to Shop-\>Orders and saw that

```
3818.231 views_plugin_query_default::execute P A E
SELECT commerce_order.order_id AS order_id, commerce_order.order_number AS commerce_order_order_number, commerce_order.uid AS commerce_order_uid, commerce_order.created AS commerce_order_created, users_commerce_order.name AS users_commerce_order_name, users_commerce_order.uid AS users_commerce_order_uid, commerce_order.status AS commerce_order_status, 'commerce_order' AS field_data_commerce_order_total_commerce_order_entity_type FROM commerce_order commerce_order LEFT JOIN users users_commerce_order ON commerce_order.uid = users_commerce_order.uid LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id LEFT JOIN commerce_payment_transaction commerce_payment_transaction_commerce_order ON commerce_order.order_id = commerce_payment_transaction_commerce_order.order_id WHERE (( (commerce_order.status NOT IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) )) ORDER BY commerce_order_created DESC LIMIT 100 OFFSET 0
default

2422.621 views_plugin_pager::execute_count_query P A E
SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM commerce_order commerce_order LEFT JOIN users users_commerce_order ON commerce_order.uid = users_commerce_order.uid LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id LEFT JOIN commerce_payment_transaction commerce_payment_transaction_commerce_order ON commerce_order.order_id = commerce_payment_transaction_commerce_order.order_id WHERE (( (commerce_order.status NOT IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) ))) subquery

```

Is it normal that on site with 3000 items and 7000 orders it takes so much time to form orders view in admin interface?

Site is hosted on server, Xeon E5-2609x2 (2.4 Ghz), 16 Gb DDR-3 memory

# Answer
6 second for a query, we can't say what is normal. However there are ways we can improve performance. with the server configuration you have, we can expect better performance.

There are several things you can do to solve this.

**Optimize View:**

In Drupal many of the performance issue are caused by views. These are mainly caused by use of `Left Join` in views. Use of pager, distinct feature etc.

**These are things that can be solved easily.**

* You can alter views query to use `Inner Join` instead of `Left Join` by disabling the distinct in query either from views ui or code.
* Avoid using last in pager or use views\_litepager module instead.

Here is a sample views alter code:

```
/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

```

There is a good post on optimizing views that you can read to understand this better here.

Other than this you should check if your mysql configuration in my.cnf is optimized as per your system resources. For this you could use mysqltuner script or mysql-tuning-primer script.

Above that use of memcached with Drupal can also increase performance to great extend.
> 0 votes

# Answer
Just looking at the query, the obvious culprit is the `recently_read` module. The join that is added to the query is fully unindexed:

```
LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id

```

The query doesn't really make sense, so I assume the Views integration for this module needs work.
> 1 votes

---
Tags: commerce, performance, database
---


title: Slow views render time

text:
# Question
Title: Slow views render time
I am using Drupal commerce for one of my clients. I notice that the view with orders which are in a checkout status take several seconds to load. After i enable views statistics the numbers are

```
Query build time    23.51 ms
Query execute time  4.33 ms
View render time    209.68 ms

```

Which are pretty fast. But despite of the 200ms it takes 6-7 secs to load the view. What could cause this?? Any directions in order to debug this??

My server is VPS and well configured. I only have this problem with this actual site.

Thank you in advance

# Answer
Though view is a powerful module, it can cause a lot of performance problems if certain things are not handled. There a certain steps you can follow to fix this.

There are several things you can do to solve improve this:

**Optimizing View:**

* Try to change `left join` to `inner join` using alter.
* Enable Cache on views and clear it when order is updated.
* Check if Distinct is marked.

**Here is a sample views alter code:**

```
/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

```

Optimizing view is a wider topic, there is a good write up on optimizing views that you can read to understand this better here.

Other than this you should check if your mysql configuration in my.cnf is optimized as per your system resources. For this you could use mysqltuner script or mysql-tuning-primer script.

Above that use of memcached with Drupal can also increase performance to great extend.
> 1 votes

---
Tags: views, commerce
---


title: Extreme slow Views rendering time

text:
# Question
Title: Extreme slow Views rendering time
On my Drupal 7 site I have some heavy performance problems. I found out (with XHProf) that the cause of that problem are some Views. The strange thing is: not the query build time nor the query execute time are to slow, but the views rendering time:

```
Query build time    4.83 ms
Query execute time  3.29 ms
View render time    1175.82 ms

```

The view is complicated because it has 7 relations. So that its build and execute time is as long as it actually shows up in the example above, is what one would expect. But the rendering can not depend on the complexity of the query, right? But only on the complexity of the resulting array or something else. So, my question is, where to start to optimize View render time?

ps.: If the view is cached it much faster. But I have to optimize its over all execution time, when it's not cache or can't be cached.

# Answer
Views can create real bottleneck for scaling and often cause great head ache by becoming resource hungry if not optimized well. Especially the use of `Left Joins` instead of `Inner Joins`, the default pagination in views and features like Distinct are major causes for the same.

The below code is a quick sample implementation which probably could fix the join issue in a view.

```
/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

```

Also, check if you can enable views cache. You can set the interval to something based on your update frequency or try to clear views\_cache when something is updated on the site.

Use of views\_litepager instead of the default page can also help, if you are using pagination in views.

There are several things you can do. You could read this detailed post on the topic for a more detailed understanding.
> -1 votes

---
Tags: views, performance
---


title: OAuth2 vs Session Authentication

text:
# Question
Title: OAuth2 vs Session Authentication
I'm setting up a OAuth2 Server using the OAuth2 Server module. Everything tests out as expected. I login, get the authentication code, which I then trade in for an access\_token, which tests out successfully.

The issue comes when requesting a resource that's handled by the services module. It looks like it's starting a session for the anonymous user instead of calling the other authentication hooks.

After all, if one authentication method fails, it shouldn't assume that it's the only authentication method possible.

Any ideas on how to use OAuth2 authentication code authorization to access services endpoints?

Here's the snip from `services.runtime.inc line 116` where it's only looking for one authentication module, it seems.

```
foreach ($endpoint->authentication as $auth_module => $settings) {
  if (isset($settings) && $auth_error = services_auth_invoke($auth_module, 'authenticate_call', $settings, $controller, $args)) {
    return services_error($auth_error, 401);
  }
}

```

# Answer
Make sure the selected authentication methods are enabled for the server, e.g:

```
admin/structure/services/list/rest_api

```
> 0 votes

---
Tags: services, users, authentication-authorization
---


# Question
Title: Need a list of terms from a vocabulary machine name
How can I get the terms of a vocabulary using vocabulary machine name.

I have used the following code, although it works for me but I am looking for efficient methods.

```
$vocabulary = taxonomy_vocabulary_machine_name_load('school_courses');
$terms = taxonomy_get_tree($vocabulary->vid);
$courses = array();
foreach($terms as $term) {
    $courses[$term->tid] = $term->name;
}

```

# Answer
What you are doing is pretty much the same as Drupal core is doing for the term reference field, so doubt you can improve the code much.

```
/**
 * Returns the set of valid terms for a taxonomy field.
 *
 * @param $field
 *   The field definition.
 * @return
 *   The array of valid terms for this field, keyed by term id.
 */
function taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

```
> 5 votes

# Answer
Using EntityFieldQuery, you can add

`->entityCondition('bundle', 'my_machine_name')` to get terms by vocabulary name:

Example:

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'taxonomy_term')
                ->entityCondition('bundle', 'my_machine_name')
                ->execute();

```
> 3 votes

# Answer
I use EntityFieldQuery:

```
// Get vid from machine_name
$my_vocabulary = taxonomy_vocabulary_machine_name_load('my_machine_name');
$my_vid = $my_vocabulary->vid;

// Build and execute the query
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $my_vid)
$result = $query->execute();

// Process the result
var_dump($result);

```

Output:

```
array(1) {
  ["taxonomy_term"]=>
  array(8) {
    [12]=>
    object(stdClass)#145 (1) {
      ["tid"]=>
      string(2) "12"
    }
    [14]=>
    object(stdClass)#149 (1) {
      ["tid"]=>
      string(2) "14"
    }
    /* etc... */
  }
}

```

http://api.drupal.org/api/drupal/includes!entity.inc/class/EntityFieldQuery/7
> 1 votes

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


# Question
Title: Making an instantiated object in a module global
I am creating a Drupal 7 module, and i have a file with a class definition in it. I am able to instantiate this class successfully. Where is the best place to instantiate this class in my .module file and make that object available to my module hooks?

For instance, I don't want to do the following:

```
function mymod_block_view{
  $obj = new Object()
  ....
}

function mymod_block_info() {
...
$obj = new Object()
}

```

Normally I would just use dependency injection, but I can't add arguments to the function definitions (so far as I know)...How can I only instantiate my object once and get the members and methods of the instantiated object available to my hooks?

# Answer
"Best" won't get you too far here; there are a bunch of different ways, none of them particular to Drupal, and all with advantages and disadvantages. Go with what you're comfortable maintaining.

That said, a simple singleton pattern would make most sense to me:

```
class MyClass {

  protected static $instance = NULL;

  protected function __construct() { }

  public static function getInstance() {
    if (!isset(static::$instance)) {
      static::$instance = new static();
    }
    return static::$instance;
  }

  // Remaining class implementation

}

// Use this as many times in a single page request to get access to the same instance of MyClass every time.
$instance = MyClass::getInstance();

```

I feel like I should add a bit about autoloading in Drupal 7, in case you haven't already come across the options...

Drupal 7 implements a simple autoloader; in the module's .info file you can specify the path to a file containing classes:

```
files[] = MyClass.php

```

and any class in that file will be automatically available to you anytime you want it, without having to explicitly include the file.

If you want to go one step further, check out the excellent X Autoload module. It provides a PSR-0 autoloader, which mirrors Drupal 8's autoloading.

I think PSR-4 is in the pipeline too, but that's another story...
> 8 votes

# Answer
In general, a singleton is just a global variable in a nice dress. We should avoid it as much as possible. But in Drupal there is no way to completely avoid globals. We can only try to reduce their usage.

---

About the singleton approach: Many existing Drupal modules use a procedural-style singleton:

```
function household_get_manager() {
  static $manager;
  if (!isset($manager)) {
    $manager = new Drupal\household\HouseholdManager();
  }
  return $manager;
}

```

This is technically not so different from Clive's answer, but I think it is used more often within Drupal. I personally prefer it, because it separates the class definition from its instance.

---

This being said, often it is more than one object that you want to treat like a "global". And often one of these objects depends on another.

With the singleton approach, your household manager instance would need to make another singleton call to e.g. the Shovel::getInstance() and Broom::getInstance(), whenever it needs one, etc.

I personally often build a "poor man's DIC" (Dependency injection container), to organize the classes/objects provided by the module, and their dependencie.

There are different ways to do this, and I am not yet sure which variation I should recommend. Heck, I am not even sure if I should recommend the entire thing :)

The Poor man's DIC object itself is still going to be a singleton. But the objects themselves have their dependencies injected by a factory.

This way you can write this in your hooks:

```
$shovel = household()->shovel;
$manager = household()->manager;

```

From outside, this still looks and behaves very global-ish. But at least on the inside, you can remove all static and global calls from your worker objects.

```
class HouseholdManager {
  protected $shovel;
  /**
   * @param Shovel $shovel
   *   Shovel object injected from the factory.
   */
  function __construct(Shovel $shovel) {
    $this->shovel = $shovel;
  }
}

```

Posting the entire Micro-DIC here would be too much. So maybe you want to look at an example instead. I could not find a really perfect one, but this here is at least simple to look at: http://drupalcode.org/project/krumong.git/blob/refs/heads/7.x-1.x:/lib/Drupal/krumong/ServiceCache/ServiceCache.php http://drupalcode.org/project/krumong.git/blob/refs/heads/7.x-1.x:/lib/Drupal/krumong/ServiceCache/ServiceFactory.php There is some magic going on here with the magic \__get(). Some people don't like this. Also, this desperately needs docblock comments.

One trick I learned is you can use @property docblock for type hints on your container's magic properties. I don't have an example for this atm, sorry. Some of this is still waiting on my localhost to be committed.
> 1 votes

---
Tags: 7
---


# Question
Title: drupal commerce rule to skip duplicate sku in cart
I have a site and i am using drupal commerce module. i want to set a rule which will prevent the user to add a product twice in the cart. suppose a user add a product A and after that if he add the same product in the same cart than the system should generate a message that the same product is already added in your cart you can add another product.

I tried to create a rule but it works on the total quantity of cart not on total quantity of same product in the cart. please help

Thanks

# Answer
You can use unique field , autosku and tokens module

using that module set the name of sku using tokens While generating sku use tokens

the parameters which u know differentiates 2 products should be used in tokens

Like if quantity and size is the parameter which differentiates your 2 products and defines two products as unique then using tokens(for e.g.) \[product:qty\] and \[product:size\] set the sku title and using unique field set the sku as required and unique field

You can try the following function to edit the quantity : you can set cart quantity for a single item to be default value 1. hook\_commerce\_cart\_line\_item\_refresh($line\_item, $order\_wrapper)

> Allows modules to perform additional processing to refresh an individual line item on a shopping cart order.
>
> Prior to this hook being invoked, product line items will have already had their sell prices refreshed via the creation of a new line item for the same product being passed through Rules for calculation.
>
> Parameters
>
> $line\_item: A line item object that should be updated as necessary for the refresh.
>
> $order\_wrapper: An EntityMetadataWrapper for the order the line item is attached to.
> 1 votes

---
Tags: commerce, rules
---


title: Organic groups organizational problem

text:
# Question
Title: Organic groups organizational problem
Apologies if this question has already been answered. I'm developing an emergency notification site using Drupal 7 and Organic Groups and currently it's building-driven -- i.e., the buildings are the groups which have users connected to them. They can add notes, photos, etc. and all works well.

Now it seems that it would be better to have an event-driven system. Admins could create an event (such as a hurricane) and then assign those buildings that are in the path of the event. I've tried creating a new Event content type and using the Entity Reference module, linking the Building list to the Event. However, when it comes time to create a View to display the information I'm running into the following error message when I build the view relationship using Entity Reference: Referenced Entity: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'og\_membership.field\_affected\_buildings\_target\_id' in 'on clause'

Here is my exported view (note that it doesn't have any fields yet but it does have the broken relationship):

```
$view = new view();
$view->name = 'event_list';
$view->description = 'Displays all emergency events with affected buildings.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Event List Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'title',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_address' => 'field_address',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_address' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['id'] = 'field_affected_buildings_target_id';
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['table'] = 'og_membership';
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['field'] = 'field_affected_buildings_target_id';
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['label'] = 'Building';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'event' => 'event',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'events';

```

Thanks to anyone who can point me in the right direction!

# Answer
I had the same case.

I removed the entity reference (which cause the problem) from Relationships and added necessary fields with Rendered Entity Formatter.

You can choose any view mode you want and show all the required data. No Relationships are required.
> 0 votes

---
Tags: views, organic-groups, entities
---


# Question
Title: Where to look for a forum thread in database?
In Drupal 6 forum, a user reported that her thread has suddenly disappeared.

I am wondering in which database table should I look for the thread, and what might be the cause?

# Answer
> 1 votes
I don't know how 6 version works with forum (because I've never used 6v), but in d7 forum is actually is a node (threads are node types). I thinks you can search for forum table which holds the nids of threads and node and node\_type tables for actually for that nodes and thread type...

To find the node by Title: Open your PhpMyAdmin from browser -\> select your db -\> open 'node' table -\> switch to SQL tab -\> SELECT * FROM node WHERE title = "YOUR TITLE"

EDIT: threads are taxonomies, not node types (based on comment of Mohammad Ali Akbari)

---
Tags: 6, nodes
---


# Question
Title: an error occurred while installing jplayer and audiofield module on server in drupal 7
I tried to install jplayer and audiofield modules on server but the following error reported and I could not understand what it is and how to solve it:

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: http://**mywebsite.com**/authorize.php?batch=1&render=overlay&id=28&op=do StatusText: Internal Server Error ResponseText: UnexpectedValueException: RecursiveDirectoryIterator::\__construct(/home/**username**/public\_html/C:/xampp/tmp/update-extraction-7a580f22/jplayer) \[recursivedirectoryiterator.--construct\]: failed to open dir: No such file or directory in RecursiveDirectoryIterator-\>\__construct() (line 408 of /home/**username**/public\_html/includes/filetransfer/filetransfer.inc

I installed these modules on `localhost` and there was no error.

# Answer
> 1 votes
Try to create a temp directory and give 777 permission and change file system's temporary directory from 'admin/config/media/file-system' to that temp directory. Because C:/xampp/tmp/ doesn't exist on your server.

---
Tags: 7
---


# Question
Title: Why can't I find the parent term of a tag when a node is being inserted?
I'm following another question I asked, How can I get the parent term in a taxonomy with a hierarchy? and I can get the parent term when I am on the view operation, but not when I'm on the insert operation. `var_dump()` shows the `$terms` variable, but `NULL` for `$pterms`. Here is my code being called in `hook_nodeapi('insert')`.

```
  foreach ($node->taxonomy as $term) {
    $terms[] = $term;
  }
  $tid = $terms[0]->tid;
  $parents = taxonomy_get_parents($tid);
  foreach ($parents as $term) {
    $pterms[] = $term;
  }

```

# Answer
> 2 votes
Did you try taxonomy\_get\_parents\_all()?

```
$parents = taxonomy_get_parents_all($tid);
  foreach ($parents as $term) {
    $pterms[] = $term->name;
  }

```

# Answer
> 0 votes
```
function Yourthemename_breadcrumb($variables)
{
  // init
    $breadcrumb = $variables['breadcrumb'];

    // taxonomy hierarchy
    $hierarchy = array();
    if (arg(0) == 'gallery' && arg(1) == 'term' && is_numeric(arg(2)))
    {
        $tid = (int)arg(2);
        $parents = taxonomy_get_parents_all($tid);
        $parents = array_reverse($parents);
        $breadcrumb = array();
        $breadcrumb[] = l('Gallery', '/');
         foreach( $parents as $k=>$v)
        {
            $breadcrumb[] = l($v->name, 'taxonomy/term/'. $v->tid);;
        }
    }

    // rendering
    if (!empty($breadcrumb))
    {
        $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';
        $output .= '<div class="breadcrumb"><ul><li>' . implode("<span>></span><li>", $breadcrumb) . '</li></ul></div>';
        return $output;
    }

}

```

---
Tags: 6, taxonomy-terms
---