# Question
Title: Setting #title or #description in node_form_alter
I have have a field of type container that is acting as a title field, see complete definintion below.

My issue is that I cannot seem to modify the title or description via form\_alter, I have tried the following approaches:

```
$form['title_field'][$language->language][0]['#title'] = $form['title_field'][$language->language][0]['#title'] . t(' (maximum @max characters)', array( '@max' => $maximum_program_title_limit));

```

And also:

```
$form['title_field'][LANGUAGE_NONE][0]['#title'] = $form['title_field'][LANGUAGE_NONE][0]['#title'] . t(' (maximum @max characters)', array( '@max' => $maximum_program_title_limit));

```

I tried both "language" options, and also tried at one higher level of the array:

```
$form['title_field'][LANGUAGE_NONE]['#title'] = $form['title_field'][LANGUAGE_NONE]['#title'] . t(' (maximum @max characters)', array( '@max' => $maximum_program_title_limit));

```

None of these take effect on the form, although other changes are actually done on the form in this same function.

```
Array
(
    [#type] => container
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => field-type-text
                    [1] => field-name-title-field
                    [2] => field-widget-text-textfield
                )

        )

    [#weight] => -5
    [#tree] => 1
    [#language] => und
    [und] => Array
        (
            [0] => Array
                (
                    [#entity_type] => node
                    [#entity] => stdClass Object
                        (
                            [vid] => 27
                            [uid] => 1
                            [title] => program 2-11
                            [log] =>
                            [status] => 1
                            [comment] => 0
                            [promote] => 0
                            [sticky] => 0
                            [nid] => 13
                            [type] => program
                            [language] => und
                            [created] => 1440515144
                            [changed] => 1440515144
                            [tnid] => 0
                            [translate] => 0
                            [revision_timestamp] => 1440515144
                            [revision_uid] => 1
                            [body] => Array
                                (
                                )

                            [field_ambassadeurs_ambassadors] => Array
                                (
                                )

                            [field_organization_organisation] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [target_id] => 2
                                                )

                                        )

                                )

                            [field_participant_reg] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [registration_type] => participant_participante
                                                )

                                        )

                                )

                            [field_prog_attachment] => Array
                                (
                                )

                            [field_program_template_ref] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [target_id] => 11
                                                )

                                        )

                                )

                            [title_field] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [value] => program 2-11
                                                    [format] =>
                                                    [safe_value] => program 2-11
                                                )

                                        )

                                )

                            [title_original] => program 2-11
                            [translations] => stdClass Object
                                (
                                    [original] =>
                                    [data] => Array
                                        (
                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                    [rdftype] => Array
                                        (
                                            [0] => sioc:Item
                                            [1] => foaf:Document
                                        )

                                    [title] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => dc:title
                                                )

                                        )

                                    [created] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => dc:date
                                                    [1] => dc:created
                                                )

                                            [datatype] => xsd:dateTime
                                            [callback] => date_iso8601
                                        )

                                    [changed] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => dc:modified
                                                )

                                            [datatype] => xsd:dateTime
                                            [callback] => date_iso8601
                                        )

                                    [body] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => content:encoded
                                                )

                                        )

                                    [uid] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => sioc:has_creator
                                                )

                                            [type] => rel
                                        )

                                    [name] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => foaf:name
                                                )

                                        )

                                    [comment_count] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => sioc:num_replies
                                                )

                                            [datatype] => xsd:integer
                                        )

                                    [last_activity] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => sioc:last_activity_date
                                                )

                                            [datatype] => xsd:dateTime
                                            [callback] => date_iso8601
                                        )

                                )

                            [name] => admin
                            [picture] => 0
                            [data] => b:0;
                            [date] => 2015-08-25 17:05:44 +0200
                            [revision] => 1
                            [menu] => Array
                                (
                                    [link_title] =>
                                    [mlid] => 0
                                    [plid] => 0
                                    [menu_name] => main-menu
                                    [weight] => 0
                                    [options] => Array
                                        (
                                        )

                                    [module] => menu
                                    [expanded] => 0
                                    [hidden] => 0
                                    [has_children] => 0
                                    [customized] => 0
                                    [parent_depth_limit] => 8
                                )

                        )

                    [#bundle] => program
                    [#field_name] => title_field
                    [#language] => und
                    [#field_parents] => Array
                        (
                        )

                    [#columns] => Array
                        (
                            [0] => value
                            [1] => format
                        )

                    [#title] => Additional title ( optional ) (maximum 50 characters)
                    [#description] => This field is optional, any text entered here will be added  between parenthesis after the default program title shown above. (maximum 50 characters)
                    [#required] =>
                    [#delta] => 0
                    [#weight] => 0
                    [value] => Array
                        (
                            [#entity_type] => node
                            [#entity] => stdClass Object
                                (
                                    [vid] => 27
                                    [uid] => 1
                                    [title] => program 2-11
                                    [log] =>
                                    [status] => 1
                                    [comment] => 0
                                    [promote] => 0
                                    [sticky] => 0
                                    [nid] => 13
                                    [type] => program
                                    [language] => und
                                    [created] => 1440515144
                                    [changed] => 1440515144
                                    [tnid] => 0
                                    [translate] => 0
                                    [revision_timestamp] => 1440515144
                                    [revision_uid] => 1
                                    [body] => Array
                                        (
                                        )

                                    [field_ambassadeurs_ambassadors] => Array
                                        (
                                        )

                                    [field_organization_organisation] => Array
                                        (
                                            [und] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [target_id] => 2
                                                        )

                                                )

                                        )

                                    [field_participant_reg] => Array
                                        (
                                            [und] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [registration_type] => participant_participante
                                                        )

                                                )

                                        )

                                    [field_prog_attachment] => Array
                                        (
                                        )

                                    [field_program_template_ref] => Array
                                        (
                                            [und] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [target_id] => 11
                                                        )

                                                )

                                        )

                                    [title_field] => Array
                                        (
                                            [und] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [value] => program 2-11
                                                            [format] =>
                                                            [safe_value] => program 2-11
                                                        )

                                                )

                                        )

                                    [title_original] => program 2-11
                                    [translations] => stdClass Object
                                        (
                                            [original] =>
                                            [data] => Array
                                                (
                                                )

                                        )

                                    [rdf_mapping] => Array
                                        (
                                            [rdftype] => Array
                                                (
                                                    [0] => sioc:Item
                                                    [1] => foaf:Document
                                                )

                                            [title] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => dc:title
                                                        )

                                                )

                                            [created] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => dc:date
                                                            [1] => dc:created
                                                        )

                                                    [datatype] => xsd:dateTime
                                                    [callback] => date_iso8601
                                                )

                                            [changed] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => dc:modified
                                                        )

                                                    [datatype] => xsd:dateTime
                                                    [callback] => date_iso8601
                                                )

                                            [body] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => content:encoded
                                                        )

                                                )

                                            [uid] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => sioc:has_creator
                                                        )

                                                    [type] => rel
                                                )

                                            [name] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => foaf:name
                                                        )

                                                )

                                            [comment_count] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => sioc:num_replies
                                                        )

                                                    [datatype] => xsd:integer
                                                )

                                            [last_activity] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => sioc:last_activity_date
                                                        )

                                                    [datatype] => xsd:dateTime
                                                    [callback] => date_iso8601
                                                )

                                        )

                                    [name] => admin
                                    [picture] => 0
                                    [data] => b:0;
                                    [date] => 2015-08-25 17:05:44 +0200
                                    [revision] => 1
                                    [menu] => Array
                                        (
                                            [link_title] =>
                                            [mlid] => 0
                                            [plid] => 0
                                            [menu_name] => main-menu
                                            [weight] => 0
                                            [options] => Array
                                                (
                                                )

                                            [module] => menu
                                            [expanded] => 0
                                            [hidden] => 0
                                            [has_children] => 0
                                            [customized] => 0
                                            [parent_depth_limit] => 8
                                        )

                                )

                            [#bundle] => program
                            [#field_name] => title_field
                            [#language] => und
                            [#field_parents] => Array
                                (
                                )

                            [#columns] => Array
                                (
                                    [0] => value
                                    [1] => format
                                )

                            [#title] => Additional title ( optional )
                            [#description] => This field is optional, any text entered here will be added  between parenthesis after the default program title shown above.
                            [#required] =>
                            [#delta] => 0
                            [#weight] => 0
                            [#type] => textfield
                            [#default_value] => program 2-11
                            [#size] => 60
                            [#maxlength] => 60
                            [#attributes] => Array
                                (
                                    [class] => Array
                                        (
                                            [0] => text-full
                                        )

                                    [maxlength_js_label] => Array
                                        (
                                            [0] => Content limited to @limit characters, remaining: <strong>@remaining</strong>
                                        )

                                )

                            [#maxlength_js] => 1
                        )

                    [#maxlength] => 50
                    [#maxlength_js] => 1
                    [#attributes] => Array
                        (
                            [maxlength_js_label] => Array
                                (
                                    [0] => Content limited to @limit characters, remaining: <strong>@remaining</strong>
                                )

                        )

                    [#prefix] => <div id="title_prefix"><strong>Default program title:</strong> template 1</div>
                )

            [#theme] => field_multiple_value_form
            [#field_name] => title_field
            [#cardinality] => 1
            [#title] => Additional title ( optional ) (maximum 50 characters)
            [#required] => 0
            [#description] => This field is optional, any text entered here will be added  between parenthesis after the default program title shown above. (maximum 50 characters)
            [#prefix] => <div id="title-field-add-more-wrapper">
            [#suffix] => </div>
            [#max_delta] => 0
            [#after_build] => Array
                (
                    [0] => field_form_element_after_build
                )

            [#language] => und
            [#field_parents] => Array
                (
                )

            [#maxlength] => 1
            [#maxlength_js] => 1
            [#attributes] => Array
                (
                    [maxlength_js_label] => Array
                        (
                            [0] => Content limited to @limit characters, remaining: <strong>@remaining</strong>
                        )

                )

        )

    [#access] => 1
)

```

I would like to know what is missing for this form\_alter to work as should?

# Answer
> 2 votes
The form element itself is a bit further down the array:

```
$form['title_field'][LANGUAGE_NONE][0]['value']['#title']

```

See Why is hook\_form\_alter() so messy? for a bit of background

---
Tags: forms
---


title: Using NOT LIKE in db condition?

text:
# Question
Title: Using NOT LIKE in db condition?
I don't see an example when looking at the api. I'm setting up a query and would like to use `NOT LIKE` as opposed to `STARTS` since `START` does not seem to be supported.

Is this possible?

# Answer
Add this snippet to your query item:

```
$query->condition(X, Y, 'NOT LIKE');

```

where `X` and `Y` are two variables. You can also replace each of them with constants.
> 5 votes

---
Tags: views, database
---


title: Straight to checkout with commerce

text:
# Question
Title: Straight to checkout with commerce
So I have created a product in Commerce: a £15 one-off donation.

I don't need a product page for this (I have a custom block with links for different donation amounts). When you click a link, I want to use the product ID, and push the product straight to checkout.

How would I go about this?

# Answer
> 3 votes
The way to programatically add a product to the cart and send a user to checkout would be to use the function:

```
function commerce_cart_product_add_by_id**($product_id,
                        $quantity = 1, $combine = TRUE, $uid = NULL)

```

and

```
function drupal_goto**($path = '', array $options = array(),
       $http_response_code = 302)

```

to redirect the user to checkout.

Here is information on the functions:

# Answer
> 0 votes
This question popped updated because of being edited and I thought I would share how to do to this via module. I wrote a custom module to do just this because we have a lot of direct marketing and I often need the ability to throw someone directly into a checkout process via URL. This module takes a URL constructed of the SKU and the quantity and puts the customer into a checkour process. The URL is http://www.example.com/product/add/SKU/QUANTITY. As an example SKU 101 at a quantity of 2 would be:

```
http://www.example.com/product/add/101/2

```

Here is the module: https://github.com/taz77/drupal-add-to-cart-url

---
Tags: 7, commerce
---


# Question
Title: How do I create a directory in webform for uploaded files
I wanted to use the 'file' field type in webform for file submission on my website, but I was getting this error message:

> The save directory could not be created. Check that the webform files directory is writable.

Any suggestions?

# Answer
First go to `"Administer -> Site Configuration -> File System -> File System Path"` configuration page. verify your file path and temp path given no error.

change permissions(writable) to files folder under "sites/default/files".
> 2 votes

# Answer
If you are Linux user go to your files directory and type the following command:

`chmod -R 0777` .
> 0 votes

# Answer
if webserver user does not owns filesystem then use 775 at most
> 0 votes

---
Tags: webforms
---


# Question
Title: How to add 2 string of code together for views in custom module?
I have a view that needs these 2 lines of code:

```
 if($form_id == "views_exposed_form" && $form['#id'] == 'views-exposed-form-hide-tweaked-advanced')

```

and

```
if($form_id == "views_exposed_form" && $form['#id']=='views-exposed-form-hide-tweak-basic')

```

function:

```
<?php
 function dropdowninteger_form_alter(&$form, &$form_state, $form_id){
  if($form_id == "views_exposed_form" && $form['#id']=='views-exposed-form-hide-tweaked-advanced'){
     $options = array('1' => '1', '2'=>'2');
     $form['field_user_age_value']['#type'] ='select';
     $form['field_user_age_value']['#size'] = null;
     $form['field_user_age_value']['#default_value'] = '';
     $form['field_user_age_value']['#options'] = $options;
  }
}

```

How do I add them together for my custom module? Not sure if my question is clear enough though....

# Answer
This is how I usually set up my views functions:

```
function dropdowninteger_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'views_exposed_form') {
    switch ($form['#id']) {
      case 'views-exposed-form-hide-tweaked-advanced':
        <tweaked-advanced code here>;
        break;
      case 'views-exposed-form-hide-tweak-basic':
        <tweak-basic code here>;
        break;
    }
  }
}

```
> 0 votes

---
Tags: views
---


title: Custom redirects and Drush/updates

text:
# Question
Title: Custom redirects and Drush/updates
I usually update Core with Drush, because it's so easy and wonderful, but I have a custom htaccess and it always overwrites it, forcing me to rely on a checklist where I have to go and put my custom one back in. Is there a way I can either tell Drush not to overwrite it when updating or automatically put the custom one back in with a bash script or something? Or should I use a module to do these redirects instead? They are all like this and are a legacy from when our main company website hosted some custom apps:

RedirectMatch 301 ^/blah/ blah blah.cgi http://anotherwebsite.com/cgi-bin/blah.cgi

# Answer
> 5 votes
Short of support directly in Drush, this is what I would recommend.

Keep your site in a structure something like this:

* srv
* . www
* . . mysite.com
* . . . .git
* . . . custom-htaccess
* . . . custom-robots.txt
* . . . htdocs
* . . . . .htaccess
* . . . . robots.txt
* . . . . ... other files in the Drupal root

I like to structure my Drupal files as shown above so that I have a place to keep files in the same git repository as my Drupal files without exposing them to the webserver (or worrying about hiding them from the webserver with custom .htaccess rules).

If you keep all of your customizations to .htaccess and robots.txt in separate files like this, it would be an easy thing to concatenate them on the end of the corresponding Drupal core files. This structure might be a good starting point for a formal Drush feature that does the same thing.

**Update:** If you are not on shared hosting, you'll do much better to store your .htaccess customization on the Apache vhost conf file, and leave Drupal's .htaccess file unmodified. The syntax of this file is about the same as the .htaccess file. The first step is to find the right file; it's often in /etc/apache2/vhost.d or /etc/httpd/vhost.d, although on Debian distros such as Ubuntu it is in /etc/apache2/sites-available. Apache configuration is not a Drupal-specific topic; there's a lot of info about it available on the Internet.

# Answer
> 0 votes
Another solution here is using the htaccess module to maintain your configurations outside the file. The module stores different htaccess profiles and lets you deploy them as you need it. Each profile contains options (e.g. www or no-www redirect) and a list of htaccess directives, helpful when you have a litany of legacy URLs to redirect.

---
Tags: drush, updating
---


title: remote DB for remote servers with Aegir

text:
# Question
Title: remote DB for remote servers with Aegir
I am working to install Aegir on an AWS EC2 instance (Amazon AMI) using an RDS mysql database. So basically a virtual box with a remote DB server. I am using the manual procedure and am running into problems at the hostmaster-install phase. The remote mysql server is correctly identified and the logon is accepted but the install fails. Here is the command I am running:

### **drush hostmaster-install --aegir\_db\_user="root" --aegir\_db\_host="the\_FQDN\_of\_the\_remote\_DB\_server"**

Install starts great but the starts giving warnings and errors which obviously have to do with problems running MySQL commands. Here is a small excerpt:

MySQL server has gone away \[warning\] query: SELECT filename FROM system WHERE name = 'jquery\_ui' AND type = 'module' database.mysqli.inc:134

MySQL server has gone away \[warning\] query: CREATE TABLE variable ( `name` VARCHAR(128) NOT NULL DEFAULT '', `value` LONGTEXT NOT NULL, PRIMARY KEY (name) ) /\*!40100 DEFAULT CHARACTER SET utf8 \*/ database.mysqli.inc:134

I noticed that the database was not created, so any table attempts will also fail. The question is why is the database not created? I am not getting any clear output indicating this. I ran the command with the --debug option, but did not get any additional information to point out why it is failing.

Amazon Web Services (AWS) RDS service does put some limitations on the "root" user. For instance it does not have the "SUPER" privilege and also does not have the "CREATE TABLE SPACE" privilege. Could these be a reason fro the failure?

Where can I see what exact SQL commands are being run? I would like to try and run them manually to debug this issue.

Of course if anyone out there has successfully installed directly on to AWS with RDS as a remote DB, I'd love to know how.

Thanks, Eric

# Answer
You're getting the error "MySQL server has gone away". Usually when this happens during Drupal installation, it's related to MySQL's max\_allowed\_packet setting. I'd recommend bumping that value up to 32MB. The process for changing that value on Amazon RDS is detailed here: https://survivalguides.wordpress.com/2012/02/02/change-the-max\_allowed\_packet-amazon-rds/
> 2 votes

---
Tags: 7, aegir
---


title: Aegir and SA-CORE-2014-005

text:
# Question
Title: Aegir and SA-CORE-2014-005
**Case:**

```
- Aegir server 2.1 on Drupal 6.31
-- Platform Hostmaster: Drupal 6.31
--- Hostmaster: ?
-- Platform 1: Drupal 7.31
--- Site 1: HACKED
--- Site 2: HACKED
-- Platform 2: Drupal 7.32
--- Site 3: ?
--- Site 4: ?

```

**Actions:**

* So the attackers get access on site 1 + site 2 using the SA-CORE-2014-005.
* Platforms 1 and sites 1 and site 2 totally deleted or restored from an old backup and then updated (files and db).

**Questions:**

1. Is there a case that the hackers gain access on Hostmaster or on sites 3 and site 4?
2. Or even worst… the hackers gain that level of access on the server that can compromise a new Aegir install?

# Answer
1. If site 1 and 2 are compromised, it's entirely possible that sites 3 and 4 are either in danger of being compromised or have already been compromised.
2. More or less, yes. If they already have sites 1 and 2, it's extremely likely that they can directly access your server.

You should consider your current server and the sites running on it as tainted and rebuild from scratch. Despite @Clive's assertion, there is no user account sandboxing happening at the per-site level.
> 1 votes

---
Tags: security, aegir
---


# Question
Title: add/change div wrapper around specific radio button?
By default, the HTML markup for radio buttons looks like (Drupal 7):

```
<div class="form-item form-type-radio form-item-SOME_ID">
  <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
  <label class="option" for="edit-bla-bla">MY LABEL</label>
</div>

```

I need to change/add some css classes in the outer `<div>` OR add a wrapper `<div>`. How do I do that?

# Answer
If you're defining the form yourself you can wrap an element with HTML using the `#prefix` and `#suffix` properties:

```
$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Options',
  '#options' => drupal_map_assoc(1, 2, 3),
  '#prefix' => '<div class="some-class">',
  '#suffix' => '</div>'
);

```

If you want to add a class to the existing wrapper you can do so using the `#attributes` property:

```
$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Options',
  '#options' => drupal_map_assoc(1, 2, 3),
  '#attributes' => array(
    'class' => array('some-class')
  )
);

```

If you're not defining the form yourself then you can still use the same logic and implement a `hook_form_alter()` to change the existing form:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'some_form_id') {
    $form['some_element']['#attributes']['class'][] = 'some-class';
  }
}

```

Note that when using the `hook_form_alter()` method you should append to the existing classes array so as not to override any classes that have been set previously.
> 9 votes

# Answer
I was able to achieve this after much work and trying every posted method using a smart tip I found deep in the internet on another site: http://e9p.net/altering-individual-radio-or-checkbox-items-drupal-7-fapi, to use `#after_build` to be able to alter the form element individual radios once they are a drupal render array.

I wanted each radio wrapped in a container with a class, so I used `#prefix` and `#suffix` to do that:

```
function _MYMODULE_options_after_build(&$element, &$form_state){
    // Each renderable radio element.
    foreach (element_children($element) as $key) {
        $element[$key]['#prefix'] = '<div class="class1 class2">';
        $element[$key]['#suffix'] = '</div>';
    }
    // Always return the element to render in after_build callbacks.
    return $element;
}

```

example use:

```
$form['style'] = array(
        '#type' => 'radios',
        '#title' => t('Select your style option'),
        '#options' => $style_options,
        '#default_value' => NULL,
        '#required' => TRUE,
        '#after_build' => array(
            '_MYMODULE_options_after_build'
        )
);

```

However if you only want the `input` element to have the class you would need to implement the solution I posted on drupal.org at https://api.drupal.org/comment/60197#comment-60197 to allow the #options\_attributes to be used correctly for individual options. Re-posting code here:

```
function MYMODULE_element_info_alter(&$info) {
    // You might want more advanced logic here, to replace instead of override altogether,
    // in case other modules have already altered the core info.
    $info['radios']['#process'] = array('safetycal_request_a_quote_process_radios');
}

function MYMODULE_process_radios($element) {
    // for some reason when I take over processing the radios the structure
    // is slightly different than with form_process_radios and it needs to be fixed
    if(isset($element['element'])){
        $element = $element['element'];
    }
    if (count($element ['#options']) > 0) {
        $weight = 0;
        foreach ($element ['#options'] as $key => $choice) {
            // Maintain order of options as defined in #options, in case the element
            // defines custom option sub-elements, but does not define all option
            // sub-elements.
            $weight += 0.001;

            $element += array($key => array());
            // Generate the parents as the autogenerator does, so we will have a
            // unique id for each radio button.
            $parents_for_id = array_merge($element ['#parents'], array($key));
            $element [$key] += array(
                '#type' => 'radio',
                '#title' => $choice,
                // The key is sanitized in drupal_attributes() during output from the
                // theme function.
                '#return_value' => $key,
                // Use default or FALSE. A value of FALSE means that the radio button is
                // not 'checked'.
                '#default_value' => isset($element ['#default_value']) ? $element ['#default_value'] : FALSE,
                // changed below line to use the #options_attributes array
                '#attributes' => $element['#option_attributes'][$key],
                '#parents' => $element ['#parents'],
                '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
                '#ajax' => isset($element ['#ajax']) ? $element ['#ajax'] : NULL,
                '#weight' => $weight,
            );
        }
    }
    return $element;
}

```

example use:

```
$style_options = array(
    'red' => 'Red',
    'green' => 'Green',
    'yellow' => 'Yellow'
);
$style_option_attributes = array(
    'red' => array(
        'class' => array(
                'red-class'
            )
    ),
    'green' => array(
        'class' => array(
                'green-class'
            )
    ),
    'yellow' => array(
        'class' => array(
                'yellow-class'
            )
    )
);
$form['style'] = array(
    '#type' => 'radios',
    '#title' => t('Select your style option'),
    '#options' => $style_options,
    '#option_attributes' => $style_option_attributes,
    '#default_value' => NULL,
    '#required' => TRUE,
    '#attributes' => array(
        'class' => array(
            'radio-element-class'
        )
    )
 );

```
> 1 votes

# Answer
You can do the above(prefix/suffix) on the items in the options array then you get anything you want around each item.

```
$form['view_mode'] = array(
    '#type' => 'radios',
    '#default_value' => isset($_GET['view'])?$_GET['view']:1,
    '#options' => array(
          1 => '1',
          2 => '2',
          3 => '3',
    ),
  ),
);
$form['view_mode'][1] = array(
    '#prefix' => '<div class="first-item container">',
    '#suffix' => '</div>'
);

```
> 0 votes

# Answer
The only way I have been able to achieve this is by creating a different form element for each radio, manually pairing up the names using #name and manually setting a value using #attributes. (#value doesn't work for some reason.)

For example:

```
$form['apple'] = array(
  '#type' => 'radio', // Notice no s here; 'radio' not 'radios'
  '#name' => 'fruit', // This will ensure the radios are in the same group
  '#attributes' => array(
       'value' => 'apple', // I know this is bad but it's the only way I could get setting a value to work
       'class' => 'class_here' // This will add class_here to the default wrapper
   ),
  '#prefix' => '<div class="some-class">', // This will prefix the individual radio, wrapper and label
  '#suffix' => '</div>' // This will suffix the individual radio, wrapper and label
);

// Then just repeat with different values

$form['orange'] = array(
  '#type' => 'radio',
  '#name' => 'fruit', // Same name
  '#attributes' => array(
       'value' => 'orange', // Different value
       'class' => 'class_here'
   ),
  '#prefix' => '<div class="some-class">',
  '#suffix' => '</div>'
);

$form['banana'] = array(
  '#type' => 'radio',
  '#name' => 'fruit', // Same name
  '#attributes' => array(
       'value' => 'banana', // Different value
       'class' => 'class_here'
   ),
  '#prefix' => '<div class="some-class">',
  '#suffix' => '</div>'
);

```

This will add a wrapper and class to the individual radio buttons rather than the radio group as the currently accepted answer does.
> 0 votes

---
Tags: 7, theming, forms
---


# Question
Title: How to show Users and Nodes in a single view?
Using the Flag module I have created a bookmark flag for User and Node entities. Working so far so good, but I cannot create a view that displays both Node and User entities in one view.

How do I do this without having to dump views and hand-create the page in PHP?

# Answer
> 0 votes
One option is to add a user view as a footer to the node view. The footer can be configured to inherit the same contextual filters as the main view.

You can't get joint paging or joint filtering using this approach but it works in some scenarios.

I've also hacked into the views hooks before and manually created a db join but that is a nightmare to maintain so I wouldn't recommend it.

---
Tags: views, flags
---


# Question
Title: Choose specific format for hms field token
I'm using a token to include an hms field in an email sent with Rules. I'd like to include the hms field in the format `m:ss`, but it's displaying as seconds.

I've tried enabling the custom display setting "Tokens" in the Manage Display tab for the specific Entity containing the field, and choosing the `m:ss` format there, without luck.

# Answer
To answer my own question: I succeeded in showing the correct formatting as `m:ss` by enabling the module Token and using this token (with low hyphens) `[entityform:field_length]` instead of `[entityform:field-length]`.
> 0 votes

---
Tags: 7, rules, tokens
---


# Question
Title: How to include CSS for a custom admin theme?
I want to include my custom **style.css** in **admin pages** in Custom Admin theme I have been create.
I am including CSS in **.info** file as follows

```
name = Example Module
description = Custom Example Module
core = 7.x
configure = admin/config/example-module/settings
permissions = admin/people/permissions#module-example-module
stylesheets[all][] = css/style.css

```

and I used `mymodule_preprocess_page(&vars)` , but I didn't see any result.

# Answer
> 2 votes
You can add **yourstyl.css** in admin theme's **.info** file. Just goto your active admin theme, find and open its **.info** file and place a simple line here; **stylesheets\[ \] = css/yourstyle.css** . It works like a charm.

# Answer
> 1 votes
When I look at your `.info` file I see it is **Custom Module** instead **Custom Theme**

```
name = Example Module
description = Custom Example Module
core = 7.x
configure = admin/config/example-module/settings
permissions = admin/people/permissions#module-example-module
stylesheets[all][] = css/style.css

```

Instead adding Style to **module info file** add it to **theme info file** in your `themename.info` add `stylesheets[all][] = css/style.css`

# Answer
> 0 votes
I misunderstood your question. It's not about a core admin theme. It's about a custom admin theme you created. Then of course you add that CSS from your custom admin theme's `.info` file.

Otherwise, if it's a core admin theme you'ld write a simple custom module or add the following to an existing custom module. All you need to implement is `hook_page_build()` and then add your own CSS file with `drupal_add_css()`. The **important** thing there is to add `'group' => CSS_THEME` as an option to prevent the styles from getting overwritten.

```
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {
  // check current path
  if (path_is_admin(current_path())) {
    // add CSS
    drupal_add_css(drupal_get_path('module', 'MYMODULE') . '/css/custom_admin.css', array('group' => CSS_THEME));
  }
}

```

# Answer
> -2 votes
Try **drupal\_add\_css()** function in your template file.

---
Tags: theming, .info
---


# Question
Title: how to create Views exposed filter with fields from custom table
I have one of custom table with fields named `title` and `id`. Now I want to add the title field in views exposed filter as drop down.

How to create exposed filter for this?

Could anyone explain where I can find this?

# Answer
> 1 votes
It should depend on how you are exposing the field to views, make sure views know about field and filter handler, so as an example in your hook\_views\_data() your title field should be exposed in following way -

```
// name field
$data['exposed']['title'] = array(
    'title' => t('Title'),
    'help' => t('title for record'),
    'field' => array(
        'handler' => 'views_handler_field',
    ),
    'filter' => array(
        'handler' => 'views_handler_filter_string',
    ),
 'sort' => array(
        'handler' => 'views_handler_sort',
    ),
);

```

---
Tags: views
---


title: How do I disable memcache?

text:
# Question
Title: How do I disable memcache?
I've inherited a site that connected with memcache even though its not necessary and its not installed on the server. Although I've disabled the memcache module, the settings file has these lines which I cannot delete or the site stops working:

```
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['cache_default_class'] = 'MemCacheDrupal';

```

I am getting this log message every two or three minutes:

> Failed to connect to memcache server: 127.0.0.1:11211

Clearing the Drupal cache and restarting Apache do not seem to fix the problem. How can I fix this?

# Answer
> 9 votes
Hi You have to follow below steps in order:

1. disable and uninstall module.
2. remove from settings.php and delete folder of module.
3. clear cache (make sure all tables are empty)

For users using drush:

```
drush dis memcache

The following extensions will be disabled: memcache
Do you really want to continue? (y/n): y

```

Thanks

---
Tags: caching
---


# Question
Title: What is the expiration time of Email verification link?
When we use the "Require email verification" in account settings for creating new accounts, does the link have an expiration time or it will last forever?

If if never expires, is is possible to add an an expiration time, preferably using a contrib module?

# Answer
The first time login link has no expiration time. Only password reset links have expiration time, which can be get or set using the system variable `user_password_reset_timeout` which has a default value of `86400` (24 hours).
> 3 votes

---
Tags: users, emails
---


title: Taxonomy exposed filter in views

text:
# Question
Title: Taxonomy exposed filter in views
I have a content type with a field 'field\_departimage' which uses entity reference to reference a taxonomy I have set up which holds the name and image.

I would like to filter by the taxonomy 'name' in views but I'm having some issues linking them

I am able to display the taxonomy but they don't seem to be linking to node to filter correctly. I'm probably doing something wrong with the contextual filters or in the relationships section.

# Answer
In views you need to add in relationship "Taxonomy term: field name" and in contextual filters you need to set "(field\_name) Taxonomy term: Name" or "(field\_name) Taxonomy term: Id".
> 0 votes

# Answer
1. Go to the content type
2. Select the field (in my case 'field\_departimage') and edit settings.
3. At the bottom, select Render Views filters as select list
> 0 votes

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


# Question
Title: Simplenews - how pass values from own input
How I can pass value from added input to database(?) in Simplenews? I want to use this value later in newsletter, e.g. print it in block template.

Below is how I created field

```
function news_hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'simplenews_block_form_2730'){
        $form['field_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First name'),
        '#required' => TRUE,
        '#size' => 20,
);
}}

```

# Answer
```
function my_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'YOUR_FORM_ID') {
    $form['field_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['field_name_submit'] = array(
      '#type' => 'submit',
      '#value' => t('SAVE'),
      '#submit' => array('my_module_name_submit'),
    );
  return $form;
  }
}

function my_module_name_submit($form,&$form_state) {
  if ($form_state['values']['field_name']) {
    variable_set('Name', $form_state['values']['field_name']);
  }
}

```

variable\_set stores textfield value in `variable table`. You can access/get this value using variable\_get as mentioned below

> variable\_get('Name')
> 0 votes

---
Tags: forms, emails
---


title: Design concern with custom tpl.php

text:
# Question
Title: Design concern with custom tpl.php
I have a custom *tpl.php* for my custom content type. As part of its content it also needs to show a (dynamic) value. The dynamic content is actually scraped from another website of ours.

My concern is, whether to have scraper logic inside `tpl.php`. My understanding is that the intention of `tpl.php` is to handle the view part.

What are the disadvantages of having my `tpl.php` to contain the logic of scraping(not just scraping. Basically anything apart from rendering)?

# Answer
> 2 votes
1. It's bad practice from a general development point of view (look up "separation of concerns")
2. It can break caching, or render it useless/pointless.
3. One bit of code should do one thing, and do it in a such a way that is testable.

In my opinion, your logic for scraping should be in its own class, a class that does nothing but scrape. Then your preprocess function should make use of that class, and prepare the variables for the template.

You don't *have* to do any of this, of course, it's up to you what best practices you want to follow. If you're new to development, take it from me that modularising your code now will probably save you a lot of time when you come back to in 2 years and something doesn't work.

---
Tags: theming
---


# Question
Title: How to get remote webpage content with drupal http request?
Would love to see some examples on getting remote webpage content with drupal http request. I have plenty of examples easily with Google with curl, but yet to find one with this drupal function.

Also, would CURL be better for getting remote content?

# Answer
> 10 votes
First, you can read the documentation about drupal\_http\_request() its pretty well documented and it will help you.

But for simple application, you can just do it like that.

```
<?php
$result = drupal_http_request('http://google.com/');
if (in_array( $result->code, array(200, 304))) {
  // Use $result->data for the content
}
else {
  // Error $result->code
}

// Also you can see all content from $result with
// if you had installed Devel Module and enable it
// dsm($result)
// or simply like that drupal_set_message('<pre>' . print_r($result, 1) . '</pre>');

```

# Answer
> 1 votes
You could also try using the Webclient module (for D7). Here is a quote about it (from the module's project page):

> This is a library module. It provides no out of the box functionality other then providing an API that other modules can use.
>
> The Webclient API is seperated into three major components:
>
> * Webclient
> * Webclient Formatters
> * Webclient Proxy

All of the above components were translated to seperate modules so that developers can create a dependency with the functionality they need.

# Answer
> 0 votes
Im using this code without any problem.

```
$base_url = 'http://route to Ws';
$data = array(
  'key' => 'foo';
  'mail' => $mail,
);

$data = drupal_json_encode($data);
$options = array(
'headers' => array(
  'Content-Type' => 'application/json',
),
'method' => 'POST',
'data' => $data
);
$response = drupal_http_request($base_url, $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->status == 'valid' {
return TRUE;
}

```

---
Tags: http-request
---


# Question
Title: Chosen module/jquery plugin not accessible on mobile devices?
I have installed the Chosen Module and was surprised to find out when viewing the page on an actual mobile device or on a desktop mobile device simulator that the Chosen menu is totally missing from the html markup and the menu items are not being displayed on the device.

Anyone know by any chance what I may be missing here? Is it possible the module only works for desktop or tablet devices?

# Answer
I just found on the Chosen jQuery documentation in the FAQ section towards the bottom they say that they have disabled the Chosen module for mobile devices by default as there are bugs with the Menu working properly on those devices. Here is a GitHub discussion about the issue.
> 1 votes

---
Tags: 7
---


# Question
Title: PDOException "column not found" but does exist
This is on Drupal 7.39 with Domain Access and Ubercart

When pressing "checkout" button the site returns and error which shows in the dblog as:

PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'uc\_payment\_method\_credit\_checkout' in 'where clause': SELECT value FROM {variable} WHERE name =uc\_payment\_method\_credit\_checkout LIMIT 0, 1; Array ( ) in uc\_domain\_variable\_get() (line 291 of /. . . /uc\_domain.module).

Line 291 of the uc\_domain\_module is:

```
$result = db_query_range("SELECT value FROM {variable} WHERE name =" . $variable, 0, 1)->fetchField();

```

The column exists in the variable table and I triple checked it for an exact format match (they all exist for the variable\_set commands I placed to be used in the install file)

This module is a Drupal 7 version module but is not an official project owned or maintained by anyone though it was originally written by the Drupal 6 project author and maintainer and released by him at https://www.drupal.org/node/946574. I am working with that released file as modified by "henk" - but this section is unchanged by "henk" either

The equivalent command in the Drupal 6 version is near identical

**D6 version starts . . .**
$result = db\_result(db\_query("SELECT value FROM {variable} WHERE name = '%s'", $variable));

**D6 version ends . . .**

I put a space in the =\> " . . . WHERE name = " . $variable . . ." to match the D6 version

But the error now simply reads " . . . WHERE name = uc\_payment\_method\_credit\_checkout . . . " with the space at "name = "

It seems to work -partly as it created an order entry in uc\_domain\_orders when i tries to test it - somehow - even though the jump to checkout failed.

This is not not like any other "column not found" issue I have searched here.

Anyone have any words of wisdom or ideas ???

# Answer
> 2 votes
Concatenating variables into an SQL query is usually a bad idea (search for SQL injection and you'll see why). The D6 version you're starting with:

```
$result = db_result(db_query("SELECT value FROM {variable} WHERE name = '%s'", $variable));

```

uses parameters, you just need to convert that to use the newer query substitution in D7. The docs for `db_query()` have some good examples, essentially what you need for this particular query is:

```
$query = 'SELECT value FROM {variable} WHERE name = :name';
$params = array(':name' => $variable);
$result = db_query($query, $params)->fetchField();

```

# Answer
> 0 votes
If you reported **exactly** both the error message and the code part, then the error is pretty "normal".

The D6 version
`"SELECT value FROM {variable} WHERE name = '%s'"`
includes simple quotes around `%s`, so the resulting query in the case you cited is
`SELECT value FROM {variable} WHERE name ='uc_payment_method_credit_checkout' LIMIT 0, 1`

At the opposite in your D7 modified version
`"SELECT value FROM {variable} WHERE name =" . $variable`
you didn't keep the quotes, so the resulting query becomes
`SELECT value FROM {variable} WHERE name =uc_payment_method_credit_checkout LIMIT 0, 1`
and without quotes SQL interprets `uc_payment_method_credit_checkout` as a column-name rather than a string.

This was only to explain why the error happens. In the other hand I totally agree with Clive recommendations.

# Answer
> 0 votes
i am not the author of any of this code; but Clive gave me the clue - while the question was on hold as off topic - so I reformulated the query to

```
 $result = db_query_range("SELECT value FROM {variable} WHERE name = :name", 0, 1, array(':name' => $variable))->fetchField();

```

Of course Clive's version works equally as well

---
Tags: 7, ubercart, domain-access
---


# Question
Title: How do I display a message after redirecting users from the logout page?
I'd like to show a message via `drupal_set_message()` after redirecting users from user/logout?destination=user.

I tested this code but it doesn't work.

```
if ($find) {
  drupal_set_message(t('This entry is ignored.'), 'error');

  $form_state['redirect'] = array(
    'user/logout',
    array('query' => array('destination' => 'user')),
  );

  drupal_redirect_form($form_state);
}

```

How do I display a message after redirecting user from the logout page?

# Answer
Reading your code, it appears to me that you want to redirect `/user/logout` to `/user`.

If that's what you actually want, then you could use the Rules module for this, using an approach that is similar to my answer to the question "How to create a redirect to point to the user's id?", in which you use values for `the_old_path` and `the_new_path` that fit your needs here, i.e.:

1. Change all occurences of `the_old_path` to `user/logout`.
2. Change all occurences of `the_new_path` to `user`.
3. Adapt the message being displayed to fit your needs, so that the user will also receive an informational message, e.g. similar to something like this one:

> *The path `/user/logout` has been redirected automatically to path `/user`.*

If you don't want such message to appear, then just delete the line containing `drupal_message` in the rule.

# Use the value of the \[destination\] variable in the redirect

In case you want to make the value (`user` in this case) of the URL argument (`destination` in this case) available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

**PS**: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.
> 1 votes

---
Tags: 7, redirection, status-messages
---


title: Displaying hook_form

text:
# Question
Title: Displaying hook_form
I have implemented a `hook_form` in my custom module and I can't figure out how I can get the form to display.

Here is my hook form:

```
   function data_retrieval_form($node, &$form_state)
    {
        $type = node_type_get_type($node);

        $form ['title'] = array(
            '#type' => 'textfield',
            '#title' => check_plain($type->title_label),
            '#default_value' => !empty($node->title) ? $node->title : '',
            '#required' => TRUE, '#weight' => -5
        );

        $form ['field1'] = array(
            '#type' => 'textfield',
            '#title' => t('Custom field'),
            '#default_value' => $node->field1,
            '#maxlength' => 127,
        );
        $form ['selectbox'] = array(
            '#type' => 'select',
            '#title' => t('Select box'),
            '#default_value' => $node->selectbox,
            '#options' => array(
                1 => 'Option A',
                2 => 'Option B',
                3 => 'Option C',
            ),
            '#description' => t('Choose an option.'),
        );

        return $form;
    }

```

I have also implemented `hook_menu` which registers a url with a callback to the form:

```
function data_retrieval_menu()
{
    $items = array();

    $items ['examples/form_example'] = array(
        'title' => 'Example Page',
        'page callback' => 'drupal_get_form',
        'access arguments' => array('access content'),
        'type' => MENU_SUGGESTED_ITEM,
    );

    return $items;
}

```

The problem I am having is that I cant understand how to get the form to display, the url does not work, how exactly do I display the form?

# Answer
It doesn't work because you set the page callback, but not the arguments to pass to that function. Without that, it will not know which form you want to render, nor which form builder should be called.

```
function data_retrieval_menu() {
    $items = array();

    $items ['examples/form_example'] = array(
        'title' => 'Example Page',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('your_form_builder'),
        'access callback' => 'user_permission',
        'access arguments' => array('access content'),
        'type' => MENU_SUGGESTED_ITEM,
    );

    return $items;
}

```

The other error that you are doing is not implementing all the hooks that Drupal requires from a module implementing a content type: `hook_form()` is just one of them, but you need other hooks. See Node API hooks for a list of all the hooks you need. Mostly, you need hook\_node\_info().

If you are not implementing a content type, but you want to simply show a form, then what you need is a form builder, which is not an implementation of `hook_form()`. Probably you need something similar to this.

```
function data_retrieval_menu() {
    $items = array();

    $items ['examples/form_example'] = array(
        'title' => 'Example Page',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('data_retrieval_form'),
        'access callback' => 'user_permission',
        'access arguments' => array('access content'),
        'type' => MENU_SUGGESTED_ITEM,
    );

    return $items;
}

function data_retrieval_form($form, &$form_state) {
  //...
  return $form;
}

```
> 0 votes

# Answer
Please check hook\_menu() documentation.

You need to specify page callback arguments like:

```
'title' => 'Example Page',
'page callback' => 'drupal_get_form',
'page arguments' => array('my_form_id'),
'access arguments' => array('access content'),
'type' => MENU_SUGGESTED_ITEM,

```
> 0 votes

---
Tags: forms, routes
---


# Question
Title: How to echo block title render in specific <div> D7
After creating a dynamic block I need to print block title in specific div or customize it to add css class . Please check image for more details

# Answer
> 1 votes
To add classes to block you can use below module:

https://www.drupal.org/project/block\_class

To add class to block title there is similar question before:

Adding classes to block title

Thanks!

---
Tags: blocks
---


title: How to restrict access to /user page?

text:
# Question
Title: How to restrict access to /user page?
I did my my own login form with custom functionality that is on `/login` url. Now I would like to restrict acces to default `/user` url in order to prevent logging in the old way.

I have a lot of different functionality in this form, so I though it is better to built it all from scratch instead of altering something. And I don't like the word in the `/user`, since in our language it sounds similar to some word that is not appropriate here.

I've tried to add `/user` item to `hook_menu` and define the same callback as `/login` item has.

I was hoping it could redirect users to new login form, but it had no effect.

What is the right way of doing this?

# Answer
Since *user* is already defined as menu item from a module, you cannot use `hook_menu()` to alter it, but you need to use `hook_menu_alter()`. Since *user* is used for the currently logged-in user, it probably a bad idea to redirect them to *login*.

As said from Mołot in his comment, the correct way of altering the login process is altering the login form, and add new validation handlers. This is similarly to what the OpenID module in Drupal core does.

```
function openid_form_user_login_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function openid_form_user_login_block_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function _openid_user_login_form_alter(&$form, &$form_state) {
  $form ['#attached']['css'][] = drupal_get_path('module', 'openid') . '/openid.css';
  $form ['#attached']['js'][] = drupal_get_path('module', 'openid') . '/openid.js';
  $form ['#attached']['library'][] = array('system', 'jquery.cookie');
  if (!empty($form_state ['input']['openid_identifier'])) {
    $form ['name']['#required'] = FALSE;
    $form ['pass']['#required'] = FALSE;
    unset($form ['#submit']);
    $form ['#validate'] = array('openid_login_validate');
  }

  $items = array();
  $items [] = array(
    'data' => l(t('Log in using OpenID'), '#openid-login', array('external' => TRUE)),
    'class' => array('openid-link'),
  );
  $items [] = array(
    'data' => l(t('Cancel OpenID login'), '#', array('external' => TRUE)),
    'class' => array('user-link'),
  );

  $form ['openid_links'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
    '#attributes' => array('class' => array('openid-links')),
    '#weight' => 1,
  );

  $form ['links']['#weight'] = 2;

  $form ['openid_identifier'] = array(
    '#type' => 'textfield',
    '#title' => t('Log in using OpenID'),
    '#size' => $form ['name']['#size'],
    '#maxlength' => 255,
    '#weight' => -1,
    '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
  );
  $form ['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())));
}

```
> 6 votes

# Answer
You could use the Rules module for this. Here is the rule you'd need for it (in Rules export format, just use copy/paste to import it in your own setup):

```
{ "rules_redirect_user_path_to_login_path" : {
    "LABEL" : "Redirect user path to login path",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "user",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, this path (= /user) is no longer in use, you will be redirected automatically to its corresponding path (= /login)" } },
      { "redirect" : { "url" : "login" } }
    ]
  }
}

```

Whenever such redirect actually happens, the user will also receive an informational message like so:

> *Sorry, this path (= `/user`) is no longer in use, you will be redirected automatically to its corresponding path (= `/login`)*

If you don't want such message to appear, then just delete the line containing `drupal_message` in the exported rule above.
> 4 votes

---
Tags: users, redirection
---


# Question
Title: Passing a single two word value into contextual filter that allows multiple values
I have a contextual filter set up to allow multiple values, and it filters the view on the city. so if I pass in "new york", the view will look for "new,york" which will not return any results. If I pass in "new york,chattanooga" the view looks for "new york,chattanooga" which will give me the results from new york and chatanooga. Lastly, if I pass in "new york, "(notice the space), the view will give me the correct results.

Is there a way to get the view to not act this way? I.E. Allow me to do `views_embed_view('places_to_stay', 'block', "new york");`? Thanks!

# Answer
in your case I think you need to separate values with plus-characters. so it would be:

```
views_embed_view('places_to_stay', 'block', "new york+chattanoog");

```

Because you have a single argument expecting multiple inputs.

in some other cases you might use the comma separator if you have multiple arguments each expecting a single inputs.
> 1 votes

# Answer
This is, unfortunately, the way that the `views_break_phrase_string()` function is designed to work. Taken from the comments in that function:

```
  // Determine if the string has 'or' operators (plus signs) or 'and' operators
  // (commas) and split the string accordingly. If we have an 'and' operator,
  // spaces are treated as part of the word being split, but otherwise they are
  // treated the same as a plus sign.

```

So you seem to have 2 alternatives:

1. Use the "new york, " syntax that you don't prefer to force it to treat your argument as an "and" argument and thus not split on the space.
2. Create your own custom views handler that calls your own. customized version of `views_break_phrase_string()`.

To do option 2 you would need to do a few things:

1. Copy `views_break_phrase_string()`, rename it, put it in your own module, and change its logic to not split on spaces.
2. Create a custom views argument handler that extends `views_handler_argument_string` but only implement the `query()` method. It can be an exact copy of the query method from views\_handler\_argument\_string but with a call to your custom version of `views_break_phrase_string()` instead. Do the same for the `title()` method, too, if you plan to use it since it also calls `views_break_phrase_string()`.
3. In your custom module, implement `hook_field_views_data_alter()` and change the argument handler for your addressfield locale field to use your new custom argument handler.
> 1 votes

---
Tags: views, entities
---


# Question
Title: Force node render with a template (giving template url not suggestion)
I need to change

```
$render_array = entity_view($entity_type, $entities, $view_mode, NULL, TRUE);
render($render_array);

```

in order to force drupal to use a specific template.tpl.php (giving a specific template url).

How can I achieve this?

# Answer
I will skip theme suggestions since your title specifically say to. There are several ways to use the menu router system to send the same node as an argument to different callback functions that handle the render process.

Most commonly used methods are Panels and Display Suite.

With Panels, you can have the panel sit at any url you want, take the node as an argument from context or url, and display parts of it or views related to it in a layout controlled by the panel manager. *yousite.com/display1/nid* and *yousite.com/display2/nid*

With Display Suite you have a similar display management, but the default (at least last time I used it) is to have the different custom displays as final tags in the url.
*yousite.com/normal-node-path/display1* and *yousite.com/normal-node-path/display2*

If you want to do it all by yourself with custom code, you can use hook\_menu to register your own page callback(s) for your own url(s). You can pass as many pieces of the url as you wish as arguments to your custom function, as long as they do not include the first word. *yousite.com/this-one* Menu\_router does not like urls to start with variables. Then, with the information that your callback preps, you can guide your node through a custom hook\_theme to use your specific template
> 0 votes

---
Tags: nodes, theming
---


title: Best technique to debug checkout panes

text:
# Question
Title: Best technique to debug checkout panes
I just need to review/explore the array of built in checkout\_panes so that I can debug it. However, the following code does not display any result.

```
<?php

function mymodule_commerce_checkout_pane_info_alter(&$checkout_pane) {
//Does not work
dpm ($checkout_pane);
//Does not work
drupal_set_message ($checkout_pane);
//Does not work
drupal_set_message (print_r($checkout_pane));
?>

```

It might be too basic but being a beginner in drupal/PHP I have already spent a day trying to resolving it. Any assistance will be highly appreciated.

# Answer
> 1 votes
You probably don't see a message because the results of the hook you're implementing are cached; you need to clear the cache to get the code to run. You'll want to clear it from within the browser so the message is put in the right session.

Perhaps the easiest method for this is to install the Admin Menu module, which gives you a direct link to flush the caches. When the page reloads after the cache clear, you should see the checkout pane details.

I'd recommend sticking with `dpm()` (assuming you have Devel installed), that's the best of the three methods in your code for inspecting vars.

---
Tags: debugging, forms, commerce
---


title: How I can management private files

text:
# Question
Title: How I can management private files
My default download method is public, but I need save some file on private folder, I am doing this:

```
//...
$file = file_save_data($handle, 'private://example.zip', FILE_EXISTS_REPLACE);
//...

```

Now when I try show to download it:

```
//...
$file = file_load($file_fid);
$url = file_create_url($file->uri);

$output['download'] = [
  '#type' => 'markup',
  '#markup' => l(t('Download'), $url),
];

return $output;
//...

```

If I do click on the url, I get:

> Access denied. You are not authorized to access this page.

I am superadmin (uid = 1). How I can management those files for me and for others users?

# Answer
For bypass Drupal permission, you can implements hook\_file\_download():

```
/**
 * Implements hook_file_download().
 */
function mymodule_file_download($uri) {
  if (someCondition()) {
    if (!user_access('some permissions')) {
      // Access to the file is denied.
      return -1;
    }
    else {
      return array('Content-Type' => file_get_mimetype($uri));
    }
  }
}

```
> 0 votes

---
Tags: 7, files
---


# Question
Title: Module for Integrating jQuery UI Multiselect Widget
I am using the jQuery multiselect widget on another non-Drupal project and I would love to be able to use it with CCK in Drupal 7. I have found this module for CCK multiselect but it is not exactly what I want. I realize I could try to write something, but I was curious if anyone has used the above with Drupal before or if there is a module out there I'm missing.

# Answer
> 3 votes
Not quite what you are requesting but thinking that chosen might be a good alternative to what your searching for.

# Answer
> 3 votes
Here you are: jQuery UI MultiSelect Widget

# Answer
> 1 votes
Since this is Drupal 7 isn't it easier just adding the `.js` files to your theme's `js` folder and adding this in your info file?

```
scripts[] = path/to/js/jquery.multiselect.min.js

```

# Answer
> 0 votes
Add the jquery.multiselect.js and jquery.multiselect.css files to your theme folder, such as /sites/all/themes/your-theme/js/jquery-multiselect/

Then add this to your template.php

```
drupal_add_js(path_to_theme().'/js/jquery-multiselect/jquery.multiselect.min.js');
drupal_add_css(path_to_theme().'/js/jquery-multiselect/jquery.multiselect.css');
drupal_add_js('$(document).ready(function(){$("#example").multiselect();});', array('type' => 'inline', 'scope' => 'footer', 'weight' => 6));

```

And to make it only show up on certain nodes types, you can use a preprocess node hook in your template.php:

```
function your_theme_preprocess_node(&$variables) {
  if ($node->type == 'my_content_type') {
    drupal_add_js(path_to_theme().'/js/jquery-multiselect/jquery.multiselect.min.js');
    drupal_add_css(path_to_theme().'/js/jquery-multiselect/jquery.multiselect.css');
    drupal_add_js('$(document).ready(function(){$("#example").multiselect();});', array('type' => 'inline', 'scope' => 'footer', 'weight' => 6));
  }
}

```

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


title: 'Most popular' view since last X days

text:
# Question
Title: 'Most popular' view since last X days
I'm using Drupal 6 and I need to display a block with the most viewed nodes from the last 7 days. I've tried using views + statistics but I can only get the total count of views. How can I get a count of node views from the last X days?

# Answer
> 11 votes
You may want to take a look at the Radioactivity module and see if it works for you. It defines a "hotness" for a node, and a "halflife" that the "hotness" wears off at. This attempts to account for popularity over time, instead of raw page views.

For example, a popular blog post from a few days ago will be more "hot" than a wildly popular blog post from last year that had more page views.

Time-decay is configurable, and it integrates with Views.

# Answer
> 1 votes
The Drupal Most Popular module uses the core statistics module, which has several shortcomings. For starters, it won't count any "reads" of cached content, so if you use the page cache or a reverse proxy cache, you are out of luck. Additionally, statistics module is a huge drain on performance, and only keeps counts of reads for a period of time (say, 30 days).

The Radioactivity module seems like the way to go - it is a really great idea in concept, and will work great for Drupal 6. Unfortunately it does not actually count page views in Drupal 7! There is something included that's supposed to do that, but it doesn't work. Several people have reported that they were able to work around this deficiency by using the Rules module (but I do not recommend it).

There's also the Scoville module for Drupal 7 which is a funny hybrid of the two.

# Answer
> 1 votes
Here are some modules that might be a possible fit, all of them have a D6 version too (quotes are from their project pages):

* Visitors **(\*)**

One of the things you get from it is a **Visitors Block**, which includes, among others, data about:

+ Total Visitors.
    + Unique Visitor.
    + Registered Users.
    + ...
* Statistics Advanced **(\*)**.

> Provides a few advanced options to the core Statistics module. Once enabled, these options can be found under "Administer \>\> Reports \>\> Access log settings."
* Statistics Filter

> ... allows customizable filtering of hits from particular user roles or from crawlers.
>
> For sites with light traffic (i.e., most sites), a large percentage of the gross hits recorded by statistics.module are either from the site administrator or from search engines. Filtering out these hits makes the collected statistics more accurately reflect traffic from real, human visitors.
* Counter

> ... counts how many visitors on your website. This module provides real time counting. All data saved to database.
* User Visits (with related User Visits Advanced).

> ... tracks visits and referrer from other users on a user's profile page. It displays the latest visitors on a user's profile page and provides two blocks one with the latest visitors on a user's profile page and one with the latest visitors on own profile page.
>
> See User Visits Advanced for additional functionality.
* Better Statistics.

> ... introduces a Statistics API, allowing developers and contributed modules a way to collect, limit, and route custom access statistics and data.

This question is about D6, but for D7 there is also the Node view count module. Some more details about it:

> ... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.
>
> This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

Disclosure: I'm the maintainer of the modules marked with **(\*)**.

# Answer
> 0 votes
In addition to Radioactivity (already mentioned by MPD), you may also want to consider the Drupal Most Popular module. Some details from its project page:

> The module is pre-packaged with several services including:
>
> * Drupal - Most Viewed pages (using Statistics module)
> * Drupal - Most Commented pages (from simple database query)
> * Google Analytics - Most Viewed pages
> * AddThis.com - Most Shared pages
> * Disqus.com - Most Commented pages
>
> The system defines Drupal hooks to allow new services to be created, which can pull data from third party providers or internally from Drupal. The system also provides an API to help service plugins normalize their results and exclude certain pages, as configured by the administrator.

---
Tags: views, nodes
---


# Question
Title: How (and Where) to store downloadable commerce files outside the file system..?
I’m building a Drupal Commerce site and am selling downloadable mp3’s. It was recommend that the downloadable commerce files should be kept outside the sites file directory. I’ve tried setting this directory in the admin in 2 places, as separate attempts:

First i created a folder called commerce\_files and set it one level up from the Drupal install

Then i tried referencing this folder in 2 places (as 2 separate attempts)

```
Configuration->Media->File System
Configuration->Product Variation Types->My MP3 Content type->File

```

Neither worked.

When searching the internet for this topic nothing much is coming up. Does anyone here have any insight or info on this topic? it would be appreciated, thanks

Or maybe i was misled and it is perfectly acceptable to store within the file system, using the Config-\>Media-\>Private Folder setting in the admin as i have been doing....?

FYI - have gotten almost no responses when posting the Drupal commerce.org,

# Answer
You can configure the "Private file system path" to be outside your Drupal installation by changing it in the admin/config/media/file-system. and you configure your commerce files there. this should do the trick. either way Drupal do not provide direct url access to the private files.
> 0 votes

---
Tags: commerce, users
---


# Question
Title: How to get into a Drupal 7 site using only Drush without touching code or anything else?
I'm working on a acquia site and right now the dev environment is replicated from the prod. I want to be able to get in as admin on the dev site, but every time i hit the /user path it redirects me back to the prod site. I tried doing a **drush uli admin** but that doesnt work neither as I still get redirected back to prod. However, I am logged in as admin on the prod by doing a drush uli admin.

Without touching any of the code/files to get me logged into the dev site and only using Drush. How can one get in logged as admin?

Keep in mind there's no way to get to the /user path on dev as it redirects you once you land on there. And I'm not sure which modules/files is doing this functionality.

I was thinking of copying the cookie session from the prod database and then copy it into the dev database to simulate myself as being logged in, but I'm not sure how to go about that or what else might be needed.

# Answer
> 0 votes
What I did was change the default theme to the basic seven theme:

**drush @mydomain.dev vset theme\_default seven**

Then reset your admin password:

**drush @mydomain.dev upwd admin --password="mypass"**

Then go and find a page that loads the seven theme and by default the seven theme has the login block somewhere in the footer area. Login with admin and your new pass! =D

If you have a theme switching module, you'll have to turn that off too. Such as **themekey** or **rules** or **securepages** (this is what was causing my issue.)

# Answer
> 0 votes
Use drush to get a list of enabled modules except for core:

```
drush pm-list --type=Module --no-core

```

If the module Rename Admin Paths is being used then you can use drush to temporarily disable it until you are logged in.

ie.

```
drush pm-disable rename_admin_paths

```

or

```
drush dis rename_admin_paths

```

I'm suggesting this as that particular module in known to be one of the causes of redirects involving administrators and the /user path.

# Answer
> 0 votes
Try the following workarounds:

* `/user/login` instead of just `/user`
* try: `drush uli` and try both `http://` and `https://`, maybe it could make a difference, or adding `?foo` at the end of the URI
* give every session an admin: `drush sqlq "UPDATE sessions SET uid = 1"` (make sure your browser session is included already there)
* hack `index.php` by adding the following line just after `drupal_bootstrap()`

```
global $user; $user = user_load(1); session_start(); user_login_finalize();

```

See also: How do I programmatically log in a user?
* create a dummy session and hijack the cookie in the browser:

```
$ drush eval 'global $user; session_start(); user_login_finalize(); echo session_name();'
$ drush sqlq "UPDATE sessions SET uid = 1 ORDER BY timestamp DESC LIMIT 1"

```

then in the browser address bar type (to set the cookie):

```
javascript:document.cookie="SESS37XXX=NGnGrXXX"

```

---
Tags: 7, drush, users
---


# Question
Title: Is the Drupal Multisite something automated once its setup?
I am looking to create a multisite system that creates websites for users. But I need the users to be able to create their own website.
something like below steps :
`Register>add domain>select theme>give donation(optional)>Done`

Does the multi site feature allow this? If not, what is the best way to achieve this functionality?

Or what do you recommend we to achieve this?

Thanks

# Answer
I build a system for a client where the client would deploy sites for *his* clients. It was pretty easy with the Aegir system. Aegir is a drupal site that manages drupal sites and different module configurations as "platforms" for those sites.

Need to depoly security updates? Make a new platform with the updated modules, and migrate the sites from the existing platform to the new one with the built in migration managment.

A manual multisite install is similar to this, where the /sites/all folder is your platform common to all the sites, and each one has a separate database.

The disadvantage is each site residing on aegir is its own site, with its own database. If you want nodes or pages common to each site you have to hardcode them into the platform's installation profile.(or make them manually for each new site) Also, the steps in your question would have to be done in the Aegir level and not in the drupal site.

With the domain module you have multiple sites using the same database, so you can more easily share nodes and content across them. Also, since it is one site holding different pieces under different subdomains, the ability to add new subdomains is in the drupal menu on the site.

Disadvantage: what affects one site affects them all, since they are all different faces of the same site. Also, I have had bad experiences with the domain module (especially in conjunction with the commerce modules) and trust it less than other solutions. Since (sub)domains are content types made by users, it is possible to delete an entire domain and lose all its content when you delete the user account that made it. I saw a guy get fired for doing that by mistake.
> 1 votes

---
Tags: 7, multi-sites
---


# Question
Title: How do I control the file appearance using File Entity?
By installing File Entity module I was hoping to be able to control the way all file items are rendered, for instance I need: file rendered as a link wrapped inside an `<li>` element, or a link with a given class to force display: block. I must say I have now more disorder among the widget, formatters and displays than I used to have before, and I can see no way to control the markup.

Please shed light on me, I assume it's my ignorance rather than the module imperfection. Thanks.

# Answer
> 0 votes
Since I've been no longer into Drupal for a long time now, I'm even not sure I remember the answer. But I managed to dig up the code below which smells like an answer @digitgopher asks for. So FWIW, and sorry for somewhat messy comments hanging around:

```
<?php

/**
* Implements hook_field_formatter_info().
*/
function fileformatter_field_formatter_info() {
  return array(
    'fileformatter_formatter' => array(
      'label' => t('File Formatter'),
      'field types' => array('file'),
      'settings' => array(
        'link_text' => '',
      )
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function fileformatter_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  //This gets the view_mode where our settings are stored
  $display = $instance['display'][$view_mode];

  //This gets the actual settings
  $settings = $display['settings'];

  //Initialize the element variable
  $element = array();

  //settings
  $element['link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Link text'),
    '#description' => t('The text to appear next to icon. Leave empty for raw file name. Possible tokens: %fn = file name, %fd = file description, %cp = node title'),
    '#default_value' => $settings['link_text'],
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function fileformatter_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  $summary = t('will be labeled ');
  $summary .= ($settings['link_text'] == '') ? t('using file name') :  $settings['link_text'];

  return $summary;
}

/**
 * Implements hook_field_formatter_view().
 */
function fileformatter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  $settings = $display['settings'];

  foreach ($items as $delta => $item) {
    $html = '';

    // LINK TEXT
    $link_text = ($settings['link_text'] == '') ? $item['filename'] : check_plain($settings['link_text']);

    /* if (module_exists('token')) {
      $link_text = token_replace($settings['link_text'], array('node' => $entity));
    } else { */
      $link_text = str_replace('%fn', $item['filename'], $link_text);
      $link_text = str_replace('%fd', $item['description'], $link_text);
      if($entity_type == 'node'){
        $link_text = str_replace('%cp', $entity->title, $link_text);
      } else {
        $link_text = str_replace('%cp', '', $link_text);
      }
    // }

    // last resort, so to not allow for empty links
    if($link_text == ''){
      $link_text = $item['filename'];
    }

    // ICON - as CSS class background, which reduces file requests and allows for easier vertical-alignment
    $dashed_mime = strtr($item['filemime'], array('/' => '-'));
    /* // img method:
      $icon = theme('file_icon', array('file' => file_load($item['fid']), 'icon_directory' => drupal_get_path('module', 'file') . '/icons'));
      $icon_html .= '<span class="link-icon">' . $icon . '</span>';
    */

    // LINK MARKUP
    $url = file_create_url($item['uri']);
    $link_options = array(
      'html'        => TRUE,
      'attributes'  => array(
        'title' => $item['filename'],
        'class' => 'file file-formatted ' . $dashed_mime . ' file-fid-' . $item['fid'],
        'type' => $item['filemime'] . '; length=' . $item['filesize'],
        'target' => '_blank',
       ),
    );

    $html .= l($link_text, $url, $link_options);

    $elements[$delta]['#markup'] = $html; // Assign it to the #markup of the element
  }
  return $elements;
}

```

---
Tags: files
---


# Question
Title: Batch operations: callback_batch_operation() not invoked
I have a batch process where the callback\_batch\_operation() functions are never called, as showed when logging with some Devel `dd()` calls.

Here is the involved code fundamental parts (all this in the same `multilang.admin.inc` file):

```
function multilang_default_form_submit($form, &$form_state) {
  $operations = array();
  if ($categories = $form_state['values']['default']) {
    foreach ($categories as $category) {
      if ($category) {
        $operations[] = array('multilang_default_process', $category);
      }
    }
  }
  $batch = array(
    'title' => '...',
    'init_message' => '...',
    'operations' => $operations,
    'finished' => 'multilang_default_finished',
    'file' => drupal_get_path('module', 'multilang') . '/multilang.admin.inc',
  );
  dd($batch, '$batch'); ## log
  batch_set($batch);
}

function multilang_default_process($category, &$context) {
  dd(func_get_args(), 'default_process'); ## log
  // ...do the desired job...
}

function multilang_default_finished($success, $results, $operations) {
  dd(func_get_args(), 'multilang_default_finished() args'); ## log
  // ...send appropriate messages...
}

```

And here is the log result, in a case where only one operation was required:

```
$batch: Array
(
    [title] => Resetting Multilang configuration
    [operations] => Array
        (
            [0] => Array
                (
                    [0] => multilang_default_process
                    [1] => multilang_exclude_paths
                )

        )
    [finished] => multilang_default_finished
    [file] => sites/all/modules/multilang/multilang.admin.inc
)

default_finished: Array
(
    [0] => 1
    [1] => Array
        (
        )
    [2] => Array
        (
        )
    [3] => 0 sec
)

```

The above log shows that the `multilang_default_process()` function is not called, though correctly stated as callback\_batch\_operation in `$batch`.

Obviously the first suspicion after the function's correct spelling, goes to its localization through the `file` index in `$batch`.
But not only I multiple checked it, but also we can notice that the `default_finished()` function gets called, while it is localized through the same `file` index.
This is also ensured by the fact that, if I intentionally set `file` to another, incorrect value, then the `default_finished()` function is not called.

Another puzzling thing (at least at my eyes) is the `default_finished()` passed arguments: despite no callback\_batch\_operation was called, `$success` (index 0) is set to `TRUE` and (remaining to process) `$operations` (index 2) is empty.

Am I missing (like it happens too often :-) something stupidly obvious...?

# Answer
> 0 votes
**Yes, it was stupidly obvious!**

When bulding my `$operations` I wrote
`$operations[] = array('multilang_default_process', $category);`
while according to the batch\_set() documentation it should be
`$operations[] = array('multilang_default_process', array($category));`

Sigh...

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