title: taxonomy delete vocabulary

text:
# Question
Title: taxonomy delete vocabulary
I have a huge taxonomy vocabulary (over 5k terms) and I'm using a shared hosting account.

Whatever I try to delete the vocabulary from drupal I get the error

```
Fatal error: Maximum execution time of 30 seconds exceeded in /home/username/public_html/drupal_site/includes/database/database.inc on line 2179

```

Anyway after looking online I found that with shared hosting I can't change the max\_execution\_time .

My next bet is to delete it from the database level in phpmyadmin.

How would I go about doing that? Are there any other ways for me to accomplish what I'm trying?

# Answer
You could also download and install the site / database on a local machine, delete the terms, and then restore the updated database using the 'backup and migrate' module. That way you would have full control of php.ini settings.
> 2 votes

# Answer
It seems that disabling the Pathauto module does the trick.
> 0 votes

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


title: Running cron results in Caches Flushed

text:
# Question
Title: Running cron results in Caches Flushed
I am unable to run cron on a Drupal 6.25 web site.

Running cron using both the **run cron** option from administration menu and the **run cron manually** link from **status report** page results in the following message:

```
Caches flushed.

```

The warning message next to the **cron maintenance tasks** entry on the status report persists and cron hasn't run.

I recently upgraded to latest version of Drupal. This issue also affects development copy of web site.

As always, I ran update.php after upgrade - no errors reported.

Tried changing number of items at /admin/settings/search to 10.

Can anyone advise how to fix the problem?

# Answer
> 0 votes
Disabling the PHP filter module, as per suggestions below solved the problem:

http://drupal.org/node/123269#comment-5696238

However, ultimately I believe the issue was caused by illegal mix of collations error.

Changing the collation of all table to utf8\_unicode\_ci using MySQL Workbench solved the problem.

# Answer
> 0 votes
`system_cron` calls `cache_clear_all` with `$cid == NULL`, which should just be clearing out expired entries.

My *guess* is that something else is wrong with the system, and cron is failing as a result.

When you upgraded, did you make sure you ran `update.php`?

Do you see cron listed as being run in watchdog (/admin/reports/dblog)?

Are there any php or other errors/warnings in watchdog around the cron run?

What does your search index status say (/admin/settings/search)? cron will index search each run. If this takes too long, you may have problems. Try dropping down the number of items per run.

If you run `drush cron` from the command line, does it run properly?

---
Tags: 6, caching, cron
---


# Question
Title: how to put arguments into contextual filters
In this post http://drupal.org/node/228959 says that i need to add an code to the argument of view2,

I add a contextual filter in views 3, but where is the spot to place the following code?

```
if (arg(0) == 'user' && is_numeric(arg(1))) {
    return array(arg(1));
}

```

# Answer
There's a comment in that article down below with a code to import for D7 and Views 3.

If you import that code into your Views 3 and then study the **Contextual Filters** and the **Relationships** you should get a good idea on how to achieve this.
> 0 votes

---
Tags: 7, views
---


title: how to fetch parts of url in javascript

text:
# Question
Title: how to fetch parts of url in javascript
I have a url like this: http://localhost/something/de/

The last one is the language code de for German. I want to fetch it using javascript. The link may also become like this: http://localhost/something/de/node/artist/117/author/98, in that case how do I fetch the language part.

Actually I want to set up placeholder using javascript, I got the help for placeholder but I dont get how to fetch the language part from url.

# Answer
You can do this in jQuery, just get the url and then split as required.

```
$(document).ready(function() {
    var $url = window.location.pathname;
});

```
> 1 votes

---
Tags: 7, javascript
---


title: how to get the node author link

text:
# Question
Title: how to get the node author link
In the node.tpl, how do i just get the `$author` profile page url?

with the `$submitted`, it prints out other things, all i need is just something like this:

```
<a href="$url">$author</a>

```

I've also used `$name`, but this only gives the name without a link.

I would also like to get the link to the current user's profile. Again, just need the username with their profile url only.

# Answer
> 3 votes
```
$url = l("user/" . $node->uid);

```

---
Tags: 7, users
---


title: How can I migrate user profile content?

text:
# Question
Title: How can I migrate user profile content?
I am using `user_save()` to migrate users from another application into Drupal, but my profile fields are not updating.

Does anyone have any suggestions as why this isn't working, or how I can get it to

```
        $newUser = array(
          'name' => $row->user_name,
          'pass' => $row->user_password, // note: do not md5 the password
          'mail' => $row->user_email,
          'status' => 1,

          'profile_title'=>$row->user_title,
          'profile_firstname'=>$row->user_first_name,
          'profile_lastname'=>$row->user_last_name,
          'profile_jobtitle'=>$row->user_job_title,
          'profile_orgname'=>$row->user_organization,
          'profile_telno'=>$row->user_contact_no,
          'profile_faxno'=>$row->user_fax_no,
          'profile_streetaddress'=>$row->user_address1.$row->user_address2,
          //'profile_address2'=>sanjay,
          'profile_city'=>$row->user_city,
          //'profile_state'=>sanjay,
          'profile_postalcode'=>$row->user_postal_code,
          'profile_country'=>$row->iso,
          //'profile_stateprovince'=>$row->sanjay,
          //'old_user_id'=> $row->user_id,
          'init' =>$row->user_initial,
        );
        user_save(null,$newUser);

```

# Answer
> 0 votes
I think User import module can help you with that

---
Tags: 6, users, migrations
---


title: Make phone calls from a Drupal site

text:
# Question
Title: Make phone calls from a Drupal site
When looking at a user's profile page, I'd like to be able to make a phone call to the user whose profile I'm viewing. Is this possible in Drupal 7?

# Answer
> 5 votes
You could use the `tel:` or `callto:` href identifiers depending on the method of your phone call (Skype uses `callto:`, mobiles that support this feature will use `tel:`.

For example, if the number is 123-456-789, your link would look like one of the following:

```
<a href="callto:123-456-789">Call this user</a>

```

or

```
<a href="tel:123-456-789">Call this user</a>

```

Check this (old) blog post for some examples/ideas on implementation.

---
Tags: 7
---


# Question
Title: hook_form_alter() exposed filter form item #weight
I'm trying to insert a form element with `hook_form_alter()`, and then rearrange the form elements so that the new form item appears at a particular point amongst the existing exposed filters.

I've tried adding `#weight` of `0` to all existing items and then `#weight` of `-1` to the new element, just to see if I can have any influence on the form item order at all, however I don't seem to be able to affect it.

**EDIT:** In addition I'm getting kinda weird behaviour regarding the container of the Form element. I'm adding my form element as a new array element at the root of `$form`, however it is be rendered inside the element `<div class="views-exposed-widget views-submit-button">` rather than getting it's own container, which seems like either a bug or I really am doing something wrong!

# Answer
> 5 votes
Take a look at comments #3, #7 and #9 in http://drupal.org/node/893392

#3 (dereine):

> The problem is that there is some theming on exposed form. You would have to override it, sadly.

#7 (manatwo):

> Yes, all of it is handled in views-exposed-form.tpl.php, which you can override in your theme to print out your fields manually. IIRC, the extra fields are gonna be in the $button variable in that template, so you might want to do some preprocessing in template.php

#9 (PadreHomer):

> I was able to alter the order without overriding the template. I am using Views 3, but I think this will work in Views 2 as well.
>
> Alter the order of the filters in $form\['#info'\] in your form\_alter and this should alter the order the widgets print out in the template without having to do any custom templating.

# Answer
> 2 votes
A small update on this (as I have just updated http://drupal.org/node/893392 too), if someone faces similar problem in the future, as I just did myself, trying to place my new exposed form item in-between "widgets" generated automatically by the view - the solution is to turn that new form item into a widget, and then re-order widget array in the `$form['#info']`.

In my case I was adding new `community` form item into Views exposed form, and then wanted it to be displayed as a second element in the form, right after `filter-title` generated by the view:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-mw-group-list-page-1') {
    // Add new form item.
    $form['community'] = array(
      '#type' => 'radios',
      '#title' => t('Community'),
      '#options' => $options_array,
      '#default_value' => $default_value,
    );
    // Create widget from new form item and place it as a second element.
    $new_form_info = array(
      'filter-title' => $form['#info']['filter-title'],
      'filter-community' => array('value' => 'community'),
    );
    $form['#info'] = array_merge($new_form_info, array_diff_assoc($form['#info'], $new_form_info));
  }
}

```

Obviously the code responsible for re-ordering `$form['#info']` will look different depending on where the new form item should be displayed.

---
Tags: views, forms, hooks
---


# Question
Title: Ubercart 2.x: Given a product nid, retrieve its manufacturer
I'm trying to figure out how Ubercart stores manufactures.

Currently it's set up as a Vocabulary, but I can't figure out how to grab that info programmatically given a product nid.

Any advice?

# Answer
> 1 votes
In Drupal 6 taxonomy terms are linked to the node object, Ubercart just piggy-backs off the way Drupal core handles this.

You can use the very handy `taxonomy_node_get_terms_by_vocabulary()` function to grab all of the terms associated with a node in a certain vocabulary. You would use it like so:

```
$vid = 1; // Vocabulary ID
$nid = 1; // Node ID

$node = node_load($nid);
$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);

```

---
Tags: 6, ubercart
---


title: Custom Page type and variables

text:
# Question
Title: Custom Page type and variables
In my preprocess\_page() function, I'm setting variables based on the user that is logged in.

I created a custom page that is used as a Welcome page with the information about the user that I set in the variables in the preprocess\_page() function.

The problem I have is that the page is not allowing me to put the print statements to echo out the variable, i.e.

```
<h1 style="font-size:18px; padding-bottom:3px;"><?php print $FirstName. " ".$LastName; ?></h1>

```

It doesn't echo out the variable values.

Also, I need later to do something based on the value of a variable. I have tried using an if statement like this:

```
<?php
  if($designations == 'ABCDE') {
?>
              <td align="center" style="width: 40px;"><img src="images/abcde.png" alt=""></td>
</php
  } else {
?>
              <td align="center" style="width: 40px;"> </td>
<?php
   }

```

but all it does is print out part of the PHP:

```
if($designations == 'ABCDE') {
?>
} else {
?>

```

What am I doing wrong here???

Updated (Added preprocess\_page function code):

```
function mix_and_match_preprocess_page(&$vars) {
  $vars['page_color'] = theme_get_setting('mix_and_match_page_bg');
  if(user_is_logged_in()) {
    // Get the user's info and assign the values to variables.
    $vars['ParticipantID'] = 1007945;
    $vars['Username'] = 'JOESMITH';
    $vars['Password'] = 'passwd';
    $vars['FirstName'] = 'Joe';
    $vars['MiddleName'] = '';
    $vars['LastName'] = 'Smith';
    $vars['Suffix'] = '';
    $vars['PreferedEmailAddress'] = 'joe_smith@mysite.com';
  } // if($logged_in)
}

```

Showing new code and results: This code:

```
<h1 style="font-size:18px; padding-bottom:3px;"><?php print $FirstName. " ".$LastName; ?></h1>

```

produces (When view source):

```
<h1 style="font-size:18px; padding-bottom:3px;"><?php print $FirstName. " ".$LastName; ??></h1>

```

this code:

```
drupal_set_message('I got here');
<?php if($designations == 'ABCDE': ?>
                  <td align="center" style="width: 40px;"><img src="images/cic-35x29.png" alt=""></td>
drupal_set_message('I got here');
<?php else: ?>
                  <td align="center" style="width: 40px;"> </td>
<?php endif; ?>

```

produces (When view source):

```
drupal_set_message('I got here');<br />
<?php if($designations == 'UACIC'): ??>
<td align="center" style="width: 40px;"><img src="images/cic-35x29.png" alt="" /></td>
<p>drupal_set_message('I got here');<br /><?php else: ??></p>
<td align="center" style="width: 40px;"> </td>
<p><?php endif; ??>

```

# Answer
Assuming you put the preprocess code in your theme's template.php, coding this inside a node ought to work - but in order for it to do so you have to

1. make sure the Core "PHP Filter" module is enabled and
2. make sure the node's Input Format is set to "PHP code."

As I noted, this is not the most secure or maintainable way to do things, but it'll let you do what you want without messing about in page or node templates.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Changing the default imagefield formatter for a node field
I am trying to change the default formatter for an imagefield node form field so that it will default to the thumbnail image and not the icon. I have already tried a form alter and that isn't doing a damn bit of good. I have already flushed all the cache. So I was wondering if anyone else knew how to do this.

I am running Drupal 6 by the way. The field in question is using imagecache presets.

# Answer
Unfortunately none of the GUI tools allowed me to change the default. So I ended up writing a little JavaScript to select the option I wanted on form load.
> 0 votes

# Answer
Go into the admin for the content type in question and look at the display fields, eg, `admin/content/node-type/THISCONTENTTYPE/display` and change up the field you want. You can select any imagecache preset you have defined on your system along with a number of other options.
> 1 votes

---
Tags: entities, 6, media
---


# Question
Title: update text format "filtered html" on old nodes
currently i have a content type with multiple nodes, that were created with a text format of plain text. is there any way to update all these nodes to be filtered html?

/admin/config/content/formats

i changed the default format to be filtered html, by making its weight -10 it is now at the top of the list. now when a user creates a new node it will have this format but how do i convert all the old ones?

# Answer
> 6 votes
Update the database directly using SQL queries. The queries are something like

```
UPDATE field_data_field_[example] SET field_[example]_format = '[text_format]';
UPDATE field_revision_field_[example] SET field_[example]_format = '[text_format]'

```

for a field named `field_[example]` that was created with the *Field UI* module and a text format with machine name `[text_format]`. Clear the cache afterwards.

---
Tags: 7, input-formats
---


title: User Module modifications

text:
# Question
Title: User Module modifications
I need to add about 64 custom fields to the user object. These fields will be filled when the user is created and updated from a 3rd-party database when the user logs in.

How would I go about making these modifications? Would I subclass the user or just make a new module to do this?

# Answer
Clive's answer is right for Drupal 6.

For Drupal 7, you'd implement a Field. This field would provide the 64-field form to fill out, the way to display the info, and know how to query the external database. (Obviously there's some room for design improvement here.. I'm chunking all the different pieces into one meta-field, but you could split it out however you want.)

Then you go to `admin/config/people/accounts/fields` and add your field to the user account profile. When you add it, there will be an initial configuration page for that field instance, and you'd check 'Display on user registration form.'

Easy as pie, right? :-)

There's a generic field implementation example in the Examples project.
> 3 votes

# Answer
Subclassing the `$user` object is not really an option as it's a `stdClass` type (this will be changed in Drupal 8 where all entities will derive from the new `Entity` class).

**EDIT**

I've re-read your question and I think this will be a bit more useful:

You can react to user login and creating/updating with the following hooks:

If you need to load that data back onto the `$user` object for use in Drupal you can do it with `hook_user_load()`:

```
function MYMODULE_user_load($users) {
  // Grab the user ids
  $uids = array_keys($users);

  // Get your data
  $data = function_to_get_data($uids);

  // Loop through the data array (which you should key by uid) and add to the user object
  foreach ($data as $uid => $item) {
    $users[$uid]->extra_item = $item;
  }
}

```

Obviously you can extend that logic as you see fit to add your multiple fields to the `$user` object.
> 1 votes

---
Tags: 7, users
---


# Question
Title: 'drush rsync' not excluding paths specified in 'exclude-paths' in "aliases.drushrc.php"
I'm trying to get drush-rsync to exclude files/paths that as specified in my alias definitions.

In /etc/drush/aliases.drushrc.php, I defined

```
$aliases['site_A'] = array(
    'root'   => '/home/test/site_A',
    'uri'    => 'site_A.loc',
    'path-aliases' => array( '%files' => 'sites/default/files', '%dump' => '/home/test/site_A-dump.sql',),
    'command-specific' => array(
        'sql-sync' => array('no-cache' => TRUE,'structure-tables' => array(
        'custom' => array('cache','cache_filter','cache_menu','cache_page','history','sessions','watchdog'),),),
    ),
    'rsync' => array ('simulate' => '0', 'no-cache' => TRUE, 'mode' => 'rlptDz', 'exclude-paths' => 'BLAH:',
    ),
);
$aliases['site_B'] = array(
    'root'   => '/home/test/site_B', 'uri'    => 'site_B.loc',
    'path-aliases' => array(%files' => 'sites/default/files', '%dump' => '/home/test/site_B-dump.sql',),
    'command-specific' => array(
        'sql-sync' => array('no-cache' => TRUE,'structure-tables' => array(
        'custom' => array('cache','cache_filter','cache_menu','cache_page','history','sessions','watchdog'),),),
    ),
    'rsync' => array ('simulate' => '0', 'no-cache' => TRUE, 'mode' => 'rlptDz', 'exclude-paths' => 'BLAH:',
    ),
);

```

When I test the rsync step,

```
drush --debug --simulate rsync @site_A @site_B
    Bootstrap to phase 0. [0.01 sec, 4.41 MB]                            [bootstrap]
    Drush bootstrap phase : _drush_bootstrap_drush() [0.02 sec, 4.67 MB] [bootstrap]
    Loading drushrc "/etc/drush/drushrc.php" into "system" scope. [0.02 sec, 4.68 MB]                         [bootstrap]
    Cache HIT cid: 5.0-dev-commandfiles-0-f008e6f6337e0f66b073976a381b26a6 [0.03 sec, 4.69 MB]                    [debug]
    Bootstrap to phase 0. [0.12 sec, 9.76 MB]                                                                 [bootstrap]
    Bootstrap to phase 0. [0.14 sec, 9.76 MB]                                                                 [bootstrap]
    Found command: core-rsync (commandfile=core) [0.15 sec, 9.76 MB]                                          [bootstrap]
    Including /usr/local/drush/commands/core/rsync.core.inc [0.19 sec, 9.77 MB]                        [bootstrap]
    Load alias @site_A [0.2 sec, 9.87 MB]                                                                       [notice]
    Load alias @site_B [0.34 sec, 9.89 MB]                                                                    [notice]
    Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --exclude="settings.php" --stats --progress /home/test/site_A// /home/test/site_B/);
    Command dispatch complete [0.75 sec, 10.05 MB]                                                               [notice]
    Peak memory usage was 11.42 MB [0.75 sec, 10.05 MB]                                                          [memory]

```

I don't see the exclusion of 'BLAH' anywhere.

How do I exclude using the config files, not just on the command line?

---

EDIT #1

I'd followed this example, http://emspace.com.au/article/drush-aliases-primer-live-dev-syncing, and miscounted nesting levels :-/

Fixing my aliases defs to,

```
$aliases['site_A'] = array(
    'root'   => '/home/test/site_A', 'uri' => 'site_A.loc',
    'path-aliases' => array( '%files' => 'sites/default/files', '%dump' => '/home/test/site_A-dump.sql',),
    'command-specific' => array(
        'sql-sync' => array(
            'no-cache' => TRUE,
            'structure-tables' => array(
                'custom' => array('cache','cache_filter','cache_menu','cache_page','history','sessions','watchdog'),
            ),
        ),
        'rsync' => array (
            'no-cache' => TRUE,
            'mode' => 'rlptDz',
            'exclude-paths' => 'BLAH:',
        ),
    ),
);
$aliases['site_B'] = array(
    'root'   => '/home/test/site_B', 'uri' => 'site_B.loc',
    'path-aliases' => array(%files' => 'sites/default/files', '%dump' => '/home/test/site_B-dump.sql',),
    'command-specific' => array(
        'sql-sync' => array(
            'no-cache' => TRUE,
            'structure-tables' => array(
                'custom' => array('cache','cache_filter','cache_menu','cache_page','history','sessions','watchdog'),
            ),
        ),
        'rsync' => array (
            'no-cache' => TRUE,
            'mode' => 'rlptDz',
            'exclude-paths' => 'BLAH:',
        ),
    ),
);

```

and re-executing the 'drush rsync' command,

```
drush --debug --simulate rsync @site_A @site_B
    Bootstrap to phase 0. [0.01 sec, 4.41 MB]                            [bootstrap]
    Drush bootstrap phase : _drush_bootstrap_drush() [0.02 sec, 4.67 MB] [bootstrap]
    Loading drushrc "/etc/drush/drushrc.php" into "system" scope. [0.02 sec, 4.68 MB]                         [bootstrap]
    Cache HIT cid: 5.0-dev-commandfiles-0-f008e6f6337e0f66b073976a381b26a6 [0.04 sec, 4.69 MB]                    [debug]
    Bootstrap to phase 0. [0.12 sec, 9.76 MB]                                                                 [bootstrap]
    Bootstrap to phase 0. [0.14 sec, 9.76 MB]                                                                 [bootstrap]
    Found command: core-rsync (commandfile=core) [0.14 sec, 9.76 MB]                                          [bootstrap]
    Including /usr/local/drush/commands/core/rsync.core.inc [0.19 sec, 9.78 MB]                        [bootstrap]
    Load alias @site_A [0.19 sec, 9.88 MB]                                                                      [notice]
    Load alias @site_B [0.33 sec, 9.89 MB]                                                                    [notice]
    Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --exclude="settings.php" --stats --progress --no-cache /home/test/site_A// /home/test/site_B/);
    Command dispatch complete [0.73 sec, 10.05 MB]                                                               [notice]
    Peak memory usage was 11.42 MB [0.73 sec, 10.05 MB]

```

there's no 'BLAH' to be seen in the exclusion list.

Removing "--simulate" just in case (how, then do we 'trial run' rsync, if we aren't to use "--simulate" with it anymore?), the sync works, but the same issue -- no 'BLAH' in the exlcusion list,

```
drush --debug rsync @site_A @site_B
    Bootstrap to phase 0. [0.01 sec, 4.41 MB]                            [bootstrap]
    Drush bootstrap phase : _drush_bootstrap_drush() [0.02 sec, 4.67 MB] [bootstrap]
    Loading drushrc "/etc/drush/drushrc.php" into "system" scope. [0.02 sec, 4.68 MB]                         [bootstrap]
    Cache HIT cid: 5.0-dev-commandfiles-0-f008e6f6337e0f66b073976a381b26a6 [0.04 sec, 4.69 MB]                    [debug]
    Bootstrap to phase 0. [0.13 sec, 9.76 MB]                                                                 [bootstrap]
    Bootstrap to phase 0. [0.15 sec, 9.76 MB]                                                                 [bootstrap]
    Found command: core-rsync (commandfile=core) [0.16 sec, 9.76 MB]                                          [bootstrap]
    Including /usr/local/drush/commands/core/rsync.core.inc [0.2 sec, 9.77 MB]                         [bootstrap]
    Load alias @site_A [0.21 sec, 9.87 MB]                                                                      [notice]
    Load alias @site_B [0.35 sec, 9.89 MB]                                                                    [notice]
    You will destroy data from /home/test/site_B/ and replace with data from /home/test/site_A//
    Do you really want to continue? (y/n): y
    Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --exclude="settings.php" --stats --progress /home/test/site_A// /home/test/site_B/);
    sending incremental file list
    ./
    sites/default/
    sites/default/files/ctools/
    sites/default/files/ctools/css/

    Number of files: 4118
    Number of files transferred: 0
    Total file size: 29639208 bytes
    Total transferred file size: 0 bytes
    Literal data: 0 bytes
    Matched data: 0 bytes
    File list size: 83532
    File list generation time: 0.004 seconds
    File list transfer time: 0.000 seconds
    Total bytes sent: 94536
    Total bytes received: 11003

    sent 94536 bytes  received 11003 bytes  70359.33 bytes/sec
    total size is 29639208  speedup is 280.84
    Command dispatch complete [3.21 sec, 10.05 MB]                                                               [notice]
    Peak memory usage was 11.43 MB [3.21 sec, 10.05 MB]                                                          [memory]

```

# Answer
> 5 votes
You accidentally placed your rsync command-specific options outside of the 'command-specific' array.

I don't think that Drush global options (e.g. 'simulate') are supported for commands such as rsync that use strict option handling. Remove 'simulate' if it causes problems in command-specific options.

**Edit for comment #4, below:**

Here is my modified alias:

```
$aliases['dev'] = array (
  'root' => '/srv/www/wherever',
  'uri' => 'wherever.net',
    'command-specific' => array(
        'sql-sync' => array(
            'no-cache' => TRUE,
            'structure-tables-list' => array('cache','cache_filter','cache_menu','cache_page','history','sessions','watchdog'),
        ),
        'rsync' => array (
            'no-cache' => TRUE,
            'mode' => 'rlptDz',
            'exclude-paths' => 'BLAH:',
        ),
    ),
);

```

Here is the command that uses it:

```
$ drush -s rsync @live @dev
Calling system(rsync -e 'ssh ' -rlptDz --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --exclude="BLAH" --exclude="settings.php" --rsync-version=2.6.8 --no-cache=1 wwwadmin@10.10.10.10:/srv/www/wherever/ /srv/www/wherever/);

```

There's an --exclude="BLAH" in there, and I can't see anything that I'm doing differently than you are. Good luck with tracking down your problem.

---
Tags: drush, backups
---


# Question
Title: how to inspect the output array from PHPVideoToolkit::getFFmpegInfo()
I got the following error message

```
PHPVideoToolkit Error: Execute error. Output for file "$DOCROOT/sites/example.com/files/private/videos/original/file.flv" was not found. Please check server write permissions and/or available codecs compiled with FFmpeg. You can check the encode decode availability by inspecting the output array from PHPVideoToolkit::getFFmpegInfo().

```

How do I inspect the ouput array from `PHPVideoToolkit::getFFmpegInfo()`?

# Answer
Quickest way I can think of:

When you run that code you should be presented with a nicely formatted array in the messages area that you can inspect.

If you get an error that `PHPVideoToolkit` does not exist then find out what file in your installation declares that class, and make sure it's included using either `module_load_include()` or PHP's `include/require`.
> 2 votes

---
Tags: 7, files
---


# Question
Title: How to set the number of front page's promoted nodes?
Is it possible to set the number of front page's promoted nodes and thus display a pager?

# Answer
> 4 votes
Configuration -\> System -\> Site Information

In the Front Page section there is an option for 'Number of posts on the front page'

---
Tags: nodes
---


title: Text format and field profile

text:
# Question
Title: Text format and field profile
I am working in Drupal 7.

I have a text-area in profile. I need the text area has a specific text format without editor but allows tags HTML.

The text format only is for the role "registered users", not for other roles and only in the text-area in the profile. This restriction is only for the field in profile.

If I have a role named "role test" that can edit articles and edit the profile, I need that the "role test" has not html tags in the text-area field in profile but the "role test" has editor in the content articles.

Thanks.

# Answer
Make sure "registered users" have permission to use that input format and "role test" does not have permission to use that input format. "role test" could have permissions for the editor format without having permissions for the input format for the profile field.
> 1 votes

---
Tags: input-formats, users
---


# Question
Title: custom views handler to show dynamic all profile fields
I'm using D6 and I like to have a view that shows all user profile fields. The situation now is, that you have to tic all fields that you like to show. I'm using OG profiles and the user is able to add profile fields to it's group. In addition to that, I need a view that get all fields that are belonging to a group (automatic).

What is the starting point for me? Found that .. http://techblog.zabuchy.net/2010/non-database-field-in-custom-drupal-views-2/

But how to start?

pseudo code:

get all field belonging to a group (arg(1)) and disp

# Answer
> 0 votes
This is probably done better in a preprocess function in a theme instead. However if you want to do it you ned to create a handler, something like this:

```
class og_group_handler_field extends views_handler_field {
  function render() {
    $og = arg(1);
    $output
    // Load the group and add to $output what needs to be displayed
   return $output;
 }
 function query() {
   // Make sure we don't add anything to the queue.
  }
}

```

and the add the handler to a table like nodes

```
function module_views_data_alter(&$data) {
  $data['node']['og_all_group_fields_from_arg_1'] = array(
    'field' => array(
      'title' => 'title',
      'help' => 'Help Text',
      'handler' => 'og_group_handler_field',
    ),
  );
}

```

For Drupal 6 you also need to register the handler, the link you posted illustrates how this is done.

---
Tags: views, users
---


# Question
Title: Is there a way to create an openlayers map that adjusts size with an adaptive layout?
I'm building a site that will incorporate data mapped from users quite extensively, and I'd like the front page to mostly be just a map showing various relevant data. I'm also trying to build the site in a way that is adapted to mobile use.

I have an openlayers map constructed, it displays data, mostly behaves as I'd like, and I have it on the front page. That's all good. What I'd like to do is have the map become narrower in order to respond to display size. I'm currently using the omega them and I can get other elements to respond, but not the map.

Is there a way to clip the map? Can I bring in different map displays for different screens? Is this in any way possible?

I'm nearly completely new to all of this, learning css/js/php on the fly as I run into issues. I feel like this might be something js can help with (I found this link, for instance: http://pastebin.com/GumWwSMB), but I'm not sure if it's appropriate/best nor where/how to implement it.

Thanks for your help.

# Answer
> 1 votes
Oy. Okay. After poking around even more I found a much, much better solution, and now the whole question seems silly.

When setting up a map to display the data (in Administration \>\> Structure \>\> OpenLayers \>\> Maps), just set map width to "auto." Then it mods all on it's own. One display (block or page), and you don't even need to add any extra css to the container. It just responds. Somehow I completely forgot that auto width was an option when building the map. Super easy!

# Answer
> 0 votes
Use CSS3 media queries. No javascript required!

```
          /* Smartphone portrait */
        @media only screen and (max-width:320px) {
    #openlayer-container{
    width:30%
    }
        }

        /* Smartphone landscape */
        @media only screen and (min-width:321px) and (max-width:480px) {
    #openlayer-container{
    width:40%
    }

        }

        /* Tablet portrait */
        @media only screen and (min-width:481px) and (max-width:768px) {

    #openlayer-container{
    width:60%
    }

        }

        /* Tablet landscape */
        @media only screen and (min-width:769px) and (max-width:1024px) {
    #openlayer-container{
    width:70%
    }

        }

        /* Standard layout */
        @media only screen and (min-width:1025px) {
 #openlayer-container{
    width:100%
    }
        }

```

Of course this is just an example. Depending on your exact html selectors, you need to put them in each media query range and style it accordingly. I assume you know CSS3.

# Answer
> 0 votes
I'm not sure if this is the best solution, but it's one I got to work.

Initially I had one large map and set it up as a page view and tried to resize it directly. Instead, I added two smaller maps and made a series of block views for each one. I made sure to give each view a unique class (large-front-map, medium-map-block, etc) and set the blocks to display only on the front page. Then I set each one to

```
.large-map {
    display:none;
}

.medium-map-block {
    display:none;
}

.narrow-map-block {
    display:block;
}

```

and so forth on the appropriate -narrow, -normal, or -wide.css and let Omega's media queries do the rest.

It seems obvious to me now, but I'm gradually poking my way through all of this. I guess maps have too complicated of a data mix for simple rescaling. Thanks for people's help and suggestions.

---
Tags: theming, javascript
---


title: Dynamic Block not showing

text:
# Question
Title: Dynamic Block not showing
My block is not showing in the blocks menu for some reason and im sure everything is correct on it, am I missing something on it?

.info file

```
; $Id: loans_zillow.info,v 1.0.0.0 2011/02/09 10:11:15 Jeremy Exp $
name = "Custom Zllow Module"
version = "1.0 Beta"
description = "A custom module from zillow's api"
core = "7.x"
package = "Custom Modules"

```

.module file

```
   function zillow_block_info(){
        $blocks['zillow_block'] = array(
            'info' => t('Zillow Block'),
        );
        return $blocks;
    }

    function zillow_block_view($delta = ''){
        $block = array();
        switch ($delta){
            case 'zillow_block';
            $block['subject'] = t('Zillow Block');
            $block['content'] = zillow_content();
            break;
        }
        return $block;
    }

    function zillow_content(){
        return'
            <div>this is a test</div>
        ';
    }

```

# Answer
> 1 votes
Your code works fine for me so I'd check the following:

* Make sure the module's installed and enabled.
* Make sure the module is definitely named `zillow` (the module file should be called `zillow.module`, info file `zillow.info`, etc).
* Make sure you've cleared Drupal's caches.

I realise these might be obvious solutions but as I say the code works for me so I can only guess your hooks are not being called for one of the reasons above.

---
Tags: 7, blocks
---


title: Overriding variables based on url

text:
# Question
Title: Overriding variables based on url
At our university we have dev/test/live versions of our sites at urls like

* dev.example.foo.edu
* test.example.foo.edu
* live.example.foo.edu (the real live url is example.foo.edu)

There are certain Drupal site variables (values in the variables table) that need to change depending on the environment (dev, test, live) where the site is running.

The first time the site is migrated to the live environment certain site variables need to magically change from their "dev" values to their "live" values.

After that initial migration we will periodically load the live database into the dev and test sites to update their content. When this happens I want certain site variables to change to their "dev" values.

I don't want the site builder to have to do anything. I want the variables to simply change to the correct values.

It's okay if the site admin wants to manually override these variables. They shouldn't have to, but there could be a need for this...

I mainly need a Drupal 7 solution--bonus if it works with Drupal 6.

Possible solutions:

**Does a module exist that will do this?**

I haven't found one. I've looked at

**Use hook\_update\_N** (http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_update\_N/7)

* This doesn't meet the requirement that the site builder doesn't have to do anything. They would have to copy paste a update\_71234() in some install file. They would also have to remember to run update.php in various situations.

**Write a custom module?**

This works:

```
/**
 * Implementation of hook_cron().
 */
function ucb_varenv_cron() {
    global $base_url;

    //if (variable_get('ucb_varenv', FALSE) === FALSE) {
        $parts = explode('.', $base_url);
        $vars = ucb_varenv_vars();
        $p1 = str_replace('http://', '', $parts[0]);
        while (list($k, $v) = each($vars[$p1])) {
            variable_set($k, $v);
        }
        //variable_set('ucb_varenv', TRUE);
    //}

}

function ucb_varenv_vars() {
    $vars = array(
      'dev' => array(
        'cas_server' => "TEST2.example.com",
    ),
       'live' => array(
         'cas_server' => "auth.example.edu",
    ),
    );
    return $vars;
}

```

Hook cron seems like a clumsy approach. The commented ucb\_varenv code was from and experiment where this would run one time only at hook\_boot()--but that seemed like a bad idea.

The more I think about this, I wonder if there is some way to leverage strongarm to do what I need.

# Answer
I changed my mind again. I'm doing it in a module. See the README for why: https://github.com/ucbdrupal/ucb\_envconf/tree/7.x-1.x
> 0 votes

# Answer
Assuming I've parsed this all out correctly, you should be able to achieve what you're looking for using Rules. You'll need to install core's PHP Formatter for its integration with Rules to call variable\_set() as an action, though beyond that it's pretty straightforward:

* Event: When cron maintenance tasks are performed
* Condition: Data comparison (Parameter: Data to compare: \[site:url\], Data value: http://example.foo.edu/)
* Action: Execute custom PHP code (Code: variable\_set('cas\_server', 'auth.example.edu');)

Mind the trailing slash in the condition URLs - it's the path to the home page, not the domain name, so the slash is required.

Of course, you could bind it to whatever event you feel is most appropriate, and duplicate the same rule for your dev and test instances with the appropriate CAS servers (going this route would also mean you could export this with Features). I've tested the above reaction rule, and it seems to work on my own D7 instance (with the URL condition set accordingly):

```
# After cron
[dmw@seraph aqueduct]$ drush vget cas
cas_server: "auth.example.edu"

```

It's been a while since I've used the old Rules, though I don't see why something similar can't work for D6.
> 2 votes

# Answer
Thanks again for the Rules idea.

In the end, it was better to code conditional logic into settings.php.

I was thinking that the settings.php approach wouldn't be good because I'd loose my code when I upgrade Drupal. But since settings.php is not actually part of a Drupal release, as long as you set up your version control correctly, you can carry this code forward.

This way we don't have to worry about cron failing to run. We also don't have to maintain these rules in the future.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: View page doesn't output but views_embed_view with same arguments does?
I have a view with a page display. A simple view with a few content types to display, and a contextual filter for taxonomy.

If I enter an argument in the views preview, it works as expected. Displays "no results found" for gibberish, and properly filtered nodes for taxonomy terms that exist.

If I put a views\_embed\_view in the page template with a hard-coded argument, it also displays as expected.

```
<?php print views_embed_view('explore', 'explore', 'About-Us'); ?>

```

My problem is that if I go to the page path www.site.com/explore/About-Us I get nothing. No errors, no "No results" dialog, no results. The content array is completely empty.

I've done dozens of views pages, with arguments and without, and never had this problem. Does anyone have any ideas?

# Answer
> 0 votes
I knew the answer would be stupid.

I had registered the path I was using for my view's page in a module a couple months ago and forgot. \>\<

---
Tags: 7, views
---


# Question
Title: How can I arbitrarily execute a rule from the UI to test a login togobban workflow using selenium?
I am trying to create tests for my Drupal site using Selenium UI. I am attempting to test Login Toboggan's "verify user" behavior, but since the account verification link is different each time, it cannot be easily included in a test.

I have several rules that should be triggered upon successful validation; since I cannot trigger validation in the normal manner, I would like to activate these rules manually. Is there a way to do this from within the UI (so that it can be added as part of selenium)?

# Answer
I ended up solving this with rules by making a new rule.

Event- "User has logged in"

Conditions- "User has roles" -\> The role of the "unverified user" (set on the logintoboggan configuration screen)

Actions- "Show a message on the site"

Message text:

```
<a href="[account:validate-url]">validate your account</a>

```

This will present a message to unverified users when they log in allowing them to verify their accounts. Of course this has to be disabled for production, but it allows one to test validation workflows in Selenium.
> 0 votes

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


# Question
Title: Forcing OpenID login instead of Drupal own authentication
Is there a way to force the users to use OpenID (e.g. Google, Facebook, Twitter) and not use Drupal's internal authentication?

# Answer
> 5 votes
I simple solution would be to alter the login form to remove the username and password fields.

Here is some sample code to get you started:

```
/**
 * Alter the login form page
 */
function MYMODULE_form_user_login_alter(&$form, &$form_state, $form_id) {
  _MYMODULE_alter_login_form($form);
}

/**
 * Alter the login form block
 */
function MYMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  _MYMODULE_alter_login_form($form);
}

/**
 * Function to change a bunch of things in the user_login form (both the block
 * and login screen).
 */
function _MYMODULE_alter_login_form(&$form) {
  unset($form['name']);
  unset($form['pass']);
}

```

Unfortunately I don't know of any contrib modules that will do this for you; the good news is that I have wrote 95% of the module for you. ;)

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


title: Restore backup solution for busy sites

text:
# Question
Title: Restore backup solution for busy sites
Today one of my users went and deleted the root of an Organic Group and wiped out all of the child nodes from that group and it's associated menu entries.

I have a backup, so I can restore, but in the time between I was informed of the problem and when it occured, other people were making updates to the site - so it wouldn't be as simple as just falling back to the last backup.

Happily, it was a simple group which is easily re-creatable - but I know one day, someone is going to delete a node which isn't trivial to re-create.

We've all had a colleage (or done it ourselves) who has called the local sysadmin and said "I accidentally deleted e-mail xxx - please restore it" - and the sysadmin goes and does it. My question is: How can I do this for a Drupal site? Ie. I want to be able to restore a node, or a set of nodes without completely rolling back.

Any ideas? Would love to hear from people with experience in dealing with this kind of problem. I can see there are modules such as "Feeds" and "Node Import" but I'm looking for peoples opinions on best solutions based on their experience.

# Answer
One answer in this situation is never to permit deletions in the first place. Use the publish flag or some other mechanism to remove the content from view, but retain it in the database. An admin would be able to restore any content simply by 'publishing' it again.
> 5 votes

# Answer
I use the Override Node Options module to allow my users to unpublish content but I have removed their ability to delete most content types.
> 0 votes

---
Tags: nodes, backups
---


# Question
Title: AJAX - How to dynamically add options to select?
In my drupal module, I want to dynamically add values to my select list. I also write them to the database. After it is added to the select and written to the db, I sort the options of the list alphabetically.

No problem at all, but whenever I add a value that will be the last one in the list (say zebra), and I select it right away, I get an "illegal choice detected" error. Why is this and how do I fix it?

Code when creating my form:

```
   $form['acategory_text'] = array(
      '#type' => 'textfield',
      '#title' => t('Nieuwe categorie'),
      '#size' => 25,
      '#maxlength' => 31,
      '#attributes' => array(
        'class' => array('textfield'),
      ),
    );

$form['acategory_button'] = array(
  '#type' => 'button',
  '#value' => t('+'),
  '#ajax' => array(
    'callback' => 'new_acategory_callback',
    'wrapper' => 'orderapp',
    'method' => 'replace',
  ),
  '#attributes' => array(
    'class' => array('button'),
  ),
);

$form['store_appcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => 'Order.app categorieën',
  '#multiple' => TRUE,
  '#options' => get_values('ac_id','appcategory',appcategories_load_multiple(FALSE, array('sid'=>$id))),
  '#prefix' => '<div class="formselect" id="appcat">',
  '#suffix' => '</div>',
  '#size' => 7,
  '#ajax' => array(
    'callback' => 'get_mapped_categories_callback',
    'wrapper' => 'orderapp',
    'method' => 'replace',
  ),
);

```

Callback method:

```
function new_acategory_callback($form, &$form_state) {
  $newappcat = $form_state['values']['acategory_text'];

  $id = $form_state['values']['id'];
  $entity = entity_create('appcategories', array('sid' => $form_state['values']['id'], 'appcategory' => $newappcat));
  entity_save('entity_test', $entity);

  $form['store_appcategories']['#options'][] = $newappcat;

  usort($form['store_appcategories']['#options'],create_function('$a,$b','return strcasecmp($a,$b);'));

  $form_state['rebuild'] = TRUE;
  return $form;
}

```

# Answer
> 2 votes
You need to build up the correct options directly in your form builder function, not in the ajax callback.

You can for example do so by converting your button to a submit type, add a specific #submit callback function, and then add something to $form\_state and trigger a $form rebuild. In your form builder function you can then look into $form\_state and build up the $options accordingly.

Logic always needs to be in the form builder/submit callbacks, the only thing that the ajax callback needs to care about is which part(s) of the form need(s) to be returned. The easiest way to correctly implement ajax in most cases is to build the form without ajax (which will just work with the method described above) and then add #ajax on top of it, once it works without.

You also don't need to set $form\_state\['rebuild'\] in your ajax callback that only has an effect in the submit callback.

---
Tags: ajax
---


# Question
Title: How does Drupal 7 determine the output of user menu?
I have the built in User Menu being displayed in a region of my template with the following code:

```
render($page['user_menu']);

```

Drupal seems to automatically handle where thsis should be output. Generally it outputs in the /user/\* pages.

However, I have recently started working on a custom module that had added a new menu item to /user/my\_module but when I visit the page the User Menu is not displayed.

Could someone tell me how Drupal manages the output of the User Menu or possibly how to get it to display on this page/path?

# Answer
You need to set `menu_name` for your menu item to `user-menu`, see userpoints\_menu() for an example (the myuserpoints menu item).
> 1 votes

# Answer
If you're adding new items to the user menu with hook\_menu\_alter() you may need to clear your menu cache before you see your changes.

You can clear you cache at: "Administer \> Site Configuration \> Performance \> Clear Cache"

Or better yet, use drush and use the command `drush cc`

You can also manually add items to the user-menu at "Admin -\> Menus -\> User Menu" (admin/structure/menu/manage/user-menu) though I'm guessing the menu/theme cache is the real issue here.
> 0 votes

---
Tags: 7, routes, users
---


title: Problem with breadcrumb on forum

text:
# Question
Title: Problem with breadcrumb on forum
I am using Drupal 7, and I want to show the breadcrumb only on the forum, so I used the following code:

```
$node = menu_get_object();
if (arg(0) == 'forum' || $node->type == 'forum') print $breadcrumb;

```

The code works, but it gives errors when I visit the admin page.

> Notice: Trying to get property of non-object in include() (line 18 of /srv/www/lusciousanime.com/public\_html/sites/all/themes/anime/page.tpl.php).

Does anyone know how to fix it?

# Answer
> 2 votes
That is because, when you visit a page that is not a node page, `menu_get_object()` (when called without arguments) doesn't return any value. The function could not return any value in other cases too, or not return an object, if the load function returns `FALSE`, as the code executed from the function is the following one.

```
  $router_item = menu_get_item($path);
  if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
    return $router_item['map'][$position];
  }

```

Your code should be similar to the following one:

```
$node = menu_get_object();

if (arg(0) == 'forum' || (!empty($node) && $node->type == 'forum')) {
  print $breadcrumb;
}

```

---
Tags: nodes, breadcrumbs
---


title: Adding options to View field settings

text:
# Question
Title: Adding options to View field settings
I want to be able to add arbitrary attributes to rendered view fields. So for example, I may want to add the attribute itemprop="url" to the rendered A tag for a url field.

I don't want to do this in the actual theming layer - I want to keep it in the view definition.

Is there a way of altering the option forms of any field handlers, so that I can add a new form element that does this. I would then need to alter the render function to ensure the field is outputted correctly with the new attributes.

So essentially I would want to change the options\_form, render functions etc. in the views handler class (e.g. views\_handler\_field\_url.inc).

Any help would be much appreciated.

# Answer
> 2 votes
What you need to do, is to subclass the handler(s) and add the methods you want to overwrite or change. Then you need to replace the normal handlers with your custom create handler(s) wherever you need this, in `hook_views_data_alter`.

---
Tags: views
---


title: Create colorbox link programmatically

text:
# Question
Title: Create colorbox link programmatically
Hello fellow druaplistas!

I have a situation where I need to output an image field using different image styles depending on some checkbox settings.

I'm doing this inside a node template. Basically this goes like this:

```
if ($layout == 1) {
  print $small_image;
}
if ($layout == 2 {
  print $medium_image;
}

```

To get the url to the correct sized image I can use `image_style_url`, but this way I have to build the links to the bigger version to open inside colorbox manually. Is there some function available that I can pass two image styles and it uses them to generate an image tag wrapped with a link to the bigger sized image?

**Update:** I took Clive's code (thanks again) and added a second parameter to be able to choose the preset that will be shown inside the colobox. Also Title and Alt is now included: As your code was better than mine I took it and extended the stuff I needed, maybe it's of use for someone:

```
function _colorbox_link($image, $style_name, $style_name_link = 'colorbox_full') {
  $image_style = theme('image_style', array(
    'style_name' => $style_name,
    'path'       => $image['uri'],
    'alt'        => $image['alt'],
    'title'      => $image['title']
  ));

  $url = image_style_url($style_name_link, $image['uri']);

  $link = l($image_style, $url, array(
    'html' => TRUE,
    'attributes' => array(
      'rel' => array('colorbox-gallery'),
      'class' => array('colorbox')
    )
   ));
  return $link;
}

```

# Answer
> 5 votes
I don't think there is, weirdly enough I've just been looking for pretty much the same thing...I couldn't find one so I just wrote a helper function:

```
function _lightbox_link($image, $style_name) {
  $image_style = theme('image_style', array(
    'style_name' => $style_name,
    'path' => $image['uri'],
    'alt' => $image['alt']
  ));

  $url = image_style_url($style_name, $image['uri']);

  $link = l($image_style, $url, array(
    'html' => TRUE,
    'attributes' => array(
      'rel' => array('lightbox-gallery')
    )
  ));

  return $link;
}

```

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


# Question
Title: Is there a simple way to alter core node/add/my_node_type to adding/my_node_type?
I don't want to show "node/add" in my url "node/add/my\_node\_type", instead I want to have "adding/my\_node\_type". Is there a simple way to hide "node/add" but not loose those args? I want to have "node/add/my\_node\_type" functionality after hitting "adding/my\_node\_type".

I can't see form add or form edit patterns in path so I think it is not so easy...

Of course after that I will need "node/%/edit" to be "editing/%"...

# Answer
> 3 votes
I didn't test this code, but if I'm not mistaken, it should be as simple as doing this in a custom module:

```
function YOUR_MODULE_NAME_menu_alter(&$items) {
  $items['adding/my-node-type'] = $items['node/add/my-node-type'];
  unset($items['node/add/my-node-type']);
}

```

Something similar could be done for the editing path.

# Answer
> 2 votes
I would do this like so:

create a new module and in this module declare:

```
function YOUR_MODULE_NAME_menu_alter(&$items) {
  $items['node/add/your-content-type-name']['page-callback'] = 'drupal_not_found';
}

```

this will override default page callback for your content type and will return 404 page

Then declare pages you need:

```
function YOUR_MODULE_NAME_menu() {
   $items = array();
   $items['adding/your-content-type-name'] = array(
     'title' => 'Add new your content type name instance',
     'page callback' => 'your_content_type_name_page_callback',
     'type' => MENU_NORMAL_ITEM,
     'access callback' => TRUE // or whatever you think the access callback should be for this content type
   );
   $items['editing/%'] = array(
     'title' => 'Edit your content type name instance',
     'page callback' => 'your_content_type_name_page_callback',
     'page arguments' => array(2),
     'type' => MENU_NORMAL_ITEM,
     'access callback' => TRUE // or whatever you think the access callback should be for this content type
   );
}

```

Declare a callback that will be serving the node edit form:

```
function your_content_type_name_page_callback($nid = FALSE) {
   $node = node_load($nid);
   if($node) {
     if($node->type == 'your_content_type_name') {
       $form = drupal_get_form('your_content_type_name_node_form', $node);
       return drupal_render($form);
     }
   }
   return drupal_not_found();
}

```

I did pretty much similar task in one of my previous projects, so I am sure this approach will work out. May be there are other ways to accomplish what you are after.

# Answer
> 2 votes
I didn't expect, but I can simply make path alias from **node/add/my\_node\_type** to **whatever/i/need**. Just one click here http://www.example.com/admin/config/search/path/add. No coding, no custom module. All I have to check is how about args - theoretically 'node/add/my\_node\_type' (3 args path) can be aliased to 'whatever' (looks like 1 arg, but is it?) or 'what/ever/and/ever' (looks like 4 args).

---
Tags: 7, path-aliases
---


# Question
Title: RSS feeds: How to reformat/rewrite/restyle? Using views? e.g. convert youtube text list of videos into thumbnails?
How can a RSS feed be reformatted/rewritten/restyled to be more useful?

For example Youtube RSS feeds from the video uploads of a youtube user appear as a plain text list by default.

Are there drupal module(s) or a solution out there that parses this content to be able to transform it into something more useful? E.g. in the case of youtube, make it show the list as thumbnail stills of the videos uploaded.

# Answer
These are 2 solutions that would provide the basis for taking an *incoming* RSS feed *into* a Drupal site and manipulating/processing/re-purposing it, USING Views:

http://dev.nodeone.se/en/learn-views-with-nodeone-part-12-building-a-custom-rss-reader-example

**Update:**

http://drupal.org/project/feeds\_imagegrabber

Feeds Image Grabber is possibly closer to what I'm looking for regarding rewriting *incoming* RSS feeds.

As for previously mentioned http://drupal.org/project/views\_rss This module is for *outputting* views from the site as an RSS feed - not what I want but useful should I wish parts of my site be available elsewhere via RSS.
> 0 votes

# Answer
Yes Views will be the perfect module choice for you, there are many ways to tweak the output with Views & it has built in Feeds support. Google about drupal views rss feeds, you'll find a ton of info. When you install views there is an example rss feed view you can enable and take a look at to see how its done. As for the thumbnails if your using emfield you should have the option to display thumbnail when tweaking the field output from within the View.

Good luck!
> 1 votes

---
Tags: 7, views, files, feeds
---


# Question
Title: Can I "drush rsync" with "chown @ destination"?
I understand that `drush rsync` is, by design, capable of preserving uid:gid.

if I am synchronizing with `drush rsync @site1 @site2`, and uid:did exists on both site1, and site2, all is well.

How would I go about changing the uid:gid to a specific selection on site2, within drush's command/alias config?

For example, on site1 all files are wwwrun:www, but on site2 I want to save all files as bob:admins, neither of which exists on site1.

Is there an integrated solution? I know I can use `'drush ssh @site2 "chown ..."'` as a subsequent step. Can I instead define/chain the command in aliases.drush.rc?

Using "remote-user=xxx" certainly works, but, apparently, it is limited to users that are allowed SSH access on the remote box.

```
@ remote
egrep -i "allowusers" /usr/local/etc/ssh/sshd_config
    AllowUsers         root locuse testuser

@ local
whoami
    locuse
drush --remote-user=testuser rsync @siteA @siteB
    You will destroy data from locuse@siteB.loc:/srv/www/siteB/ and replace with data from /srv/www/siteA//
    Do you really want to continue? (y/n): y

@ remote
ls -al PROD/ | head -n 5
    total 248K
    drwsrws--- 10 testuser users 4.0K Mar  8 00:08 ./
    drwxrwx---  4 wwwrun   www   4.0K Mar  8 08:11 ../
    -rw-rw----  1 testuser users 6.5K Mar  6 17:31 authorize.php
    -rw-rw----  1 testuser users  64K Mar  6 17:31 CHANGELOG.txt
    -rw-rw----  1 testuser users  996 Mar  6 17:31 COPYRIGHT.txt

```

That doesn't address my particular issue/interest.

More clearly, what I want to do is ssh-in from local-\>remote as an authorized user ('locuse' or 'root'), but I have the remote files' uid:gid set to an existing pair, where the target uid does/will NOT have ssh-access (e.g., wwwrun:www).

Reading the output of "man rsync," I read:

> USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION

Then @siteB

```
mkdir -p            /path/to/target
chown -R wwwrun:www /path/to/target

vi /etc/rsyncd.conf
    transfer logging = true
    log format       = %h %o %f %l %b
    log file         = /var/log/rsyncd.log
    pid file         = /var/run/rsyncd.pid
    lock file        = /var/run/rsync.lock
    hosts deny       = *
    use chroot       = no
    [siteB]
        path = /path/to/target
        hosts allow = *
        comment = COMMENTS
        uid = wwwrun
        gid = www
        read only = no
        list = yes

```

and @local

```
whoami
    locuse
ls -al ~/SourceDir
    total 240K
    drwxrwxrwx  2 locuse users 4.0K Mar  8 10:42 ./
    drwxr-xr-x 27 locuse users 4.0K Mar  8 10:41 ../
    -rw-r--r--  1 locuse users 5.2K Mar  8 10:43 file1.txt
    -rw-r--r--  1 locuse users 2.8K Mar  8 10:43 file2.txt

rsync -av --rsh=ssh ~/SourceDir/ root@siteB.loc::SiteB

```

Checking on remote:

```
ls -al /path/to/target
    total 240K
    drwxrwxrwx  2 root   root 4.0K Mar  8 10:42 ./
    drwxr-xr-x 27 wwwrun www  4.0K Mar  8 10:41 ../
    -rw-r--r--  1 wwwrun www  5.2K Mar  8 10:43 file1.txt
    -rw-r--r--  1 wwwrun www  2.8K Mar  8 10:43 file2.txt

```

It ends up with exactly the end-state I'm after.

# Answer
> 3 votes
If you do not tell rsync to preserve the uid, then it will create all transferred files under the ownership of the user that you connected as. The key, then, is to make sure that you put `'remote-user' => 'bob'` in the site alias for your destination site.

The rsync flags I use to achieve this are -rlptz. So, in my drushrc.php, I have:

```
$command_specific['rsync'] = array('mode' => 'rlptz');

```

See also:

http://drupal.org/node/1169776#comment-4612944

http://drupal.org/node/1343892

Supporting rsync modules in Drush would be awkward. If you want to use modules, it's probably best to call rsync directly. e.g.:

rsync -av --rsh=ssh `drush dd @siteA` root@siteB.loc::SiteB

You would need to configure your SiteB module to point to the Site B Drupal root anyway, so it seems like there is little value to tying this to a site alias.

---
Tags: drush
---


# Question
Title: How can I create a Google compliant video sitemap
I'm use Drupal 6, and I'd like to be able to create a sitemap that conforms to the Google Video Sitemap protocol. Are there any modules for this?

# Answer
> 0 votes
This should be of some help. In fact, definitely follow that thread for updates on integrating with XML site map.

You might also want to check out the Schema.org module - that might be helpful. Either way, it looks like you'll have to add fields manually that contain video length etc.

---
Tags: 6, files
---


# Question
Title: How do I get the $language object inside a form builder?
I have this necesity to use $language inside `MY_MODULE_form($form, &$form_state)` function and it seems is not available. I tried to define it as global, but it displays blank.

```
global $language_content;
dpm($language_content->language);

```

My simplified structure of `MY_MODULE_form()` looks like this:

```
function MYMODULE_form($form, &$form_state) {
global $language_content;
$form['name'] = array(
      '#type' => 'fieldset',
      '#title' => t('Name'),
  );
  $form['back'] = array(
      '#markup' => '<div class="link" ><a href="/project/$LANG-HERE/my/home">'.t('Back').'</a></div>',
  );
  return $form;
}

```

I found a hardcoded PHP solution:

```
if(strpos($haystack, 'en')) {
    $back_path = "/project/en/my/home";
    }
  if(strpos($haystack, 'fi')) {
    $back_path = "/project/fi/my/home";
  }
  $form['continue-shopping'] = array(
      '#markup' => '<div class="link" ><a href="'.$back_path.'">'.t('Back').'</a></div>',
  );

```

I am looking however to something more elegant.

# Answer
> 4 votes
Always use l() (or url(), which justs generates the URL) for generating links; then you, don't have to worry about the current language, base path, whatever clean URLs are enabled or not.

```
l(t('Back'), 'my/home');

```

That said, `global $language` should always work.

# Answer
> 1 votes
Using `global $language;` should always get you the language object.

---
Tags: forms
---


# Question
Title: Drupal menu callback create node permissions
I am creating a small menu, where I want to give access to a menu item when your are an authenticated user.

So I gave permission to authenticated users to create nodes of the type 'donation', but how would I formulate that in the menu acces arguments ?

```
$items['donate/%'] = array(
    'title' => 'Donate',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('get_donate_form'),
    'access arguments' => array('create donation'),
    'type' => MENU_CALLBACK,
);

```

# Answer
you can use user\_is\_logged\_in() if you want only to check if the user is loged in or you can use a custom function like

```
$items['donate/%'] = array(
    'title' => 'Donate',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('get_donate_form'),
    'access arguments' => 'my_custom_permission',
    'type' => MENU_CALLBACK,
);

function my_custom_permission()
{

}

```
> 2 votes

# Answer
Don't use access arguments. Use user\_is\_logged\_in() as access callback.
> 2 votes

---
Tags: routes, users
---


title: Override path with Views

text:
# Question
Title: Override path with Views
How can I override the default display of a taxonomy term with a view ?

eg : the path of a taxonomy term taxonomy/artist/artist\_name take me to the default display of a taxonomy term and I want to display a specified view to the same path.

in resume override the path.

thanks !

# Answer
> 1 votes
When you changed the path of the taxonomy term as you state in your comment on George's answer, I assume you mean that you defined an alias using the Pathauto module. The problem with this is that Drupal reads the alias and converts it to taxonomy/term/% before it acts upon the URL. This means that your view is never called and the the default taxonomy view is used to display the content.

There are two ways to get to your view. The first is to use the default taxonomy view that George mentioned. The second is to remove the taxonomy alias in path auto so that no conversion is made to the path. Drupal will then direct its response to your View with that path name.

Also, it is not necessary to convert the path argument to to a term number for use in the contextual filter. You can also use the name. Set the configuration of the contextual filter to content:term id. Under the settings for "When the term is in the URL..." select the validation option and pick the validator "taxonomy term" and the vocabulary that applies. Then pick "term name converted to term ID" from the filter drop down box. You must also check "transform spaces..." if your URL can have multiple words for the term so that dashes and spaces are interpreted correctly together.

# Answer
> 1 votes
Make the page display path taxonomy/term/% and the first argument to the view should be the term ID. There is a disabled view for this purpose which should set these up for you, but if you already have a view you can also make that override the core taxonomy path by making the two adjustments I mentioned.

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


# Question
Title: What is the relationship between hook menu() and menu_link_save()?
I am trying to create a menu using code in D7 (see my related question) and have found that these two Drupal API functions have different arrays for the $item variable. My intent is to create a three level menu hierarchy but with all of the associated paths being the same format `/name/%/something` so that I can use views to refine the content. In hook menu, the parents are defined using the Path name (eg. `parent/child/something`). In menu\_save\_link, the hierarchy appears to be established using the `pid` array value in $item. Hook\_menu is called when my custom module is read by drupal and the menu links are established. What I am wondering is if `menu_link_save`, could be used to do the same thing but with the same path style for all links, rather than a parent-child pattern?

I have been trying to trace the logic between the two functions in the API, but have not found the link between them. My thinking is that `menu_link_save`is used by `hook_menu` after some preprocessing and that I might be able to define a uniform paths and establish the hierarchy through the `pid`. Failing that, is there another way to alter the paths and preserve the hierarchy?

# Answer
I don't totally get what you are trying to do, but I think this will do what you want.

* Use your `hook_menu()` to just set up the paths that Drupal needs to respond to. Don't actually add the paths to a menu.
* Make a new menu in the UI.
* Loop through the items you need and call `menu_link_save()`

This should get you started

```
$item = array(
    "link_path" => "some/path/to/a/page",
    "link_title" => "Some Title",
    "menu_name" => "menu-the-name-of-the-menu",
    "plid" => $plid,
    "router_path" => "some/path/to/a/page",
);

$sql = "
    SELECT menu_links.mlid
    FROM {menu_links} menu_links
    WHERE menu_name = :menu_name AND plid = :plid AND link_path = :link_path
";

$result = db_query($sql, array(
    ":menu_name" => "menu-the-name-of-the-menu",
    ":link_path" => $item["link_path"],
    ":plid" => $plid
));

$record = $result->fetchObject();

if (isset($record->mlid) && $record->mlid > 0) $item["mlid"] = (int) $record->mlid;

menu_link_save($item);

```

When your loop is done, call `menu_cache_clear_all()`.

This is the inner loop from a module I have to automagically build some menus for non-node pages. I also have the full function wired up via hook\_menu, so people can rebuild as needed.
> 3 votes

# Answer
They're slightly different concepts to be honest; the items defined in `hook_menu()` are saved in the `menu_router` table, while `menu_link_save()` saves items to the `menu_links` table.

They come together in `menu_rebuild()`:

1. `hook_menu()` is invoked through the `menu_router_build()` function to get a list of router items
2. The router items are saved to the database using `_menu_router_save()`
3. The menu links are generated/updated using `_menu_navigation_links_rebuild()`; the menu router items are passed to this function to build the links.
4. Finally the caches are cleared.

There doesn't seem to be any way to pass custom data from the router items to the links I'm afraid, and I don't think `hook_menu()` supports the sort of hierarchy you're trying to build natively.
> 3 votes

---
Tags: routes
---


# Question
Title: How to redirect a user to a visited sub-domain on his next visit to main domain
I have a website say example.com with 5 sub-domains: site1.example.com, site2.example.com, site3.example.com, site4.example.com, and site5.example.com.

When users visit example.com, they are presented with the other 5 sub-domains to choose from. I want to implement something that redirect the users to the sub-domain they choose the first time they visit the main domain. I know I can use cookies for this, but how can I implement this in Drupal?

# Answer
> 2 votes
This implementation of `hook_init()` should be present on your subdomains but not on your main domain:

```
function YOUR_MODULE_NAME_init() {
  if(!isset($_COOKIE['your_cookie_name'])) {
    /*Your need to set cookie for your main domain, as well as for all your subdomains otherwise once a user visits another subdomain by typing the url directly in the address bar the cookie would be overwritten*/
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site1.example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site2.example.com');
    ...
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site5.example.com');
  }
  else {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

```

Your main domain should have a module with the following code:

```
function YOUR_MODULE_NAME_init() {
  if(isset($_COOKIE['your_cookie_name'])) {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

```

I didn't test this code, but I am positive it should work, or at the very least it illustrates the approach.

---
Tags: redirection, multi-sites, cookies
---


# Question
Title: Dynamic menu linking to the forum associated with the current Organic Group
I've got two groups. I've got two forums belonging to each group. I've got a panel set up to display a custom view of forum topics that are defaulted to the group id, so that when given the group id arg in the url it shows the forum topics that belong to that group.

The problem is, I now want a menu item on each group page which says 'forum' which points to the forum view with a group id argument which causes the display of only related forum topics.

# Answer
You do this with contextual filters. In the forum view, under the advanced settings, go to relationships and add OG membership: OG membership from Node. Then add a contextual filter OG membership: OG group gid. You will also need a default argument for "When the filter value is not in the url". You will use "Current OG group from context" for that. Rearrange your contextual filters if necessary so that is the first one.

Then in your page settings, set the path to group/%/forum (or whatever the correct path to your group page is). The % will be expanded to the group id, so that group/1/forum will show you the forum view for the group with gid=1.

You can then set the menu option just below the path option. That will put the menu on any page in the path you set.

Give that a try.
> 1 votes

---
Tags: views, routes, organic-groups, panels, nodes
---


# Question
Title: Clear cache doesn't clear the cache tables?
I don't fully understand the Clear Cache action. I just click in clear cache **Clear All caches** in: admin/config/development/performance , then I go to the database to check all cache\_... tables and I find that none of them are empty.

Is this normal?
Can I just truncate all cache\_... tables?

In fact I just need to clear cache\_form. Can I truncate this table?

# Answer
> 13 votes
> Can I just truncate all cache\_... tables?

You should not truncate the "cache\_form" table, as it contains the data used from Drupal to validate them; if you delete that table, the form currently being submitted from the user would be invalidated, and the users would need to submit the form again.

There could be some other cache tables that cause a module to act strangely. That is the reason modules that are using extra cache tables (whose name generally starts with "cache\_") are supposed to implement hook\_flush\_cache() to return the cache tables that can be cleared from Drupal, and which is then called with the following code, from drupal\_flush\_all\_caches().

```
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
    cache_clear_all('*', $table, TRUE);
  }

```

`drupal_flush_all_caches()` is the function called from system\_clear\_cache\_submit(), the submission form handler called when you click on the "Clear all caches" button, in the performance settings page.

During cron tasks, system\_cron() clears the cache using the following code.

```
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_page', 'cache_form', 'cache_menu');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
    cache_clear_all(NULL, $table);
  }

```

As the first argument of cache\_clear\_all() is `NULL`, the code executed in DrupalDatabaseCache::clear() (Drupal 7) is the following one.

```
if (variable_get('cache_lifetime', 0)) {
  // We store the time in the current user's $user->cache variable which
  // will be saved into the sessions bin by _drupal_session_write(). We then
  // simulate that the cache was flushed for this user by not returning
  // cached data that was cached before the timestamp.
  $user->cache = REQUEST_TIME;

  $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  if ($cache_flush == 0) {
    // This is the first request to clear the cache, start a timer.
    variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
  }
  elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
    // Clear the cache for everyone, cache_lifetime seconds have
    // passed since the first request to clear the cache.
    db_delete($this->bin)
        ->condition('expire', CACHE_PERMANENT, '<>')
        ->condition('expire', REQUEST_TIME, '<')
        ->execute();
    variable_set('cache_flush_' . $this->bin, 0);
  }
}

```

The code removes only the rows, which are not marked as permanent, and are expired, from the tables returned from `hook_flush_caches()`, and from various cache tables used from Drupal, including "cache\_form." There should not be too much rows in "cache\_form"; if that happens, you can reduce the time passed between two consecutive executions of the cron tasks, or execute the following code from a custom module.

```
cache_clear_all(NULL, 'cache_form');

```

An alternative is to manually cause the cache to be cleared, using the Devel module, and the menu link it shows.

# Answer
> 6 votes
If you are cache clearing via the UI, then as soon as the page reloads, then the cache will start filling up again. In other words, the act of refreshing that page causes Drupal to start to cache things again (especially `cache_menu`).

You can `DELETE FROM cache` on the various tables safely.

I am also pretty sure that doing a `drush cc all` will result in fully empty cache tables, too.

---
Tags: caching
---


# Question
Title: Pathauto patterns produce segment duplicates
I have set up a pathauto pattern for a wiki-section that looks like this:

```
wiki/[node:menu-link:parent:url:alias]/[node:menu-link:title]

```

I want it to produce links such as `wiki/page` and `wiki/page/subpage` and it works fine for first level links, but for sublinks it duplicates the first segment and produces links such as `wiki/wiki/page/subpage`.

What is the correct pattern I should use?

# Answer
Use just `[node:menu-link:parents:join-path]/[node:menu-link:title]` and make sure that you set the root node's URL alias manually as 'wiki'.
> 1 votes

---
Tags: 7, path-aliases
---


# Question
Title: Change Drupal interface language back to English
I made the mistake to translate the Drupal interface in my local language. But since the language is set into the database, I can't delete this language using the Drupal UI. And I'm not sure which file(s) to delete in the database.

Does anyone know a (faultlessly) way to translate the Drupal interface back to English?

# Answer
> 4 votes
You can change the language back to English by adding this to the url of any page:

```
&language=en

```

EDIT:

To have a seperate admin and front end language I'd suggest looking at the Admin Language module - http://drupal.org/project/admin\_language

SECOND EDIT:

To do this via role have a look at this page - http://deglos.com/blog/2010/06/12/overriding-language-drupal-backend

They are doing what you want with a custom module. You could throw in the user role code there using the global $user.

---
Tags: i18n-l10n
---


# Question
Title: How to use Views to make slideshow of the content created using block type
To Explain further:

Please I have created a block content type directly from block, say Item\_1 using ADD BLOCK then published. I did the same 3twice (item\_2,item\_3) each carries its contents(body). all published. Now I want to use views to view this block type via slideshow method. Could this be possible?

All I saw in the filter list of views 3 version are all nodes, content types none points to this. Please help.

# Answer
I assume you're trying to create a View from Blocks? It's not possible as far as I know, and it's not really a good idea I think. You could instead create a new Content Type (Structure -\> Content Types), and add each of your block's contents into a separate node of the type you made.

Then use Views to create a node view, filtered by the Content Type you created. You can then display this view as a Block, with a "Slideshow" display style using the Views Slideshow module
> 1 votes

---
Tags: views, entities, nodes, javascript
---


# Question
Title: How to modify a core theme and what is the correct way to do this?
I modified the core's Bartik theme file, node.tpl.php. I simply added

```
echo "Last updated by $name on " . format_date($node->changed);

```

The problem is that when there is a new core update, my change will be overwritten. Is there a way to create a module that will easily add this simple line in the node.tpl.php of Bartik's node.tpl.php theme file so that future updates will not overwrite my change?

# Answer
What you want to do is create a subtheme of Bartik, and make your modifications to node.tpl.php there instead. Themes support the notion of inheritance, so this can be leveraged to tweak core themes without actually hacking core. As a rule, it is best practice not to hack core for the reasons you mentioned and a slew of others, security not the least among them.
> 7 votes

---
Tags: 7, theming
---


# Question
Title: Rules react on event for file_managed table?
Im looking for a solution to be able to create a "react on event" in rules for when a file is added to the file\_managed table. Is it possible and if so, how?

# Answer
> 0 votes
I have looked and it is not an easy thing to accomplish with rules/drupal strictly. So instead I took a different approach that works great :)

I have a separate database that I use for various things which is added through my settings.php so available to drupal. I have added a newfiles table to this db. I then use on the file\_managed table a trigger:

```
CREATE TRIGGER `newfile_trigger` AFTER INSERT ON `file_managed` FOR EACH ROW INSERT INTO otherdb.newfiles (fid,uid,filename,uri,filemime) VALUES(NEW.fid,NEW.uid,NEW.filename,NEW.uri,NEW.filemime);

```

In my custom module I then have a hook\_cron that looks up the entries on the newfiles table every minute, performs the necessary functions and then deletes the row.

---
Tags: rules, files
---


title: How to code custom 404 error handling?

text:
# Question
Title: How to code custom 404 error handling?
I was planning on using a new domain name when migrating my legacy site to Drupal. I already have the php script that will translate old urls into Drupal Urls (I'm not using pathauto for that).

Now there is a chance I have to keep showing content on the old domain (mainly for SEO purposes). This site won't have any login or write-backs at all, it basically just shows the content and link to the new site.

How would I intercept the 404's that Drupal would now generate, preferably at a very low bootstrap level since there could be tons of invalid requests?

**Update:**

Sounds like I could use hook\_boot() to intercept every page request early and then have the query string parsed and redirected to the matching node/... page on the same site.

Or, similar to Fast404 I could add an include\_once to settings.php and do the redirect there:

```
include_once('.sites/default/modules/myredirect_module/myredirect_module.inc');

```

Will there be a big difference between those two options?

# Answer
You could just use the Fast404 module (if I'm understanding your question correctly).

> Drupal has expensive 404 errors. On an 'average' site with an 'average' module load, you can be looking at 60-100MB of memory being consumed on your server to deliver a 404. Consider a page with a bad .gif link and a missing .css file. That page will generate 2 404s along with the actual load of the page. You are most likely looking at 180MB of memory to server that page rather than the 60MB it should take.
>
> That's where Fast 404 comes in. This module combines a very common method of handling missing image/file 404 errors (discussed here and planned for Drupal 8) with a method created by dpardo (a co-maintainer of this project) to deliver super fast 404 error pages for both missing images and bad paths. Depending on which method of implementation you choose (aggressive or super aggressive) you can deliver 404 errors using less than 1MB of memory on your server.
> 8 votes

# Answer
```
function YOUR_MODULE_NAME_init() {
  if(!menu_get_item($_GET['q'])) {
    //do whatever you want if page not found
  }
}

```
> 5 votes

---
Tags: 7, bootstrapping
---


# Question
Title: Showing "Explanation or submission guidlines"
How can I get the Explanation or submission guidelines (one of the boxes when you edit/create a new content type) when the form is displayed? It obviously works fine in the default themes, but I can't figure out how/where to put the info to get those guidelines to be displayed. I'm not even sure which template it belongs in (node, page, region, etc).

# Answer
The "Explanation or submission guidelines" set on the edit/create content type form is actually displayed using the "System help" Block. So you just need to add the "System help" block to a region in your custom theme and it will be displayed there as long as you are actually printing the region in your theme.

I figured this out using the Theme developer module, which really is an extremely useful module for this kind of stuff. When you enable Theme developer, it adds a checkbox labeled "Themer info" to the bottom of each page. Check that box then click on any element in the page and you'll see information about how that element was themed. For example, enable Theme developer and use one of the default themes where the "Explanation or submissions guidelines" content is displayed correctly. Check the "Themer info" box and click on the submissions guidelines text, it will popup a box with information about how the submission guidelines where themed, like the image below. This should give you all the information you need to figure out how to theme something, or at least where to start looking.

**NOTE:** The Theme Developer module can actually end up breaking parts of your theme when enabled. It injects lots of `<span>`s to do it's magic. If something looks broken in your theme, disable Theme Developer and check again. Also, don't enable Theme Developer on a live site.
> 6 votes

---
Tags: 7, nodes
---


title: How do I hide a field after login?

text:
# Question
Title: How do I hide a field after login?
Could anyone tell me how I can hide a field after user login? For example, at the top of my front page I have:

> login | register

However, upon successful login, I would to hide this field.

The above 'login | register' field is just a 'div' block with 'href'.
One good example is the hiding of the default Drupal login block after login in.

I am using Drupal 7.

# Answer
> 3 votes
If you're outputting this directly in a template file it would be as simple as:

```
<?php if (user_is_anonymous()) : ?>

<a href="...">login</a> | <a href="...">register</a>

<?php endif; ?>

```

If you're using a block then you most likely won't want to put PHP code directly into it as that would involve using the evil `eval()` function. Instead you could add a new menu and use the block that's automatically created for that menu to output the links.

Since the menu system respects permissions, and the logged in users don't have access to the register or login page, the links simply won't show when a user is logged in.

---
Tags: users
---


# Question
Title: Returning a db query for select options in webform
I am trying to return dynamic select options for a webform component. I have it working to return node titles, but I need to instead return values from a manually created table in the db that is not drupal related. How would I alter this function to achieve that?

```
function _MY_MODULE_get_rate_options() {
    $nodes = array();
    $select = db_query("MY DB QUERY HERE");
    foreach ($select as $node) {
        $nodes[$node->nid] = $node->title;
    }
    return $nodes;
}

```

# Answer
> 0 votes
If you're creating a select list then you only need two fields from the database, so you can use the excellent `fetchAllKeyed()` method of the database query. This will let you get your results in a single line of code:

```
function _MY_MODULE_get_rate_options() {
  return db_query('SELECT id, name FROM {my_table}')->fetchAllKeyed();
}

```

The result is an array keyed by the first field (`id`) with values from the second field (`name`).

---
Tags: 7, hooks
---


# Question
Title: What can be put in 'Full HTML' node/fields?
The obvious answer to this question is HTML code of course, but my deeper question is, is this an `HTML body` content-like HTML? I suppose I can't put `HTML header` content-like HTML? Correct? I mean I can't put `META tags` for example.

# Answer
> 3 votes
You technically can use `<meta>` tags, since they will not be stripped out of the content that you place into a textfield that uses the default "full HTML" input filter. However, this content will be output in the `<body>` of the HTML document, which means using `<meta>` tags here will cause invalid HTML and most likely be ineffectual.

If you are looking for a way to customize the `<meta>` tags used on your Drupal site, there are many modules available to help with this. The Meta Tags module is the most popular, but that project's page also lists some other meta tag-related modules.

# Answer
> 1 votes
Drupal themes are broken down into regions, where content and other blocks are displayed. Therefore, you can add any HTML that would be valid inside whatever container your content region is wrapped in (typically a `<div>`). So the `<header>` tag would work if you're supporting HTML5, but `<head>` won't work as you'd expect, because you're putting it in the `<body>` of your document.

If you want to edit markup outside of that region, or even modify regions, have a look at the breakdown of core templates.

If you're looking to edit `<meta>` tags specifically, have a look at the Meta tags module.

# Answer
> 1 votes
When the full HTML is set as input format, what entered is not filtered in any way; this means that you could also enter tags that are not normally supported where you are adding them, such as `<meta>` tags that would appear inside the `<body>` tag, or miss a closing tag, such as in `<div><strong>This is wrong</div>`.

If you want to avoid both those problems, you could use the filtered input format, and add all the tags you are sure your users need, leaving out tags such as `<meta>`, which should not be added in the `<body>` tag.
It would also avoid there aren't tags left open, which would cause layout/formatting problems, when the users leave open tags. In fact, the code used to filter the entered HTML, in that case, is the following one.

```
  $allowed_tags = preg_split('/\s+|<|>/', $filter->settings['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);
  $text = filter_xss($text, $allowed_tags);

  if ($filter->settings['filter_html_nofollow']) {
    $html_dom = filter_dom_load($text);
    $links = $html_dom->getElementsByTagName('a');
    foreach ($links as $link) {
      $link->setAttribute('rel', 'nofollow');
    }
    $text = filter_dom_serialize($html_dom);
  }

```

---
Tags: nodes, theming
---


# Question
Title: Remove tabledrag statuses on Ajax submit and display status message after Ajax submit
1. I've added `drupal_add_tabledrag()` on one of my custom forms, it enables the users to drag to reorder the elements' weights, which then gets submitted via ajax to a callback function that saves the weights.

It's all working and the weights get saved, but after the save, the asterisks that indicate the weights have been changed, and also the message "Changes made in this table will not be saved until the form is submitted" won't go away.

What's the best way to let the dragtable know that the weights have been saved?
2. What's the best way to display status messages from an ajax callback function? I'd like to say "Weights saved successfully" after the callback function gets called. Currently I'm using `drupal_set_message` and `return true` from the callback function. This works as `theme_system_messages()` get prepended to the responses (see **#ajax\['callback'\]**), but I'd like to know if there's a better way to achieve this.

# Answer
> 4 votes
I managed to solve this finally. My answer to both questions was Ajax Commands.

To anyone looking for the solution, here's what I did:

## Question 1:

Instead of messing around with Dragtable, it's easier to just re-create the form and pass it back so it replaces the original form. I had to rebuild the form in my ajax callback function, then return it with an ajax command. To rebuild the form, you needed to create a new `form_state` variable and use `drupal_rebuild_form` function like so:

```
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);
}

```

The original form button that submits to this callback also should have the `form-container-element-id` in the `wrapper` element of the `#ajax` array (it should always be a CSS ID so it shouldn't have the # to indicate it's an ID):

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'my_ajax_form_callback',
    'wrapper' => 'form-container-element-id',
    'method' => 'html',
    'event' => 'click',
  ),
);

```

Here's the API documentation link for ajax commands: Ajax framework commands (Drupal 7)

## Question 2:

The best way to display status messages after an ajax callback is to use `theme_status_messages()` function. The snippet below also goes in the `my_ajax_form_callback` function before returning from the function:

```
drupal_set_message('This is a status message', 'status', FALSE);
$messages = theme_status_messages(array('display' => 'status'));
$commands[] = ajax_command_html('#status-message-container', $messages);

```

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