# Question
Title: How to pre-populate multiple "field collection" fields in node form
I'm building a multistep node add form where you upload a zip of files on page 1, let the module read file names into an array when the uploader presses the "next" button, and then allows the uploader to enter some meta info for each file on page 2. I have set up the field collection "field\_files" to hold info for each file.

However, I can't seem to figure out how to generate the field collection form code for page 2. I would like it to be pre-populated with one field collection entry for each file. I've been reading module source code and huge var\_dumps all day without getting anywhere. Does anyone know if this is even possible, and if it is, what would be the best way to do it?

# Answer
After hours of debugging I found a good working solution to pre populate fields in field collections. (see Drupal forum)

So whats the plan?

1. Manually generate a node-add form for the desired bundle.
2. Change the form state of the generated form and set the desired number of fields you want to pre-populate.
3. Rebuild the node-add form with the new form state values.
4. Use **`hook_form_alter()`** to pre-populate values.

Ok. So lets assume we have a bundle called **`bundle_with_unlimited_fc`** which belongs to the node entity type. Furthermore all our custom code will reside in our module named **`my_module`**.

We can use hook\_menu\_alter() to define a new page callback. Everytime a new **`bundle_with_unlimited_fc`** is added Drupal will call now this function.

```
function my_module_menu_alter(&$items) {
  $items['node/add/bundle_with_unlimited_fc']['page callback'] = 'my_module_build_form';
}

```

Now definde our form builder function. Notice the function argument which comes from the Drupal implementation of our altered menu item.

```
function my_module_build_form($type) {
  // get the standard node form;
  // we cannot get it from drupal_get_form() because we need the form_state reference,
  // so we copy a bit of code from node_add() and drupal_get_form()
  global $user;
  $form_id = 'bundle_with_unlimited_fc_node_form';
  $form_state = array();
  $form_state['build_info']['args'][] = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE
  );
  $form = drupal_build_form($form_id, $form_state);

  // we now have exactly the form which node_add() is returning BUT
  // we also have a reference of the form state array ready to alter;

  // how many items do we want?
  $num_items = 5;
  // this is exactly what the ajax request for the add more button does
  $form_state['field']['--machine-name-of-field--'][LANGUAGE_NONE]['items_count'] = $num_items;

  // now this is important!! set a flag inside the form state so that the hook_form_alter() function
  // is able to know when it should pre-populate (remember: hook_form_alter() will be called twice
  // during this process)
  $form_state['my_module_prepopulate'] = TRUE;

  // reset the html ids so that our new rebuilted form will get nice ids and not form_id--2
  drupal_static_reset('drupal_html_id');

  // rebuild the form and return it;
  // through drupal_rebuild_form() hook_form_alter() will be called again - this time with our
  // prepopulate flag and 5 empty form elements ready to prefill
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

```

Thats nearly all there is. Just setup your hook\_form\_alter() and you will be ready.

```
// hook_form_FORM-ID_alter().
function my_module_form_bundle_with_unlimited_fc_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['my_module_prepopulate']) && $form_state['my_module_prepopulate']) {
    $delta = 0;
    $max_delta = $form['--machine-name-of-field--'][LANGUAGE_NONE]['#max_delta'];
    while ($delta <= $max_delta) {
      // prepopulate whatever you like with help of #default_value'
      $form['--machine-name-of-field--'][LANGUAGE_NONE][$delta]['#default_value'] = 'Value to show';

      $delta++;
    }
  }
}

```

So thats it basically. Hope that this solution will help some people to save time...
> 7 votes

# Answer
I've found a way to do this that is entity-agnostic (works on more than just node forms), and doesn't require any form rebuilding:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form_name') {
    $items_count = 6;
    $field_name = 'field_field_name';
    $form_theme = $form[$field_name][LANGUAGE_NONE]['#theme'];
    // Remove delete and add more buttons
    $form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
    $form[$field_name][LANGUAGE_NONE]['add_more']['#access'] = FALSE;
    $items = &$form_state['field'][$field_name][LANGUAGE_NONE];
    // Generate required number of fields collection
    if ($items_count > 1 and $items['items_count'] != $items_count) {
      $items['items_count'] = $items_count;
      $items['field']['cardinality'] = $items_count;
      $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
        // Reset theme function, as field_multiple_value_form hijacks it
        $form[$field_name][LANGUAGE_NONE]['#theme'] = $form_theme;
    }
    // Fill generated fields with data
    for ($delta = 0; $delta < $items_count; $delta++) {
      $form['field_course_preferences'][LANGUAGE_NONE][$delta]['field_user_qualified_adjusted'][LANGUAGE_NONE][0]['value']['#default_value'] = 'new value';
      }
  }
}

```

The trick is in the field\_multiple\_value\_form, which attaches the extra widgets properly so that the form doesn't fail validation, but lets you do a straight copy from the first form item. (Note, some of this stolen from others in the thread. :)
> 3 votes

# Answer
So the form attribute I think you're looking for is the `#default_value`. Populating this attribute for a given form element, will set it's default value, e.g. what appears in the field when the form is rendered.

You'll probably run a loop to generate the form for page two, as the number of files in the source zip will vary. Within this loop you will generate at least one, perhaps multiple form fields for each file. The field you want prepopulated should look something like this:

```
$form['file_meta_form'][$file_count]['prepopulated_textfield'] = array(

  '#title' => t('File info'),

  '#type' => 'textfield',

  '#default_value' => $file_meta_info,

  '#description' => t("Helpful instructions here"),

  '#size' => 50,

  '#required' => TRUE,

);

```

The form API page looks a little daunting at first, but if you are searching for specifics it is a valuable resource. Also check out the examples module as that's where I learned everything I know about forms. You can also control the all the varying details of the above form field by changing the attributes as desired. Again, the form API will be a good reference.

Update: Oh, and about saving to the db; I don't think you will need to do anything special as the default form submission and data storage should do everything you need. More directly, yes all the prepopulated fields will be saved to the db as with any other field. (if I understand what your after)

I'm new to answering, so just comment if you need clarification or...
> 0 votes

---
Tags: forms
---


title: "Merging" rows output

text:
# Question
Title: "Merging" rows output
Via the Drupal GUI, I have created the following content types and fields:

```
ContentType(Company)

ContentType(Site)
    Field(Company) <- entity reference to Company content type

ContentType(Contact)
    Field(Company) <- entity reference to Company content type
    Field(Site)    <- entity reference to Site content type

```

I'm trying to make a view (via the Views UI) which outputs a table like this:

```
-------------------------------------------
Company1    Site1   Contact1
-------------------------------------------
Company2    Site2   Contact2, Contact3
-------------------------------------------

```

I.e if two or more contacts are related to the same Company\Site combination, the output should be one row only, with all Contacts concatenated (with ", " as a separator in the example above).

But all I get is:

```
-------------------------------------------
Company1    Site1   Contact1
-------------------------------------------
Company2    Site2   Contact2
-------------------------------------------
Company2    Site2   Contact3
-------------------------------------------

```

Is there any way to get the output I want?

# Answer
> 3 votes
I know this is old but maybe it will help someone. I have found two possibilities, both with certain downsides.

* **Views merge rows module** does exactly what you need in terms of displaying results, however it **messes up views pagination** because it only changes the display of the query. But if you don't need pagination it's the way to go. **Edit**: I wrote a patch for the Views merge rows module to address the pagination issue. It now works perfectly.
* Views Aggregation with concat function patch \- if patching is an option - do it, then enable aggregation under Advanced in the view. Next step is to click on aggregation settings under the right field (in your case the 'contact' field) and set it to 'group concat'. This will aggregate the company and contact field and summarize the contact data as you specified.

Whereas this should work for the majority of use cases both solutions don't work for mine, that's why I created a new question here. Kind regards.

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


# Question
Title: How to hide a Fivestar field in a comment when the user didn't vote?
The comments on my articles have a Fivestar field called 'Stars', but rating nodes isn't always required (see: How to hide rating field when adding comment to own node?). When the user didn't rate the node on which he/she is reacting, 0 stars (not saved in the database) are now being displayed in his/her comment, but I don't really like that.

How can I hide the stars when the user didn't vote?

---

**Edit:** I'm trying to find a workaround with flags. I've created a flag called 'Reaction on own' and a rule that flags a comment when the comment's author equals the author of the commented node. In my case, it's sufficient that the 'Stars' field isn't displayed when a comment is flagged with 'Reaction on own'. This is the code of my custom module:

```
function hiderating_comment_view($comment) {
  $flag = flag_get_flag('reaction_on_own');
  if ($flag->is_flagged($comment->cid)){
    unset($comment->field_stars);
  }
}

```

Unfortunately, this isn't working. What's going wrong?

---

**Note:** In fact, the edit above isn't entirely true in my case, because 'zero' stars appear when a user reacts on his/her article *or* when the user has commented before. I've provided an answer for both cases.

# Answer
I'm excited to announce that I finally found a working solution! It turned out to be a bit more difficult than I had assumed in the beginning: I had to work with flags, rules and a custom module. Perhaps it was also possible to achieve this without flags, but they can come in handy elsewhere on one's website (e.g. for granting userpoints to users), so that's a little bonus.

**Step 1:** Create a flag for comments 'First reaction on article'.

**Step 2:** Create a flag for articles 'Commented on this article'.

**Step 3:** Create a rule similar the one with the following settings:

```
{ "rules_new_reaction_on_article" : {
    "LABEL" : "New reaction on article",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag", "comment" ],
    "ON" : { "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "comment:author" ],
          "roles" : { "value" : { "2" : "2" } },
          "operation" : "OR"
        }
      },
      { "NOT flag_flagged_node" : {
          "flag" : "commented-on-this-article",
          "node" : [ "comment:node" ],
          "flagging_user" : [ "comment:author" ]
        }
      },
      { "NOT data_is" : { "data" : [ "comment:author" ], "value" : [ "comment:node:author" ] } }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "commented-on-this-article",
          "node" : [ "comment:node" ],
          "flagging_user" : [ "comment:author" ],
          "permission_check" : 1
        }
      },
      { "flag_flagcomment" : {
          "flag" : "first-reaction-on-article",
          "comment" : [ "comment" ],
          "flagging_user" : [ "comment:author" ],
          "permission_check" : 1
        }
      }
    ]
  }
}

```

**Step 4:** Create a custom module 'Hiderating':

```
function hiderating_comment_view($comment) {
  $flag = flag_get_flag('first-reaction-on-article');
  $uid = db_query('SELECT n.uid FROM {node} n INNER JOIN {comment} c ON c.nid = n.nid WHERE c.cid = :cid', array(':cid' => $comment->cid))->fetchField();
  if ($comment->uid == $uid OR !$flag->is_flagged($comment->cid, $comment->uid)){
    $comment->content['field_stars']['#access'] = FALSE;
  }
}

```
> 0 votes

# Answer
You could try an approach like this (untested) but may work

```
/**
 * Implements hook_comment_view
 */
function hiderating_comment_view($comment) {
  if($flag = flag_get_flag('reaction_on_own')){
    // Debug comment to find field to hide, check dblog / watchdog
    debug($comment);
    if (!$flag->is_flagged($comment->cid)){
      unset($comment->field_stars);
    }
  }
}

```
> 0 votes

---
Tags: 7, entities, comments, rating
---


# Question
Title: Adding optional insurance service to existing shipping service
This is my first question here, sorry if I miss something and for my bad english. I have a D7 drupal commerce site, and custom wants to add an optional insurance for shipping. There is only 1 shipping service calculated with shipping weight tariff module. At checkout users should be ablen to choice wether buying insurance for shipping or not. If yes I should add 10% of order total with at least 10€ amount.

Thank you very much.

# Answer
You'd probably add this using a combination of Rules (module) plus an additional custom field for Shipping line items.
> 0 votes

# Answer
I'm trying in this way: \- I've created a new fee with Commerce Fees \- Created two shipping service, say "Service 1" and "Service 2", with the same calculation rule (I use Weight Shipping tariff) \- Created a rule: when shipping service is "Service 2", apply the fee.

The fee is based on total amount, while the shipping tariff is based on totale weight.

The problem is my insurance service figure as shippping service, not as an optional service in a new checkout step. It would be choosen not among shipping services, but in another step.

So, I'm trying this solution:

* created a new checkout page with Commerce Checkout Pages
* created a new checkout pane with Commerce extra panes, named "Insurance"

Now I would create something like a checkbox in "Insurance" pane to let the user choose to purchase the service or not; than get the value of input field, and write a rule like this: "if input field is checked, apply the fee to total order amount", using appropriate rules event, provided by Commerce Fees module.

Ho could I make that form or input filed in my custom pane and than get the value for rules?

Thank you very much.
> 0 votes

---
Tags: commerce
---


title: How to understand Views SQL statement?

text:
# Question
Title: How to understand Views SQL statement?
I try to figure out the meaning of View's sql statement.

This following is Views auto-generate sql statement:

```
SELECT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_hierarchy ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
INNER JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE (( (taxonomy_vocabulary.machine_name IN  ('book_category')) ))

```

What's the meaning of `{...}`?, It seems a table name, I try to copy above sql to mysql, But mysql alert me:

**SQL Syntax error**.

So I try to remove `{...}`, Like this :

```
SELECT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM
 taxonomy_term_data
LEFT JOIN  taxonomy_term_hierarchy ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
INNER JOIN taxonomy_term_data ON taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN  taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid

```

But Mysql alert me:

**Not unique table/alias: 'taxonomy\_term\_data'**

What's the problem of Views's SQL?

# Answer
> 4 votes
Only remove the curly brackets, not what's inside the them. The brackets contain the actual table name, and directly after is the table alias which is used later.

This should work (only brackets removed):

```
SELECT taxonomy_term_data.name AS taxonomy_term_data_name,
       taxonomy_term_data.vid AS taxonomy_term_data_vid,
       taxonomy_term_data.tid AS tid,
       taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM   taxonomy_term_data taxonomy_term_data
       LEFT JOIN taxonomy_term_hierarchy taxonomy_term_hierarchy
              ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
       INNER JOIN taxonomy_term_data taxonomy_term_data_taxonomy_term_hierarchy
               ON taxonomy_term_hierarchy.parent =
                  taxonomy_term_data_taxonomy_term_hierarchy.tid
       LEFT JOIN taxonomy_vocabulary taxonomy_vocabulary
              ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE  ((( taxonomy_vocabulary.machine_name IN ( 'book_category' ) )))

```

Note that if your tables has a prefix, i.e. `drupal_` then you need to add that to the table name, because that's the reason the brackets are used, in case of table prefix.

Cheers,

---
Tags: views
---


# Question
Title: Available tokens in the Filter Section of Views
Are any tokens(as nid) available in the FILTER CRITERIA of Views (see pic bellow). For example I can sort out all nodes with greater than the current NID...

# Answer
> 2 votes
I don't see any way in the Views UI to do this, but you certainly can with a hook:

```
function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='THE_VIEW_YOU_ARE_LOOKING_FOR' && ($node=menu_get_object())) {

    $filters = $view->display_handler->get_option('filters');

    $filters['nid']['value']['value'] = $node->nid;

    $view->display_handler->override_option('filters', $filters);

  }

}

```

which would set the value in the node nid filter to that of the node nid the View is displayed on.

---
Tags: views, tokens
---


# Question
Title: Log out is not redirecting to front page
I have a problem where once the user log out, the page is not redirecting to login page(home page) instead it is redirecting to the profile page.

I have used login destination module to redirect the user to profile page once login. The same path is taking even for log out. If I remove the login destination module this problem is not happening.

Kindly suggest.

# Answer
> 1 votes
It is a bug in the module which already submitted in the module issue queue. But you can solve it by applying this patch in the module. if you don't know to apply patch then check this post.

---
Tags: 7, users
---


# Question
Title: Uninstalled fb module, but page still pings fb connect for every pageload
I uninstalled the fb module and all its submodules from my site and deleted /sites/all/modules/fb folder completely. But for every pageload, the site still calls for these files:

1. http://connect.facebook.net/en\_US/all.js and a few others.

I want them removed as these slow down my pages completely. I have nothing other than a facebook like button on my homepage, and this was added with sexybookmarks. Any help?

# Answer
> 0 votes
It was added by the facebook share button added by sexybookmarks, Disabling that removed the files as well.

---
Tags: social-network
---


# Question
Title: Drupal 7 page template for right to left languages e.g. page--rtl.tpl.php
Trying to create a custom page.tpl dependant on language or 'right to left' support, here is what i have so far.

```
function THEMENAME_preprocess_page(&$variables) {
    if($variables['language']->language == 'ar') {
      $variables['template_file'] = 'page--ar';
    }
}

```

Am i on the right track?

# Answer
> 2 votes
In Drupal 7, what you'll want to do is something along these lines:

```
function THEMENAME_preprocess_page(&$variables) {
  if($variables['language']->language == 'ar') {
     $variables['theme_hook_suggestions'][] = 'page__ar';
  }
}

```

which will cause Drupal to look for a `page--ar.tpl.php` file (or even a `THEMENAME__page__ar()` function, which is the reason for the underscores in the variable value btw) when `$language` is set to `ar`.

A possible enhancement:

```
function THEMENAME_preprocess_page(&$variables) {
  if(isset($variables['language'])) {
     $variables['theme_hook_suggestions'][] = 'page__' . $variables['language']->language;
  }
}

```

will cause Drupal to look for `page--XX.tpl.php` files and will use them if they exist; otherwise, will just keep looking for a less specific template and will end up using `page.tpl.php`. This way, you don't have to have a lot `if's` in your preprocess logic.

For that matter, you can also do something like this:

```
function THEMENAME_preprocess_page(&$variables) {
  if(isset($variables['language']) && $variables['language']->dir=='rtl') {
     $variables['theme_hook_suggestions'][] = 'page__rtl';
  }
}

```

and now you would have one `page--rtl.tpl.php` file for all `rtl` languages.

Lots of possibilities abound here, a quick:

```
drupal_set_message('<pre>' . print_r($variables['language'], TRUE) . '</pre>');

```

in the beginning of your preprocess function will show you what you have to work with.

---
Tags: theming, i18n-l10n, 7
---


# Question
Title: Display number of tagged nodes for each term in a view?
I have a view of all of the terms in a vocabulary. How can I in the same view list the number of tagged nodes for each term? Thanks

# Answer
> 1 votes
First you have to make sure you can get the nodes tagged with each term to display, and then we'll get them so their COUNT is listed.

1. Add the 'Taxonomy term: Content with term' Relationship to your terms view (under the 'Advanced' section)
2. Now you should be able to see, in the list of fields, things such as Content: Title, etc. Add the content title, and make sure it's set to use your newly created relationship.

This should get all the nodes tagged with each of your terms to be displayed under the term. But how to count them??

The way you can do that is by enabling the use of aggregation for your view! Under the 'Advanced' section of your view, locate the 'Use aggregation' setting and make sure you enable it. It's disabled by default:

Once you've done that, you'll see by all of your fields a new 'Aggregation settings' field, which you can set to be 'Count' for the node title that relate to each taxonomy term.

That should do it! Let us know if you get it working! :-)

# Answer
> 1 votes
If the tag name is a contextual filter, there is also another alternative:

1. Go to the view's contextual filter definitions

> >
2. On the resulting popup, check the 'Dispay a Summary' radio option:

> >
3. Notice that the 'Display record count with link' option is checked by default.
4. Press 'Apply' to save the changes.

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


# Question
Title: Increasing the search query limit (Apache Solr)
We want to create a search page with Apache Solr with an increased query limit. I was reading that using `hook_search_execute` was not a recommended way to do this.

Is this statement correct? What would be the recommended way to go about this?

Apache Solr Views module?

Some other solution?

The page absolutely has to have more than 10 search results, and no pager.

# Answer
To do that programatically, you can implement `hook_apachesolr_query_alter()` to play with the `rows` parameter :

```
function yourmodule_apachesolr_query_alter($query) {
  // Increase the number of results per query
  $query->replaceParam('rows', 50);
}

```

Note : To disable the pager you can set a very very large number of rows, but it may impact performance. In this case you may prefer to bypass the pager at another level (for example in a preprocess function) and go with a more reasonable `rows` value.
> 4 votes

# Answer
There is apparently a setting for this in the Apache Solr module itself.

Go to the specific search that you want to modify, and edit the "Advanced Search Page Options" value.
> 1 votes

---
Tags: 7, views, search
---


# Question
Title: Installation Profile: $install_state['task_not_complete'] = TRUE doesn't seem to work
I need to set up multiple user in the last step of my install profile. My idea was to create a form like form\_example\_tutorial\_9

But every time I click on the add\_teammember button my form is submit and go to the last task which display the link "Visit your site". Although the user as been created I'm unable to display the form again in order to add other team members

So here is my code in the .profile file:

```
/**
 * Implements hook_install_tasks().
 */
function drupal_base_install_tasks() {
  $tasks = array(
    'team_members_form' => array(
      'display_name' => st('Team members'),
      'type' => 'form',
    ),
  );
  return $tasks;
}

function team_members_form($form, &$form_state) {
  $form['#tree'] = TRUE;

  $form['description'] = array(
    '#type' => 'item',
    '#title' => st('Setup team members accounts'),
  );

  if (empty($form_state['num_members'])) {
    $form_state['num_members'] = 1;
  }

  // Build the number of member fieldsets indicated by $form_state['num_members']
  for ($i = 1; $i <= $form_state['num_members']; $i++) {
    $form['member'][$i] = array(
      '#type' => 'fieldset',
      '#title' => st('Member #@num', array('@num' => $i)),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );

    $form['member'][$i]['name'] = array(
      '#type' => 'textfield',
      '#title' => st('Name'),
      '#description' => st("Enter member's name."),
      '#size' => 20,
      '#maxlength' => 20,
      '#required' => TRUE,
    );

    $form['member'][$i]['email'] = array(
      '#type' => 'textfield',
      '#title' => st("Enter member's email"),
      '#required' => TRUE,
    );

    $form['member'][$i]['password'] = array(
      '#type' => 'textfield',
      '#title' => "Enter member's password",
      '#required' => TRUE,
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save and continue',
  );

  // Adds "Add another member" button
  $form['add_members'] = array(
    '#type' => 'submit',
    '#value' => st('Add another member'),
    '#submit' => array('add_another_team_member'),
  );

  // If we have more than one member, this button allows removal of the
  // last member.
  if ($form_state['num_members'] > 1) {
    $form['remove_member'] = array(
      '#type' => 'submit',
      '#value' => st('Remove latest member'),
      '#submit' => array('remove_latest_team_member'),
      // Since we are removing a member, don't validate until later.
      '#limit_validation_errors' => array(),
    );
  }

  return $form;
}

function team_members_form_validate(&$form, &$form_state) {
  for ($i = 1; $i <= $form_state['num_members']; $i++) {
    if (!valid_email_address($form_state['values']['member'][$i]['email'])) {
      form_set_error('email', t('Please enter a valid email address'));
    }
  }
}

function team_members_form_submit($form, &$form_state) {
  $values = $form_state['values'];

  for ($i = 1; $i <= $form_state['num_members']; $i++) {
    $account = array(
      'name' => $values['member'][$i]['name'],
      'pass' => !empty($values['member'][$i]['password']) ? $values['member'][$i]['password'] : user_password(),
      'mail' => $values['member'][$i]['email'], 'status' => 1,
      'init' => $values['member'][$i]['email'],
    );
    $account = user_save(null, $account);

    // Assign the member of the team to the "administrator" role.
    $role = user_role_load_by_name('administrator');
    db_insert('users_roles')
      ->fields(array('uid' => $account->uid, 'rid' => $role->rid))
      ->execute();
  }
}

function add_another_team_member($form, &$form_state) {
  //reload the same step
  //$install_state['task_not_complete'] = TRUE;
  $form_state['num_members']++;
  $install_state['task_not_complete'] = TRUE;
  return drupal_render($form);
}

function remove_latest_team_member($form, &$form_state) {
  if ($form_state['num_members'] > 1) {
    $form_state['num_members']--;
  }
  $form_state['rebuild'] = TRUE;
}

```

My question:

Inside the function add\_another\_team\_member, I don't want the installation to go to the next step but I want it to display the form again. That's the reason I used $install\_state\['task\_not\_complete'\] = TRUE. But the installation continue to the next and final step anyway.

Thanks.

# Answer
This patch allows Ajax in install profiles https://drupal.org/node/1334818
> 0 votes

---
Tags: 7, users, installation
---


# Question
Title: get list of product line item in rule php
how can I get product id of line items in checkout process with rule, I know $commerce\_order are there in rule, but how can I get list of product id ?

# Answer
> 1 votes
This is a good way to get them

```
$line_items = $commerce_order->commerce_line_items['und'];
 foreach($line_items as $lid) {
 $line_item = commerce_line_item_load($lid['line_item_id']);
$pid[] = $line_item->data['context']['product_ids'][0];
//also you  can load products
//  $product =  commerce_product_load($pid);
 }

```

---
Tags: commerce
---


# Question
Title: When to use the Flag module versus a boolean field?
In terms of performance, maintenance, and future expansion/migration, what are the advantages and disadvantages of using the **Flag** module versus a **boolean field**?

In my case I would use the module to mark articles in a newspaper website that will be featured on the front page.

# Answer
For this particular use case, you could go with the **field**. There is no need to install a contrib module for something that a field can do fine.

**Flags** create a new entity for each new flag you create. This adds an extra layer of complexity when you are need to migrate or deploy.

It would make sense to use flags, if for example, you wished that your each of your users could mark this article (eg mark it as favorite)

Drupal also offers the 'promote to front page' functionality that you could use.
> 3 votes

# Answer
One of the main features of the Flag module is per-user flags (useful for things like bookmarking, flagging as spam, etc). If you don't need this functionality, a single value checkbox (boolean) field would work fine to make articles for inclusion on a home page. Fields are built-in and are easy to maintain and migrate.
> 0 votes

---
Tags: entities, flags
---


# Question
Title: How to create Ubercart recurring order with initial $0.00 charge
Is there any way to configure (or trick) Ubercart (7.x-3.4) into accepting an order with initial 0 charge, then subsequently charge non-zero amount?

Goal is to offer a promotion with $0.00 initial charge, then start charging after n-number months or days.

When 0 is set as the cost of the recurring product, Ubercart responds with an erroneous error about no payment method being set up.

# Answer
If you look at ubercart subscription it offers the ability to create a subscription product with an initial trial period of x days/months and then the amount to charge per day/month following the trial period.
> 1 votes

---
Tags: ubercart
---


title: A select list of user created nodes

text:
# Question
Title: A select list of user created nodes
I am creating a commerce store for custom clothing. I am trying to implement a product line item where users are posed with a dropdown of their uploaded artwork via a select list. I have created a content type called artwork that users will create. Now I just need to create a field that is a dropdown list of user-created nodes of artwork type. Does anyone know how to implement this?

# Answer
> 1 votes
Depending on the purpose of that dropdown, you should have a look at the entity reference module. Here is an excerpt about it from the module's project page:

> Provides a field type that can reference arbitrary entities:
>
> * A generic entity reference field
> * Four widgets:
>     + Two implemented on top of the Options module (Select and Radios/Checkboxes),
>     + Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)
> * Two formatters:
>     + A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
>     + A "Rendered entity" formatter, that renders the references entity using a configurable view mode
> * Integration with Views (for both forward and backward references)
> * Integration with Entity Metadata (and as a consequence with Search API and the like)
> * Integration with Devel generate
> * Integration with Feeds and Migrate (\>= 2.3) for painless data import

---
Tags: entities, commerce
---


# Question
Title: How to hide Fivestar field when editing a comment from another user?
My comments on articles have a required Fivestar rating field called 'Stars' and I hid it with the following custom module (see: How to hide rating field when adding comment to own node?):

```
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_article_form") {
   if ($form['#node']->uid == $user->uid) {
      unset($form['field_stars']);
    }
  }
}

```

As an administrator, I've permission to edit comments from other users. Suppose that a user commented on his own article. That means he didn't have to set the 'Stars' field, due to the code above. But when I try to edit that comment, I *do* have to select a value for the 'Stars'.

How can I prevent this? It's sufficient to check that the uid from the user who wrote the comment differs from the uid from the user who edits the comment. Finally, mark that the obligation to select stars when I leave a new comment myself must be preserved!

---

**Edit:** I tried the following code:

```
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $comment->uid = $form_state['values']['uid'];
  if ($form_id == "comment_node_article_form") {
   if ($comment->uid != $user->uid) {
    unset($form['field_stars']);
    }
  }
}

```

Apparently, `$form_state['values']` isn't well defined, because I get the following error:

> "Notice: Undefined index: values in hiderating\_form\_alter()".

What's the correct code?

# Answer
The code in the edit doesn't work, because `$form_state['values']` isn't present before the submit. This is the correct code:

```
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_article_form") {
   if ($form['uid']['#value'] != $user->uid AND $form['uid']['#value'] != 0) {
    unset($form['field_stars']);
   }
  }
}

```

Using `dpm($form)`, I discovered that `$form['uid']['#value']` returns the uid from the user who wrote the comment. The value is only different from 0 if a comment is edited. When a user writes a new comment, the uid from the form is 0. That's why the `AND` in the second `if` is necessary.
> 0 votes

---
Tags: 7, comments, rating
---


# Question
Title: In Drupal 6, how to display two grouping fields such as Country then Province?
In Drupal 6, I have a view for certain objects with Location:Country and Location:Province fields, both set to Exclude From Display; sort criteria to sort first by country then by province; and Style setting Grouping Field to be Location:Province. That displays all the objects in the order I want, everything with the same country grouped together, then within each country objects are grouped by Province/State, each state's group of objects labelled with the name of the state.

However, I would like to have a group title displayed for Country, not just Province, so it would look like

```
Canada
  Ontario
    object 1
    object 2
  Quebec
    object 3
United States
  Arizona
    object 4
  California
    object 5
    object 6

```

I'm a newbie to Drupal. Is there a standard way to do this? I've tried search terms such as nested grouping and multiple groups but haven't found mention of this use case.

# Answer
If you are comfortable with theme templates, you could do this by modifying the Style output, eg:

for your View. Here I created a quick View called `for-da-grouping` like this:

which has the node title and then two fields, country and province which are excluded from display. I am sorting first on Country and then within that Province, so, given the same information in your example, this produces:

But, if you add some logic to your new Views template:

```
<?php
/**
 * @file views-view-unformatted.tpl.php
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */

$country='';
$province='';

/*
  drupal_set_message('<pre>' . print_r($view->result[0], TRUE) . '</pre>');

    [node_title] => object 1
    [nid] => 660
    [node_language] =>
    [node_data_field_da_country_field_da_country_value] => Canada
    [node_type] => page
    [node_vid] => 660
    [node_data_field_da_country_field_da_province_value] => Ontario

*/

?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if ($view->result[$id]->node_data_field_da_country_field_da_country_value!=$country): ?>
    <div class="country-group-title">
      <?php print check_plain($view->result[$id]->node_data_field_da_country_field_da_country_value); ?>
      <?php $country=$view->result[$id]->node_data_field_da_country_field_da_country_value; ?>
    </div>
  <?php endif; ?>
  <?php if ($view->result[$id]->node_data_field_da_country_field_da_province_value!=$province): ?>
    <div class="province-group-title">
      <?php print check_plain($view->result[$id]->node_data_field_da_country_field_da_province_value); ?>
      <?php $province=$view->result[$id]->node_data_field_da_country_field_da_province_value; ?>
    </div>
  <?php endif; ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

You can get:

Now, things to look at in specific:

1. You need to sort your View first by country and then by province so the data is in the right order to begin with.
2. You need to know your Views results, they are stored in `$view->result` and you can get what you need out of looking at `$view->result[0]` and in my view, my two fields I want to group on are called `node_data_field_da_country_field_da_country_value` and `node_data_field_da_country_field_da_province_value` but yours are most probably going to be different but the logic is still the same: Only display the country and/or province if it has changed since the last time it was displayed.
3. Add some css to your new group headings and you should be all set.

If not, you can investigate the Views Field Module and so forth mentioned in https://stackoverflow.com/questions/9015500/how-to-group-by-more-than-one-field-in-drupal-view for alternative methods.
> 1 votes

---
Tags: views, 6
---


# Question
Title: How to rename a field with hook_ds_fields_info()
In a contrib module I maintain, I define a DS field via hook\_ds\_fields\_info().

Now it happens that I want to rename this field (the machine name). (actually it is not about renaming but splitting the one field into multiple fields, but that's a detail)

The first step is trivial: Rename the machine key in hook\_ds\_fields\_info().

Next step, in hook\_update\_N(): Every entity view mode that uses the field with the old name, should be updated to use the field with the new name instead.

How would I implement this second step?

It seems that the ds\_field\_settings and ds\_layout\_settings db tables are what I need to look at. But is this enough? Which API functions could I use?

# Answer
> 0 votes
I managed to implement this, thanks to @aspilicious.

See \- https://drupal.org/node/2190599 \- http://drupalcode.org/project/views\_content\_ds.git/blob/refs/heads/7.x-2.x:/views\_content\_ds.install

The solution is to edit this directly in the database, with db\_update() called from hook\_update\_N().

The tables are `ds_field_settings` and `ds_layout_settings`. Columns you need (same for both tables):

* 'id' is the primary key. Typical value: `taxonomy_term|categories|full`
* 'settings' holds the settings (field settings or layout settings), serialized.

Use drush sqlc + describe (table) to look at the table structure.

It also helps to implement the upgrade as a drush command, ideally with a downgrade option. This allows to quickly test this a lot of times, which is not that easy with hook\_update\_N().

---
Tags: display-suite
---


title: Stuck in site maintanance mode

text:
# Question
Title: Stuck in site maintanance mode
I've been trying to update my drupal installation with the security patch from 7.20 to 7.26 using a patch file. Problem is I cannot get out of maintenance mode. I've tried everything indicated in other posts: http://example.com/index.php?q=user, http://example.com/user/login. Also tried to go the DB route, but that does not work either since the variable do not seem to contain anything with the "site\_offline" name. This is very frustrating. I've also backtracked on the changes by reinstalling the DB and site from backup, but unfortunately I had already put the site in maintenance mode when I took the backups. Grrr. Any help greately appreciated.

# Answer
> 2 votes
The name entry in variable table is supposed to be `maintenance_mode` following updates in D7 after which `site_offline` and `site_offline_message` were replaced with `maintenance_mode` and `maintenance_mode_message`. Refer the inline comments in `update_fix_d7_requirements` in update.inc

```
  // Rename 'site_offline_message' variable to 'maintenance_mode_message'
  // and 'site_offline' variable to 'maintenance_mode'.
  // Old variable is removed in update for system.module, see
  // system_update_7072().

```

Assuming you have access to the database or drush try updating the variable which is likely set as 1 to 0.

```
drush vset maintenance_mode 0

```

or

```
UPDATE variable SET value = 's:1:"0";' WHERE name= 'maintenance_mode';

```

You might also want to ensure that this value is not set as 1 with a `$conf` variable in your site's settings.php. Many users with similar issue also suggest even clearing the cache table entries named variables for this to work after changing the variable value. If things go well this should bring your site back online.

---
Tags: updating, maintenance-mode
---


title: Can't create a new view

text:
# Question
Title: Can't create a new view
I am having trouble creating a new View. I am just testing out the module, but when I click "Save" after setting everything up, I receive the following error:

> PDOException: SQLSTATE\[HY000\]: General error: 1267 Illegal mix of collations (utf8\_general\_ci,IMPLICIT) and (utf8\_unicode\_ci,IMPLICIT) for operation '=': SELECT s.uid, c.updated FROM {ctools\_object\_cache} c INNER JOIN {sessions} s ON c.sid = s.sid WHERE s.sid \<\> :session\_id AND c.obj = :obj AND c.name = :name ORDER BY c.updated ASC; Array ( \[:session\_id\] =\> 3nTvCCvx2\_Zopg07JqIBReKxL3TzvilIkwmHjFKZ93o \[:obj\] =\> view \[:name\] =\> recently\_posted\_jobs ) in ctools\_object\_cache\_test() (line 145 of /home1/mt/public\_html/mtnet/sites/all/modules/ctools/includes/object-cache.inc). The website encountered an unexpected error. Please try again later.

Any ideas why this is happening?

# Answer
> 0 votes
Clear all your caches and try again.

You db seems to become corrupted or misconfigured. Your ctools module is using a different collation to store values in the db. So most of your site is utf8\_general\_ci and the ctools is using utf8\_unicode\_ci.

I gathered all of that from this line:

> (utf8\_general\_ci,IMPLICIT) and (utf8\_unicode\_ci,IMPLICIT) for operation '=': SELECT s.uid, c.updated FROM {ctools\_object\_cache}

---

If the clearing of caches fails then...

If you have phpmyadmin installed, go to the site's db and check what the Collate value is. Try changing it to utf\_8 or something.

---

**NOTE: I would create a backup of the db before you play with any collate value stuff.**

---
Tags: views, 7
---


# Question
Title: Multilingual "Posted on: ... - By: ..." labels
I would like to ask how to translate labels in drupal 7 like "**Posted on: ... - By: ...**". I also have difficulties with translation for **prev-next** buttons text in calendar. I created a multilingual website based on Nexus 7.x-1.3 theme.

# Answer
> 0 votes
The Nexus 7.x-1.3 theme didn't considered internationalization for some of its templates: To enable it to translate **"Posted on: ... - By: ..."**, edit the node.tpl.php on line 90.

```
<ul class="meta clearfix">
  <li><strong>Posted on:</strong> <?php print $date; ?></li>
  <li><strong>By:</strong> <?php print $name; ?></li>
</ul>

```

you will need to use the t() function to change the lines to:

```
<ul class="meta clearfix">
  <li><strong><?php print t('Posted on:'); ?></strong> <?php print $date; ?></li>
  <li><strong><?php print t('By:'); ?></strong> <?php print $name; ?></li>
</ul>

```

I'm not sure about which calendar you mean, in case that you are using the one bundled with Date module (Date popup), I believe those buttons can be translated using the Translate interface (admin/config/regional/translate/translate).

---
Tags: 7, i18n-l10n
---


# Question
Title: Replicating a page.tpl Region in Omega's structure
I have a theme with a specific region and it is being printed using some PHP within the page.tpl.php file. It is also using a .js file and a .css file both within the PHP.

Here is the current code found within my old site's page.tpl.php file that allows for my region to show up:

```
<?php if (isset($page['sidepulltab'])) : ?>
    <div id="style-picker">
      <div id="toggler" class="closed"></div>
      <div id="body">
        <div class='section'>
            <?php print render($page['sidepulltab']);?>
        </div>
      </div>
    </div>
<?php endif;?>

```

I have added to my subthemes .info file 3 lines (.js, .css and region):

scripts\[\] = js/stylepicker.js stylesheets\[all\]\[\] = css/stylepicker.css regions\[sidepulltab\] = Side Pull Tab

I am not sure how to transfer this type of PHP region within Omega's Subtheme under the Appearance tab.

I tried adding the above code to page.tpl.php file which I copied into my subtheme from its original Alpha theme location. I do get my CSS and DIVs to show up, however my block region isn't printing inside.

**Note**: I'm using Omega 3, I have also cleared the cache. The region is showing up as "disabled" inside the Omega3 Apperence tab.

# Answer
I have solved this issue.

I had to create a Zone. Then add the created Region to the new zone. I then created a zone--zonename.tpl.php file and within that i added

```
<div id="style-picker">
<div id="toggler" class="closed"></div>
<div id="body">
    <div class='section'>
    <?php print $content; ?>
    </div>
</div>

</div>

```

after that all content printed within this zone will be wrapped within my divs and .js and .css files will be applied.

Thank you 2pha for sticking in there with me and helping me with my overall brainstorming =-) hopefully this helps someone else messing around with this stuff.
> 2 votes

---
Tags: theming
---


# Question
Title: Save form when user refreshes page from browser or click on any anchor tag inside page
I have made a form in drupal.

What I want is when the browser unload the page from any click whether by clicking on anchor tag or from browser refresh buttons I want to save data of my form through js/ajax or anything possible in drupal.

If any more explanation needed please do ask me. Thanks in advance.

I was trying do this by browser 'unload' event and 'beforeunload' event. But unable to save data of my form because browser doesn't wait for anything writtent inside and just ask for confirmation. Any help will appreciated.

This what I was trying to do:

```
$(window).bind('beforeunload', function() {
  return 'Do you really want to leave?';
  //coming here instead of it what i want
  //is save the form then return if user says yes and no the don't save the form.
});

```

# Answer
You would need to create your own AJAX implementation to achieve this. Upon some trigger, whenever you want that to be, (I would make it save any time a field looses focus), you would perform an AJAX call saving the information into a database. When the user returns, provided they are traceable in some way either through their UID or a valid session, you would fill the form out again with the information from the temporary table in the database. When the user completes the form, let Drupal write the data accordingly. Otherwise, there is no way to save the users information and present it to them again. This method, if the user is registered, would always work. Make sure you add a "clear form" button though so they can clear it if they want.

Update: You could use .unload
> 0 votes

# Answer
I have implemented above on anchor with ajax. (i.e.) I have checked if a form is edited then a alert is shown if user clicks on any anchor element. Afterwards user form is saved if user agrees else changes discarded. For browser refresh, I didn't get any solution. Thanks for this help and discussion.
> 0 votes

---
Tags: 7, theming, forms, ajax, javascript
---


title: I can't get hook_menu() to work

text:
# Question
Title: I can't get hook_menu() to work
Hi I am running the code on p247 of "Pro Drupal 7 Development", which includes the code below and then defines a form. I have enabled the module and cleared the cache but this isn't showing up in my menu system. What am I doing wrong?

```
/**
 * Implements hook_menu().
 */
function formexample_menu() {
  $items['formexample'] = array(
    'title' => 'View the sample form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formexample_nameform'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM
  );
  return $items;
}

```

# Answer
> 0 votes
check http:localhost/formexample

Back-end admin panel menu :

```
$items['admin/structure/formexample'] = array(
    'title' => 'View the sample form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formexample_nameform'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM
  );

```

used this code

---
Tags: routes
---


title: Quicktab visibility by programing

text:
# Question
Title: Quicktab visibility by programing
I have a **Quicktab** with 2 tabs. The block is placed in **user profile**.

Now I want to show one of the blocks only when the user visits his own profile and hide it when he is visiting other profiles. How may I do this?

# Answer
> 1 votes
In Drupal 7 you can use **hook\_quicktabs\_alter**

```

    /**
     * Implementing hook_quicktabs_alter
     * @param type $quicktabs
     */
    function MODULE_NAME_quicktabs_alter(&$quicktabs) {
        global $user;
        foreach ($quicktabs->tabs as $key => $tab) {
            if ($tab['title'] == 'Tab1' && arg(0) == 'user' && is_numeric(arg(1)) && $user->uid == arg(1)) {//check condition as per your requirement
                unset($quicktabs->tabs[$key]);
            }
        }
    }

```

# Answer
> 0 votes
you would need to put that code right where you want the quicktab to render:

```
<?php
// Current user uid.
global $user;
$userUid = $user->uid;

// Uid of the user's viewed profile.
$userUidViewedProfile = $arg(1)

// Condition if current userId = userId's viewed profile. If it is, render the quicktab.
if ($userUid == $userUidViewedProfile)
{
    $block = module_invoke('quicktabs', 'block_view', 'machine_name'); // Only change the machine name here,
    print render($block);
}
?>

```

---
Tags: users, blocks
---


# Question
Title: Why do I get an AJAX error during installation?
I tried to install Drupal 7.10. When the installation has installed 28/29 modules, I get the following error.

> An AJAX HTTP error occurred.
> HTTP Result Code: 200
> Debugging information follows.
> Path: http://localhost/drupal/install.php?profile=standard&locale=en&id=1&op=do
> StatusText: OK
> ResponseText: ( ! )
> Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\drupal\includes\database\mysql\database.inc on line 153

Can anyone help me to fix it?

# Answer
The problem is the maximum execution time being exceeded. To fix this, you should change the maximum execution time in your php.ini file. Click on the Wamp icon on the taskbar, select PHP -\> php.ini, find "max\_execution\_time" and change it from 30 to like 100-300, to make sure even the slower scripts get their job done before the timeout.

Remember to restart the server after you change the settings.
> 7 votes

# Answer
I was also getting a similar error during Drupal installation, with *Drupal already installed* as response text. I fixed the error by changing the following values in the php.ini file used for the site.

```
max_execution_time = 180
max_input_time = 180
max_input_nesting_level = 300
memory_limit = 512M

```
> 0 votes

---
Tags: installation
---


# Question
Title: Shutdown functions not working on php-fpm setup?
I have a problem with `drupal_register_shutdown_function()`: my callback is not being called =| Here's example code:

```
<?php
/**
 * Implements hook_node_update().
 */
function example_node_update($node) {
  if ($node->type == 'test') {

    drupal_register_shutdown_function('_example_shutdown');
    dpm(drupal_register_shutdown_function()); // This outputs callbacks array showing that '_example_shutdown' really gets registered.
  }
}

function _example_shutdown() {
  dpm('Shutdown callback executed'); // This is not shown
}

```

I use php-fpm, and php.net register\_shutdown\_function discussion suggests to use `fastcgi_finish_request()` instead of `register_shutdown_function()` with php-fpm. Also, see this D8 issue: "Ensure register\_shutdown\_function() works with php-fpm". Is there any D7 workaround?

I think there could be two different approaches:

1. Global: Fix `drupal_register_shutdown_function()` to check for php-fpm environment and use `fastcgi_finish_request()` in that case.
2. Local: Use some hook to force `_drupal_shutdown_function()`. Maybe `hook_exit()` would be ok for some cases, but in my case it is too late (as my callback updates nodes, and by the time `hook_exit()` runs the response is already sent to the browser, so user would get an "old" node, I'm afraid).

Maybe there is something simpler that I'm missing?

# Answer
Example shutdown is getting called ; you can't use dpm in a shutdown function though, because at that point the session already got written to the database and there's just no way to add a new message to it.

In PHP-FPM, the connection also could have already been closed, so print or var\_dump is not really a good test to check if you're shutdown function is getting called in general ; it should work in D7 though if you're not using a module that's specifically closing the request, so you should be able to use `print "Hello world";` and get it to show on screen (that's what the core "Shutdown functions tests" is doing in D7).

If you want something realiable to use in a shutdown function to check if it got invoked, try something like `file_put_contents('/tmp/drupal-debug.txt', 'Shutdown function called');`
> 5 votes

---
Tags: 7
---


# Question
Title: Change the pager and the number of elements per page of a specific view
I create a view (FO) that lists certain content type. By default, I put a pager (mini) and a number of items per page (content 10 per page).

This view, I integrated into a content type (CFTO) in addition to other parameters. If I agree, I want to use my other variables to redefine this view without saving it in a database (eg disable the pager / display 3 content page / ...)

I try different hooks as hook\_views\_pre\_view, hook\_views\_pre\_render, views\_pre\_build, but nothing works. I can not change the number of a content page. This is my different test :

I wish i could change my view different information as enable / disable pager and more then change the number of elements of the page.

I find a way of hook\_views\_pre\_render(&$views) to change the pager and more. It works well.

```
function my_views_pre_render(&$view){
//For more
$view->display['page']->handler->options['use_more'] = TRUE;

//For pager
if(!$this_node_pager_value) {
    $view->query->pager->set_items_per_page($view->total_rows);
    $view->query->pager->update_page_info();
}}

```

Now i wish i could change the number of elements in my page to display, I tested this code in different hook sities previously.

```
function my_views_pre_render(&$view){
if($this_node_pager_value) {
//TEST 1
$view->query->pager->set_items_per_page(3);
$view->query->pager->update_page_info();

//TEST 2
$view->exposed_raw_input['items_per_page'] = 3;
}}

function my_views_pre_view(&$view, &$display_id, &$args){
//TEST 1
$view->display_handler->display->display_options['pager']['options']['items_per_page'] = 3;

//TEST 2
$view->query->pager->set_items_per_page(3);
$view->query->pager->update_page_info();

//TEST 3
$view->exposed_raw_input['items_per_page'] = 3;
}

function my_views_pre_execute(&$view){
//TEST 1
$view->display_handler->display->display_options['pager']['options']['items_per_page'] = 3;
//TEST 2
$view->query->pager->set_items_per_page(3);
$view->query->pager->update_page_info();
//TEST 3
$view->exposed_raw_input['items_per_page'] = 3;
//TEST 4
$view->display_handler->set_option('items_per_page', 3);
}

function cci_generic_views_pre_build(&$view){
//TEST 1
$view->pager["items_per_page"] = 3;
//TEST 2
$view->display_handler->options['pager']['options']['items_per_page'] = 2;
//TEST 3
$view->display_handler->options['pager']['options']['expose']['items_per_page'] = 2;
}

```

None works. Would you know what should be done to make it work?

You would know what is the right hook to use? And how to change this value? thank you for your help

Djik

# Answer
> 0 votes
The following should work in `hook_views_pre_build(&$view)`:

```
$view->set_items_per_page(5);

```

---
Tags: views, hooks
---


# Question
Title: How to link taxonomy term with current loaded NID?
I want to link taxonomy term with current loaded node I am using

```
$nid = arg(1);
$term=taxonomy_term_load($tid)
print $term;

```

but noting happened. Please tell what is the correct way

# Answer
> 0 votes
```
$nid = arg(1);
$node = node_load($nid);
//field_taxonomy is the taxonomy field used in the node
$tid = $node->field_taxonomy['und'][0]['tid'];
$term=taxonomy_term_load($tid)
print $term;

```

# Answer
> 0 votes
In Drupal 6 and Drupal 7, taxonomy and node ids' are linked in term\_node and taxonomy\_index tables respectively. To programmatically link nid and tid, load the node and enter tid in it under **hook\_node\_presave()**

Create a new taxonomy object, if not already exist

```
$taxonomy = new stdClass();
$taxonomy->vid = xxx; // id of the vocabulary term
$taxonomy->name = 'abc'; // name of the term
$new_term = taxonomy_term_save($term);
$tid = $new_term->tid; // This will get you tid of new term
                       // that is created or use taxonomy_term_load() if you have tid

```

Attach this tid in the node

```
$node->taxonomy_field_name_in_the_node['und'][]['tid'] = $tid;

```

submit this node.

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


# Question
Title: Large, regular product import for Commerce
I am in the process of developing a new site using Commerce Kickstart.

The site needs to import a fairly large amount of data from a CSV on a regular basis - perhaps 50,000 to 100,000 products at a time, at least every week. (And maybe more often than that.)

I have tried to use Feeds to do a test import of around 30,000 products. (So this creates 30,000 product variations and 30,000 display nodes.) This has proved to be far too slow for my purposes, taking around 18 hours.

So I see my options as follows:

1. Run some profiling to attempt to see why the import is slowing down so much (It starts off at around 200 products / minute and slows down to 10-20 by the end of the import run.)
2. Following the strategy here, import into a single table, and use entities to do what I need to do. With this approach, I am concerned about losing or having to re-implement the functionality I need to make the site work - namely faceted search / unknown regular commerce functionality. Each product - each line of the CSV - has numerous fields of data that would have to be stored, so I'm not even sure if this approach would work.

Does anyone have any advice on the best way to progress? Or any hints about the above? Or strategies to import the data that I might not have considered?

Thanks in advance.

EDIT:- Looking at the Feeds log, it looks like the product variations imported in 1 hour 20 mins, whereas the product display nodes took 17 hours to create.

# Answer
> 0 votes
Hopefully this helps someone else.

I used XHProf in an attempt to figure out why the Feeds import was slowing down so much. It appears that the culprit is DrupalDefaultEntityController::cacheGet.

As the number of entries in DrupalDefaultEntityController's entityCache increases, performance drops off a cliff.

I resolved the issue by importing the nodes manually.

---
Tags: commerce, feeds, migrations
---


# Question
Title: How is webform node type is defined in webform module?
Reading the webform module code I could not figure out how webform content type is defined. I only found this piece of code:

```
function webform_node_type($op, $info) {
  $webform_types = webform_variable_get('webform_node_types');
  $affected_type = isset($info->old_type) ? $info->old_type : $info->type;
  $key = array_search($affected_type, $webform_types);
  if ($key !== FALSE) {
    if ($op == 'update') {
      $webform_types[$key] = $info->type;
    }
    if ($op == 'delete') {
      unset($webform_types[$key]);
    }
    variable_set('webform_node_types', $webform_types);
  }
}

```

In variable table of drupal database I found the following webform\_node\_types variable: a:1:{i:0;s:7:"webform";}. When applying variable\_get to this variable I recieve an array of 1 element with value - 'webform'. Please help me understand how webform node type actually is defined and how it works? Thanks

# Answer
The initial webform content type is created during install as an entity of type node. The code can be found in the webform\_install() function:

```
$webform_type = array(
  'type' => 'webform',
  'name' => st('Webform'),
  'base' => 'node_content',
  'description' => st('Create a new form or questionnaire accessible to users. Submission results and statistics are recorded and accessible to privileged users.'),
  'custom' => TRUE,
  'modified' => TRUE,
  'locked' => FALSE,
);
$webform_type = node_type_set_defaults($webform_type);
node_type_save($webform_type);
if (variable_get('webform_install_add_body_field', FALSE)) {
  node_add_body_field($webform_type);
}

```

Additionally it might be worth noting, that you can turn any content type into a webform by checking the appropriate setting on the content types main configuration page. You can think of webform as an add-on extension to other content types. To find out which content types are "webform enabled" you should use the provided API functions. In webform-7.x-4.0-beta for example that would be `webform_node_types()`.
> 2 votes

---
Tags: nodes, webforms
---


# Question
Title: Is there any way to know if a string is not translated?
I have my own module that I want to translate to some languages. I use the `t` function and also I have my *lang.po* files.

I try to update the *lang.po* files every time I use the `t` function but maybe I forget to update some text string.

Is there any way to know if there are some *t-strings* without translation in the *lang.po* files?

I can go to `admin/config/regional/translate/translate` but I only need to check the strings of my module.

# Answer
> 1 votes
Install l10n\_client then flush your cache.

If you switch to any other language you'll see a small box with blue bg in the bottom right. Click it and in the left it'll show all translated & untranslated strings. The green ones have been translated, while other ones you'll need to. Just select one and add the translation there itself.

---
Tags: 7, i18n-l10n
---


# Question
Title: Anonymous users can't see new content type in feed
I've made a new content type, and I've made a View that is a list of that new content type. Anonymous users don't get any content in that list but can see the individual content types. Admin users can see the content in the view fine. Is it a permissions issue?

# Answer
> 1 votes
There are multiple possible problems. First of, dealing with unpublished content - assuming you created a content type with unpublished option as default, you will have to make sure that you tick the publish option on save/ create of new items. As per default registered and anonymous users can't see unpublished content.

Going further there could also be a problem inside of your view. You can manage access for the view itself in the middle column of the views ui edit page. There might also be a filter to only show published / published or admin items only.

also make sure that anonymous user can see content at all: `/admin/people/permissions`

---
Tags: views, users
---


title: Undefined index und error

text:
# Question
Title: Undefined index und error
I'm getting undefined index:und error. below is my code

```
$photoItem = file_create_url($node->field_thumb_img[LANGUAGE_NONE][0]['uri']);

```

# Answer
> 0 votes
why not

> file\_create\_url($node-\>field\_thumb\_img\[$node-\>language\]\[0\]\['uri'\]);

# Answer
> 0 votes
you can do $photoitem = field\_get\_items('node', $node, 'field\_thumb\_img') ;

field\_get\_items($entity\_type, $entity, $field\_name, $langcode = NULL);

see https://api.drupal.org/api/drupal/modules!field!field.module/function/field\_get\_items/7

---
Tags: views
---


# Question
Title: Do I need different content types for correlated items
I have different types of correlated content items like news, articles, ebooks and books. Some items have same fields, for example news and articles, but some have different fields.

Do I make different content types, or just manage that with different vocabularies?

# Answer
> 1 votes
it depends on your later plans with those content entities and how your editors will be using the system, I guess it will be easier for them to create a new "news" article if there's an actual create news link, instead of having a "somewhat" containing all of the information holding magic content type called "content".

You can reuse fields you created on another content type, so you will not create countless fields for the same type of content across multiple content types. (each field will be a at least 2 tables in your database - more).

* news
    + title (default)
    + body (default, can be reused)
    + source (can be reused)
* articles
    + title
    + body
    + source
* ebook
    + title
    + body
    + source
    + author
    + downloadlink

If you plan to theme these entries differently you will almost always want to create a own content type for them, so you can have multiple templates, panel panes or what-else you are going to use. Just so you don't get me wrong: you can create different templates for a node based on it's related taxonomy term, but this will require additional code while there are default template suggestions for content types already, also dealing with content types in views is probably easier than having the same content type and variants created by taxonomy term.

---
Tags: nodes
---


# Question
Title: How to link taxonomy term with its content?
This is the code below that i am used

```
$ch=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
  INNER JOIN taxonomy_term_data td ON th.tid=td.tid
  INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
  WHERE td.vid = '6' AND th.parent = $tid AND book.entity_id = $nid")->FetchField();

"<h1>Pages</h1>";

$chap = taxonomy_get_children($ch);
foreach($chap as $ca){
  print "<br>Chapter===>".$ca->name;
}

```

how I link taxonomy terms using the above code?

# Answer
In Drupal 7 you can use **l()**

```
  $ch = db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
        INNER JOIN taxonomy_term_data td ON th.tid=td.tid
        INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
        WHERE td.vid = '6' AND th.parent = $tid AND book.entity_id = $nid")->FetchField();

  $chap = taxonomy_get_children($ch);
  foreach ($chap as $ca) {
    print l($ca->name, 'taxonomy/term/' . $ca->tid);
  }

```
> 0 votes

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


# Question
Title: Injecting Views blocks into another View template
I have a View containing the latest news in a very standard way (ie: one below the other)... I would like to inject, at certain points, other blocks containing other views (ie: latest news with a certain tag), like in this image:

https://i.stack.imgur.com/3c9Dw.jpg

An easy but impractical approach would be to create different views: one for the latest 2, then one for another 3 news with an offset of 2, etc...

But is there some magic that the new D8 theme layer can do to make this more practical?

# Answer
> 0 votes
You could create a new View field in modules/yourmodule/lib/Drupal/yourmodule/Plugin/views/Field and "attach" it via hook\_views\_data\_alter() or hook\_views\_data(). This field would returns a hardcoded view or dynamic, depends on your needs. Another way would be to use Views templates.

---
Tags: views
---


# Question
Title: Datepicker and form_state with different formats
I'm using custom form for getting results from a web service.

This is a part of my form

```
<?php

$form['starting_date'] = array(
   '#type' => 'date_popup',
   '#title' => 'Starting date',
   '#date_format' => 'd.m.Y',
)

```

As you can see I'm using the date\_popup from the Date module.

It's displaying correct with this format d.m.Y. but after submitting the form, I've got error from a web service, because the string I'm passing `. form_state['values']['starting_date'] .` on print, the values are with different format.

Lets say a user selects 10.02.2014 (today), the form\_state displays as 2014-10-02.

How can I fix that? The web service has to receive only with this format d.m.Y to display the results, otherwise it doesn't work.

# Answer
1.Add a js file to the module and
2.In the js add the following code using the id of date field to change the date format of the date picker
3.check the link for reference

```
$( ".selector" ).datepicker({ dateFormat: "yy-mm-dd" });

```
> 0 votes

---
Tags: forms, datetime
---


title: #states not working properly in IE 9

text:
# Question
Title: #states not working properly in IE 9
I am using `#states` form API to do the show hide animation of one element based on the values of another form element.like follows,

```
$price['#states'] = array(
    'visible' => array(
        ':input[id="edit-field-paid-event-und"]' => array('value' => 1),
    ),
);

```

It's working fine in all the browsers except in Internet explorer 9 and 10. Any solution for this.

# Answer
> 17 votes
I found the answer from this Link. So Internet Explorers never accepts element value as integer. I changed my code as follows it's working for me,

```
$price['#states'] = array(
  'visible' => array(
    ':input[id="edit-field-paid-event-und"]' => array('value' => '1'),
  ),
);

```

---
Tags: 7, forms
---


# Question
Title: Authenticathed users can't edit Etherpad-enabled field
I integrated Etherpad on my Drupal site. I did everything as instructed, but still only the administrator role can edit the Etherpad field.

This is how it goes:

Content type X has a text field which is set to be Local Editable in Manage Display (as instructed by the Etherpad readme file).

Furthermore, using the Field Permissions module, the same text field has custom permissions and is editable by authenticated users.

The url for the Etherpad-enabled field goes like this:

http://mysite.com/etherpad/\[node:nid\]/\[etherpad-field-name\]#

Despite all this, when I log in as a regular, non-administrator user, I get an "Access denied" message for the field page.

When logged in as admin, when viewing the node, by hovering over the top right corner of field, the "Edit" dropdown appears with the above mentioned url. As a regular user I don't have that option.

# Answer
I just found out that the user needs to have permissions to edit the *entire* node. Don't know why the field-specific permissions don't work. I had to create a separate content type in order to implement this.
> 0 votes

---
Tags: entities, users
---


# Question
Title: Allow user to select which registration type on Entity Registration module
H, I am using the Entity Registration module, but I would like the user to be able to select what kind of registration type - e.g. registering as a participant, a facilitator or a resource-provider. Is this possible? as it seems as though its only possible to enable one registration type on a registration field.

# Answer
I haven't use the Entity Regisration module for registration but for my suggestion. You should use the Profile2 module for that purpose. It allows you to:
\- Create many type of user profiles
\- The link for registration of each kind of users (Must use the Profile2 Registration Path module)
\- The custom fields for each kind of users
> 0 votes

# Answer
If you wish you should be able to define several registration types. On your event (content type) if you specify a field type as registration, the widget will allow the person defining the event to select which type of registration is required.

Based on your description though, I believe you only need one registration form with a select list field to allow them to indicate his role in the event.

So for Registration type event\_registration you will need to define a field called type\_of\_registration with a select list field that contains 3 types, participant, facilitator or resource provider
> 0 votes

---
Tags: entities, users
---


# Question
Title: How do I get the translated node type of a node?
I am trying to use the node type name in `page.tpl.php` for certain content types. Actually, we have modified the `article` type and renamed it as `News`. It's name is `News` in all languages but in Spanish, where it is `Noticias`.

The translations are defined under `Structure>Content Type>Article`.

I tried to use this code :

```
if(!empty($node) && $node->type == 'article'):
  print node_type_get_name($node);
endif;

```

but the node type is always printed as `News`, even on Spanish pages.

I tried wrapping this in a `t()` , but no change. Am I doing something wrong here ? Thanks for your help !

# Answer
> -1 votes
I have edited html.tpl.php

I have added this code before starting the body tag in order to replace body css classes with translated

```
<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>

```

after this modification, you can search css class name in translate page and put a suitable translation for it.

so final html.tpl.php is

```
<?php

/**
 * @file
 * Default theme implementation to display the basic html structure of a single
 * Drupal page.
 *
 * Variables:
 * - $css: An array of CSS files for the current page.
 * - $language: (object) The language the site is being displayed in.
 *   $language->language contains its textual representation.
 *   $language->dir contains the language direction. It will either be 'ltr' or 'rtl'.
 * - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.
 * - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.
 * - $head_title: A modified version of the page title, for use in the TITLE
 *   tag.
 * - $head_title_array: (array) An associative array containing the string parts
 *   that were used to generate the $head_title variable, already prepared to be
 *   output as TITLE tag. The key/value pairs may contain one or more of the
 *   following, depending on conditions:
 *   - title: The title of the current page, if any.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site, if any, and if there is no title.
 * - $head: Markup for the HEAD section (including meta tags, keyword tags, and
 *   so on).
 * - $styles: Style tags necessary to import all CSS files for the page.
 * - $scripts: Script tags necessary to load the JavaScript files and settings
 *   for the page.
 * - $page_top: Initial markup from any modules that have altered the
 *   page. This variable should always be output first, before all other dynamic
 *   content.
 * - $page: The rendered page content.
 * - $page_bottom: Final closing markup from any modules that have altered the
 *   page. This variable should always be output last, after all other dynamic
 *   content.
 * - $classes String of classes that can be used to style contextually through
 *   CSS.
 *
 * @see template_preprocess()
 * @see template_preprocess_html()
 * @see template_process()
 *
 * @ingroup themeable
 */
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

I hope my post can help you.

---
Tags: nodes, i18n-l10n
---


# Question
Title: How can I filter/sort a Drupal view in this way?
I have created a content type called PDF Publication with two fields - a pdf file upload field that allows one file to be uploaded and a term reference field where the user selects an area e.g. area1 area2 or area3

I now need to create a view block that shows just the latest pdf uploaded for each area. so the block will show three pdfs - one for each area

I have followed instruction from here and other forums on the Internet but am struggling to do this.

I would be really greatful for some help, thank you so much for reading.

# Answer
> 0 votes
The easiest way I can think of you doing it since you have just three areas, is creating One block display with two attachments.

The block contains one area with the most recent pdf, and the two attachment, would contain one area each with the most recent attachment, and link the attachments to the block display.

See Image of how to add an attachment

UPDATE

When you are using more than one diaplay and are adding a display you want to make sure at the top of the popup dialog you choose for this display, rather than all display. See image below

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


# Question
Title: How do I render a node queue as custom JSON?
What would be the most sensible way to render a nodequeue queue in a custom JSON format (using Drupal 6)

We have a nodequeue that is both included in the UI in various places and served in a RSS feed.

I've found that I can use `drupal_json()` to convert a PHP data structure to JSON so now I'm mostly after what would be the right place for this?

As a hack, I tried to use RSS feed and to have a custom template for the feed. My problem there is that a) it feels pretty hackish and b) in the "general template" available I don't have the content available.

(As background, I'm pretty new with Drupal so the answer here is probably pretty straight-forward)

Where to continue?

# Answer
There are some Views JSON modules if you look around, but I typically do this outside of views itself. And you are correct, you are halfway there.

You want to wire up a `hook_menu()` to create a custom path in a module. See our canonical question on this topic for more information.

Then in the menu callback, you do use `views_embed_view()`. Something like this:

```
function MYMODULE_the_callback() {
  $output = views_embed_view('nodequeue_1', 'the_display');

  print drupal_json($output);
  exit;
}

```

You can also use the `$view` object directly:

```
function MYMODULE_the_callback() {
  $view = views_get_view('nodequeue_1');
  $view->set_display('the_display');
  $view->pre_execute();
  $view->execute();

  $output = $view->render();

  print drupal_json($output);
  exit;
}

```

Using the later form, you can poke through the `$view` object and tailor your JSON accordingly.

This should give you a head start.

Keep in mind as you research this, that the plumbing is a little different for rendering JSON in Drupal 6 vs 7. In 7, you would use `drupal_json_output()` and `drupal_exit()`;
> 2 votes

---
Tags: nodes, 6, feeds
---


# Question
Title: Appropriate theme function for alter specific field for a view
I have used a view in my drupal.

In this view, I have used an "add to cart button" field.

In my theme, I am searching for a theme function in order to alter this field. For example want to remove css classes from this button and add another attributes to it.

what is the suitable theme\_function in order to achieve this goal?

# Answer
> 0 votes
Fences should be the answer of your problem: https://drupal.org/project/fences

Or you could create a template for this view-field: https://drupal.org/node/352970

---
Tags: theming, forms
---


title: Has Pressflow 6 been discontinued?

text:
# Question
Title: Has Pressflow 6 been discontinued?
There is a week since Drupal 6.30 is released to fix some XSS vulnerability, but Pressflow is still on 6.29.

I am wondering if it is discontinued. If so, are there any new forks that up to date?

# Answer
There are a few questions here:

## What was the timeline of events for the 6.30 release of core and Pressflow?

## Why isn't there news about Pressflow 6?

Well, it depends on where you want to go to get news and what your expectation is. Drupal 6 and Pressflow 6 are pretty slow in terms of news. They are stable except for these security updates. I think it's reasonable that the promotion/updates about it are minimal beyond what is necessary for development. If you want to know what's going on (including the sate of the last release) check the issues and pull requests. And if you went there on January 15th you'd see a pull request that you could try out to get the security update and help in the process of releasing the next version by providing a review.

## Will there be timely updates moving forward?

Peter Wolanin (and Gabor Hojtsy, I'm told) are now able to commit changes to the Pressflow repository on github. It seems likely that they are interested in Pressflow because many of the users of Pressflow are clients of Acquias. Peter and Gabor are both Security Team members (and Gabor a D6 maintainer) who stay aware of the core security releases. So, I think it's safe to say that updates will flow more quickly in the future.
> 4 votes

# Answer
No, it is still being kept up to date, but it will always take a few days after an official Drupal core release before Pressflow is updated as they are making sure that new changes don't interfere with the Pressflow code in core. From the FAQ:

> When there is a new version of Drupal, does Pressflow also get updated?
>
> "Yes! All patches and security updates provided for both Drupal 6 and 7 are also be applied to Pressflow 6 and 7. We will release updates to Pressflow in a few days after they are available on Drupal.org."
> 1 votes

---
Tags: 6
---


# Question
Title: Do All Drupal themes support subtheming?
I heard that only some themes can have a subtheme. Is this true?

# Answer
> 4 votes
No, of course it isn't true. **All themes can be subthemed.** Subtheming is a part of Drupal's core and themes cannot simply turn it down. You can always create a theme, name it's parent theme and override some CSS.

Fun starts when you want to override things from template.php, or if parent theme provides advanced configuration - not all themes are built in a way that makes subtheming **easy**. But even if it's not easy, it's not really blocked.

---
Tags: 7, theming
---


# Question
Title: Attaching a system js library using #attached property (D7)
When defining a form using the form api I can attach my own css and js like this:

```
$form['#attached']['css'] = array(
    drupal_get_path('module', 'my_module') . '/my_css_file.css',
);
$form['#attached']['js'] = array(
    drupal_get_path('module', 'my_module') . '/my_js_file.js',
);

```

This page on Drupal.org suggests that we can attach system libraries the same way and gives this example:

```
$form['#attached']['library'][] = array('system', 'jquery.cookie');

```

However when I add this line to my form:

```
$form['#attached']['library'][] = array('ui.droppable');

```

Then the library does not get added.

If I go with the old method of:

```
drupal_add_library('system', 'ui.droppable');

```

Then is does get added.

What am I doing wrong?

# Answer
> 12 votes
Going from the working example, I imagine this is what you need:

```
$form['#attached']['library'][] = array('system', 'ui.droppable');

```

Without the module name Drupal won't know where to find the library hooks.

But if you want to add a custom library from `sites/all/libraries/myAwesomeLibrary` this is the right way:

```
$form['#attached']['libraries_load'][] = array('myAwesomeLibrary');

```

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


# Question
Title: Let users choose from pre-defined user set options for creating a node
I want to provide the ability for users to make and save a set of pre-defined options when they create a node.

They can then choose from their predefined set of options when creating future nodes.

(At the moment I allow users to create nodes with a custom form, I could possibly switch to the standard add node method but I'd prefer not to, unless it's a lot easier.)

Has anyone on here tried this before? At a high level, how did you go about trying to save user presets?

# Answer
I find using a custom form always seems to be more work then just using the one Drupal provides to add nodes. Even if they are not quite what you want hook\_form\_alter makes it easy to modify them to suit your needs.

I would create an unpublished node for each of my 'presets'. This way it is easy for an administrator to update the preset values, but normal user won't be able to see them.

Then using hook\_form\_alter I would add a selectbox to the top of the node add form allowing the users to choose between any of the presets. You could add an #ajax property to the selectbox that rebuilds the whole form.

Again in hook\_form\_alter if $form\_state\['values'\]\['yourselectbox'\] is not empty then you can load the values from that node and populate the form with them.

As an example (none of this code is tested but I think should be almost right):

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

    $templates = db_query("SELECT nid, title FROM node WHERE type='my_type' AND status=1")->fetchAllKeyed();
    // TODO: Should maybe add a field to control if this node is a template or not?
    $default_template = 0;

    if(!empty($form_state['values']['templates'])) {
        $default_template = $form_state['values']['templates'];

        $selected_template = node_load($default_template);

        // if your fields have multiple values you will need to loop here
        $form['other_field_1'][LANGUAGE_NONE][0]['#value'] = $selected_template['other_field_1'][LANGUAGE_NONE][0]['#value']
        $form['other_field_2'][LANGUAGE_NONE][0]['#value'] = $selected_template['other_field_2'][LANGUAGE_NONE][0]['#value']

    }

    $form['#prefix'] = '<div id="whole_form_wrapper">';
    $form['#suffix'] = '</div>';

    $form['templates'] = array(
        '#type' => 'select',
        '#title' => 'Template',
        '#options' => $templates,
        '#default_value' => $default_template,
        '#ajax' => array(
            'callback' => 'change_template_callback',
            'wrapper' => 'whole_form_wrapper',
            'event' => 'change',
        ),
    );

}

function change_template_callback($form, $form_state) {
    return $form;
}

```

See the examples module - it has loads of good stuff on forms and ajax.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Drupal Commerce: Set Order as Paid in Full
I am trying to import records from a CSV file (from another non-drupal database) for a membership site I am porting to Drupal 7. I have Drupal Commerce, Commerce Recurring Framework set up. Everything works as it should when you go through the proper work flow. However, I have 2000+ records that need to be added to the site and going through that process doesn't make sense. In other words, I am writing a script to set up the order and then recurring entity for each user.

I have code that creates my order, the issue is that Commerce is looking for a payment to be made before it creates the recurring entity for the order. Again, that doesn't make sense from a time perspective, not to mention all of these members have already paid as these are being ported. So my question is how to I trigger the order paid in full event that will trigger the creation of the recurring entity being created? Or is there a way to just create the recurring entity?

Here is my code:

```
<?php
foreach ($records as $record) {
$product_sku = $record['sku'];

$order = commerce_order_new($user->uid, 'completed');

commerce_order_save($order);

$product = commerce_product_load_by_sku($product_sku);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

commerce_line_item_save($line_item);

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

commerce_order_save($order);
}
?>

```

Thanks, Aaron

# Answer
> 2 votes
If you want to trigger the paid in full event you just need to make the order balance 0. You can do that by adding a payment transaction for the full amount to the order. The event is then triggered when that new successful transaction is saved.

The relevant Commerce function is

`commerce_payment_commerce_payment_transaction_insert`

```
/**
 * Implements hook_commerce_payment_transaction_insert().
 *
 * When a new payment transaction is inserted that is already completed, check
 * the order balance and invoke a Rules event if the order is paid in full.
 */
function commerce_payment_commerce_payment_transaction_insert($transaction) {
  // If the inserted transaction was marked as a success and placed against a
  // valid order...
  if ($transaction->status == COMMERCE_PAYMENT_STATUS_SUCCESS &&
    $order = commerce_order_load($transaction->order_id)) {
    // Then check to make sure the event hasn't been invoked for this order.
    if (empty($order->data['commerce_payment_order_paid_in_full_invoked'])) {
      // Check the order balance and invoke the event.
      $balance = commerce_payment_order_balance($order);

      if ($balance['amount'] <= 0) {
        // Invoke the event including a hook of the same name.
        rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);

        // Update the order's data array to indicate this just happened.
        $order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

        // Save the updated order.
        commerce_order_save($order);
      }
    }
  }
}

```

The key part is here:

```
// Invoke the event including a hook of the same name.
rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);
// Update the order's data array to indicate this just happened.
$order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

// Save the updated order.
commerce_order_save($order);

```

In any case, you'll need to create a valid transaction for the order to trigger the `commerce_payment_order_paid_in_full` event. Rules reacting to that event will expect the transaction object as an assumed parameter.

# Answer
> 0 votes
You can use the example from `commerce_payment_example` module e.g.

```
<?php

  commerce_checkout_complete($order);

  if ($is_cli) {
    drush_print('Marking order as fully paid...');
  }

  $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

  if (!$payment_method) {
    if ($is_cli) {
      drush_print("  No example payment method found, we can't mark order as fully paid. Please enable commerce_payment_example module to use this feature.");
    }
  }
  else {
    if ($is_cli) {
      drush_print("  Creating example transaction...");
    }

    // Creating new transaction via commerce_payment_example module.
    $charge      = $order->commerce_order_total['und'][0];

    $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
    $transaction->instance_id = $payment_method['instance_id'];
    $transaction->amount = $charge['amount'];
    $transaction->currency_code = $charge['currency_code'];
    $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    $transaction->message = 'Name: @name';
    $transaction->message_variables = array('@name' => 'Example payment');

    if ($is_cli) {
      drush_print("  Notifying Commerce about new transaction...");
    }

    commerce_payment_transaction_save($transaction);

    commerce_payment_commerce_payment_transaction_insert($transaction);

```

For full working example, please see:

Programmatically creating an order in Drupal Commerce for anonymous users redirecting to payment page

---
Tags: 7, commerce
---