title: Two views blocks content synchronized

text:
# Question
Title: Two views blocks content synchronized
I have two content types: "banner wallpaper" and "banner1".

I'm using two views blocks. The view "banner wallpaper" displays the content from content type "banner wallpaper" and "banner1" the content from "banner1".

I have two wallpaper banners and two banners1 content.

With format views slideshow, timer delay set to 0 and marked random option in view I successfully managed to display the two banner wallpapers by refreshing the page. That goes same for Banner1.

My goal is: when the first wallpaper banner is displayed, the first banner from banner1 to be displayed too. When I refresh the page the second wallpaper banner and the second banner from Banner1 will be displayed, so they will be synchronized.

For an example we have two brands that will wants to advertise in the website.

Green and Orange.

These two brands wants to have wallpaper banner and flash banner. So, when Green wallpaper banner is displayed, the flash banner from Green has to be displayed too, not to be mixed with Orange. After refresh the wallpaper from Orange will be displayed and the flash banner from Orange too... I think I'm clear.

Is there any filter or sorting available to achieve this with views?

# Answer
I would use a taxonomy to tag your content.

Create a taxonomy vocabulary (E.g.: Brand), add the two terms (Green, Orange), add a new field of "term reference" to your content types and tag the content.

Then in your views, you can add a "Contextual Filter" (in the advanced options) to get term\_id from the URL, so both will show the same tagged content.

Note that I've set the Path component to be 2, that's because the term\_id will be passed as 2nd argument on your URL (can be anything you want).

Don't forget to validate the value to be one from your vocabulary. That's on "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED", check the option "Specify validation criteria" \> "Validator" = Taxonomy Term \> Check your vocabulary from the list.

Then you need to set your view URL, so you can pass the term\_id by the URL:

By doing all that, you should be able to go to your page, type http://yoursite.com/brand/term\_id and your content should appear.
> 0 votes

---
Tags: views
---


# Question
Title: Views isn't pulling custom field correctly
I've been developing a custom module, which uses the node id, with the rate module, to output the results to a simple mathematical equation (which uses the rate module - i.e. voting api) to calculate the total number of votes.

The calculation is completed as part of hook\_field\_formatter\_view for the field. It is then passed through to the node's display.

The issue arises when passing through this same value to a Views output. It seems the node id isn't passing through to the field, which renders this whole problem impossible. I have been using this to access the node id:

```
  $node = menu_get_object();
  $nid = $node->nid;

```

Which is then used to retrieve the necessary values from the database for the calculation. However, all fields are returning 0 (null) values in the views output.

Is this because the node id is not passing through, or could it be something else?

# Answer
When using menu\_get\_object(), you'll get the node currently displayed from the menu. So for example, if you're on a page with a path like node/123, it will load the node with nid "123" (source). So that won't work inside a views for sure.

You should be able to retrieve the nid from the $entity element, which should be a parameter of your hook\_field\_formatter\_view (as described here).
> 0 votes

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


# Question
Title: storing value in session with ctools wizard
I have created a `multi-step form` using `Ctools wizard` and its working fine.

In multi step form, there is only images, so user will select the image and click on "Continue" button for next step. In the final step, I am showing the result of merged images which are selected in all previous step.

Images are rendering as ajax link in each step and when user click on any image, an ajax callback be executed.

In each step form load and ajax callback, `fid` of the images be stored in `$_SESSION` variable.

But the problem is that `$_SESSION` are not updating on the ajax call.

Suppose, there are five images in step 1 in the `Ctools multi step form`. When `step 1` load, I am storing `fid` of first image into `$_SESSION` variable and If user click on any images, I am updating the `fid` in `$_SESSION` variable.

But, if I check `print_r($_SESSION)` in next step, its not showing the updated `fid`. Its only showing `fid` of the first image in previous step.

If I check `ajax callback` in `fire bug` console, its showing correct value of `fid` and `$_SESSION` variable.

Please suggest me what I am doing wrong.

Thanks in advance.

# Answer
> 1 votes
you cannot use form\_state. every step will have it's own. cache the date with ctools\_object\_cache\_set

# Answer
> -2 votes
Here is a nice example how to create customizable multistep form without ctools wizard.

---
Tags: 7, chaos-tool-suite, forms
---


# Question
Title: Deleting User Picture changes the password of user?
I have used following code to delete the user picture on click of a form `button` element (using `#ajax`).

```
function delete_user_picture($form, &$form_state){
  global $user;
  $account = user_load($user->uid);
  unset($account->picture);
  $edit = (array) $account;
  user_save($user, $edit);
}

```

This successfully deletes the picture but also changes the password. How can I prevent it from doing so?

UPDATE: Based on Molot's Suggestion, I made the following change to code and now it works perfectly:

```
function profile_delete_user_picture($form, &$form_state){
  global $user;
  $account = user_load($user->uid);
  $file = file_load($account->picture->fid);
  unset($account->picture);
  $edit = array();
  //add just the picture info and not the whole account info and password won't be changed
  $edit['picture'] = $account->picture;
  user_save($user, $edit);
  if ($file != NULL) {
    file_delete($file);
  }
}

```

Also added code to delete the file from database as per SlakeFistcrunch's Suggestion.

# Answer
Yes it does. This works as designed, but you made mistake. When you obtain user object, it does not contain a password. It contains a password field, but it's not populated with actual password as it is impossible by design to know it. So you are feeding all fields to user\_save, including field for password, but without password in it.
> 0 votes

# Answer
Building off what Molot suggested (I was going to add as a comment, but not enough rep), is it possible to save the hashed password from the DB, and place it back in afterward? (Not an ideal solution of course, but I would think it's possible.)

Also, that doesn't actually delete the user picture from the filesystem, does it? If not, be sure to delete the images themselves, otherwise you'll wind up with a bunch of disconnected/useless images in your public files.
> 0 votes

---
Tags: users
---


# Question
Title: Help with PDOException and hook_schema()
I'm trying to set up an install file for a custom module that I'm creating but having a little trouble when Drupal tries to create my tables.

It's probably a simple syntax error but can't track it down at all. Here's the error I'm getting:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL, `logo_url` VARCHAR DEFAULT NULL, `url` VARCHAR DEFAULT NULL COMM' at line 3: CREATE TABLE {survey_compare_companies} ( `id` INT unsigned NOT NULL auto_increment COMMENT 'The primary key for this table.', `company_name` VARCHAR DEFAULT NULL, `logo_url` VARCHAR DEFAULT NULL, `url` VARCHAR DEFAULT NULL COMMENT 'The company’s website address.', `int_url` VARCHAR DEFAULT NULL COMMENT 'URL to the Survey Compare page for this company', `payment_per_survey` VARCHAR DEFAULT NULL COMMENT 'The payment amount per survey', `min_payout` VARCHAR DEFAULT NULL COMMENT 'The minimum amount required to qualify for a payout', `ave_survey_length` VARCHAR DEFAULT NULL COMMENT 'The average length of individual surveys', `ref_bonus` VARCHAR DEFAULT NULL COMMENT 'The bonus offered for referrals', `other_bonus` VARCHAR DEFAULT NULL COMMENT 'Details of other bonuses', `age_id` INT DEFAULT NULL COMMENT 'The ID of the age group that this company offers surveys to', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Holds details for various survey companies'; Array ( ) in db_create_table() (line 2717 of C:\xampp\htdocs\drupal\includes\database\database.inc).

```

Here's my code:

```
<?php

/**
* Implements hook_schema()
*/

function survey_compare_schema() {

    $schema = array();

    $schema['survey_compare_companies'] = array(

        'description' => 'Holds details for various survey companies',

        'fields' => array(

            'id' => array(
                'description'   => 'The primary key for this table.',
                'type'          => 'serial',
                'unsigned'      => TRUE,
                'not null'      => TRUE
            ),

            'company_name' => array(
                'description'   => 'The name of the company.',
                'type'          => 'varchar'
            ),

            'logo_url' => array(
                'description'   => "A URL to the company's logo",
                'type'          => 'varchar'
            ),

            'url' => array(
                'description'   => "The company's website address.",
                'type'          => 'varchar'
            ),

            'int_url' => array(
                'description'   => 'URL to the Survey Compare page for this company',
                'type'          => 'varchar'
            ),

            'payment_per_survey' => array(
                'description'   => 'The payment amount per survey',
                'type'          => 'varchar'
            ),

            'min_payout' => array(
                'description'   => 'The minimum amount required to qualify for a payout',
                'type'          => 'varchar'
            ),

            'ave_survey_length' => array(
                'description'   => 'The average length of individual surveys',
                'type'          => 'varchar'
            ),

            'ref_bonus' => array(
                'description'   => 'The bonus offered for referrals',
                'type'          => 'varchar'
            ),

            'other_bonus' => array(
                'description'   => 'Details of other bonuses',
                'type'          => 'varchar'
            ),

            'age_id' => array(
                'description'   => 'The ID of the age group that this company offers surveys to',
                'type'          => 'int'
            )

        ),

        'primary key' => array('id')

    );

$schema['survey_compare_payment_types'] = array(

    'description' => 'Holds details about the types of payment offered',

    'fields' => array(

        'id' => array(
            'description'   => 'The primary key for this table.',
            'type'          => 'serial',
            'unsigned'      => TRUE,
            'not null'      => TRUE
        ),

        'name' => array(
            'description'   => 'The name of this payment type',
            'type'          => 'varchar'
        )

    )

);

$schema['survey_compare_companies_payment_types_relation'] = array(

    'description' => 'Specifies links between companies and the payment types that they offer',

    'fields' => array(

        'id' => array(
            'description'   => 'The primary key for this table.',
            'type'          => 'serial',
            'unsigned'      => TRUE,
            'not null'      => TRUE
        ),

        'company_id' => array(
            'description'   => 'The ID of the company',
            'type'          => 'int'
        ),

        'payment_type_id' => array(
            'description'   => 'The ID of the payment type',
            'type'          => 'int'
        )

    )

);

$schema['survey_compare_min_age'] = array(

    'description' => 'Specifies the minimum age required to fill in surveys for this company',

    'fields' => array(

        'id' => array(
            'description'   => 'The primary key for this table.',
            'type'          => 'serial',
            'unsigned'      => TRUE,
            'not null'      => TRUE
        ),

        'min_age' => array(
            'description'   => 'The minimum age',
            'type'          => 'int'
        )

    )

);

$schema['survey_compare_payment_options'] = array(

    'description' => 'Specifies the payment options available',

    'fields' => array(

        'id' => array(
            'description'   => 'The primary key for this table.',
            'type'          => 'serial',
            'unsigned'      => TRUE,
            'not null'      => TRUE
        ),

        'name' => array(
            'description'   => 'The name of this payment option',
            'type'          => 'varchar'
        ),

        'logo_url' => array(
            'description'   => 'The URL to the logo for this payment option',
            'type'          => 'varchar'
        )

    )

);

$schema['survey_compare_companies_payment_options_relation'] = array(

    'description' => 'Specifies links between companies and the payment options that they offer',

    'fields' => array(

        'id' => array(
            'description'   => 'The primary key for this table.',
            'type'          => 'serial',
            'unsigned'      => TRUE,
            'not null'      => TRUE
        ),

        'company_id' => array(
            'description'   => 'The ID of the company',
            'type'          => 'int'
        ),

        'option_id' => array(
            'description'   => 'The ID of the payment option',
            'type'          => 'int'
        )

    )

);

$schema['survey_compare_countries'] = array(

    'description' => 'Specifies countries for use with this module',

    'fields' => array(

        'id' => array(
            'description'   => 'The primary key for this table.',
            'type'          => 'serial',
            'unsigned'      => TRUE,
            'not null'      => TRUE
        ),

        'name' => array(
            'description'   => 'The name of the country',
            'type'          => 'varchar'
        ),

        'country_code' => array(
            'description'   => 'The country code',
            'type'          => 'varchar'
        )

    )

);

$schema['survey_compare_companies_countries_relation'] = array(

    'description' => 'Specifies links between companies and the countries that they cover',

    'fields' => array(

        'id' => array(
            'description'   => 'The primary key for this table.',
            'type'          => 'serial',
            'unsigned'      => TRUE,
            'not null'      => TRUE
        ),

        'company_id' => array(
            'description'   => 'The ID of the company',
            'type'          => 'int'
        ),

        'country_id' => array(
            'description'   => 'The ID of the country',
            'type'          => 'int'
        )

    )

);

return $schema;

}

```

I've tried reading the error but without seeing the whole statement, I'm ha

# Answer
`length` is required for `varchar` columns...

All tables except the first are missing a primary key, as well. Also, adding some indexes will probably save you some performance problems down the line.
> 1 votes

---
Tags: 7, database
---


# Question
Title: SMB shared video files from Windows to Linux
So, this might be more of a general Linux question, but I've tried everything I can think of with permissions, andI'm having the issue in Drupal, so I'm hoping someone here has an idea.

What I want to do: Use the Video module to play video files from a shared network folder; the folder is on a Windows Server 2012 system. (I realize the Vide module is geared towards uploading files, but if I manipulate the uri in the file\_managed tables, I can change it, so I'm going to use the module to add the content, then edit the uris accordingly.)

```
1) Video defaults to the files/default/videos/originals folder for storing uploaded videos
2) I mounted the network folder at files/default/videos/originals/movies
3) Then I changed the uri for the video file to point to the mounted network folder

```

Now, I can change the uri to other local directories, and it works fine (I even had a symlink at one point leading out to my own user directory), but whenever I try to play the file (with the DivX player, since it seems to be the only one I tried that gives me an error message, instead of just hanging), I get a 403 error.

I've set the group and user of all involved to apache (and using ls -l, that seems to have been set), and my mount command in /etc/fstab is listed below

```
\\192.168.0.3\movies /var/www/html/sites/default/files/videos/original/movies cifs uid=48,gid=48,ro,suid,username=userName,password=passWord 0 0

```

(I used uid and gid because if I tried user and group, nothing happened.) I've been fighting with this for hours, and I have no clue. Thanks for any help.

Running the following code from within Drupal returns nothing, but running the exact same code after placing it in "file.php", and calling "php file.php", and it returns the files in the directory fine.

```
glob('/var/www/html/sites/default/files/videos/original/movies/*.*')

```

I could really use some help with this.

# Answer
> 0 votes
Found the problem! It has to do with SELinux. After looking at the folder with

```
ls -Z

```

And seeing that files that were accessible had a context that the folder didn't (httpd\_sys\_rw\_content\_t), I disabled SELinux with

```
sudo setenforce 0

```

and I was able to access the files. Of course, I have more work to do, and I don't intend on keeping it turned off, but this at least shows me where the problem is. Wu!

---
Tags: files
---


# Question
Title: Is my web hosting company's "Full Backup" sufficient protection before an update?
I'm learning how to work my little Drupal site, which is currently hosted on HostGator. It's well past time to update, and I want to make sure I'm safely backing up my site.

HostGator can facilitate "Full Backups" of my files, which they describe thus:

A full backup includes all of the files in your home directory, your MySQL databases, and your email forwarders and filters. You can back up your account to preserve your data, or to move your account to another cPanel server.

Thank in advance, and/or apologies if this is a crap question.

# Answer
You need two things to restore a Drupal site: A copy of the database and the folders that hold Drupal.

I'm not familiar with shared hosting, but I'm guessing that Drupal is installed in your home directory as opposed to `/var/www` or `/srv/www`.

That means a full backup does give you everything you'll need to restore Drupal. Make sure you know how you'd restore it though. No point backing up if your not sure where the files are and how to restore them.

If you want to extra safe or do it yourself, install the Backup and Migrate Module, make a backup and make a copy of your Drupal root directory. (That's the one with sites, includes, themes etc. in it).

Then if you want to restore Drupal. Delete the bad Drupal root directory and put your old drupal root directory back in. Install Drupal as normal, enable backup and migrate module (it'll be there because you've put in your modified Drupal root folder) and then restore from the Backup and Migrate backup.
> 1 votes

---
Tags: backups
---


title: Add field_tags on module install

text:
# Question
Title: Add field_tags on module install
Is it possible to add the field field\_tags in mymodule\_install() like the body field? I added a body field with node\_add\_body\_field. I can see the field in field\_config\_instance table. Is there a posibility to add field\_tags in hook\_install() without doing it in the GUI?

Is it done by field\_create\_field?

```
if (!field_info_field('my_field')) {
  field_info_cache_clear();

  $field = array(
    'field_name' => 'my_field',
    'type' => 'custom_field_type',
    'cardinality' => 1
  );
  field_create_field($field);
}

```

But how to set the values for a default article or gui custom like tags field?

# Answer
Yeah, i know according to strict forum rules it's not fine to answer your own question :-) But anyway ...

I not realized, that the default fields are stored in table field\_config and just a instance for a node in table field\_config\_instance.

I added the following lines to mymodule\_install() of my module:

```
$instance = array(
  'field_name' => 'field_tags',
  'entity_type' => 'node',
  'label' => 'Tags',
  'bundle' => 'mynode',
  'widget' => array(
    'type' => 'textfield',
  ),
);

```

I don't need field\_create\_field() because the field\_tags already exists.

And i added a field to the custom node form:

```
function mymodule_node_form($form, &$form_state, $node) {
...
   $form['field_tags'][LANGUAGE_NONE] = array(
       // '#entity_type' => 'node',
      '#type' => 'textfield',
      '#title' => t('Tags'),
       // '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
      '#field_name' => 'field_tags',
       // '#bundle' => 'mymodule',
      '#element_validate' => array(
                                 0 => 'taxonomy_autocomplete_validate',
                             ),
       //    '#after_build' => array(
       //                        0 => 'field_form_element_after_build',
       //                      ),
      '#field_parents' => array(),
      '#language' => LANGUAGE_NONE,
      '#columns' => array(
                        0 => 'tid',
                    ),
      '#parents' => array(
                       0 => 'field_tags',
                       1 => LANGUAGE_NONE,
                    ),
   );
...
}

```

I tried to find out the obligate values. I'm not sure if it's wise to add more values?! I just realized that some values are not nescessary (the commented ones).
> 2 votes

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


title: drupal 6 using form api number field

text:
# Question
Title: drupal 6 using form api number field
Currently i am using drupal six form api. I just wanted to add number field to form but there is no way that i found to add numeric field to form. Is there is any way to do this by using form api drupal6 to add numeric field in drupal 6.

Thanks

# Answer
The Elements module provides an HTML5 number field element to the FAPI. You can use it like this:

```
$form['foo'] = array(
  'type' => 'numberfield'.
  'title' => t('Bar'),
  ...
);

```
> 0 votes

---
Tags: hooks
---


title: Repeating group names in Pathauto path

text:
# Question
Title: Repeating group names in Pathauto path
My pathauto patterns are giving me trouble with organic groups. All books are contained within groups.

Book\_main\_page shows as:

> Group\_name/Book\_main\_page

A child of Book\_main\_page shows as:

> Group\_name/Group\_name/Book\_main\_page/Child

A child of the child page shows as:

> Group\_name/Group\_name/Group\_name/Book\_main\_page/Child/Child\_of\_child

How do I get rid of the repeated group names?

The group content type "book page" has a "Pattern for all Book page paths" of:

> \[node:og-group-ref\]/\[node:book:parent:url:path\]/\[node:book:title\]

The group type "Group" has a "Pattern for all Group Paths" of:

> \[node:og-group-ref\]/\[node:title\]

My page uses one group content type "book page" (from the books module) and one group type "group".

# Answer
> 0 votes
For the "book page" content type, try using the path:

```
[node:og-group-ref:title]/[node:book:parents:join-path]/[node:book:title]

```

---
Tags: organic-groups, path-aliases
---


# Question
Title: How would I use DATEDIFF(), NOW(), and BETWEEN in a db_delete() query?
Is the something like the following possible?

```
db_delete('note_dates')
    ->condition("DATEDIFF('start', NOW()) BETWEEN 0 AND 30")
    ->execute();

```

# Answer
> 4 votes
You can use `DeleteQuery::where()`, e.g.

```
$args = array(':arg1' => $foo, ':arg2' => $bar);
db_delete('note_dates')
  ->where("DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2", $args);
  ->execute();

```

That'll give you

```
DELETE FROM {note_dates}
WHERE  (DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2)

```

---
Tags: 7, database
---


title: Add fields to user roles

text:
# Question
Title: Add fields to user roles
I'm using Drupal 7 to create a project linking organizations to volunteers. My initial approach is to use profile module to create different profiles for each role (volunteer & organization). Is it possible to create new fields which would attach only to a selected role?

# Answer
This is a great example use-case for the Profile 2 module.

As listed on the project page:

> Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
> 3 votes

# Answer
I guess you could also try to add all fields to the user directly and then use a custom hook\_field\_access() implementation to control when they are shown for edit/view.
> 3 votes

# Answer
I think you can use https://drupal.org/project/user\_role\_field This module allows you to specify role specific fields. When creating a new field, you specify for what roles this field is enabled..
> 0 votes

# Answer
Sounds like a good idea to collect all fields in one entity. You could then have a enumerator-field, where you could choose entity-sub-type (organization or volunteer). That would be needed in case the author had authority to create both. You can use User Role Field to hide the fields that the author is not allowed to see. You can use Field Permissions to restrict access that the author and viewer is not allowed to access. You can use also hide or show fields dependent on values of other fields with Conditional Fields. The dependee field would then be the enumerator-field. You could probably use Computed Field to add extra logic dependent on sub-type.

I like to use taxonomy for enumerator, but it could be a text list instead.

You would probably also like to group the subtype specific fields together in a drupal.org/project/field\_group

This pattern could just as well be applied on contenttypes. I think I will try it out.

In Microsoft Sharepoint, ContentTypes has had inheritance for years. I wonder if it will come in a future Drupal version.
> -1 votes

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


# Question
Title: How to track down possible module conflict?
I am trying to get the SMTP Authentication Support module working on my development site. Whenever I try to send a test message, I get the error "SMTP -\> ERROR: Failed to connect to server: Permission denied (13)." Our SMTP server is configured to accept relay from any client on our internal network, which is where my server lives. When I look at the logs, I see two errors - one of type "mail" and one of type "smtp". Each say about the same thing. This leads me to believe that the SMTP module is conflicting with something, but no other modules are currently installed. I have tried/removed other versions of the SMTP module and the PHPMailer module. I can't find a "mail" module in the Core section, so I don't think that's it.

When I install the module on my local machine, in a clean Drupal instance, with all the same configuration settings, the test message flies right through. So, I'm guessing that maybe one of the other modules left some cruft behind in the database somewhere, and this may be causing a conflict with the SMTP module. However, I don't know how to hunt down and eradicate the problem.

Any ideas?

# Answer
After much beating my head against the wall, I found a solution:

https://drupal.org/node/1593684

Turns out, it was SELinux snuffing out the SMTP attempt before it could even reach the server! Doh!
> 1 votes

---
Tags: 7, emails
---


# Question
Title: Drupal: user directory shows blocked users
I have a simple user directory in drupal, but when I block certain user in the admin, they still show up in the directory, although clicking on the user gets you to "access denied" page for the user profile. Do I need to add something about the user status to make this work?

Here is the code:

```
$result = db_query('SELECT * FROM users_roles LEFT JOIN users ON users_roles.uid = users.uid left join node on users.uid = node.uid left join content_type_bio on node.vid = content_type_bio.vid WHERE users_roles.rid = 6 and node.type = "bio" ORDER BY users.name');

while ($data = db_fetch_object($result)) {
  // we're working off user names, so replace . with space and captitalize   $string = $data->name;   $pattern = '[\.]';   $replacement = ' ';   $name = preg_replace($pattern, $replacement, $string);   $name = ucwords($name);   $data->picture = 'http://example.com/' . $data->picture;   $image = $data->picture != "http://example.com/" ? theme_image($data->picture, $alt = $name, $title = $name, $attributes = array('class' =>'left'), $getsize = FALSE) : theme_image('http://example.com/files/pictures/default.jpg', $alt = $name, $title = $name, $attributes = array('class' =>'left'), $getsize = FALSE);
  $item[] = array('text' => $name, 'path' => 'user/'. $data->uid, 'avatar' => $image, 'title' => $data->field_occupation_value); //  $item[] = l($text = $name, $path = 'contact/'. $data->uid); //  $item[] = l($text = $name, $path = 'user/'. $data->uid .'/contact');   // this is an example of the url we're constructing   //http://example.com/user/27/contact
}

```

# Answer
From your query and the default `Block User` account user settings option available to the Site Administrator per User:

Simply add into your SQL query `WHERE` clause the following:

`and users.status <> 0`

and this will change your user list to NOT include blocked users.
> 2 votes

---
Tags: users
---


title: Complete export of Drupal nodes

text:
# Question
Title: Complete export of Drupal nodes
I am programatically generating nodes in my local Drupal 6 installation. I have to do it locally because I don't have access to some of the more nifty PHP commands / modules that I need in order to create the modules on the production server.

These nodes come out properly formatted with aliases already created, and I would like to export those to the production server with aliases intact.

I have been attempting to use the Node Export module, however that doesn't preserve aliases (as far as I can see anyway). The Deployment module has never left alpha for Drupal 6, and I have been running into errors while using it. When it did work, aliases were not preserved.

Is there a method to preserve aliases available?

# Answer
If you are using D6 why not modify your PHP scripts to generate a .CSV file with the required node information and path aliases, then use the node\_import module to import the nodes into the production site.
> 1 votes

# Answer
I've successfully used a combination of the following modules to do similar migrations:

* feeds (for import)
* feeds\_tamper (data normalization and mapping)
* views\_rss or views\_bonus (RSS feed of nodes or CSV export)

I can see (although I've never used) a patch for the Feeds module to maintain aliases as found here http://drupal.org/node/1284522

One big bonus with using the Feeds module for import is it understands (through a hashing system) data that has already been imported. So, if you used the ViewsRSS module you can setup a timed event for Feeds to grab only the new or update existing content without having to initiate a transfer on the production server -- they just stay in sync. I've also implemented a workflow where nodes are only published in the RSS feed after they have been reviewed by an editor ...

Cheers,

Rob McCrea
> 2 votes

# Answer
In my experience, what I normally do is work on the exact copy of the database locally and then upload the whole database.. isn't this something you might be able to do?

On the other hand, if you are creating everything problematically, can't you execute the PHP code on the server unsing the devel module?
> 1 votes

# Answer
If you have complex data and you have to do the import export several times http://drupal.org/project/migrate might is an option.

Another option might be http://drupal.org/project/content\_staging

If you have the possibility the route I would take is:

* Export & Backup your live site.
* Put it to maintaninance mode.
* Download the current live data to your development envoironment.
* Do the heavy lifting generation tasks locally.
* Test locally.
* Deploy the db to your live site.

Drush and backup and migrate can support this a lot. The other mentioned options generally work but every one will take lots of time.
> 1 votes

# Answer
I know this is an old link but I had a similar issue: I have two drupal systems and I wanted to export nodes from one drupal install and import them into another. When exporting/importing nodes via node-export, the menu links and the node path alias were not getting imported.

I noticed settings on admin/config/content/node\_export/ for each content type. There are checkboxes that allow you to "reset the values" of the alias, parent menu, etc. on import. Make sure the items you need are unchecked.

Drupal 7.
> -1 votes

---
Tags: 6, nodes, path-aliases, importing-exporting
---


# Question
Title: How to set jquery datapicker options from within Drupal?
I want to customize a jQuery datapicker in Drupal 7. I found code to set an event:

```
(function ($) {
Drupal.behaviors.only_monday = {
  attach: function (context, settings) {
   // $( ".selector" ).datepicker( "option", "showWeek", true );
   $.datepicker._defaults.beforeShowDay = onlyMonday;
    function onlyMonday ( date ) {
      if ( date.getDay() == 1 ) {
        return [true, 'ui-datepicker-days-cell'];
      }
      else {
        return [false, 'ui.datepicker-unselectable'];
      }
    }
  }
};
}(jQuery));

```

This works great, except for commented line. According to the jQuery docs that line (added by myself) should make visible the numbers of the weeks:

```
$( ".selector" ).datepicker( "option", "showWeek", true );

```

The context from within Drupal is probably different. But I have no knowledge of js :-(

In what way does this code for setting an option has to be adjusted ?

# Answer
Your are working within a Drupal behavior that could be reapplied several times on the DOM tree, in order to avoid processing the same element several times you should limit the `$($selector)` call to the passed-ind \`context and use a marker CSS class for already processed class. Something like

```
$('.selector:not(.only-monday-processed)').addClass('only-monday-processe').doSomethingwithTheElements();

```

To defines then set the datepicker options from Drupal server-side PHP, you need to store the selector(s) and options in the `settings` object received by your behavior `attach` function using the `drupal_add_js()` function or the `#attached` property of your form/render array element. Then your function can use the selector to apply the option to the element. Something like

In your module code, store the selector and options in `settings`:

```
drupal_add_js(array('myModule' => array('.selector' => array('showWeek' => TRUE))), 'setting');

```

In your JavaScript, for each stored selector, apply the datepicker options:

```
(function ($) {
  Drupal.behaviors.only_monday = {
    attach: function (context, settings) {
      var selector;
      if (typeof settings.myModule === 'object') {
        for (selector in settings.myModule) {
          if (settings.myModule.hasOwnProperty(selector)) {
            $(selector, context).filter(':not(.only-monday-processed)')
              .addClass('only-monday-processe')
              .datepicker('option', settings.myModule[selector]);
          }
        }
      }
    }
    // ...
  };
}(jQuery));

```
> 2 votes

# Answer
Via '#datepicker\_options':

First we add a callback to the #process on date field:

```
/**
 * Implements hook_element_info_alter().
 */
function MODULE_OR_THEME_element_info_alter(&$type) {
  if (isset($type['date_popup'])) {
    array_unshift(
      $type['date_popup']['#process'],
      '_process_date_popup_helper'
    );
  }
}

```

And now in the helper we can set any js option:

```
function _process_date_popup_helper($element, &$form_state, $form) {
  $element['#datepicker_options']['changeMonth'] = FALSE;
  $element['#datepicker_options']['changeYear'] = FALSE;

  return $element;
}

```
> 1 votes

---
Tags: javascript
---


# Question
Title: JSON Data Export in Views Displaying Hierarchal Taxonomy Terms
I am trying to create a JSON feed to be read by an external application (iOS app). I want to be able to set up a structure similar to below with views but have not been able to do so.

```
{
   "Term 1":{
        image: "http://image.com/url.jpg"
      "Term Child 1":[
         {
            "image":"2013-11-19"
         }
      ],
      "Term Child 2":[
         {
            "image":"2013-11-19"
         }
      ]
   }
}

```

I made a view but I do not have the option to create a contextual filter with depth. Any ideas?

Here is my view export:

```
$view = new view();
$view->name = 'configurator_options';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Configurator Options';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'field_image' => 'field_image',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_image' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'parent';
$handler->display->display_options['fields']['name']['label'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: Field: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = 'image';
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['type'] = 'image_url';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'url_type' => '0',
  'image_style' => '',
  'image_link' => '',
);
/* Field: Taxonomy term: Weight */
$handler->display->display_options['fields']['weight']['id'] = 'weight';
$handler->display->display_options['fields']['weight']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['weight']['field'] = 'weight';
$handler->display->display_options['fields']['weight']['separator'] = '';
/* Sort criterion: Taxonomy term: Weight */
$handler->display->display_options['sorts']['weight_1']['id'] = 'weight_1';
$handler->display->display_options['sorts']['weight_1']['table'] = 'taxonomy_term_data';
$handler->display->display_options['sorts']['weight_1']['field'] = 'weight';
$handler->display->display_options['sorts']['weight_1']['relationship'] = 'parent';
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  1 => '1',
);

/* Display: Data export */
$handler = $view->new_display('views_data_export', 'Data export', 'views_data_export_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'views_data_export_json';
$handler->display->display_options['style_options']['provide_file'] = 0;
$handler->display->display_options['style_options']['parent_sort'] = 0;
$handler->display->display_options['path'] = 'api/vehicles';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'temp';

```

# Answer
> 2 votes
I ended up doing just that. I was able to take a code sample from here and retrofit it. http://api.drupal.org/comment/50023#comment-50023

Here is the code I ended up with:

```
<?php
function configurator_menu() {
    $menu['api/configurator'] = array(
      'title'                   => t('Configurator JSON'),
      'page callback'   => array('configurator_api'),
      'access callback' => true
    );

    return $menu;
}

function taxonomy_get_nested_tree($vid_or_terms = array(), $max_depth = NULL, $parent = 0, $parents_index = array(), $depth = 0) {
  if (!is_array($vid_or_terms)) {
    $vid_or_terms = taxonomy_get_tree($vid_or_terms, 0, NULL, TRUE);
  }
  foreach ($vid_or_terms as $term) {
    foreach ($term->parents as $term_parent) {
      if ($term_parent == $parent) {
        $return[$term->tid] = $term;
      } else {
        $parents_index[$term_parent][$term->tid] = $term;
      }
    }
  }
  foreach ($return as &$term) {
    if (isset($parents_index[$term->tid]) && (is_null($max_depth) || $depth < $max_depth)) {
      $term->children = taxonomy_get_nested_tree($parents_index[$term->tid], $max_depth, $term->tid, $parents_index, $depth + 1);
    }
  }
  return

$return;
}

function taxonomy_nested_tree_render($tree, $recurring = FALSE) {
  $items = array();
  if (count($tree)) {
    foreach ($tree as $term) {

            $image = file_create_url($term->field_image['und'][0]['uri']);
      $item = array('name' => t($term->name), 'image' => t($image));

      if (isset($term->children)) {
        $item["children"] = taxonomy_nested_tree_render($term->children, TRUE);
      }

      $items[] = $item;
    }
  }

  if ($recurring) {
    return $items;
  }

  return $items;
}

function configurator_api() {
    $tree = taxonomy_get_nested_tree(1);
    $items = taxonomy_nested_tree_render($tree);

    print drupal_json_output($items);
    drupal_exit();
}

```

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


title: Date range display in views using PHP

text:
# Question
Title: Date range display in views using PHP
How do I display date ranges for Value1 and Value2 in the following format where value2 is display as the difference between Value1 and Value2 expressed in days. I'd like to rewrite the results of a view field using PHP code.

Value1=1-Jan-2013

Value2=6-Jan-2013

i.e. result expected:

```
1-Jan-2013 +5d

```

# Answer
> 1 votes
```
<?php
$datetime1 = date('d-M-Y', strtotime(value1));
$datetime2 = date('d-M-Y', strtotime(Value2));
$interval = date_diff($datetime1, $datetime2);
$result = $datetime1 . ' ' . $interval;

```

result will be 1-Jan-2013 +5d

---
Tags: datetime, views
---


# Question
Title: Drupal 6 : views Exposed Form : rename the label of a field : please how?
I need the checkboxes labels exposed in views search pages to be different than the checkboxes labels displayed in the node/xx/edit forms.

I found the same documentation everywhere about the way to change the label of a submit button using a template.php function (works fine) :

```
function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  if ($vars['form']['#id'] == 'views-exposed-form-XXX') {
    $vars['form']['submit']['#value'] = 'gagarine' ;
    unset($vars['form']['submit']['#printed']);
    $vars['button'] = drupal_render($vars['form']['submit']);
  }
}

```

I can't find any accurate documentation to rename a cck field label when exposed in a search page.

edit² : cleaning the thread for relative readability since I got something working

# Answer
> 1 votes
ok I came to this : this looks like it does the job. maybe this could be rewieved by a DOCUMENTED drupal hacker.

```
function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // only alter the jobs search exposed filter form
  if ($vars['form']['#id'] == 'views-exposed-form-MYFORMID') {

    // change the text of an exposed field label (BEF checkboxes here)
    $vars['form'][FIELDNAMEasinurl]['#options'][0] = 'a different label in search pages' ;
    $vars['form'][FIELDNAMEasinurl]['#options'][1] = 'than in edit forms' ;
    // this particular field has a common layout not the case here :
    // this will work but not with the BEF checkboxes layout I want
    //$vars['widgets'][FIELDNAMEinternal]->widget = drupal_render($vars['form']['partage']);

    // or the field was rendered by better exposed filters (here cheboxes)
    // search into better_exposed_filters.theme the function call you need (theme_select_as..)
    $vars['widgets'][FIELDNAMEinternal]->widget = theme_select_as_checkboxes_fieldset($vars['form']['partage']);

    // Change the text on the submit button
    // [...]

  }

```

---
Tags: theming, forms, views
---


# Question
Title: How to set mysql port for Drupal and Drush
My site was running fine with the following default setting in settings.php file:

```
'host' => 'localhost',
'port' => ''

```

Then I created a separate mysql instance on another port:

```
'host' => 'localhost',
'port' => '123'

```

But this does not affect drupal - it still connects to the old db on default port!

With the following settings drupal connects to the new db, but now I can\`t make archive-dumps with drush. Drush reports an "Unknown MYSQL server host error".

```
'host' => 'localhost:123',
'port' => ''

```

# Answer
> 1 votes
For the port configuration in settings.php you can do by following(in example i used MYSQL in 33066) and the value of port is integer not string:

```
//D6 DB config
$db_url = 'mysqli://mysqluser:mysqlpassword@dbhost:33066/yourdb';

//D7 DB config
$databases = array('default' => array('default' => array(
  'driver' => 'mysql',
  'database' => 'yourdb',
  'username' => 'mysqluser',
  'password' => 'mysqlpassword',
  'host' => 'dbhost',
  'port' => 33066 )));

```

---
Tags: drush, database
---


# Question
Title: How to set value to login form's submit via themename_form_alter
I have theme\_form\_alter function, I want to set input submit value with it too

```
function ivanco_form_alter( &$form, &$form_state, $form_id )
{
    if (in_array( $form_id, array( 'user_login', 'user_login_block')))
    {
        $form['name']['#attributes']['placeholder'] = t( 'Email' );
        $form['pass']['#attributes']['placeholder'] = t( 'Password' );
        $form['name']['#attributes']['title'] = t( 'Введите email, указанный при регистрации' );
        $form['pass']['#attributes']['title'] = t( 'Введите пароль' );
        $form['submit']['#default_value'] = t( 'Принять' ); // this line doesnt work((
    }
}

```

# Answer
> 1 votes
Buttons and Submits (yes, they are different things in Form API) does not have default value. All you can set for submit is: #access, #after\_build, #ajax, #attributes, #button\_type (default: 'submit'), #disabled, #element\_validate, #executes\_submit\_callback (default: TRUE), #limit\_validation\_errors, #name (default: 'op'), #parents, #post\_render, #prefix, #pre\_render, #process, #submit, #states, #suffix, #theme, #theme\_wrappers, #tree, #type, #validate, #value, #weight

As you can see, no #default\_value. As user is not supposed to be able to change that value, it's simply #value - no need for defaults.

Read more on Form API Reference.

---
Tags: forms, theming
---


# Question
Title: Will removing the X-Drupal-Cache header break anything?
I have a client that wants to get rid of as much server information as possible from their headers, including "X-Drupal-Cache".

I know that anyone technical enough to be looking at headers can very likely tell that Drupal in plenty of other ways but that's beside the point.

It is easy to remove the header but if I do will it potentially break anything?

Note: I'm aware that there is a similar question at X-Drupal-Cache http header but that issue has long ago had an accepted answer that does not cover my specific question.

# Answer
> 1 votes
`X-` headers are optional, and are not allowed to be officially required, except in the same family of products. You can search Internet for some bizarre examples. My favourite is `X-PoweredBy: Unicorns` and `X-hacker: If you’re reading this, you should visit ******.com/jobs and apply to join the fun, mention this header.`

That said, it may not be required, but it may still be used. If your hosting company provides caching and load balancing, it may use this header to know that page came from Drupal's cache and thus there is no need to use that data to repopulate cache server's storage. It can be also used to track statistics. and of course you are using it to test if cache works OK on production, aren't you? All these uses will get impossible if you will remove this header, or rename it without coordination with other users. Site should be served OK, but in specific circumstances there is a risk of worse performance and crippled debug/analytic options. Maybe you can afford that risk. Maybe not.

**TL;DR** You need to ask anyone who might be using it, not us.

---
Tags: 7, caching
---


# Question
Title: How do I load a third-party PHP library in a module?
Suppose I want to load facebook-php-sdk in my Drupal website, how can I load that class file in a custom module? I tried with the Libraries module, with different functions provided by that module, but everytime I fail.

# Answer
> 5 votes
You can do the same way in Drupal for Facebook module and put these code in your custom module:

```
 $fb_lib_path = function_exists('libraries_get_path') ? libraries_get_path('facebook-php-sdk') : 'sites/all/libraries/facebook-php-sdk';
 $fb_platform = $fb_lib_path . '/src/facebook.php';
 try {
     if (!class_exists('Facebook') && !@include($fb_platform)) {
      //show error
      return NULL;
     }
     $fb = new Facebook(array(
       'appId' => $appId,
       'secret' => $secret,
       'cookie' => $cookie));
 }
 catch (Exception $e) {}

```

You can check the fb\_api\_init function of Drupal for Facebook module for more detail.

# Answer
> 3 votes
Libraries API is a module designed to take the burden of this from your shoulders. You probably have it already installed, as it is required by many other modules.

> The common denominator for all Drupal modules/profiles/themes that integrate with external libraries.
>
> This module introduces a common repository for libraries in sites/all/libraries resp. sites//libraries for contributed modules.

When you put library where it needs to be, simply use:

```
libraries_load($name);

```

> You can also attach library to renderable array like that:

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

```

More detailed documentation here: Using Libraries API 2.x (as a module-developer). That's the source of code snippets I pasted here .

---
Tags: 7
---


# Question
Title: Content disappeared for authenticated users
Suddenly, I have encountered a weird problem. I see my site flawlessly as admin and unauthenticated users. But all the timestamp-based content (Like blocks-forum thread etc.) disappear when I log in as a (non-admin) user.

I have checked server's time and truncated session table and flushed all cache but the problem persists. Really appreciate your hints.

# Answer
> 0 votes
Go to `admin/user/permissions` and then tick the check-box for authenticated users under **access content** and then click save.

---
Tags: 6, nodes, sessions
---


# Question
Title: After registration password : Your password is not correct
Once i registered my account with email and username, mail from account settings is getting. In that mail Password : Your password is displaying. If i used that password, it shows incorrect. I check ed in my account settings, its shows username: \[user:name\] password: Your password What i need to change to get the correct password in mail

# Answer
> 0 votes
Try this module : Registration Password Token. It will provide the user register password as a token.

> This small module provides token \[user:password\] during user registration. Site administrator allowed to customize the text of the e-mail that is sent to the user after registration.

---
Tags: users, emails
---


# Question
Title: How to make fields required for one type of user but not others? (registration and profile forms)
I would like to know what is the best way to handle this scenario using Drupal 7.

The issue I am facing is that the Join (registration) forms, and Profile forms are different for all 4 types of users I am working with. The registration and profile forms are all connected to one master profile form. This means that if a field is required for one, it will be for all of users, how can I avoid this? What is the best way to go about it?

Thanks!

# Answer
> 2 votes
Required By role

> Field required by role is a module that improves core "required" functionality.
>
> Similar to CCK Required by role brings extra features such as:
>
> Ready for all entities, including custom entities. Doesn´t need extra configuration, just install. Respects previous configuration. Configuration per field instance.

# Answer
> 1 votes
You can do it by hook\_form\_alter. Alter the **#required** attribute of field according to specific condition.

For example:

```
function mymodule_form_alter(&$form,&$form_state) {
    if ($form_id == 'user_register_form') {
      $form['profile_detailp']['field_name']['und']['#required']=0;
   }

}

```

---
Tags: users
---


# Question
Title: I enabled certain page view (which is a clone of currently working view), but its page link returns 404 page
The view is enabled, but its page returns 404. in what cases can such problem exist?

# Answer
> 0 votes
Save the views and then in `admin/config/development/performance` do `clear cache`

---
Tags: views
---


# Question
Title: Manually populating fields using SQL queries
I have created a new field on an existing content type. The field is called "Global News." It's a checkbox and I need it to be checked for all existing nodes. I ran a SQL query to gather all nodes of a specific type joined with the latest revision ID. Both the "field\_data\_field\_global\_news" and "field\_revision\_field\_global\_news" tables are populated with the correct fields but the checboxes remain unchecked. Is there another table I need to update so this field is linked to the correct nodes?

I tried editing one of the nodes manually, which worked, but the table entry remains the same which leads me to believe there is another table that needs populating.

Any ideas?

# Answer
> 0 votes
Drupal acts a bit differently,

1) Can you try cleaning your cache.

2) Write a function in a custom module

```
function _get_nodes() {
  $options = array();
  $sql = "SELECT nid, type FROM {node}";
  //adjust the query to filter on content types, if needed
  $result = db_query($sql);
  foreach ($result as $row) {
    $node=node_load($row->nid);
    //dpm(node); maybe you have different naming convengion
    $node->field_global_news['und'][0]['value']=1;
    node_save($node);
    unset($node);
  }
  return $options;
 }

```

---
Tags: entities, database
---


# Question
Title: Show a message after file_transfer is executed
I am using file\_transfer to send a download to the http client. The problem is that file\_transfer executes drupal\_exit so that no more code is executed after it. How do you show a message or redirect to another page after sending a file\_transfer ?

# Answer
> 1 votes
By default, you can't - when someone clicks a link to a file that's force-downloaded, it happens as a separate request/process entirely. For security reasons your web site will not be able to tell when/if that download has completed.

I think the easiest thing you can do is implement some javascript on the download link, which auto-refreshes the page as soon as you've clicked it, and while the file is still downloading. You could use a query string or similar to note that a message should be displayed or that a redirect should happen.

If you need something more complicated, you might be able to implement an AJAX-based polling mechanism, which contacts the server and checks the connection status for that file. It's not a trivial task though, and I think you'd need to change the file\_transfer module quite a bit to implement that. It also might require some advanced server configuration. All beyond the scope of Drupal, so I'd advise getting a solution working independently first, and only then worry about getting it inside Drupal.

There are some ideas here, and related logic here

---
Tags: files
---


# Question
Title: Advanced form block - fields not showing in block configuration
I have installed Advanced Form Block (AFB) in a Drupal 7 site.

At first the AFB settings didn't show. But after applying the patch from issue 1863852 that got resolved. I can now create blocks, but in my block configuration form no fields are showing up. I am not getting options like in this image:

Basically I have a content type add content form that I was hoping to be able to split up into different blocks. I created an add type of block but when I go to that blocks configuration page I don't get any options beyond the normal options (no field selection options are presented to me).

Any idea why?

Infact the block isn't displaying at all, and I tried using different content types. When I go to the block configuration and save it I also get these notices:

I have been and am continuing to use Form Block.

Thinking about it those notices appearing would seem to be part of the problem as they would hint that the fields aren't being found and therefore cannot be displayed.

# Answer
> 1 votes
It seems formblock and afb (advanced form block) conflict with each other. On my development site i disabled and uninstalled formblock and then all aspects of advanced form block worked as it should. I do not want to do this to my production site because I am unsure of whether I will switch due to the work invovled

---
Tags: entities
---


title: Redirect node form in D7

text:
# Question
Title: Redirect node form in D7
It looks like silly question but I'm really confused about redirection after node save and update.

I tried to set `$form['#redirect']` \- without any success. I tried to set some other vars for instance: `$_REQUEST['destination']` or in `$form['buttons']['submit']['#submit']` setting function name to call that sets `$form_state['#redirect']` but none of this solution works.

Can you give me some source that explains node forms redirecting in D7?

# Answer
> 2 votes
1.Use hook\_node\_create and hook\_node\_update, judge your node type to drup\_goto, like:

```
function hook_node_create ($node) {
  if ($node->type == 'YOUR_NODE_TYPE') {
     drupal_goto('YOUR_DESTINATION');
  }
}

```

2.Use hook\_form\_alter change your node form, like:

```
function hook_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'YOUR_NODE_FORM_ID') {
    $form['actions']['submit']['#submit'][] = 'YOUR_NODE_FORM_ID_ls_submit';
  }
}

function YOUR_NODE_FORM_ID_ls_submit ($form, &$form_state) {
  $form_state['redirect'] = 'YOUR_DESTINATION'; // Not $form_state['#redirect']
}

```

# Answer
> 2 votes
You have to add a new submit callback to your validate button with a hook\_form\_alter and add a $form\_state\['redirect'\] :

```
mymodule_form_alter(&$form, $form_state, $form_id){
$form['actions']['submit']['#submit][] = 'mymodule_redirect_callback';
}

mymodule_redirect_callback($form, &$form_state){
$form_state['redirect'] = array('___your__phath____');
}

```

Don't forget to pass the $form\_state variable in your callback BY REFERENCE ( '&$form\_state' and not juste '$form\_state').

I used this method hundreds of times.

Finally, don't forget that a 'destination' parameter in the URL will always override any redirect set in $form\_state\['redirect'\]. See drupal\_redirect\_form for more information

# Answer
> 0 votes
There is the Node Save Redirect module for this purpose. Check it out! Here is a quote about it (from the module's project page):

> ... provides a method of specifying a location to take the user after saving a piece of content.
>
> A set of radios buttons are added to the submission vertical tab on the content type edit form.
>
> The available options are:
>
> * Default - Default behaviour
> * Return to Edit page after saving
> * Return to content overview page (assuming the user has access permissions
> * Re-redirect to another location. (any valid drupal path)

---
Tags: redirection, forms
---


title: MySQL join custom field to uid

text:
# Question
Title: MySQL join custom field to uid
I need to export some data directly from a D7 DB. I'm not that familiar with the Drupal DB schema. Some additional profile fields have been added to users profiles and I would like to export that along with some columns from the `users` table.

In this case the `job_title` custom field data appears to be stored in the `field_data_field_user_job_title` table.

In that table I notice there are columns `entity_type` and `entity_id`. The value `entity_type` is set as `user` for all rows in this table.

Does this mean that the `entity_id` field for rows in this table where `entity_type='user'` can be joined to `users.uid` to associate the custom profile data with the correct user record?

# Answer
If the fields you're interested in are attached to the user entity directly (i.e. not using something extra like the Profile2 module), then your assumption is 100% correct. You'll also see a `field_revision_field_user_job_title`, which is used to store the current revision (for entities that have that functionality).

The user entity doesn't have revisions, so in my experience if you need to go directly into tables, the `field_data_*` ones are the best bet.

To get as much reusability as possible, though, you should really use the `EntityFieldQuery` class to perform such queries. For example, if you wanted to get all users with a certain "job\_title", you can use something like this:

```
$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_title', 'value', 'foo');

$results = $query->execute();
if (!empty($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
}

```
> 2 votes

---
Tags: 7, users, database
---


title: Using colorbox with media files

text:
# Question
Title: Using colorbox with media files
The components I am using are:

* CKEditor 3.6.6.1
* Media 7.x.2.x-dev
* Media Colorbox 7.x-1.0-rc4
* Colorbox 7.x-2.4
* Panels 7.x.3.3

The Theme I am using is: Bootstrap 7.x-2.2

I am trying to figure out how when I insert an image via the WYSIWYG editor CKEditor to have the image be smaller then be able to be opened in a colorbox. I am currently using the above modules with this process:

1. Create a new article
2. Click insert media
3. Click Library
4. Click a preloaded image I already have selected
5. Display as Colorbox
6. Click submit
7. Save the content

After all of that nothing happens. The image is not clickable at all (as to mean that a pointer does not render when I move my mouse over the image). What I am asking is simple. I have read that Media should handle colorbox integration now for images... how? I want to be able to insert images via the WYSIWYG but cannot seem to find instructions on this matter.

# Answer
Did you customize this page: http://yoursite.com/admin/config/media/file-types/manage/image/file-display/colorbox ?

You should select a display mode for thumbnail (small image) and Colorbox (full size image). Once you have updated this, clear caches or edit your content and save it again. Otherwise, your changes won't have any effect.
> 1 votes

---
Tags: 7, wysiwyg, media, javascript
---


# Question
Title: How to change Read more option in the front page of drupal 7?
I am using drupal7. If we published a content to "promoted to front page". It will act as from the default front page view. I want to change the "Read More" option as "More". Where i can change the option? Please help me?

Thanks, Sathish

# Answer
```
function MODULE_node_view_alter(&$build){
  if( isset($build['links']['node']['#links']['node-readmore']['title']) )
    $build['links']['node']['#links']['node-readmore']['title'] = t('More');
}

```

You can apply more checks in order to change the link title for some special scenario or for some specific content type.
> 3 votes

# Answer
You can also edit the node.module file changing 'Read more\<span ..... to 'More as I did below:

```
if ($view_mode == 'teaser') {
  $node_title_stripped = strip_tags($node->title);
  $links['node-readmore'] = array(
    'title' => t('More<span class="element-invisible"> about @title</span>', array(
       '@title' => $node_title_stripped
     )
   ),

```
> 0 votes

# Answer
String Overrides Module have been my best bet when not in mood to touch codes for small things like that.

Define *Read more* in **Original** and *More* in **Replacement**.
> 0 votes

---
Tags: nodes
---


# Question
Title: Problem installing Drupal 6.22 with Drush
I'm trying to install Drupal 6.22 with Drush 4.4 on my CentOS 5.6 box, but am having problems getting it to work.

I run the following command:

```
drush dl drupal-6.22 --drupal-project-rename=drupal1

```

Then I run:

```
drush status

```

and get:

```
 Drupal version         :  6.22
 Default theme          :  garland
 Administration theme   :  garland
 PHP configuration      :  /etc/php.ini
 Drush version          :  4.4
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /var/www/html/drupal1

```

Which seems to suggest that all was downloaded properly.

Then I run the following command to start setting it up:

```
drush site-install standard --account-name=admin --account-pass=REMOVED --db-url=mysql://admin:REMOVED@localhost/drupal1db

```

It asks me if I want to continue and I choose 'yes'. After a second or two, it returns me to the command line prompt.

Then I run 'drush status' again, which returns the following error:

Table 'drupal1db.access' doesn't exist \[warning\] query: SELECT 1 FROM access WHERE type = 'host' AND LOWER('127.0.0.1') LIKE LOWER(mask) AND status = 0 LIMIT 0, 1 database.mysql.inc:135 Table 'drupal1db.cache' doesn't exist \[warning\] query: SELECT data, created, headers, expire, serialized FROM cache WHERE cid = 'variables' database.mysql.inc:135 Table 'drupal1db.variable' doesn't exist \[warning\] query: SELECT * FROM variable database.mysql.inc:135 Table 'drupal1db.cache' doesn't exist \[warning\] query: UPDATE cache SET data = '', created = 1309816902, expire = 0, headers = '', serialized = 0 WHERE cid = 'variables' database.mysql.inc:135 Table 'drupal1db.system' doesn't exist \[warning\] query: SELECT name, filename, throttle FROM system WHERE type = 'module' AND status = 1 AND bootstrap = 1 ORDER BY weight ASC, filename ASC database.mysql.inc:135 Table 'drupal1db.url\_alias' doesn't exist \[warning\] query: SELECT COUNT(pid) FROM url\_alias database.mysql.inc:135 PHP Fatal error: Call to undefined function filter\_xss() in /var/www/html/drupal1/includes/common.inc on line 655 Drush command terminated abnormally due to an unrecoverable error. \[error\] Error: Call to undefined function filter\_xss() in /var/www/html/drupal1/includes/common.inc, line 655

I go to the Drupal directory in my browser and it just shows a blank white page.

Any ideas?

# Answer
> 5 votes
I had a similar problem when trying to install Drupal 6.26 with drush 4.5 and 5.0 (I tried both).

You do not have to create the database. You can but drush will drop it and re-create it.

I fixed my problem by doing :

```
drush site-install default --db-url=mysql://drupaldbuser:REMOVED@localhost/drupal-6-25

```

I used the profile `default` rather than `standard` since drupal 6.x uses `default` as the default profile. The `standard` profile is the new default name in Drupal 7.

# Answer
> 4 votes
given the "doesn't exist" errors you're seeing, i'll ask -- have you in fact created the DB, and aassigned proper permissions?

just for reference, although on Drupal 7 with Drush 5x (not sure it's the same for older Drupal & Drush), this works for me.

1st create the DB manually,

```
mysqladmin create my_D7_db

```

assign permissions,

```
mysql
  mysql> GRANT CREATE, DROP, SELECT, UPDATE, DELETE, ALTER, LOCK TABLES, INSERT, INDEX, CREATE TEMPORARY TABLES ON `my_D7_db`.* TO 'my_D7_dbadmin'@'localhost' IDENTIFIED BY 'my_password';
 FLUSH PRIVILEGES;
 quit

```

then exec the Drupal install,

```
drush site-install standard -y --site-name=www.mysite.com --site-mail=me@myemailhost.com --account-name=my_D7_admin --account-pass=my_D7_admin_password --db-url=mysql://my_D7_dbadmin:my_password@localhost/my_D7_db --db-prefix=my_D7_

```

immediately after this, the site's available, assuming your webserver's properly pointed at the Drupal root, at:

```
http://www.mysite.com

```

maybe give that a try?

# Answer
> 0 votes
In certain distributions, like Acquia, the default profile does not exist, and `drush site-install` fails. In this example, the following code will work:

```
drush si acquia --db-url=mysql://user:password@localhost/db -y

```

---
Tags: drush
---


# Question
Title: I can create content type fields pragmatically, but I set het widget options too?
Im using field\_create\_instance to create all my defined fields, and use the correct field types and widget types and such, but Im not sure how to set the widget options.

In my use case, Im using the colorfield module and am trying to save the default options for the widget so the content type automagically uses farbtastic but I'm not the greatest drupal dev yet and am not sure how to do that.

Right now, my instance looks like:

```
'fill_color' => array(
    'field_name' => $fields['field_map_fill_color']['field_name'],
    'label' => 'The inactive state colors',
    'bundle' => 'nji_map',
    'entity_type' => 'node',
    'widget'      => array(
        'type'    => 'colorfield_unified_textfield'
    ),
    'description' => 'This is the color of the inactive color of the state.',

),

```

So that sets the field to use the colorfield field widget alright, but I need to set it up so it also uses the farbtastic option. I took a look at the module and theres a hook called hook\_field\_info with this option:

```
    'instance_settings' => array(
        'colorfield_enable_colorpicker' => TRUE,
        'colorfield_colorpicker_type' => 'farbtastic',
    ),

```

I looked at the drupal field\_create\_instance hook and i feel like it needs to go into widget-\>type right? Well I cant seem to get it to work.

Ive also tried:

```
    'background_color' => array(
        'field_name' => $fields['field_map_background_color']['field_name'],
        'label' => 'The background color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'description' => 'The background color is the color between.',
        'widget'      => array(
            'type'    => 'colorfield_unified_textfield',
        ),

        'instance_settings' => array(
            'colorfield_enable_colorpicker' => TRUE,
            'colorfield_colorpicker_type' => 'farbtastic',
        ),

    ),

```

# Answer
> 0 votes
I think it should look like this :

```
    'field_instance' => array(
  'bundle' => 'fo',
  'default_formatter' => 'text_default',
  'default_value' => NULL,
  'default_widget' => 'text_textfield',
  'deleted' => '0',
  'description' => 'blah blah blah.',
  'display' => array(
    'default' => array(
      'label' => 'above',
      'module' => 'text',
      'settings' => array(),
      'type' => 'text_default',
      'weight' => 0,
    ),
  ),
  'entity_type' => 'taxonomy_term',
  'field_name' => 'test',
  'instance_settings' => array(
    'text_processing' => 0,
  ),
  'label' => ' test',
  'required' => FALSE,
  'settings' => array(
    'max_length' => 255,
    'text_processing' => 0,
    'user_register_form' => FALSE,
  ),
  'title' => 'test',
  'widget' => array(
    'module' => 'text',
    'settings' => array(
      'size' => 60,
    ),
    'type' => 'text_textfield',
    'weight' => 31,
  ),
),

```

# Answer
> 0 votes
In a moment of clarity I checked out the "features" plugin and realized that I could make the proper configurations with the manage fields UI and then export the code I needed to produce:

```
$field_instances['node-nji_map-field_map_background_color'] = array(
    'bundle' => 'nji_map',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => 'The background color is the color between.',
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'colorfield',
        'settings' => array(
          'height' => 20,
          'width' => 20,
        ),
        'type' => 'colorfield_color_swatch',
        'weight' => 5,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 0,
      ),
    ),
    'entity_type' => 'node',
    'field_name' => 'field_map_background_color',
    'instance_settings' => array(
      'colorfield_colorpicker_type' => 'farbtastic',
      'colorfield_enable_colorpicker' => TRUE,
    ),
    'label' => 'The background color',
    'required' => 0,
    'settings' => array(
      'colorfield_colorpicker_type' => 'farbtastic',
      'colorfield_enable_colorpicker' => TRUE,
      'user_register_form' => FALSE,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'colorfield',
      'settings' => array(
        'colorfield_options' => array(
          'colorfield_colorpicker_type' => 'farbtastic',
          'colorfield_enable_colorpicker' => 1,
        ),
      ),
      'type' => 'colorfield_unified_textfield',
      'weight' => 35,
    ),
  );

```

---
Tags: 7, entities
---


title: HTML5 doctype with RDFa

text:
# Question
Title: HTML5 doctype with RDFa
I'm using Omega 3, and have a redundant HTML doctype header line.

How do I correct this so I have my HTML5 `<!DOCTYPE html>` line, and specify RDFa?

Currently, the first two lines of my pages are:

```
<DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">
<html lang="en" dir="ltr" version="HTML+RDFa 1.1"...>

```

# Answer
> 3 votes
Omega4 supports

```
<!DOCTYPE html>
<html lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

```

where you don't have to manually define RDFa.

Beside Omega4 I normally do (usually I use Zen, but you can do this in other themes too):

```
<!DOCTYPE html>
<html lang="en" prefix="dc: http://purl.org/dc/elements/1.1/">

```

and define `property="http://purl.org/dc/terms/TERMS` wherever I use RDFa

Dublincore Metadata Initiative has detailed information about the terms

Drupal7 core has RDF support via `rdf_namespaces`. The hook implementation is:

```
function hook_rdf_namespaces() {
  return array(
    'content' => 'http://purl.org/rss/1.0/modules/content/',
    'dc' => 'http://purl.org/dc/terms/',
    'foaf' => 'http://xmlns.com/foaf/0.1/',
    'og' => 'http://ogp.me/ns#',
    'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
    'sioc' => 'http://rdfs.org/sioc/ns#',
    'sioct' => 'http://rdfs.org/sioc/types#',
    'skos' => 'http://www.w3.org/2004/02/skos/core#',
    'xsd' => 'http://www.w3.org/2001/XMLSchema#',
  );
}

```

so you can simple do `<?php print $rdf_namespaces; ?>` in your **html.tpl.php** file where you start `<html>`.

If you want latest RDF support there is a module for that one too called RDFX.

# Answer
> 1 votes
I don't have a lot of experience with Omega, specifically, but many themes take their doctype expressions right out of the variables array when the theme templates are run. I would recommend undoing whatever you did that has caused the double-doctype issue and consider changing gears.

In your theme/sub-theme's template.php, add some code to your hook\_preprocess\_html().

According to as recently as April 2013, this code snippet appeared to work for an Omega user (see: https://groups.drupal.org/node/295068#comment-916713)

```
/**
 * Implements hook_preprocess_html().
 **/
function YOURTHEMENAME_preprocess_html(&$vars) {
  $vars['doctype'] = '<!DOCTYPE html>' . "\n";
  $vars['rdf'] = new stdClass;
  $vars['rdf']->version = '';
  $vars['rdf']->namespaces = '';
  $vars['rdf']->profile = '';

  // Serialize RDF Namespaces into an RDFa 1.1 prefix attribute.
  if ($vars['rdf_namespaces']) {
    $prefixes = array();
    foreach (explode("\n  ", ltrim($vars['rdf_namespaces'])) as $namespace) {
      // Remove xlmns: and ending quote and fix prefix formatting.
      $prefixes[] = str_replace('="', ': ', substr($namespace, 6, -1));
    }
    $vars['rdf']->namespaces = ' prefix="' . implode(' ', $prefixes) . '"';
  }
}

```

---
Tags: 7, theming, rdf
---


# Question
Title: Facet API and Entity Reference Autocomplete
I have two content types, with Drupal 7 :

* City
* Job Offer, with an Entity Reference CCK field named "City" that accept Node Entities of Type City.

I am also using the apachesolr module, with Facet API, and I would like my users to be able to filter the offers by city. However, as I have thousands of cities in the database, the "Links" widget is unusable.

How could I easily integrate the Entity Reference module's autocomplete widget (or https://drupal.org/project/entityreference\_autocomplete, or any other one...) with the Facet API ?

# Answer
> 3 votes
If you are using the Search API Solr with the Facet API, you can create a search index view and use the Facetapi Multiselect along with Chosen to allow your users to select the city via a user friendly drop down box (chosen not only supports typing the search term, but it also allows fuzzy matching). Even if the content type city is not indexed in Apache solr, you can create a relationship in your search view and make the city available to FacetAPI system. You can even expose the city as a filter (if you do not want to mess with facets at all) to your users with a views' relationship.

---
Tags: entities, ajax, search
---


title: Drupal AJAX forms & commands

text:
# Question
Title: Drupal AJAX forms & commands
I have a form updating with AJAX on select element change. Easy so far. The problem is that I need to return the form & also an ajax command at the same time.

If I need the form, I just return the `$form` array and if I need to return an ajax command I use `return array('#type' => 'ajax', '#commands' => $commands);`. Both works just fine.

The problem is that I don't get it how to combine both of them in the same return object.

Any ideas how can I do that?

# Answer
> 2 votes
As a backup solution, I'll do it this way:

```
$form['#suffix'] = '<script type="text/javascript">some_function_to_do_what_i_need();</script>';
return $form;

```

this should work.

# Answer
> 1 votes
You have to pass to `drupal_render()` the form array, then add it to your `$commands` as an AJAX command. You should use code similar to the following one.

```
function my_ajax_form_callback($form, &$form_state) {
  $new_state = array();
  $new_state['build_info'] = $form_state['build_info'];
  $new_state['rebuild'] = TRUE;
  $new_state['values'] = array();
  $new_state += form_state_defaults();

  $new_form_array = drupal_rebuild_form('my_ajax_form_id', $new_state);
  $new_form = drupal_render($new_form_array);

  $commands = array();
  $commands[] = ajax_command_html('#form-container-element-id', $new_form);

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 1 votes
I would use `hook_ajax_render_alter(&$commands)` e.g.

```
function myModule_ajax_render_alter(&$commands) {
  $commands[] = myModule_custom_command('hi');
}

```

See the documentation for details.

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


# Question
Title: user-profile.tpl.php and render($user_profile) not working
Pulling my hair out after googling all day to solve this.

I am using a corolla subtheme on drupal 7. I am trying to override the user account edit page in a template file.

For that I am using the default user-profile.tpl.php that comes with core's user module.

But without preprocessing the file won't be recognized by my theme. So I googled here and there and came up with the following:

```
function mytheme_theme(&$existing, $type, $theme, $path){

  $hooks = array();
    // Make user-profile.tpl.php available
    $hooks['user_profile_form'] = array (
       'render element' => 'form',
       'path' => drupal_get_path('theme','mytheme'),
       'template' => 'templates/user-profile',
       'preprocess functions' => array('mytheme_preprocess_user_profile_form'),
    );
  return $hooks;
}

function mytheme_preprocess_user_profile_form(&$vars) {
  $args = func_get_args();
  array_shift($args);
  $form_state['build_info']['args'] = $args;
  $vars['form'] = drupal_build_form('user_profile_form', $form_state['build_info']['args']);
}

```

My php is at a level copy/paste + minor adjustments with a lot frustration.

This preprocessing makes my site read the user-profile.tpl.php, but I can't access the array $user\_profile. Instead fields are in the array $form, which misses some fields I need, and all fields miss their default values which should come from the user whose account is shown.

This way I can't rebuild the default password-inputboxes and the 2 new password-inputboxes, and I need a lot of extra php to supply the values for all fields.

I am missing something here, but my knowledge won't go that far that I know what to change, and my google-fu is depleted. I think I need to change some things in the preprocessing-code, so that the array $user\_profile is loaded and all the fields have the correct values allready.

How to accomplish this?

How can I make this to work?

# Answer
In order to have the `$user_profile` renderable array available within your tpl, you can use the same logic used by Drupal `user` core module.

Build the content for a user object, loop through each field and assign it to the `$user_profile` variable.

In your case, it would something like this:

```
function mytheme_preprocess_user_profile_form(&$vars)
{
    // load user
    $account = user_load(arg(1));

    if (!$account) {
        // user not found
        return;
    }

    // retrieve all profile fields and attach to $account->content.
    user_build_content($account);

    // loop through each field attached to the user object
    $vars['user_profile'] = array();
    foreach (element_children($account->content) as $key) {
        // add it to the $user_profile variable, which will be available in tpl
        $vars['user_profile'][$key] = $account->content[$key];
    }

    $args = func_get_args();
    array_shift($args);
    $form_state['build_info']['args'] = $args;
    $vars['form'] = drupal_build_form('user_profile_form', $form_state['build_info']['args']);
}

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to modify module output via another module - whois module?
In drupal 7, can we access and read return value of a specific module via another module?

Specifically, I am using the whois module, and would like to access its output from a custom module, with the goal of modifying the output.

How can I do this? What is the suitable hook function? How can I access the output from whois before it gets rendered.

Please guide me.

Thanks a lot.

# Answer
> 1 votes
You can change the output through preprocessing, for example in your theme's template.php file, or in your custom module (see also: https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook\_preprocess\_HOOK/7).

The $variables\['content'\] variable contains the content of the block to be displayed. The individual elements come from $variables\['elements'\]. If you add:

debug(array\_keys($variables\['elements'\]));

to the script, you get the following output:

```
array (
  0 => 'whois_form',
  1 => 'whois_lookup_data',
  2 => '#block',
  3 => '#weight',
  4 => '#theme_wrappers',
  5 => '#children',
)

```

When looking at these in detail, you see that $variables\['elements'\]\['#children'\] is comprised of $variables\['elements'\]\['whois\_form'\]\['#children'\] and $variables\['elements'\]\['whois\_lookup\_data'\]\['#children'\].

Ultimately, $variable\['content'\] is comprised of $variable\['elements'\]\['#children'\] (see also https://api.drupal.org/api/drupal/modules!block!block.module/function/template\_preprocess\_block/7)

So, there are two options:

1. Alter $variables\['elements'\]\['whois\_lookup\_data'\]\['#children'\], and recreate $variable\['elements'\]\['#children'\]
2. Alter $variable\['elements'\]\['#children'\] directly.

I chose the second option below.

To use the hook\_preprocess\_block hook, as shown below, the core module "Block" needs to be enabled.

If used in a module, in yourmodule.info:

```
name = Whois Alter Module
description = A module to change the output of whois.
core = 7.x
package = Drupal 7 Misc
files[] = whois_alter.module
dependencies[] = block
dependencies[] = whois

```

In whois\_alter.module:

```
<?php
// $Id$
/**
* @file
* A module to demonstrate hook_preprocess_block to alter the output of another module
*
* This module alters the output of the whois module
*/

/**
* Implements hook_help().
*/
function whois_alter_help($path, $arg) {
  if ($path == 'admin/help#whois_alter') {
    return t('A module to alter whois output.');
  }
}

/**
* Implements hook_preprocess_block().
*/

function whois_alter_preprocess_block(&$variables, $hook){

  if (isset($variables['elements']['whois_lookup_data'])) {
     $whois_modified = whois_alter_modify_whois($variables['elements']['#children']);
     $variables['elements']['#children'] = $whois_modified;
     $variables['content'] = $variables['elements']['#children'];
  }
}

function whois_alter_modify_whois($content) {
   // do what you want to do to modify the output
   return $altered_content;
}

```

For Theme preprocessing, just use the functional part of the module in template.php:

```
function yourtheme_preprocess_block(&$variables, $hook){

  if (isset($variables['elements']['whois_lookup_data'])) {
     $whois_modified = yourtheme_modify_whois($variables['elements']['#children']);
     $variables['elements']['#children'] = $whois_modified;
     $variables['content'] = $variables['elements']['#children'];
  }
}

function yourtheme_modify_whois($content) {
   // do what you want to do to modify the output
   return $altered_content;
}

```

---
Tags: 7, hooks
---


# Question
Title: In drupal 7 views, can views data be cached for logged in authenticated users?
For drupal 7 views 3.x, can you cache the data for logged in authenticated users? And where would this setting be located? A screenshot would be great! thanks!

# Answer
You click on the Caching link (here shown in the lower portion of the right column) and click Time-based (or whatever other cache()ing you have implemented on your system).

Then you can tell Views how long you want the cache()ing to be on the next menu presented:
> 1 votes

---
Tags: 7, views, caching
---


title: Language/Region selection i18n drupal 7

text:
# Question
Title: Language/Region selection i18n drupal 7
I would like to implement a Region selector in a Drupal 7 website. Not the default i18n where you have 1 language for multiple countries but English content for the USA and different English content for the UK.

For configuration I would like to select the applicable regions on my node (maybe with taxonomy items?) so when the content is the same for multiple region's we don't need to duplicate it in all region's/languages.

Is there a solid solution for my needs?

THANKS!

# Answer
To get a different content and/or interface for the USA and UK, go to *admin/config/regional/language/add* :

In predefined language, select **English, british**. This will add a new "english British" language with *en-gb* prefix, while default english has *en* prefix, and will import related .po files.

If you have only en-US and en-GB in your project, when the content is the same for both, simply set it as *Language neutral* in the content node submission.

Maybe you already know the great article series Drupal 7's new multilingual systems compilation. It is a valuable source to get a complete overview of Drupal 7 multilingual setup.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: How do I compare a field of a node with all nodes of a content type with rules?
In Rules on Drupal 7, how do I set up a rule / ruleset so when a node is saved compares a textfield from the saved node with a textfield in all nodes of a content type and if match, not the saved node but the matching node should be unpublished?

# Answer
> 0 votes
I am not sure this can be accomplished with rules entirely. I am interested if a solution exists. Since I am much more comfortable with "custom module" solutions, I will give you some pseudo code that might help you achieve this functionality.

Imagine you are creating a custom module called "mymodule"

```
function mymodule_node_update($node){
  //get content type
  //if content type="x"
     // run entity_query(because it has field condition property) to get all PUBLISHED nodes where field Y == node -> field Y. and store the node id's (shorthand: NIDS).
  //save all the NIDS into an array
  // run db_update query to set the status to unpublished
}

```

how to use entity query Regards !

Oleg

# Answer
> 2 votes
I haven't found a solution using only rules yet, maybe it would be possible with rules and views bulk operations (vbo)? A custom module is what I did to solve it (thanks Oleg for pointing me to EntityFieldQuery). Here is the code:

```
<?php

/**
 * @file
 * custom_unpublish.module
 *
 * This module compares a field in a node when updated with a field in all
 * nodes of a content type and if match, the matching nodes is unpublished
 */

function custom_unpublish_node_update($node) {
  // Only check nodes of a certain content type
  if ($node->type == 'article') {
    $wrapper = entity_metadata_wrapper('node', $node);

    // Get the wanted field
    $id = $wrapper->field_id->value();

    $query = new EntityFieldQuery();

    // Check only a certain content type (bundle) and make a fieldCondition
    $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'accepted_article')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_id', 'value', $id, '=');
    $result = $query->execute();

    if (isset($result['node'])) {
      $result_items_nids = array_keys($result['node']);
      $result_nodes = node_load_multiple($result_items_nids);
      foreach ($result_nodes as $result_node) {
        // Unpublish the node
        $result_node->status = 0;
        node_save($result_node);
        watchdog('custom unpublish', 'Match for ' . $id . '. ' . $result_node->title . ' was unpublished.');
      }
    }
  }
}

```

---
Tags: rules
---


# Question
Title: Translate was disallowed for HTML input in a view- how to enable?
I have created a custom field in view and I want to translate it but the Drupal prevent me, It shows this error

How I can resolve this problem? I used Drupal 7.7

# Answer
By default, `Filtered HTML` and `Full HTML` are not available for translation. You can override this by enabling the i18n module and visiting:

* `/admin/config/regional/i18n/strings` (on Drupal 7)
* `admin/settings/language/configure/strings` (on Drupal 6)

Just check the boxes for the text formats which you wish to enable.

Depending on your situation, you may also need to enable the i18n Views module.
> 8 votes

# Answer
Patrick answer is good. In some cases though you might run into the same error even with Full HTML available for translation. In this case you may have to turn down validation (this has security implications so do not use if untrusted people have access to the translation interface (I strongly recomand not to give access to the translation interface to untrusted people ;) )).\*

Anyway to turn down translation validation create a custom module with this fonction :

```
  function YOURMODULE_form_i18n_string_locale_translate_edit_form_alter(&$form, $form_state) {
    unset($form['#validate']);
    // could also replace default validation handler function
    // (locale_translate_edit_form_validate) with a modified version.
  }

```
> 6 votes

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


# Question
Title: Integer field with unix timestamp convert to readable date in views
I have an Integer field in a content type, which contains a unix timestamp. \*(It is not a date module field; just a simple Integer field). In a View, I am rendering this field, but obviously it is just going to spit out the long unix timestamp; and I want it to read Feb 20th, 2013. How can I have Views format this field so that it spits out the readable date? I imagine I would create the views-view-field--field-MYTIMESTAMP.tpl.php, and copy in the default code, then use some php logic to convert it, right? But I am not sure how to do that part.

# Answer
> 2 votes
First you should define a suitable format- Do this in the administrative GUI:

1. Navigate to: Administration » Configuration » Regional and language » Date and Time
2. Click the tab "Formats" and click on link "Add format".
3. Create a new format. You use the same string as you would pass to the PHP `date` function, i.e.: `M jS, Y`. Save it.
4. Click the tab "Types". Click on link "Add date type".
5. Select the newly created format from the menu, and name it: `dateonly`, and save it by clicking on "Add date type".

You now have a type of date format named `dateonly` defined you can use *anywhere* on your site there is a date field to be displayed without the hour and minutes part.

To format the date in your View, you may should Drupal `format_date` function with `'dateonly'` passed as the type of format to use (second argument). To output this in your view you may have the following in your `view-view-field--fieldname.tpl.php`:

```
<?php
$nicedate = format_date($output, 'dateonly');
print $nicedate;
?>

```

IMHO, there is a big advantage in first defining a standard type of date format and giving it a name. This ensures that dates are displayed consistently throughot the site.

However, if you can't be bothered to first define the `dateonly` type of format, you can use `custom` as your second argument to `format_date` and then, as your third argument, pass a string that can be passed on to the PHP `date` function:

```
<?php
$nicedate = format_date($output, 'custom', 'M jS, Y');
print $nicedate;
?>

```

# Answer
> 0 votes
You can override the template for that field as you mentioned, and use the date function to output a timestamp with the "Feb 20th, 2013" format:

```
print date("M jS, Y", $timestamp);

```

---
Tags: views, entities, datetime
---


# Question
Title: Where do i enable caching for drupal 7 panels data for Logged in Authenticated users?
For drupal 7 panels where do i set the settings to enable caching for logged in authenticated users?

# Answer
> 3 votes
You can enable Panels caching on a per-panel-pane basis.

Edit the panel pane and set the "Cache" configuration there.

You can also create your own cache plugins via the ctools plugin API.

---
Tags: 7, panels, caching
---


# Question
Title: How to popup a dialog when a checkbox is unchecked on webform?
I have a checkbox in Webform. By default, the checkbox is selected. I'd like to popup a message dialogbox if the user uncheck the checkbox. How can that be done in Webform?

# Answer
> 3 votes
```
$('#checkbox-id').click(function(){
  if(!$(this).is(':checked')){
    alert('You unchecked the checkbox');
  }
});

```

---
Tags: 6, webforms, javascript
---