# Question
Title: User registration form throws validation errors on already unset profiles´ fields
Using Drupal 7 with Profile2: I have a number of profile types, with different fields, some of which I want a registrant to already fill up during the registration process. I´ve checked "Show during user account registration" for all. In my custom module, I´m first taking the registrant´s choice of profile, then unsetting (unset(); also tried hide() and ...\[#access\]=FALSE) all the other profiles and then rendering the registration form. This 'shows up' correctly because I only get to see the chosen profile fieldset. However, when I submit the form I get validation errors (required fields) on the unset profiles´ fields. So apparently only unsetting/hiding/etc. won´t do the trick. What am I missing?

Appreciate any help!

Best, Mir

# Answer
The Profile2 Registration Path module solves the issue!

> This module enables administrators to set unique registration paths per Profile2 profile type.
> -1 votes

---
Tags: users
---


# Question
Title: How to sort comments by a new field in the comment table?
I'm writing a module which allows users to put comment on each paragraph.

I have added a new field to the comment table, called `paragraph_id`, and in the comment form I have added a field that asks users which paragraph do they want to put comment on.

So now all I have to do is to alter the comment query. So something like what sort comment module does, it alter the comment query so that they got sorted by date, now I have to sort them by paragraph\_id field.

**This is the sort\_comment.module :**

```
  <?php
  /* drupal@ganovelli.it - blackice78 */
 define('SORT_COMMENTS_OLDER_FIRST', 1); // default
 define('SORT_COMMENTS_NEWER_FIRST', 2);
 /* Alter node type form: allow user to decide comments sorting */
  function sort_comments_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['comment_default_sorting'] = array(
 '#title' => t('Sort'),
 '#type' => 'select',
 '#options' => array(1 => t('Older first'),
                     2 => t('Newer first')),
 '#default_value' => variable_get('comment_default_sorting_' . $form['#node_type']-           >type, SORT_COMMENTS_OLDER_FIRST),
    );
  }
 /* Alter comments query */
 function sort_comments_query_comment_filter_alter(QueryAlterableInterface $query){
 if ( ($node = $query->getMetaData('node')) && (get_class($query) == 'PagerDefault') ) {
  $sort = variable_get('comment_default_sorting_' . $node->type,           SORT_COMMENTS_OLDER_FIRST);
  if ($sort == SORT_COMMENTS_NEWER_FIRST) {
  $orderby =& $query->getOrderBy();
  $expressions =& $query->getExpressions();
  if (isset($orderby['torder'])) {
      unset($expressions['torder']);
      unset($orderby['torder']);
        $orderby['c.thread'] = 'DESC';
      } else {
       $orderby['c.cid'] = 'DESC';
     }
  }
}

```

So, does anybody know how can I sort the comments by `paragraph_id` field?

# Answer
The sort\_comments.module checks if a special value is set to use its' ordering:

```
if (isset($orderby['torder'])) { /* ... */ }

```

You likely want to set an sql `expression` like they do for your own module.

Then in sort\_comments.module they just set an SQL `order by` or leave the default ordering by comment\_id (`cid`):

```
// ...
$orderby['c.thread'] = 'DESC';
} else {
   $orderby['c.cid'] = 'DESC';
}

```

You likely want to mimic this functionality in your own vesrion of `hook_QUERY_TAG_alter`, a specific version of `hook_query_alter`.
> 1 votes

---
Tags: comments
---


title: Boostrap Responsive Menu Not Working

text:
# Question
Title: Boostrap Responsive Menu Not Working
I'm having an issue with my menu on the responsive size. For some reason my menu doesn't collapse so I cannot see any of my items on my menu on a tablet or a mobile. Using the inspect element I check and all the pages from my menu are in the html but the collapsing part is not working anymore. I'm currently using the Project Bootstrap.

Can anyone provide me some tips on how to troubleshoot this problem? Any help will be appreciated.

# Answer
Taking a look at the HTML on your homepage there, I'm seeing you're loading bootstrap in your `<head>` section, and then calling jQuery from near the footer, way down on line 223 (that'd be the line `<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>`. That's why I'm at least seeing the error `Uncaught Error: Bootstrap requires jQuery`. You want to load jQuery before you load Bootstrap, so ultimately your `<head>` should include the two lines:

`<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>`

I hope this at least gets you closer.
> 1 votes

---
Tags: theming
---


# Question
Title: How to send an email from user email templates programmatically?
There are some email templates on the admin interface of the user account settings.

I want to load that email template and change the token value dynamically in my custom module and then send that email?

Any one who have some idea?

# Answer
> 1 votes
I have found the solution. Below is the method I followed.

I added the new email template to the user account settings form using the following code.

```
$form['custom_email_template'] = array(
    '#type' => 'fieldset',
    '#title' => t('Contributor Email on Miles recieved'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#tree' => TRUE,
    '#group' => 'email',
  );
  $form['custom_email_template']['user_mail_custom_email_template_subject'] = Array(
    '#type' => 'textfield',
    '#title' => 'Subject',
    '#default_value' => variable_get('user_mail_custom_email_template_subject'),
    '#maxlength' => 180,
  );
  $form['custom_email_template']['user_mail_custom_email_template_body'] = Array(
    '#type' => 'textarea',
    '#title' => 'Body',
    '#default_value' => variable_get('user_mail_custom_email_template_body'),
    '#rows' => 15,
  );

```

And then on the 2nd submit handler of the user account settings form I used the following code to save the email content in a drupal variable.

```
variable_set('user_mail_custom_email_template_subject', $form_state['values']['custom_email_template']['user_mail_custom_email_template_subject']);
variable_set('user_mail_custom_email_template_body', $form_state['values']['custom_email_template']['user_mail_custom_email_template_body']);

```

and then use the following code to get the content of the email template.

```
$body = variable_get('user_mail_custom_email_template_body');
$subject = variable_get('user_mail_custom_email_template_subject');

```

and used the `str_replace()` function to replace the tokens with the dynamic values.

Hope it will help someone.

# Answer
> 0 votes
Use the Mime Mail module. It contains a `mime-message.tpl.php` which we should copy to our theme's template folder. Modify it as per your requirement.

We cannot send HTML tags using SMTP mail type.

---
Tags: 7, emails
---


# Question
Title: Devel's dpm needs two refreshes to display message from (pre)process
I use `Zen` and have copy/pasted the `STARTERKIT` to my `foo` template. `Devel` is enabled with the "Rebuild the theme registry on every page load" setting on.

In my completely empty `template.php` I type in the following and save:

```
function foo_process_node(&$variables, $hook) {
    dpm('test');
}

```

I then do `drush cc all` and refresh page. The message is not shown. If I refresh again the message shows.

If I change `test` to `foobar` on the 1st refresh I get the old `test` and on the second I get `foobar`.

Why does this happen and how can I avoid it?

Note that this lagging behavior is the same for `preprocess` and `process` but not there if I print the message from the `foo_page_alter(&$page)` function.

# Answer
> 6 votes
This is a common issue people encounter when themeing Drupal (it used to drive me crazy).

In basic terms what's happening is that the messages held in the `$_SESSION` super global have already been committed to the page by the time the template file containing your call to `dpm()` is invoked.

This means that the messages are added to the `$_SESSION` but aren't dumped out to the messages area until the next page...as `$messages` has already been set up for/printed in page.tpl.php.

The normal way to get around this is to invoke the `dpm()` at an earlier stage of the process, like in `hook_page_alter()` as you mention, or `hook_node_view()`, etc.

Also I think if you implement your preprocess hook at the module level, rather than the theme level, that your calls to `dpm()` will happen in time for the messages to be displayed in that particular page request.

# Answer
> 3 votes
This has been an issue for me as well. Another workaround for this by using kpr($your\_variable), which is also a function in devel and that seems to display the output on the first page load.

# Answer
> 0 votes
`dsm` method is called to `dpm` method. so we need to call `dpm`.

in `dpm` -- p indicate the `print_r()`.

`dpm` is just show the array and object as print\_r only difference is it show it in error display block. because internally it use `drupal_set_message`.

---
Tags: 7, debugging, theming
---


title: Batch operation isn't called

text:
# Question
Title: Batch operation isn't called
I have a module with batch operations, this is my hook\_menu

```
$items['some-pretty-url'] = array(
    'title'            => 'Title',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('import_form'),
    'access arguments' => array('access content'),
    'type'             => MENU_NORMAL_ITEM,
);

```

...and this is my batch config

```
$batch  = array(
    'title'            => t('Lorem ipsum Elit pariatur Duis et elit aute.'),
    'init_message'     => t('Commencing...'),
    'operations'       => $operations,
    'progress_message' => t('Processed: @current out of @total.'),
    'error_message'    => t('An error occurred during processing.'),
    'finished'         => '_import_finished',
);

```

Batch works pretty good if I have the module definition in the .module file, but if I move the functions to another file the batch simply does not work at all.

```
$items['some-pretty-url'] = array(
    'title'            => 'Title',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('import_form'),
    'access arguments' => array('access content'),
    'type'             => MENU_NORMAL_ITEM,
    'file'             => 'module_definition.inc', //move module to another file
);

$batch  = array(
    'title'            => t('Lorem ipsum Elit pariatur Duis et elit aute.'),
    'init_message'     => t('Commencing...'),
    'operations'       => $operations,
    'progress_message' => t('Processed: @current out of @total.'),
    'error_message'    => t('An error occurred during processing.'),
    'finished'         => '_import_finished',
    'file'             => 'module_definition.inc', //batch functions are here
);

```

Batch function is not being called even if I set the file argument in the batch configuration.

# Answer
When you run a batch the URL automatically changes to /batch...at that path, Drupal doesn't know to include your module\_definition.inc file. It'll only process the menu hook when the path is 'some-pretty-url', so module\_definition.inc will only be included then.

If you move your batch *definition* into the module file it'll start working, and the `file` you've told the batch system to find the processing function in will be included as you'd expect, because now Drupal knows it needs to be included.
> 1 votes

---
Tags: 7, batch-operations
---


# Question
Title: Using another html.tpl.php for specific page
I have googled this alot but none of the suggestions I found works for me.

I want to use another html.tpl.php template for a specific page, preferably matched with the url-string to that page, but the id works aswell.

This is the code I'm trying now (in template.php):

```
function mytheme_preprocess_html(&$variables) {

    $nid = arg(1);

    if ($nid == '1715') {
        $vars['theme_hook_suggestions'][] = 'html__test';
        echo "testing testing";
    }
}

```

My custom template file is named: html--test.tpl.php.

The echo part does print on the page so the $nid is correct.

mytheme is not the actual name of my theme, but I replaced it here.

# Answer
> 7 votes
Note, there's already template suggestions for `html.tpl.php` generated by `template_preprocess_html` (see last lines in the function there)

For a specific node page, you can use `html--node--1715.tpl.php` where `1715` is the target node id.

---
Tags: theming
---


title: IE fix for Omega theme?

text:
# Question
Title: IE fix for Omega theme?
In the past, I have used the Fusion theme for designing web sites. Recently I started using the Omega theme, and realized a big problem with it. I went to look at it in IE, and it looks terrible. In Fusion, there is an IE fix in which, there is a separate css file for ie. I can't seem to figure out how to do this in omega. I know that there has to be a way, because the acquia site is themed in Omega, and it looks fine in IE. how is it that I go about fixing this problem?

# Answer
As dddave mentioned it is probably because you have on your site more then 31 css files. Ie will use only 31 first files - other will be left alone.

What can you do with it? On live site - turn on standard drupal css aggregation. I will make creating theme painfull - you will need to clean cache(admin/settings/performance) after every css file change. So you can use the IE CSS Optimizer module:

Then there will be more option for css aggregation. It will make possible to aggregate all module's css, and having all theme's files included directly. Hopefully total number of files will be below 31.

For making easier adding condition styles for IE try the Conditional Stylesheets module:
> 2 votes

# Answer
You can just add the following code into your template.php file

```
drupal_add_css(path_to_theme() . '/css/ie8.css', array('weight' => 999, 'browsers' => array('!IE' => FALSE, 'IE' => '(lt IE 9)&(!IEMobile)'), 'group' => CSS_THEME));

```
> 2 votes

# Answer
The module conditional styles and Omega don't work well (last time I checked), so basically what I did was adding this to template.php

```
function custom_theme_preprocess_html(&$variables) {
  drupal_add_css(path_to_theme() . '/css/ie-lte-8.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie-lte-7.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
}

```

Doing it this way, IE-specific styles get rendered last, after all the other CSS files in Omega.
> 1 votes

# Answer
As well, if the earlier reposes didn't help: Omega is in HTML5. You have to be certain a link html5shiv.js or html5shim.js is included in the head of the page.tpl.php file. Older versions of IE just won't know how to behave.
> 0 votes

# Answer
Add this function to your template.php

```
function theme_preprocess_html(&$vars) {
  // Setup IE meta tag to force IE rendering mode
  `enter code here`$meta_ie_render_engine = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'content' =>  'IE=edge,chrome=1',
      'http-equiv' => 'X-UA-Compatible',
    ),
    '#weight' => '-99999',
  );

  // Add header meta tag for IE to head
  drupal_add_html_head($meta_ie_render_engine, 'meta_ie_render_engine');

   drupal_add_css(path_to_theme() . '/css/ie-lte-8.css', array(
    'group' => CSS_THEME,
    'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE),
    'preprocess' => FALSE)
  );
}
function omega_subtheme_css_alter(&$css) {
  foreach ($css as $key => $value) {
    if (preg_match('/^ie::(\S*)/', $key)) {
      unset($css[$key]);
    }
    else {
      $css[$key]['browsers']['IE'] = TRUE;
    }
  }
}

```
> 0 votes

---
Tags: 7, theming
---


title: Auto login to LinkedIn

text:
# Question
Title: Auto login to LinkedIn
I have installed HybridAuth module. I can login from my website using LinkedIn. But my question is, how can I login automatically into LinkedIn when I login from my website using LinkedIn login?

I have gone though various APIs but could not get proper information.

# Answer
> 2 votes
Got something closely related to your case and I won't say this is not possible, you can have some workaround by following these threads:

Login to Drupal using LinkedIn

This feature is not available right now, to login into Linkedin while using its credential on your site. But it seems that, this thread is in knowledge of Linkedin Officials as well and there may be some work is going on to provide you create app feature just like Facebook.

Here is something to elaborate the same:

http://developer.linkedin.com/forum/how-create-linkedin-application-tripit-or-slideshare

# Answer
> 1 votes
This is only done with both website communicate each other. It means that your website and **linkedin** both assured each other **credential information** and surely linkedin cant trust your website so it is not possible

---
Tags: 7, authentication-authorization, social-network
---


# Question
Title: How to avoid duplication of data using feeds module?
I've set up a CSV importer using the Feeds module. My CSV is not a drupal file but one that i have, of my own. I've mapped the name of the coupon(a column in my CSV file) onto the title of my content type "coupon". This is just a test run. On importing the same data twice, it's being duplicated. I want the repetitive data to be deleted. Can someone help please?

# Answer
Use Target configuration as unique to avoid duplication
> 1 votes

---
Tags: feeds
---


# Question
Title: Create referenced node on the fly in Drupal 7?
I have a node called "house" which references another node called "room". When I create a house, i.e. go to node/add/house, there will be a block where I can choose all the rooms I've created. What I want instead is to create the room on the fly, right on that page, and then reference it automatically. So basically, next to where you can choose rooms, you must be able to click a button that says "create new" and then ajaxically it must then open a an area on the page where you can create room.

Does that make sense? Is there a way to do this? I have the entity reference part of things setup, but before I look into trying to figure out which hook to plug into, perhaps someone knows of an inherent way that already uses entity?

# Answer
> 2 votes
You should use the Inline Entity Form module.

> Provides a widget for inline management (creation, modification, removal) of referenced entities.
>
> The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.

# Answer
> -1 votes
You could also look at Entity connect

> Entity Connect now expands both Entity reference and References (node\_reference and user\_reference) fields by adding "add new content" and "edit current content" buttons. It will work with all default widgets provided by Entity reference and References (node\_reference and user\_reference) .

or

References dialog

> This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

---
Tags: entities
---


# Question
Title: Commerce PayPal commerce_payment_transaction PDOException[23000]
I'm using commerce paypal to accept payment on a drupal website. i have configured the module as described in drupal commerce support website and created sandbox accounts both for buyer and seller. i created a test order and paid with paypal, the IPN is received successfully and it is verified according to report/dblogs with message:

> IPN validated for Order 2 with ID 7DW624906V374562U.

But after this db log there's another one which is an error with message:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created, data) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 13054 \[:db\_insert\_placeholder\_1\] =\> 1396116964 \[:db\_insert\_placeholder\_2\] =\> a:1:{s:7:"contact";i:1;} ) in drupal\_write\_record() (line 7194 of /home/findaper/public\_html/includes/common.inc).

and type:

> commerce\_payment\_transaction

So, the payment is validated, but there's this error, and the event "when order first paid in full" is not firing. i have no idea how to fix this. can anyone help me with this??

drupal and all modules are the latest version. \[drupal7\]

# Answer
> 2 votes
```
Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created, data)

```

This is incorrect code, since no `name` value defined for inserting, so user name is empty and name should be unique - you cann't insert second user with empty name.
Try find this code `INSERT INTO {users} (uid, created, data)` on your drupal files (modules), if no success, investigate your Rules for custom code.

# Answer
> 1 votes
I encountered the same issue. I have a custom rule that add a role to a user after he has completed his payment. I used **site:current-user** instead of **commerce-order:owner**. site:current-user is not defined because PayPal is an anonymous user when the IPN is processed.

So you should use **commerce-order:owner** in your custom rules when accessing user.

Hope that can help someone ;-)

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


# Question
Title: Sort a Table View by Fivestar Rating Fields
I'm currently using Fivestar-7.x-2.0-alpha2 and Views-7.x-3.7. And running Drupal 7.

I am trying to create a table view that displays the information from fields on a certain node type. In this case, the "Program" node and all of the rating fields (fivestar fields) and two text fields (Discipline and University). You can see what I have currently here.

The problem I am having is I can't seem to get the table to sort properly. I have cleared out the Sort Criteria so there isn't any sorting being applied other than from the table settings (I think?). I went into the table settings for the view and checked off sortable for all of the fields. However, when I try to sort them they either don't change at all (the fivestar and computed fields) or they sort improperly (the University field).

I'm at somewhat of a loss. I've done hours of Googling but I can't seem to come up with any sort of solution. If anyone could offer some advice I would be most appreciative.

I should also note that the "Overall" field is a computed field that averages all of the fivestar fields.

# Answer
> 3 votes
This is incredibly late, but I just found the answer to the Fivestar rating issue:

You need to add *"Content: Vote results"* as a View relationship, then sort by *"Vote results: Value"*.

Sorting by "Rating: Average Rating" seems to do nothing, as the queried fields seem to be undefined. This method, however, will work.

---
Tags: 7, views, rating
---


# Question
Title: How to compare Profile2 field with PCP percentage in drupal 7 while creating Rule?
I am using Rules, PCP & Profile2 Module in drupal 7. I want to send mail to those user whose profile is \<60%, how to add condition for sending mail? How can i compare the profile2 field with pcp %. I already created a Event & Action. Problem in add contion. Please help. Thanks

I want condition like this i.e. $complete\_profile\<60. If by using php code then how can i implement.

# Answer
See Rules Integration for D7 version issue in Profile Complete Percent issue queue. Only condition they implemented is, it seems, *"User profile is completed"*.

Maybe there are additional conditions now. Open this window and see. If condition you want is lacking, you will need to either file a feature request for PCP, or write own custom module, clone *"User profile is completed"* in it, changing name and switching from `=100%` (or how they actually implemented it) to `<60%`.
> 2 votes

---
Tags: 7, users, rules
---


# Question
Title: URL variable not respected when ajax call happens in user registration form
There are some fields (some required, some not) I need to (conditionally) hide in the user creation form:

```
function hook_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
    case 'user_register_form':
        //variable_name is sent using hook_menu_output_alter()
        if ($_REQUEST['variable_name'] == 'variable_value') {
            $form['field_id'][LANGUAGE_NONE]['#required'] = FALSE;
            $form['field_id']['#access'] = FALSE;
        }
}

```

This generally works but not when I override a (required) entity reference field in the form to change its autocomplete path:

```
//in another module:
function hook_alter(&$form, &$form_state, $form_id){
    $form['entity_ref_field'][LANGUAGE_NONE][0]['target_id']['#autocomplete_path']= 'custom_autocomplete';
    $form['entity_ref_field'][LANGUAGE_NONE][0]['target_id']['#ajax'] = array(
            'callback' => 'custom_callback',
            'wrapper' => 'custom_wrapper',
            'method' => 'html',
            'effect' => 'fade',
    );
}

function hook_menu(){
    $items = array();
    $items['custom_autocomplete'] = array(
        'title' => '',
        'page callback' => 'custom_page_autocomplete',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function custom_page_autocomplete($string) {
  $string = array(':s' => $string . '%');
    if ($string) {
        $results = db_query("SELECT title, nid FROM {node} as n WHERE type = 'custom_type' and title LIKE :s", $string);

        $items = array();

        foreach ($results as $result) {
            $items[$result->title.' ('.$result->nid.')'] = $result->title;
        }
        print drupal_json_encode($items);
    }
}

function custom_callback(&$form, &$form_state) {
    //if an entity reference field value is set, then find & assign values to some other fields, based on that entity:
    $entity_id = $form_state['values']['field_id']['und'][0]['target_id'];
    if ($selected_entity = node_load($entity_id)) {
        $form['field_somefield1'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield1['und'][0]['value'];
        $form['field_somefield2'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield2['und'][0]['value'];
        $form['field_somefield3'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield3['und'][0]['value'];
    }

    $commands = array();
    $commands[] = ajax_command_replace("#edit-field-user-somefield1", render($form['field_user_somefield1']));
    $commands[] = ajax_command_replace("#edit-field-user-somefield2", render($form['field_user_somefield2']));
    $commands[] = ajax_command_replace("#edit-field-user-somefield3", render($form['field_user_somefield3']));
    return array('#type' => 'ajax', '#commands' => $commands);
}

```

So, whenever an AJAX call is made by the overridden field and I then submit the form, all the (previously hidden) fields are visible again and the required fields become required again.

Any ideas why this is happening?

# Answer
The AJAX callback shouldn't alter the form (that should be handled by the form constructor or a form alter). This tends to be a good thing, because it forces you to put all your form logic in form functions, and that means they can degrade gracefully if JS isn't available. When dealing with AJAX forms, the callback typically just decides what part of the form to return. Take a look at the example from the examples module:

```
/**
 * Basic AJAX callback example.
 *
 * Simple form whose ajax-enabled 'changethis' member causes a text change
 * in the description of the 'replace_textfield' member.
 *
 * See @link http://drupal.org/node/262422 Form API Tutorial @endlink
 */
function ajax_example_simplest($form, &$form_state) {
  $form = array();
  $form['changethis'] = array(
    '#title' => t("Choose something and explain why"),
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      // #ajax has two required keys: callback and wrapper.
      // 'callback' is a function that will be called when this element changes.
      'callback' => 'ajax_example_simplest_callback',
      // 'wrapper' is the HTML id of the page element that will be replaced.
      'wrapper' => 'replace_textfield_div',
      // There are also several optional keys - see ajax_example_autocheckboxes
      // below for details on 'method', 'effect' and 'speed' and
      // ajax_example_dependent_dropdown for 'event'.
    ),
  );

  // This entire form element will be replaced whenever 'changethis' is updated.
  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("Why"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '<div id="replace_textfield_div">',
    '#suffix' => '</div>',
  );

  // An AJAX request calls the form builder function for every change.
  // We can change how we build the form based on $form_state.
  if (!empty($form_state['values']['changethis'])) {
    $form['replace_textfield']['#description'] = t("Say why you chose '@value'", array('@value' => $form_state['values']['changethis']));
  }
  return $form;
}

/**
 * Callback for ajax_example_simplest.
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return array
 *   Renderable array (the textfield element)
 */
function ajax_example_simplest_callback($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['replace_textfield'];
}

```

Note how the dynamic change of the form happens in the form constructor while the callback is minimal.
> 0 votes

---
Tags: ajax, entities, users, forms
---


# Question
Title: How to copy address on node translate action
My website is an i18n web site. When it's time to manage content with a location field (address) I need to manually copy the address. Is there a way to make the location copy automatically on translated node?

Let's say I have node type Retail. This node type contains a Location (Field) provide with Location Module for Address purpose.

**Use case:**

User clicks on Add Retail (in French first). He filled the Location field like (Address, city province, country etc.). After that, the user clicks on save and then clicks on the Translate button. The user chooses to translate in English. The Address field that was previously entered in French is empty and the user needs to enter it again.

# Answer
> 0 votes
Instead of copying the content of the field you can try the Entity Translation module and only make some fields translatable. It will be much less messy than any kind of copying, where you'll end up with 2 or more copies of data that should actually just be one piece of data.

If you enable Entity Translation on your site you shouldn't enable Translation for this Address field, but you should enable it for other fields that you want to be translated.

> Allows (fieldable) entities to be translated into different languages, by introducing entity/field translation for the new translatable fields capability in Drupal 7. Maintained by the Drupal core i18n team.
>
> This project does not replace the Internationalization project, which focuses on enabling a full multilingual workflow for site admins/builders. Some features, e.g. content language negotiation or taxonomy translation, might overlap but most of them are unrelated.

I'm using this on a multilingual website. I don't want the product status field to be translatable:

But the body should be translatable:

---
Tags: i18n-l10n, location
---


title: How do I use the 'Filebrowser' module?

text:
# Question
Title: How do I use the 'Filebrowser' module?
I have installed/enabled the Filebrowser (v 7.24) module and set permissions...

It is said to provide ftp style file browsing capabilities, but I can't find any way of invoking it.

I am used to installing and getting modules working, and I have read the sparse documentation which refers to it as a node, but I can find no way to create a node or navigate to a page that is anything like the screenshot.

There are no new content types, nothing changed on creating new content, nothing new appears under any of the admin menus, appending filebrowser and variations to my site's URL does nothing.

How to open file browsing window?

# Answer
I could be going blind or it could have been a page refresh that was needed...

You create a new node and select "create a new directory listing"

Really straight-forward...
> 1 votes

---
Tags: 7
---


title: Menu Token - roles issue

text:
# Question
Title: Menu Token - roles issue
I am using Menu Token to create a link to a customized profile edit page that uses the url "user/%uid/edit". I've set the title of the link to "My Account" and although it works for my (admin) account, for the other roles the title is "Edit" instead (the default Drupal tab name for the /user menu item) and futhermore it does not appear to be the active trail. My thinking is that it's something to do with permissions since it works in one role but I can't seem to figure this out. Any help?

# Answer
I think I got the answer.. just check for the snapshot. It seems you were using the wrong value of token in menu path. Use `user/[user:uid]/edit` instead.
> 2 votes

# Answer
Encountered the same problem using `user/[current-user:uid]/edit` and switched to `[current-user:edit-url]` which worked for me. The link title is now displaying as entered for all roles, not just admin.
> 1 votes

---
Tags: routes, 7
---


# Question
Title: Rendering nodes of a same content type in different templates
My Client would like to have multiple templates for one content type. How to allow a user in Drupal to select a specific template when creating a node?

# Answer
> 2 votes
It seems you are looking for Template Picker module:

> Template picker gives content creators a list of templates to choose from as they create nodes.

---
Tags: theming
---


# Question
Title: How to deal with the "Payment failed at the payment server" error?
I'm trying to get my website integrated with SagePay. Everything works well untill the payment is made. Once a client makes payment he/she gets the following error message:

```
Notice: Undefined index: crypt in commerce_sagepay_form_redirect_form_validate() (line 55 of /sites/all/modules/commerce_sagepay/includes/commerce_sagepay_form.inc).

Payment failed at the payment server. Please review your information and try again.

```

And I get the following info in the logs:

```
Response could not be converted to tokens

```

Despite these errors the payment was taken, but the order remains in the shopping cart with the status Checkout: Review

I'm using Commerce SagePay 7.x-1.0 and the integration option is Form.

# Answer
> 1 votes
I had a similar problem with the token conversion, be sure you're using the -dev version (2014-May-23 or later) of Commerce Sagepay before trying anything else.

Note: probably related to: https://drupal.org/node/2115203

# Answer
> 0 votes
The error which you're having:

```
Payment failed at the payment server. Please review your information and try again.

```

indicates the problem with your SagePay Server Integration. The other Notice is not related to it.

The most common reasons that the Sagepay payment could fail at this point are:

* Network issues:

+ sagepay server can't contact your host from outside the network, so check your firewall,
    + your IP address is not on the white list in Sagepay panel, so try to add it then,

    ```
    Error Code: 4020 : Information received from an Invalid IP address

    ```
* You're posting the invalid form:

+ you're e-mail is in invalid format (this especially happens when synching the db with sanitization and the e-mail looks like: foo@localhost)

    ```
    Error Code: 3078 : The CustomerEMail format is invalid.

    ```
    + the amount is empty or zero (e.g. when using discount/coupons)

    ```
    Error Code: 4009 : The Amount including surcharge is outside the allowed range.

    ```

To check with what kind of issue you're dealing with, you can:

* In Drupal, check the Payment result message from SagePay by going to: Administration » Store » Shopping carts, and click on 'payment' for the Order which you're having problem with,
* In Sagepay, check the logs which should be available somewhere in MySagepay panel.
* Enable additional debugging by going to Administration » Store » Configuration » SagePay settings (e.g. Show Post (for debugging with SagePay)).

---
Tags: 7, commerce
---


# Question
Title: how to add a "add user" tab to admin/people
Currently on the user administration page admin/people there is a link below the tab row that lets admins add users (links to admin/people/create). Instead I would like to place that link in an additional tab next to the tabs "list" and "permissions". Has anybody experience in this? Or is there even a module for this?

I currently have difficulties finding anything because "add user tab" are quite generic search terms and there is a lot to find – but not meeting my problem.

*thank you!*

# Answer
I think what you're asking is the same as this. Apologies if not.

Here I've added a menu item that links out to another page. So you should be able to change the links to your needs. For this I created a module 'taskmenuextras'

```
    **
* Implementation of hook_menu_alter
*/
function taskmenuextras_menu_alter(&$items) {
    $items['user/%user/featuredjobs'] = array(
        'title' => t('Featured Jobs'),
        'page callback' => 'taskmenuextras_redirect_nodequeue',
        'access callback' => 'taskmenuextras_user_has_role',
        'access arguments' => array(1, array('admin')),
        'type' => MENU_LOCAL_TASK,
        'weight'  => 0,
        );

    return $items;
}

function taskmenuextras_redirect_nodequeue() {
  drupal_goto('admin/structure/nodequeue/featured_jobs/view/1');
}

function taskmenuextras_user_has_role($user, $roles = array()) {
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

```
> 0 votes

---
Tags: users
---


# Question
Title: What is wrong when Open atrium is installed with no colors and images?
I have successfully installed Open Atrium. Upon opening the site first time in the browser, i literally see no images, layouts of colors. Here is the screenshot:

I also have a series of warning messages being displayed as shown below:

Anyone has a clue, what's wrong really?

# Answer
> 2 votes
This is certainly a permissions issue on your temp and possibly also files directory. Go to `admin/config/media/file-system` and make sure that the directory set as your temporary directory exists, is writeable to the webserver, and is specified from your server's root directory. Also make sure `sites/default/files` and/or `sites/[yoursite]/files` (if using a multisite) exists and is writeable to the webserver.

---
Tags: media, distributions
---


title: Load .js only if block is loaded

text:
# Question
Title: Load .js only if block is loaded
Yes, something like that. If block and it's content are loaded in the page (so I guess detect by ID or something) it would load the .js, but if block is not loaded, it wouldn't load the .js.

I need this, because now each time when the block is not loaded, it still always loads the .js from theme in every page no matter what and that code interacts for some reason with other javascript elements like flexslider and it disables it for some reason and etc. Which is bad.

So it should load the .js only when the block is rendered/printed.

# Answer
Depends on what type of block your need the js for. If it's a custom block you created in a module, you can just tack drupal\_add\_js into the block definition function.

If your trying to add it to a block was created by someone else's module, or drupal created (IE, you didn't create it with a module), you could create a simple module that uses hook\_block\_view, which is fired whenever a block is loaded. You should be able to check from there if that is the block you want, then use drupal\_add\_js to load your js from that module.
> 2 votes

---
Tags: 7, theming, blocks, javascript
---


title: Drupal entity from different database

text:
# Question
Title: Drupal entity from different database
I have an existing database (which is not under my control) that i want to use as base database for my entity. However I'm stuck at getting the data from the database. There already exists a question about this problem. However that question is only about installing the module and that doesn't apply to loading an entity.

Hope I stated my problem clear enough.

# Answer
I think your talking about remote entity.

Remote Entity API provides a system for treating data from remote sites as local, Drupal entities. Remote data is stored locally in an entity base table, and can be periodically refreshed with data from the remote source.

Once a custom entity type is defined, entities can be manipulated just as normal Drupal entities: they can be loaded and saved to the local database, and have fields added to them. Remote Entity API provides ways to load an entity remotely, query the remote source for multiple entities, and save back to the remote source.

From the Remote Entity Documentation page:

> Creating a connection
>
> TODO.
>
> Creating a resource
>
> The Clients Resource for the remote entity type is composed of two parts, and as such can't be created in the UI:
>
> * hook\_entity\_info() defines the remote entity type. See remote\_entity\_hook\_entity\_info() for the additional keys that must/can be defined here.
> * The Clients resource itself must be defined with hook\_clients\_default\_resources():

```
/**
 * Implements hook_clients_default_resources().
 *
 * Define our remote entity resource.
 */
function example_clients_default_resources() {
  $items['my_entity_type'] = entity_import('clients_resource', '{
    "component" : "my_entity_type",
    "connection" : "my_connection_name",
    "name" : "my_entity_type",
    "label" : "My Entity Type",
    "type" : "remote_entity", // do not change @see function remote_entity_load_by_remote_id
    "configuration" : null,
    "rdf_mapping" : []
  }');
  return $items;
}

```
> 2 votes

---
Tags: entities, database
---


# Question
Title: "Add to cart" form with complicated attributes
I'm creating a Drupal Commerce based solution with 2 product types. One product has a constant price; it will be added to the cart, and that's all. The other product has many attributes (more complicated than color and size), and usually price depends from the selected attributes. Prices for various attributes are set by the administrator users. These prices are then multiplied by various other attributes, and added to the product price. For example:

* additional price = some attribute unit price * customer entered width
* complete product price = customer entered width * customer entered height * product default price + additional price

First attribute is width and height, which is entered from the customers before adding to the cart; the default value is 1x1.

More complicated attributes contain checkbox. If customers check it, the radio buttons becomes visible (first selected by default with no price; if customers select a different radio, they will enter a custom value). Another complicated attribute is price set individually for taxonomy term. I have colors, and for each color I can set the price for the current product. Thus I can't set price as a field of taxonomy term.

Now I'm trying to accomplish this with the Commerce Option and the Commerce Product Attributes modules.
Is there any simpler way to get the result?

The biggest problem is that the Drupal Commerce module adds to cart products with different attributes as a single product. So administrator Commerce/Order, or even customers viewing the cart don't really know what was added to cart.
Is there any simple way to distinguish the same product (ID) but with different attributes?

# Answer
> 1 votes
> The biggest problem is that the Drupal Commerce module adds to cart products with different attributes as a single product.

Have you tried *unchecking* the option to: "Attempt to combine like products on the same line item in the cart."

It's on the "Add to cart" product reference field formatter settings on the product display content type

e.g: admin/structure/types/manage/product-display/display

# Answer
> 0 votes
Drupal Commerce is built on Views, so if you want your attributes to show up in any list (like the shopping cart, checkout page, or admin views) you can simply add the appropriate fields using Views.

I highly recommend two approaches:

1) Commerce Bulk Operations: https://vimeo.com/34385004 -- you can select multiple attributes and it will create all of the product with each of those variations.

and/or

2) Drupal Commerce Inline Entity: https://vimeo.com/40933753 -- once your products are created, you can edit them like a single product with the variations inline with the display node form.

# Answer
> 0 votes
I' m sure you achieved your project now, but this could be useful to anybody : you were definitively looking for **Commerce Customizable Products**.

> Commerce Customizable Products allows you to sell customizable products that require customer input when added to the cart. Use cases for this functionality include:
>
> * Business cards that require contact information and a logo upload.
> * Event registrations that require attendee information.
> * Donations : allow the customer to specify a donation amount.
>
> (...) It gives you the ability to define new line item types on the fly at Administration \> Store \> Configuration \> Line item types.

1. Install the module, then set up a new *product line item type* to begin adding fields to it, i.e your fields customer height/width
2. Configure a *product display node type* to use the custom *product line item type*, through the Add to Cart form display formatter of your node type's Product reference field.
3. Using **Pricing Rules**, do the magic to calculate each custom product price
4. You could even ask these detailed information a step further, in the shopping cart instead of add to cart form, with Commerce Line Item Cart Form

---
Tags: 7, commerce
---


# Question
Title: UPDATE database field with value from other table
I'm basically trying to build a query which looks something like:

```
UPDATE table_a, table_b
SET table_a.value = table_b.value
WHERE table_a.id = table_b.id;

```

It seems that a query like this is functionally equivalent:

```
UPDATE table_a
INNER JOIN table_b
  ON table_a.id = table_b.id
SET table_a.value = table_b.value;

```

The thing is that I can't figure out how the UpdateQuery allows me to attach a second table like that. I tried just adding a `->join('table_b')` to my update query object, but I'm told that method is undefined. Argh.

I've ended up cheating by using `db_query()`, though I'm still curions to know if there's a way to do this properly using the API.

# Answer
> 0 votes
Given the specific nature of your SQL statement, it would appear db\_query() is the way to go. Just be sure to do it as an update hook in your .install (so you can drush updb) to implement smoothly.

---
Tags: 7, database
---


# Question
Title: Doctrine annotations for custom field formatters in Drupal 8
I am trying to port my Drupal 7 module, Views Hybrid, to Drupal 8. It provides a custom field formatter. In order to provide the field formatter, I am using the Doctrine annotation roughly following this tutorial provided by realize.be. However, I am getting PHP exceptions:

`Uncaught PHP Exception Doctrine\Common\Annotations\AnnotationException:
"[Syntax Error] Expected PlainValue, got '>'
at position 168 in class
Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter."
at ~/core/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php line 41`

If I remove the double quotes from the keys inside the `settings` array then I get a different error:

`Uncaught PHP Exception Doctrine\Common\Annotations\AnnotationException:
"[Semantical Error] Couldn't find constant items_count, class Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter."
at ~/core/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php line 52`

```
/**
 * Plugin implementation of the 'views_hybrid' formatter.
 *
 * @FieldFormatter(
 *   id = "views_hybrid",
 *   label = @Translation("Views hybrid"),
 *   field_types = {"entity_reference"},
 *   settings = {
 *      "items_count" => "5",
 *      "view" => "frontpage",
 *      "display" => "linked_title_only",
 *      "classes" => {},
 *      "view_mode" => "teaser",
 *      "arguments" => "",
 *   },
 * )
 */

```

I am not clear about the syntax that Doctrine expects for these nested arrays, or even on whether Drupal 8 expects the settings array to be included in the Doctrine annotations block when declaring a new field formatter, and my usually debugging techniques aren't very useful for debugging annotations since they're not exactly code. What is the expected syntax and content of a Doctrine annotation for defining a field formatter in Drupal 8?

# Answer
I confused PHP array syntax for annotation syntax. Those `=>` should be `=` and the trailing commas need to be removed from lines that are the last in their set. So it should be:

```
    /**
     * Plugin implementation of the 'views_hybrid' formatter.
     *
     * @FieldFormatter(
     *   id = "views_hybrid",
     *   label = @Translation("Views hybrid"),
     *   field_types = {"entity_reference"},
     *   settings = {
     *      "items_count" = "5",
     *      "view" = "frontpage",
     *      "display" = "linked_title_only",
     *      "classes" = {},
     *      "view_mode" = "teaser",
     *      "arguments" = ""
     *   }
     * )
     */

```
> 3 votes

---
Tags: 8, entities
---


# Question
Title: send REQUEST_URI with header location redirect via settings.php
I'm in predicament where I must use settings.php to do what I'd normally just do via mod\_rewrite... the site is being hosted on Pantheon and I am referring to this article: http://helpdesk.getpantheon.com/customer/portal/articles/368354

I need to send the original requested path for reference. Trying to pass a the SERVER\_URI as a parameter via header location in setting.php gets me an infinite loop.

My code:

```
if (preg_match('/article\/[0-9]?[0-9]\/[0-9]?[0-9]\/[aA-zZ].+/', $_SERVER['REQUEST_URI'])) {
    header('HTTP/1.0 301 Moved Permanently');

    header("Location: http://answers3x-ec-core-community.gotpantheon.com/catchall/?dest=" . urlencode($_SERVER["REQUEST_URI"]));  exit;
}

```

Anybody have any suggestions as to how I might accomplish passing the $\_SERVER\["REQUEST\_URI"\] via header location from settings.php without an infinite loop?

# Answer
> 0 votes
In the end what really I needed to accomplish was a way to grep for a contained (not beginning) directory name in the path that wouldn't bomb into an infinite loop continually calling settings.php. What worked for me was to negate the regex like so:

```
if(preg_match('/^((?!catchall).)*$/', $_SERVER['REQUEST_URI'])) {

```

since 'catchall' is the directory I am redirecting to including the old path as a parameter, it allows for the redirect to get to this page (and custom module to handle it) without an infinite loop. I basically surrounded the above check first around all preg\_match checks for the particular patterns I needed to find.

# Answer
> 3 votes
While it's technically possible to use Drupal contrib to perform the redirect, it's faster and more efficient to redirect without having to fully bootstrap your web application.

For web only actions, like redirects, check for the existence of `$_SERVER['PANTHEON_ENVIRONMENT']` \- if it exists, it will contain a string with the current environment (`dev`, `test` or `live`).

To perform redirection for the pattern you've supplied, make sure to only match for it *at the beginning of the URI* in order to avoid an infinite loop problem:

```
// Pantheon - web only.
if (isset($_SERVER['PANTHEON_ENVIRONMENT'])) {
    // Check if you only want redirection from the live web environment.
    if ($_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
        if (preg_match('/^\/article\/[0-9]?[0-9]\/[0-9]?[0-9]\/[aA-zZ].+/', $_SERVER['REQUEST_URI'])) {
            header('HTTP/1.0 301 Moved Permanently');
            header('Location: http://answers3x-ec-core-community.gotpantheon.com/catchall/?dest=' . $_SERVER["REQUEST_URI"]);
            exit();
        }
    }
}

```

Sources:

Configuring settings.php

PHP preg\_match() Examples

preg\_match

---
Tags: redirection, configuration
---


# Question
Title: Is it possible to disable the Node module?
Is it possible to disable the Node module in Drupal 7?

As I understand from the interface, it is not possible. Why is the Node module is so important? What if I'm going to use only custom entities?

# Answer
In Drupal 7 the answer is no, it's a piece of functionality built into the system more than required by anything else. I've heard rumors long ago maybe in Drupal 8 it would not need to be enabled by default -- but I'm not sure of that status now.

It's needed for example because it provides paths to content on the site at `node/NID` by *non-developers* -- yes `Entities` can do that. Drupal caters to a wide range of audiences, not just those that understand what a `Node` is and what an `Entity` is. In Drupal 8 there may be an install profile which is super minimal to even not include any content types, I'm not sure what happened regarding that ... ah in Drupal 8 they still require the `Node` module in the `Minimal` profile installer: https://github.com/drupal/drupal/blob/8.0.x/core/profiles/minimal/minimal.info.yml

If you want to use entities then use a module like Rabbit Hole to hide any node content and do not use default nodes at all.
> 0 votes

---
Tags: 7
---


# Question
Title: How can I retrieve the profile2 fields selected in a custom module?
I am totally new to entities in Drupal. I have used the Profile2 module to add a few profile types. This is displayed in the add/user screen as Customer.

After adding the profile type I manage the fields and add a new entry called `cust` with a `field_id` of `field_cid`. This is setup as a list(text) and checkbox widget.

When I edit a user I have a checkbox list for Customer that can be selected by each user. I have a custom module that I am trying to read the selected value by `$user->uid` from the profile2 field.

The idea is to retrieve the selected item in my module and format the return values to the user from a custom DB table. Here is what I have tried and got results but cannot get all the values.

In my module using:

```
$profile = profile2_load_by_user($user->uid);$list = field_view_field('profile2', $profile['customer'], 'field_cid');print_r($list)

```

I get this result:

```
Array ( [#theme] => field [#weight] => 0 [#title] => cust [#access] => 1 [#label_display] => above [#view_mode] => _custom_display [#language] => und [#field_name] => field_cid [#field_type] => list_text [#field_translatable] => 0 [#entity_type] => profile2 [#bundle] => customer [#object] => Profile Object ( [pid] => 9 [type] => customer [label] => Customer [uid] => 1 [created] => 1409542969 [changed] => 1409545821 [entityType:protected] => profile2 [entityInfo:protected] => Array ( [label] => Profile [plural label] => Profiles [description] => Profile2 user profiles. [entity class] => Profile [controller class] => EntityAPIController [base table] => profile [fieldable] => 1 [view modes] => Array ( [account] => Array ( [label] => User account [custom settings] => ) ) [entity keys] => Array ( [id] => pid [bundle] => type [label] => label [revision] => ) [bundles] => Array ( [customer] => Array ( [label] => Customer [admin] => Array ( [path] => admin/structure/profiles/manage/%profile2_type [real path] => admin/structure/profiles/manage/customer [bundle argument] => 4 [access arguments] => Array ( [0] => administer profiles ) ) [rdf_mapping] => Array ( ) ) ) [bundle keys] => Array ( [bundle] => type ) [label callback] => entity_class_label [uri callback] => entity_class_uri [access callback] => profile2_access [module] => profile2 [metadata controller class] => Profile2MetadataController [static cache] => 1 [field cache] => 1 [load hook] => profile2_load [translation] => Array ( ) [schema_fields_sql] => Array ( [base table] => Array ( [0] => pid [1] => type [2] => uid [3] => label [4] => created [5] => changed ) ) [configuration] => ) [idKey:protected] => pid [nameKey:protected] => pid [statusKey:protected] => status [defaultLabel:protected] => [field_cid] => Array ( [und] => Array ( [0] => Array ( [value] => 1 ) [1] => Array ( [value] => 2 ) ) ) [field_test] => Array ( [und] => Array ( [0] => Array ( [value] => 3 ) ) ) [rdf_mapping] => Array ( ) ) [#items] => Array ( [0] => Array ( [value] => 1 ) [1] => Array ( [value] => 2 ) ) [#formatter] => list_default [0] => Array ( [#markup] => Disney ) [1] => Array ( [#markup] => Burger King ) )

```

I want the name in the last line `[#markup]` only returned to my function. In the above output the returned values should be *Disney* and *Burger King*.

How can I retrieve these values only?

# Answer
Finally this is giving me the results I am after:

```
$profile = profile2_load_by_user($user->uid);
$customer = field_get_items('profile2', $profile['customer'], 'field_cid');
$key = array();
foreach($customer as $item=>$value){
  $output = field_view_value('profile2', $profile['customer'], 'field_cid', $customer[$item]);
  $key[] = strip_tags(render($output));
}
foreach($key as $word) {
  echo $word . "</br>";
}

```
> 0 votes

---
Tags: 7, entities, database
---


# Question
Title: How to add twitter tracking code to a Drupal site?
Twitter now creates code to track visits to your site from twitter. https://support.twitter.com/articles/20170807-conversion-tracking-for-websites#

Where would be the best place to put this code, into a template? is there a module for this like there is for google analytics?

# Answer
> 3 votes
The proper way is to use `hook_page_alter()` in your template.php or a custom module. But there's also a module out there to accomplish this task:

Take a look at the module Tracking Code. It allows you to inject arbitrary code inside `<HEAD>`, after `<BODY>` or before `</BODY>`.

---
Tags: 7
---


# Question
Title: Custom field widget: hook_field_is_empty()
I'm creating a custom module that has implemented these hooks:

```
<?php
/**
 * Implements hook_field_widget_info().
 */
function MYMODULE_field_hook_info() {
  return array(
    'CUSTOM_field' => array(
      'label' => t('Custom Text Area'),
      'field_types' => array('text_long'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch($instance['widget']['type']) {
    case 'CUSTOM_field':
      $element['MYFIELD_field'] = array(
        '#type' => 'textarea',
        '#attributes' => array('id' => 'MYFIELD', 'rows' => '5', 'cols' => '3'),
        '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
      );
      break;
  }
  return array('value' => $element);
}

```

All it is supposed to do is provide a custom widget to the Long Text field type that enables some custom functionality. My custom widget appears in manage fields and I can enable it and use it on a node edit form. However, when I save the node with text in the field, nothing saves to the database the data saves to the database, but doesn't display in the field when the node is edited again.

After some searching, I found some posts that said hook\_field\_is\_empty() is mandatory and is a common problem for values not saving. I attempted to implement the hook exactly as the API said:

```
<?php
/**
 * Implements hook_field_is_empty().
 */
function MYMODULE_field_is_empty($item, $field) {
  if (empty($item['value']) && (string) $item['value'] !== '0') {
    return TRUE;
  }
  return FALSE;
}

```

This immediately started throwing an error in Drupal:

> Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain() (line 1573 of /includes/bootstrap.inc).

So I looked around some more on here and Google and changed the hook based on this answer:

```
<?php
/**
 * Implements hook_field_is_empty().
 */
function MYMODULE_field_is_empty($item, $field) {
  if ($field['type'] == 'text_long') {
    if (empty($item[$field['type']]['CUSTOM_field'])) {
      return TRUE;
    }
  }
  return FALSE;
}

```

This returns the same error and it also doesn't save the value of the field into the database display the field data from the database. Do I have to create a custom field with a MYMODULE.install and the appropriate hooks, or can I just use an existing field type like I'm doing. Why is the data not saving to pulling from the database?

# Answer
> 0 votes
Turns out it wasn't working because I have WYSIWYG enabled. Apparently this means my values for textareas get passed as value/type arrays instead of strings. Changing default\_value accordingly works:

```
'#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',

```

This change solved my problems. I also removed the hook\_field\_is\_empty() and haven't noticed any problems using the widget. Perhaps it's only mandatory for custom field types.

# Answer
> 0 votes
I think you want to change your default values to `variable_get('yourmodule_variable')` so that it displays the value that was saved previously.

---
Tags: entities
---


# Question
Title: What's the best practice way to test block Views with SImpleTest?
I've created a block view, which I've positioned on the page using the admin UI. I've exported my view using Features and fe\_block for its block.

I'd like to write a SimpleTest to verify that content from the view is displaying on the front page.

I've written a test that creates some nodes (of the type being displayed by the view), then does a drupalGet('/') and some assertText() statements to verify the content is displayed.

However, these are currently failing. When I view the HTML of the frontpage as seen by SimpleTest, the view isn't there.

Have I missed something? Is there a better way to be testing this?

# Answer
The simpletest code needs to place the block into a region. Then, you should see the content after doing the drupalGet('/').
> 0 votes

---
Tags: views, features, testing
---


title: How to replace classnames in sub theme

text:
# Question
Title: How to replace classnames in sub theme
How to replace two classnames by writing a function in template.php

The two classnames given are:

```
comment-add

```

and

```
comment-comments

```

# Answer
> 0 votes
Generally this is a matter of figuring out which preprocess function or functions are setting those classes and then implementing those preprocess functions within your own theme and modifying the $variables\['classes\_array'\] variable to meet your needs.

Without knowing what theme you're using as a base theme I can't say for sure how this is being done. But using the following steps you should be able to figure it out.

1. Figure out which template file (\*.tpl.php) file contains the markup where the classes are being printed out, and note the name of this file. Example, 'comment-wrapper.tpl.php'.
2. Working backwards up the chain you should be able to find the preprocess function that's setting these classes.

* YOURTHEME\_comment\_wrapper\_preprocess()
    * BASETHEME\_comment\_wrapper\_preprocess()
    * template\_comment\_wrapper\_preprocess()

This will at least confirm that you're on the right track, and allow you to see in what context those classes are set and what other classes may be set.

1. Implement HOOK\_comment\_wrapper\_preprocess() in your own theme. (Comment wrapper being the example here, you'll need to know the appropriate template file that's being used to know which preprocess function to implement.)
2. Modify the $variables array inside your template file to change the classes.

Here's some additional information about preprocess functions: https://www.drupal.org/node/223430

---
Tags: theming
---


# Question
Title: Where can I find the upcoming DrupalCamps and DrupalCon?
Where can I find the upcoming DrupalCamps and DrupalCon ? I'm not aware of any website that contain information about upcoming DrupalCamps and DrupalCon other than social media. I think will be nice if I can have a page where I can see upcoming DrupalCamps and DrupalCon.

# Answer
> 3 votes
I have always enjoyed http://www.drupical.com/ It takes a direct feed from http://groups.drupal.org/events

# Answer
> 1 votes
The community pages of drupal.org are probably a good starting point. From there you can find entry points groups and events where local meetups, user group meetings, drupalcons etc. are announced and discussed. (You can even filter the event list by event type!)

# Answer
> 1 votes
There is one page in drupal.org and they display the Upcoming DrupalCons and the past events with their official sites

Drupalcon association page

Past DrupalCon

About drupal camps the domains drupalcamp.org and drupalcamp.com were donated by Noel Hidalgo to the Drupal Association.

Archive of past drupalcamps

# Answer
> 0 votes
I was looking something like this page where it have all drupal camps and conference http://buildamodule.com/drupal-camps-calendar

---
Tags: community-official-site
---


# Question
Title: How To Assign Breadcrumb To Commerce Kickstart Omega Collection Or Category?
How does one assign 'Collection' or other Taxonomy vocabularies to the Crumbs that Kickstart Omega uses. They give examples for Content Types but not for taxonomies.

So any pages based on taxonomies just show 'Home' as the breadcrumb.

I've looked in admin/structure/crumbs and the text pane seems to be correct for some tests I ran with the Debug tab. (ie. the item appears to be in the key menu.link\_title.menu-specialties) but I don't know what to -do- with that information.

Maybe there is a -straightforward- tutorial on how to configure this text file?

Below is a screen cap of the crumbs screen I'm seeing.

# Answer
> 0 votes
Version:
First, i usually work with the latest Crumbs version from the 7.x-2.x branch.
If you have problems with the latest version, you should report them in the issue queue. But then you can downgrade either to 7.x-2.0-beta13 or to the 7.x-1.x branch.
Upgrade and downgrade should work fine (I think), but you should clear the caches if you do. Also I don't guarantee if your Crumbs settings are all kept or some of them are lost. Let me know in the comments :)
(Probably this paragraph will soon be obsolete)

Entity parent settings:
I don't remember how much of that is in the 7.x-1.x branch. But in the recent versions, you go to `admin/structure/crumbs/entity-parent/taxonomy-term` and configure the parent path. That's it.

Plugin weights:
The plugin will be available as `crumbs.entityParent.taxonomy_term.categories` on the weights configuration form. But probably you don't need to do anything there, the plugin will already be enabled through the general wildcard "\*".

---
Tags: commerce, theming, breadcrumbs
---


# Question
Title: Site performance , cache not working properly
I am using the Performance Logging Module. Above screenshot, one strange thing I noticed that Insert Cache\_bootstrap on every page. When you go to any page (both admin theme and frontend theme) Insert cache and then delete cache is running. It means that cache is set and destroyed in each page and actually no cache is occurring. How can I further elaborate it? To diagnose that issue because currently I am working on performance of the site.

I am also using New Relic for performance check. It also shows that database load is high.

**and my.cnf information.**

# Answer
> 8 votes
Slide #85 from my performance presentation talks about max packet size in MySQL, you need to increase that value; `SET GLOBAL max_allowed_packet=33554432;` or change it inside of the configuration file https://dev.mysql.com/doc/refman/5.7/en/packet-too-large.html

# Answer
> 3 votes
Max allowed packet size could be one reason this is happening, but I can see multiple reason why it is probably something else in this case.

1. You don't just have cache writes, you also have explicit cache deletions. A failed cache write would just result in repeating cache writes and then cache misses, but not deletions.
2. This is the cache\_bootstrap table. There are some caches that can get big but they're usually not from that bin.

The most common reason for this pattern are variable\_set() calls that happen on every page. Have a look at the where those cache deletions are coming from, either with xhprof, with xdebug and setting a breakpoint or by adding a debug\_print\_backtrace(DEBUG\_BACKTRACE\_NO\_ARGS). I'm pretty sure that you will see a variable\_set() call there.

The problem is that there is a single global cache for variables. Every cache write results in a cache delete and the next request will read out the whole `{variables}` table and write it back into the cache.

Many developers aren't aware of that and are doing things like "ensuring values" by calling variable\_set() directly in a .module file or another place that is executed on every request.

# Answer
> 3 votes
It is just a hypothesis but if your bootstrap cache rebuilds on every page load it may happen that some of your modules missing in modules folder but still present in system table. On each page load drupal tries to find it and rebuild bootstrap\_cache.

Try the Bootstrap optimizer module, it will help to find such records and delete them.

---
Tags: caching, database, performance, bootstrapping
---


# Question
Title: How to set different default images in an image field per domain?
I'm working on a set of similar websites (promoting products of different regions) separated by Domain Access module. I'd like to set different default image in an image field in each site. Is it possible?

# Answer
Point the image to a .php file instead of a .jpg file, and then write a script to

1. Find the domain name (https://stackoverflow.com/a/17201254/836995)
2. Output the appropriate image (https://stackoverflow.com/a/1353867/836995)

Something like this should work (untested):

```
<?php

$img_file = NULL;

switch ($_SERVER['SERVER_NAME']) {
  case "www.a.com":
    $img_file = "filename_a.jpg";
    break;
  case "www.b.com":
    $img_file = "filename_b.jpg";
    break;
  default:
    break;
}

if (!empty($img_file)) {
  header("Content-type: image/jpeg");
  readfile($img_file);
}

```

This is a bare minimum script. A more elaborate version here: https://stackoverflow.com/a/9453207/836995 (although you don't need the `.htaccess` part to do this for only one image).
> 0 votes

---
Tags: 7, entities, media, domain-access
---


title: Ajax field default value on edit form

text:
# Question
Title: Ajax field default value on edit form
I want ajax dependent fields in one of my node's form so I am altering the form.

here is the code

```
    function mymodule_form_alter(&$form, &$form_state, $form_id) {
      $selected_first = isset($form_state['values']['field_first'][LANGUAGE_NONE][0]['nid']) ? $form_state['values']['field_first'][LANGUAGE_NONE][0]['nid']: '0';
    $form['field_first'][LANGUAGE_NONE]['#ajax'] = array(
      'callback' => '_first_callback',
      'wrapper' => 'second-field-wrapper',
    );
    $form['field_first'][LANGUAGE_NONE]['#default_value'] = $selected_first;

    $form['field_second'][LANGUAGE_NONE]['#prefix'] = '<div id="second-field-wrapper">';
    $form['field_second'][LANGUAGE_NONE]['#suffix'] = '</div>';
    $form['field_second'][LANGUAGE_NONE]['#options'] = _get_second_options($selected_first);
}
/**
 *
*/
function _first_callback($form, $form_state) {
  return $form['field_second'];
}
/**
 * Ajax callback for second field
 */
function _get_second_options($occ_id) {
  //array which contains some int values
  return $second_options;
}

```

Some more information: `field_first` is select list of type node reference and `field_second` is checkboxes.

> **Issue**: This works fine while creating the node. But when I edit the same node, the second field doesn't show and also values selected for this field while creating the node are also not checked by default.

# Answer
You can try to use this module https://www.drupal.org/project/dfv
> 1 votes

---
Tags: forms, ajax, nodes
---


# Question
Title: Change the Mandatory field based on selection in webform
I have Webform with a radio button type field named as "preferred contact method", for selecting email or phone.

When user select the email I want to set the email field as mandatory or if user select the phone I want to set phone field as mandatory.

How to handle this in Webform Drupal 7.

# Answer
> 1 votes
That is an interesting thing to have, but i don't think Webform support such a functionality. However they are some other way to achieve the same result.

Using Webform Conditional module. you can have two sets of hidden questions, and only one set of question could be visible base on user selected choice.

If user click on phone the first set of question will be display to user where the phone is a mandatory and email optional.

If user click on email the second set of question will be display to user where you can have email as mandatory and phone as optional.

You can ready more about alternative ways here .

# Answer
> 0 votes
You can add '#states' for the field in hook\_form\_alter() . Check this question How to make a form required with states?

---
Tags: 7, webforms
---


title: drupal_add_js and url encoding

text:
# Question
Title: drupal_add_js and url encoding
In my module, I add javascript with a url parameter:

```
drupal_add_js(libraries_get_path('mylibrary') . '/MyLibrary.js?config=MY_CONFIG_PARAM');

```

When I view the HTML page source, the line loading the script looks like this:

```
<script src="http://example.com/sites/all/libraries/mylibrary/MyLibrary.js%3Fconfig%3DMY_CONFIG_PARAM&nbbffw"></script>

```

The '?' and '=' are encoded. Trying to load this script results in an error, because browser can't find it (but if I manually decode it in the browser bar, it's found).

How to add javascript with a parameter, so that it won't get encoded?

# Answer
Try this code

```
drupal_add_js(
  url(
    libraries_get_path('mylibrary') . '/MyLibrary.js',
    array(
      'query' => array(
        'config' => MY_CONFIG_PARAM
      )
    )
  )
);

```
> 2 votes

---
Tags: 7
---


# Question
Title: How can I modify the values in variable table using phpmyadmin?
I modify the site name in variable table using phpmyadmin as below.

`s:21:"example@example.com";` to `s:21:"example@example.info";`

But then when I run cron I get the follwoing message.

> Warning: Cannot modify header information - headers already sent by (output started at /public\_html/includes/bootstrap.inc:566) in /public\_html/includes/bootstrap.inc on line 739

This is just a examle, but if I change something in variable table using phpmyadmin I always get the same error.

When I modify variable table do I need to modify also other tables at the same time ?

# Answer
As stated in comments serialized string variable lenght must match the integer prefixed, eg

```
s:20:"example@example.info";

```

drush vset is alot better for this kind of adjustements.

That beeing said, for users with drush 4.5 where modifying more complex variables is not available (use variable-set with arrays and objects. Accept JSON via STDIN like cache-set), direct access to database can be handy way to tweak the system. Remember to clear caches after.
> 2 votes

---
Tags: 6, configuration
---


# Question
Title: How can I pass an array of variables from php to javascript?
I use this but cannot find solution.

```
drupal_add_js(
  array('YOURMODULE' => array(
    'testvar' => $testvar
  )),
  array('type' => 'setting')
);

```

# Answer
> 0 votes
Check the object **Drupal.settings** using Firebug.

Or insert the code into your a js file.

```
Drupal.behaviors.YOURMODULE = function (context) {
  alert(Drupal.settings.YOUMODULE.testvar);
}

```

---
Tags: javascript
---


# Question
Title: Ajax callback change "checked" radio button
I have a radio button group like this:

```
$options = array('2' => t('Active (2)'), '1' => t('Upcoming (1)'), '0' => t('Finished (0)'));
$form['active'] = array(
'#type' => 'radios',
'#title' => t('Update state:'),
'#default_value' => $default_entry->active,
'#options' => $options,
);

```

which works fine. However, based on a drop-down list of entries, it calls an ajax function which should update the selection:

```
foreach (array('name', 'test') as $item) {
$form[$item]['#value'] = $entry->$item;
}
foreach (array('active') as $item) {
???
}

```

Now, the "name" and "test" work as expected as they are text fields.... but the active radio button stays the same as it was (i.e. based on the '#default\_value').

I have tried

```
$form[$item]['#value'] = $entry->$item;
$form[$item]['#default_value'] = $entry->$item;

```

but neither change which radio button is selected. Is there something I'm missing based on updating the "checked" attribute for that radio group?

Any help and/or points in the right direction much appreciated.

# Answer
You would need to show more code (the form definition), I would recommend you to try:

`unset($form['input'][$item]);`

Right prior to calling:

`$form[$item]['#default_value'] = $entry->$item;`

Relative links: https://www.drupal.org/node/1082818#comment-5335080
> 1 votes

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


# Question
Title: What Causes DatabaseTransactionOutOfOrderException and how do I fix this?
I am working on plugin to Drupal Commerce, and I started getting this error:

```
DatabaseTransactionOutOfOrderException: in DatabaseConnection->rollback() (line 1058 of /Library/WebServer/Documents/includes/database/database.inc).

```

Can anyone shed some light on what this error means? If I install a fresh drupal and reinstall my plugin, is that likely to clear things up?

Any advice?

Thanks!

# Answer
The DatabaseTransactionOutOfOrderException exception is part of the rollback() method (DatabaseConnection class) and it is thrown when a rollback() resulted in other active transactions being rolled-back instead of rollback to correct earlier savepoint.

You may debug it checking the backtrace when this exception is thrown.

In example defining the following hook:

```
/**
 * Implements hook_watchdog().
 */
function foo_watchdog($log_entry) {
  if ($log_entry['type'] == 'php' && $log_entry['severity'] <= WATCHDOG_WARNING) {
    // Old school
    // var_dump(debug_backtrace()); // Optionally add: exit();

    // Devel: Log the backtrace into temporary file: drupal_debug.txt
    // Locate via: $ drush eval "echo file_directory_temp() . '/drupal_debug.txt'"
    function_exists('dd') && dd(debug_backtrace());
  }
}

```

Don't forget to install Devel module (for `dd`) and clear the cache before testing it.

Then try to reproduce the problem and then check your /tmp/drupal\_debug.txt debug file which should contain something like (section \_drupal\_exception\_handler):

```
[function] => _drupal_exception_handler
[args] => Array
    (
        [0] => DatabaseTransactionOutOfOrderException Object
            (
                [file:protected] => /var/www/includes/database/database.inc
                [line:protected] => 1071
                [trace:Exception:private] => Array
                    (
                        [0] => Array
                            (
                                [file] => /var/www/includes/database/database.inc
                                [line] => 1933
                                [function] => rollback
                                [class] => DatabaseConnection
                            )
                        [1] => Array
                            (
                                [file] => /var/www/sites/all/modules/contrib/commerce/modules/order/includes/commerce_order.controller.inc
                                [line] => 123
                                [function] => rollback
                                [class] => DatabaseTransaction
                            )
                        [2] => Array
                            (
                                [file] => /var/www/sites/all/modules/contrib/commerce/modules/order/commerce_order.module
                                [line] => 734
                                [function] => save
                                [class] => CommerceOrderEntityController
                                [type] => ->

```

So based on the above example, you know that something goes wrong in commerce\_order.module on line 734 during CommerceOrderEntity save.

If it's still not clear, other suggestion is to enable MySQL query logging and check the suspicious queries which are sent.
> 3 votes

---
Tags: commerce
---


title: Post or upload file to specific user

text:
# Question
Title: Post or upload file to specific user
I am new to Drupal, I wonder how can I post file(s) that should be viewable to specific user? for example upload a pdf invoice to a specified user? Thank you!

# Answer
> 1 votes
If you want to send private message with file, use Privatemsg module. It used to have issues with attachment privacy, but it is Closed (fixed) - should work for you.

# Answer
> 1 votes
Normally permissions are configured per role, but, if you don't mind some PHP, you can extend the field permissions with `hook_field_access`

One suggestion would be to add the file field to the user entity itself at admin \> config \> account settings \> manage fields (e.g field\_pdf\_invoice)

Then, you can attach the file to the user.

After that, something like

```
/**
 * Implements hook_field_access
 */
function MODULE_field_access($op, $field, $entity_type, $entity, $account){
  // Check view access to invoice field
  if ($field['field_name'] == 'field_pdf_invoice' && $op == 'view') {
    // Allow access if current user is viewing own account field
    if($entity_type == 'user' && $account->uid == $entity->uid){
      return TRUE;
    }elseif(user_access('administer users'){
      // Allow access to admins
      return TRUE;
    }
    // Default deny view.
    return FALSE;
  }
}

```

# Answer
> -1 votes
**Step 1: Install following modules and enable it.**

Entity reference

Chaos tool suite (ctools)

Entity API

Views

**Step 2 : Create Content Type:**

Here you can add extra field One for upload file and another for select user who can acess this file(Which is generated from user list of our site using entity reference module).

Please see:

Edit Field select user: If you want to allow file to many users then choose Number of values : Unlimited (its give option to checkbox) If you want to allow file to acess only one user then choose Number of values : 1.

**Step 3: Now Add content.**

**Step 4 : Create view.**

**Step 5 : User can only see files which is accessible/permission**

---
Tags: files
---


# Question
Title: How to display a view without using a page template - drupal 7
So on a drupal site I am working on the client has a page where they have a view without a page template applied to it, and now the client wants to change the url of that page. As soon as I change the url of the view it applies the page template to the view. Obviously this was hard-coded in by url by the person who originally built the site, however, I have no idea how they did it. So i'm hoping someone on here has had a similar experience or knows how to make a view without a page template being applied to it.

# Answer
> 1 votes
You can create a block view and display it anywhere in the code.

If your text format allow you to use PHP code you can insert a views anywhere in your website by adding something like this.

```
  <?php
    $block1 = "Name_Of_The_View";
    print views_embed_view($block1);
  ?>

```

And this will print a view inside of a node without using a page template. The beauty about this is that you can add HTML around this without using the block module.

For more information I will recommend you to read this documentation page Placing the contents of a block in any location

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


title: How To Remove Content Types?

text:
# Question
Title: How To Remove Content Types?
I installed a custom module that created few content type that I'm no longer need it. I disable and uninstall that module but I still have the content type. And it bother me every time I see it. So I try to delete it however, I cant because for some reason doesnt have the delete button. So now I have 5 content type that I don't need. Can anyone have a solution on how to remove these content types ?

In this picture you will see that doesnt allow me to delete the content type.

# Answer
> 1 votes
If nothing else helps, delete them in the database directly (its probably advisable to make a backup):

```
DELETE FROM `your_database`.`node_type` WHERE `node_type`.`type` = \'blog_post\'"

```

---
Tags: nodes
---


# Question
Title: Uploading via default image on Articles not working
I am trying to upload images on the default Article node type on D7.

The upload works and the image is confirmed via Linux on the file system.

However, the icon of the uploaded image is a broken link image and the same when viewing the page.

I get the following error message:

```
Forbidden

You don't have permission to access /RT/sites/default/files/field/image/prayer.jpg on this server.

```

Please help.

**UPDATE:**

I have been looking into permissions as a solution but with no luck. I went as far as assigning 777 permissions to the files folder and all it's sub-folders and even the target image.

Strangely, I tried uploading an image to an article node on a different website running on the same server which worked. I installed a fresh website and tried it there and that also worked.

Basically, it seems one website among three all on the same server is not responding correctly when I attempt to upload images.

# Answer
This is a permissions issue. You need to chmod the directory tree.

Edit: A tutorial on setting directory permissions can be found on drupal.org at Securing file permissions and ownership.
> 1 votes

# Answer
I had the same problem.

My apache log file said something about ensuring that the blah/sites/default/files/blah/blah/ directory was executable, so after a lot of trial and error I gave execute permission to all in the files folder:

```
chmod -R a+x files

```

I'm not saying this is "the solution" and don't know if this brings security issues to the Drupal installation.

Still cannot understand what suddenly happened since I did not modified file permissions my self and everything was working fine. The problem occurred after editing an article entry with an image.
> 0 votes

---
Tags: 7, media, files
---


title: Hook Form Alter Specific Node

text:
# Question
Title: Hook Form Alter Specific Node
I want to put a hook to a form on one specific form that I created. Based on Node ID. The code i currently have is .

# Answer
> 2 votes
The `$form` array contains a `#node` key which has the `nid` attribute. Use that to filter like so:

```
if($form['#node']->nid == 1072) { ... }

```

However, since you ask for `page-node-1072` it sounds like you want to put something in that particular page template, in which case you should use a process or preprocess function to add or alter variables for the template.

# Answer
> 1 votes
If you only want to alter the form on a single page @betherwisser 's answer is the right one. If you want to alter all pages of type webform\_client\_form, then leave out:

```
if (strpos($form_id, 'webform_client_form') !== FALSE) {}

```

and relpace it with the function hook\_form\_FORM\_ID\_alter. In your case:

```
jhumobileform_form_webform_client_form_alter(&$form, &$form_state, $form_id)

```

to find out the actual form\_id (not sure whether 'webform\_client\_form' is the right one) install the devel module and activate it, then put dpm($form) in your function:

```
 function jhumobileform_form_alter(&$form, &$form_state, $form_id) { dpm ($form); //or directly dpm($form_id); }

```

Then, navigate to the site of the form as admin. Within the $form array you can also find the #node key.

---
Tags: nodes, webforms, forms
---


title: Find all the unused files

text:
# Question
Title: Find all the unused files
In Drupal 7 (I also have the Media module installed), there is a functionality in `/admin/content/file`

that lists all files being uploaded. If you click on a single file's "Usage" link, you can see exactly how many times that file has been used in the whole site, I would like to order that table by the column "Usage" to see files that haven't been used and then delete them.

Unfortunately it's not possible to order that column. Is there another way to achieve this? Is Views Bulk Operations the best available option?

# Answer
It maybe isn't exactly what you are after but I found the answer at Find orphaned unused files and images to be most helpful. Particularly the comment by @Marcos Buarque mentioning comment 7427898 which mentions a nice query to tidy up using the file\_delete() function built into D7
> 1 votes

# Answer
The latest dev version of the file\_entity module use a view that shows how many places the file is used in. Instead of a "Usage" column, it say's "Used in." You can see this in action if you try https://www.drupal.org/project/media\_dev -2.x-dev on simplytest.me

Hope that helps
> 0 votes

---
Tags: 7, files, media, views
---


# Question
Title: Drupal 7 website layout/styling breaks all a sudden (random), how to debug? there are no logs
One of my websites running Drupal 7 goes out of format, most often when user login.

This is how it should be

After running out of format this how it looks This may be a CSS issue, it may be a caching issue, or it may be something else. As I know Drupal core code is almost perfect but contributed, custom modules and themes can spoil something by adding bad code.

After spending sometime doing research I come across many question and answer which were not that clear at all because there are many factors that can cause such a problem therefore it is really hard to say what is happening specially in some cases when there is no sign of error or warning.

For example in my case I am using Drupal7, Superfish menu and following modules

addressfield, addressfield\_staticmap, admin\_views, ajax\_register, auto\_nodetitle, autoassignrole, backup\_migrate, captcha, ckeditor, colorbox, content\_access, css\_injector, ctools, currency, custom\_search, date, entity, entity\_translation, faq, field\_collection, field\_permissions, field\_slideshow, flexslider, flood\_unblock, follow, galleria, gmap, google\_analytics, i18n, i18nviews, image\_captcha\_refresh, jquery\_update, l10n\_update, lang\_dropdown, languageicons, libraries, link, Location, login\_destination, markup, menu\_block, mlpanels, modal\_forms, money, mortgage\_calculator, page\_manager\_redirect, panels, pathauto, real\_estate, realname, rules, select\_translation, serial, simple\_fb\_connect, simple\_gmp, simpleads, simplify, smart\_ip, social\_share, superfish, tablefield, tabtamer, taxonomy\_acces, taxonomy\_acces\_fix, taxonomy\_csv, token, translation\_overview, unique\_field, user\_role\_field, variable, viewfield, view, view\_bulk\_operation, views\_content\_cache, views\_data\_export, views\_field, views\_horizontal\_slider, views\_jqfx, views\_jqfx\_Cycle, views\_php, view\_Slideshow, views\_slideshow\_galleria, workspace, wysiwyg

The website is hosted in Cpanel

Itry may options to look for the error and identify the problem which where not helpful at all, I tried Mozilla browser and Firebug and there is no error or warning at all. I tried to add parameters into setting.php

```
error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

And still nothing changed. finally I decided to post the question here and ask all the great and genius developer to post their view and solution on:

* What can cause a Drupal website to run out of format and broke the layout
* What are the available tools or option that we can use to debug a Drupal

Can anyone please explain how to debug Drupal and deal with theme issue in a step-by-step way to make it simpler for everybody?

# Answer
> 1 votes
Above all, I assume that you have Google Analytics Installed. Go to the ***Behaviours*** menu and from there look at ***Site Speed*** and ***Page Timings*** to see how much times it takes to load a page. Use the ***Speed Suggestion*** option to allow Google suggest you a number of fixes/tricks that can potentially improve the performance of your web page. This is very handy.

This is clearly a problem of CSS. Open your site in chrome, enable the development tool F12 and then keep refreshing and monitor ***Network*** and ***Console*** windows. I observed that every reload of the page causes a request to a CSS to break (hence the resource is never downloaded - each time a different CSS from a different module).

It would be a great idea if you could give this module a go https://www.drupal.org/project/advagg, I highly recommend that you aggregate all your site's CSS into few or single CSS file.

It is always better to download one slighty larger file than make over a hundred calls to a web server requesting for tiny tiny CSS files, because there is high chance that your request fail or die (to to waiting).

I will update my answer with more findings but, give that module and a go and let us know your findings.

# Answer
> 0 votes
After the user logs in, the menu in the left upper corner appears (appearance to edit shortcuts) Your css is probably reacting to it (relative positioning etc.). For debuigging: Navigate with firebug to the menu's uppermost (most likely with the class user-menu or navigation) Then add in the styles frame in firebug (on the right side) for that class

`display: none;`

Thats mostly faster for debugging than doing it through your css files. If its the problem change your css files accordingly.

Another often encountered problem is that while using https for certain content (after a user logged in) the same-origin-policy of most browsers prevents the loading of additional resources, like javascript or css. Are you using https?

---
Tags: javascript, theming
---


title: Commerce : products with 2 prices

text:
# Question
Title: Commerce : products with 2 prices
In a Commerce project, the customer should be able to choose between 2 options with a radio field, for some products only, **with a different price for each option**. When a customer selects a radio option, the unit price should be changed accordingly and with ajax, and the line item updated I guess.

We also need that the admin enter PRICE A, PRICE B in 2 `commerce_price` fields when he creates new products, not by rule calculation neither +90 or -100 as in Commerce Pricing Attributes (because prices vary a lot and having to calculate each price difference would be a source of errors).

At the moment the lone idea I got to configure this is :

* set a *line item field* with these radio options, shown in the add to cart form.
* Then or a pricing rule which detects if the 2nd price exists, and is selected ; sets the 2nd price as the unit price ?

Or programmatically, with some hook ? Any suggestion would be really helpful.

# Answer
> 3 votes
**Pricing rules** was the right track. In order to configure 2 main prices for a single product :

Add a 2nd price field to the product type:

Add a boolean field to the corresponding *line item type*:

In the Add to Cart form settings of this field (`admin/commerce/config/line-items/CUSTOM-line-item/fields/field_avec_aerien`), check *Include this field on Add to Cart forms for line items of this type.*

Finally, in `admin/commerce/config/product-pricing/rules/manage/`, create (or clone & edit) a new **pricing rule** which set the unit price to 2nd price amount, when the boolean is checked by the customer in the add to cart form.

Pricing rules are very powerful, indeed !

# Answer
> 0 votes
Well, you should go for product attribute.

You've got a few tutorial about it on the drupalcommerce website :

Lucky you, one the commerce guys (Randy Fay) also make a video where he briefly talk about it : http://vimeo.com/user5912539 (can't remember which one :x)

---
Tags: commerce
---