# Question
Title: How to remove h1 tag from Drupal Garland theme in the header
I was shocked to see Bing Webmaster Tools notification that my site: http://www.articlesdirectoryindia.com using Garland theme has two H1 tags and that only one should be there for SEO reasons.

Actually the site name : "Free Articles Directory India" is wrapped within h1 on all pages in the header which I want remove.

I want to know if there is any standard & tested workaround for removing this h1 and replacing this with some div etc?

I tried to change h1 to div for 10 minutes but I could not do it. Even if I'm able to it'd be difficult to test of all browser versions.

# Answer
```
if ($logo || $site_title) {
        print '<h1><a href="'. check_url($front_page) .'" title="'. $site_title .'">';
        if ($logo) {
          print '<img src="'. check_url($logo) .'" alt="'. $site_title .'" id="logo" />';
        }
        print $site_html .'</a></h1>';
      }

```

These are the lines 39-45 in Garland Themes page.tpl.php. This is probably the h1 tag you're talking about. If you want to change it to div it should look like this afterwards:

```
if ($logo || $site_title) {
        print '<div class="youclassname"><a href="'. check_url($front_page) .'" title="'. $site_title .'">';
        if ($logo) {
          print '<img src="'. check_url($logo) .'" alt="'. $site_title .'" id="logo" />';
        }
        print $site_html .'</a></div>';
      }

```
> 1 votes

---
Tags: 6, theming
---


# Question
Title: how to display the machine name of module at /admin/modules?
I use Drush to enable and disable module, to do this I need to know the machine name of the module.

At /admin/modules I can see the list of modules, but this list doesn't show the machine name, jut the human readable name.

I created a view to list the machine name of modules but I'd like to have it at /admin/modules. Is there any way to do this?

# Answer
If you don't mind going low-tech you can just look at the value of the checkbox next to each module; it contains a string like:

```
modules[Core][aggregator][enable]

```

In that example, `aggregator` being the machine name of the module.

If you don't want to go low-tech you'll need to implement `hook_form_alter()`, loop through the module data in the form and add the machine name somewhere.

For example, the following code will add the machine name in brackets after the title of each module:

```
function MYMODULE_form_system_modules_alter(&$form, &$form_state, $form_id) {
  foreach (element_children($form['modules']) as $group_key) {
    foreach (element_children($form['modules'][$group_key]) as $module_key) {
      $machine_name = " ($module_key)";
      $form['modules'][$group_key][$module_key]['name']['#markup'] = $form['modules'][$group_key][$module_key]['name']['#markup'] . $machine_name;
    }
  }
}

```

Screenshot of the results on a blank Drupal installation:
> 3 votes

# Answer
Try the development snapshot of the Module Filter module. It overrides the entire modules page and displays the machine name below the human name.

> The modules list page can become quite big when dealing with a fairly large site or even just a dev site meant for testing new and various modules being considered. What this module aims to accomplish is the ability to quickly find the module you are looking for without having to rely on the browsers search feature which more times than not shows you the module name in the 'Required by' or 'Depends on' sections of the various modules or even some other location on the page like a menu item.
> 2 votes

# Answer
FYI you can get the same info with `drush pm-list`, you can even filter extensions by status or other criteria.

Also, to see the extension's description and dependencies use for example `drush pm-info views_ui`.
> 2 votes

---
Tags: drush
---


title: Drupal ExtJS4 (Sencha) integration

text:
# Question
Title: Drupal ExtJS4 (Sencha) integration
Has anyone used ExtJS with Drupal? Is there any module for Drupal that supports Ext JS? If so, what are steps to get it work? I'm wondering if there is any feasibility of creating an Ext based drupal theme.

# Answer
There is just a module that integrates Ext in Drupal that I know of: the Ext module.

> Loads the Ext JavaScript library (version 2.2 & 2.3 for now) with Drupal. Other modules requiring Ext may use this module as a basis, or it may run on its own, simply loading the Ext library.
>
> Note: A new version of this module is being developed to provide relatively comprehensive integration functions with Ext 4.x (currently 4.1). For details please see http://drupal.org/node/1316616.

The module doesn't have a version for Drupal 7, though.
> 1 votes

---
Tags: theming, javascript
---


# Question
Title: How to add custom fields in Apache Solr's search result?
I'm trying to add some custom fields(image field, text field) in Apache Solr's search result. I ended up found the code below; however, I don't know:

1. Where to put this code (is it template.php?)
2. How to get the information to display them.

\`

```
function mymodule_apachesolr_update_index($document, $node, $namespace) {
  // When indexing nodes, add field from my custom content type.
  if ($node->type === 'my_contenttype') {
    // Grab the image URI and the description.
    $image_uri = $node->field_image['und'][0]['uri'];
    $description = $node->field_description['und'][0]['safe_value'];
    // Add the image and description to the document in the solr index.
    $document->addField('ss_my_contenttype_image', $image_uri);
    $document->addField('ts_my_contenttype_description', $description);
  }
}

function mymodule_apachesolr_query_prepare($query) {
  // Add the image.
  $query->addParam('fl', 'ss_my_contenttype_image');
  // Add the description text.
  $query->addParam('fl', 'ts_my_contenttype_description');
}

```

I appreciate any advice. Thank you.

# Answer
If you have D7 and latest Solr search integration module then you can follow these steps:

* Create a custom module with the following code (If your field is single value text then you should add "ts\_" prefix to its name.)

```
function mymodule_apachesolr_query_alter($query) {
  $query->addParam('fl', 'ts_field_name');
}

```
* Add the following function in the template.php file

```
function YOUR_THEME_preprocess_search_result(&$variables) {
  $variables['ts_field_name'] = $variables['result']['fields']['ts_field_name'];
}

```
* Display the field in search-result.tpl.php

```
<?php if ($ts_field_name): ?>
  <?php print $ts_field_name; ?>
<?php endif; ?>

```

This is a quick way that doesn't use any theme function like `theme_apachesolr_search_snippets()` for search results snippets.

You can find more information here:
> 5 votes

# Answer
Those functions would go to a custom module, in this case named mymodule.module. You can dig out the queried fields in your theme, either in template.php (in mytheme\_preprocess\_search\_result(), where you would typically perhaps process the fields further and modify the $variables array to include the modified fields) or in your search-result.tpl.php directly.
> 0 votes

---
Tags: search, entities
---


# Question
Title: Is it necessary to use cache in hook_init?
I wonder, since hook\_init doesn't run on cached pages, is it useful to use cache\_set in a hook\_init() ?

I am going to retrieve an array of strings from the database on each page request (not on cached pages obviously), so I am wondering how to do it properly. For this purpose, should I use cache\_set, a persistent variable or maybe no cache at all in hook\_init ?

# Answer
Sure, why not. All three options should work fine. But using Drupal's cache mechanism will work the best. The page cache is not the same as other caches which can still be used for whichever purpose you require, in this case, to store the results of a DB call. There are a number of core caches each with their own purpose besides the generic one (simply named cache), and you can also roll your own cache table if you like.

Here's an example on using `cache_set` and `cache_get` which should be similar to what you are attempting to do (albeit not in hook\_init).
> 3 votes

---
Tags: 7, caching
---


title: Modifying teaser node comment links

text:
# Question
Title: Modifying teaser node comment links
I've been at this for a few hours now but can't find a good way to solve this.

Basically what i want to achieve is to trough my template.php file completely override the comment modules output of links when displayed on a node teaser.

So i want to remove the "Add New Comment", "2 New Comments", "2 Comments" for example and have it replaced by only one single button saying something like "Comments (2)" instead.

# Answer
This specifically answers your question on how to override the comment links. The important part is using the value of `$vars['comment_count']` to add the count into your altered link title.

```
function YOURTHEME_preprocess_node(&$vars) {
    if(!empty($vars['content']['links']['comment'])){
        // Get rid of other comment link with counts
        $vars['content']['links']['comment']['#links']['comment-comments'] = array();
        // Override the title of the add a comment title displaying a count
        if($vars['comment_count'] > 0)
            $vars['content']['links']['comment']['#links']['comment-add']['title'] = 'Comments ('.$vars['comment_count'].')';
        else
            $vars['content']['links']['comment']['#links']['comment-add']['title'] = 'Comments';
    }
}

```
> 4 votes

---
Tags: comments, navigation, nodes
---


# Question
Title: Completely Locked out of website via User Permissions
The story:

Here's the full story. I disabled the Drag 'n Drop uploads module and then I was prompted to rebuild user permissions. So I was like, Ok and I rebuilt the user permissions. Then I noticed I couldn't see my admin toolbar, so I scrolled down the list of modules and it was unchecked, so was almost everything else. I went through and rechecked the modules I needed and then I clicked save. Nothing happened so I decided I'd put my site in maintenance mode until I sorted out the problem (so I did). I couldn't figure out what was wrong or how to fix it so I restored my entire website from a backup made earlier (1:28 AM) today but now it's giving me an error and I can't even access my site.

The Error:

PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'drupal.role' doesn't exist: SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users\_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids\_0); Array ( \[:uids\_0\] =\> 0 ) in UserController-\>attachLoad() (line 314 of ...public\_html/modules/user/user.module).

The question:

Is there any way to fix this error?

# Answer
> 2 votes
It sounds like the roles database table got randomly deleted, which should basically never happen under the circumstances you describe.

If you have a recent database backup, I suggest you grab the structure and content of the roles table from that database backup and restore that to your site database so you have the right content.

If you don't have a backup, I suggest you do a new installation on a separate site (or your local computer) and then export JUST the roles table from that new installation and import the roles.

---
Tags: users
---


# Question
Title: How to create a list of similar nodes in Drupal 7/Views 3
I face a rather common problem of displaying a list of nodes similar to current one. Similar node is defined as one having at least one taxonomy term that current node has. There are few solutions available as modules, however most modules I've found are in beta stage for Drupal 7.

I've also found a couple of solutions based on Views and contextual filters (such as http://scito.ch/content/show-related-nodes-block-based-taxonomy-terms-views-3-and-drupal-7) or relations. I quite like this way as it saves me installing extra modules and with Views being actively developed and supported I'd prefer to use them rather than any custom solution. The problem I can't get around is how to sort "similar nodes" by the number of terms they share. For example, if I have "IPhone 4S" Node with Terms "Gadget", "Apple", and "Phone", I want similar nodes in the following order:

1. IPhone 3 (Apple, Gadget, Phone)
2. IPad (Apple, Gadget, Tablet)
3. Mac (Apple, Computer)
4. Bramley (Apple, Fruit, Tree)

How can I sort nodes in this view by the number of terms they share?

# Answer
For those upvoting and favoriting, I've got the answer here: https://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3

It boils down to:

1. Create a block view
2. Add Contextual filter -\> Content: Nid -\> Provide default value -\> Content ID from URL
3. Add Relationship -\> Content: Taxonomy terms on node -\> specify the appropriate vocabulary
4. Add Relationship -\> Taxonomy term: Content using vocabulary as specified above -\> Check off Require this relationship
5. Turn on Views aggregation
6. Assuming you are listing title only, edit the title field to use the Relationship you set up in #4 above.
7. Add new sort criteria of Content: Nid. In aggregation settings, select Count. Use relationship from #4 and sort descending
8. Add Contextual filter -\> Content: Nid -\> Use relationship from #4 -\> Provide default value - Content ID from URL -\> Scroll down and expand "More" then check "Exclude" to remove current node from the view.
> 5 votes

# Answer
To get the results easily, try the Similar By Terms module.
> 1 votes

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


title: Updating custom modules

text:
# Question
Title: Updating custom modules
I have a module I wrote that is used on a production site. I had to make some changes and need to update the module.

Where do I begin to learn to do this?

# Answer
"Updating a module" can comprise of two things:

1. If it's just code, then simply replacing the old code with the new code should be sufficient. However, when your code is complex or you are working in a multi-user environment, it is best to bring your code under version control like svn or git (as you have tagged), and maintain it with branches and tags depending on the version of Drupal that you are working with.
2. If your module also involved database updates, then you will need to become familiar both with the .install file as well as hook\_update\_n() functions. The documentation for the latter along with source examples from the .install files of core modules should guide you to creating update functions correctly.

On a related note, if your custom code is generic enough to be of use to the rest of the community, you can post it as a Drupal project and leverage drupal.org's project management feature which comes with git access.

You should also test everything out on a development server rather than on the production site. Adding lots of documentation to your update functions as well as maintaining a CHANGELOG.txt is also recommended.
> 4 votes

---
Tags: updating, version-control
---


# Question
Title: Filtering PrivateMsg types by "sent" or "inbox"
I'm wondering what approach programmatically I should take when displaying message links that are either sent to the user loading the list, or sent out to other users.

Using some modifications to the example code listed at http://drupal.org/node/624528, I've loaded all unread and read messages regardless of author:

```
foreach ($query->execute() as $key => $thread) {

if ($count <= 25) {
                        // Generate a link with the subject as title that points to the view message page.
                        $items[] = array(
                            'data' => '<a href="' . 'messages/view/' . $thread->thread_id . '">' .
                            '<div class="messages-icon"></div>' .
                            '<div class="messages-from">' . $username . "</div>" .
                            '<div class="messages-subject">' . $thread->subject . "</div>" .
                            '<div class="messages-date">' . format_date($thread->last_updated, 'short') . "</div></a>",
                            'class' => array($class),
                            'id' => $key
                        );
                        $count++;
                    } else {
                        break;
                    }

```

and the output is done through a theme() call. I'm seeing that messages sent return null in $thread-\>participant. Would this be a sufficient use case to track for sent messages?

# Answer
From the page that you linked to:

```
// Replace 'inbox' with 'sent' to display sent messages or 'list' to display all messages.
$query = _privatemsg_assemble_query('list', $user, 'inbox');

```

Note that the privatemsg\_filter module needs to be enabled for that to work.
> 2 votes

---
Tags: privatemsg
---


# Question
Title: Drupal 7 on new Linode stack, POST/GETS 404ing but pages still loading?
I'm trying to migrate a site to a new linode environment, and my website has made the journey with the exception(s) that:

I cannot login at /user/login, console shows 404s when submitting credentials and the page simply refreshes. Note: ?q=user DOES work.

When logged in (through ?q=user method), every page i request shows a 404, but then still loads the page. For example, when going to mysite.com/t-shirts, console shows 404 on that address, even though the page loads fine.

Trying to login via colorbox returns (in the modal): Request unsuccessful: error.

All the elements in my pages that use ajax fail, showing 404s in console.

Short URLs SEEM to work, i.e. /catalog returns the proper page (despite 404 in console). I can also get to admin pages with /admin paths, but cannot seem to change anything on those pages because submitting the changes always fails.

What am I missing in migrating this drupal install? Drupal install status whines about GD and cURL missing, but I don't believe this has anything to do with it..

base URL is set to the proper address in settings.php (http://dev.skinnyboyswagclub.com)

# Answer
The reason for this is most likely that clean url's are disabled. Make sure that mod\_rewrite is enabled in Apache.

Fetching pages still works, because the 404 triggers Drupal, which is then able to return the correct page. That does, as you found out, not work for form submits, because the submitted data is lost when doing the redirect.
> 4 votes

# Answer
I would suggest the following:

1. Check all your logs. These include D7, webserver and syslogs.
2. Get a vanilla D7 site up & running and iron out all dependency issues.
3. Make sure that clean URLs and caching are working correctly.
4. On the migrated site, turn off clean URLs and caching, caching modules etc.
5. Try commenting out the `$base_url` option.
6. Check all your logs. These include D7, webserver and syslogs.

I would also get drush installed (if not already) to both check the status and keep an eye on the watchdog logs.
> 0 votes

---
Tags: 7, users, uri, migrations
---


# Question
Title: Site upgrade to D7 using drush stuck on the "Run update.php" step
I am attempting upgrading my site from D6 to D7 using Drush Site upgrade.

The process gets stuck on the 13th step. This is the last output I get :

```
    UPGRADE.txt Major Upgrade Step 13

13. Run update.php by visiting http://www.example.com/update.php (replace
    www.example.com with your domain name). This will update the core database
    tables.

    If you are unable to access update.php do the following:

    - Open settings.php with a text editor.

    - Find the line that says: $update_free_access = FALSE;

    - Change it into: $update_free_access = TRUE;

    - Once the upgrade is done, $update_free_access must be reverted to FALSE.

Note that Drush will copy your database and run updatedb on the copy. The
source database remains unchanged.

Drush will automatically do this step now.

```

Why is this happening and how can I fix it?

# Answer
> 2 votes
You may get the information you need by running drush with the verbose flag: -v or --verbose.

---
Tags: drush, upgrading
---


# Question
Title: Multiple Drupal sites using the same code base
Is it possible to use the same Drupal code base for different Drupal sites, just by changing `settings.php` and the database settings, and accessing it through a subdomain?

# Answer
> 5 votes
coleopterist is right.

Let's say you want ***mydomain.com*** and ***sub.mydomain.com*** to share the same codebase, you will have to put two folders in sites/ :

* sites/mydomain.com/
* sites/sub.mydomain.com/

If you want modules and themes to be available to all domains defined in sites/, all you have to do is to put them in all/ :

* sites/all/modules/
* sites/all/themes/

Then, in sites/{domain}/settings.php you can redefine the databases strings like so :

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database_name',
      'username' => 'user_name',
      'password' => 'p4ssw0rd',
      'host' => '127.0.0.1',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
  ),
);

```

Note that you should launch the DrupalRoot/install.php script for each different domain to create its database tables.

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


title: How to load user via user email?

text:
# Question
Title: How to load user via user email?
I am going to import data from a csv file, specifically linking a node to a user. I see that I can link a node to a user via user id, however I won't know the user id on import. Is there a way I can link the node to the user via user email?

Thanks!

# Answer
Ofcourse you can get user id by email, check this out: http://api.drupal.org/api/drupal/modules!user!user.module/function/user\_load\_by\_mail/7
> 1 votes

---
Tags: 7, nodes, feeds
---


# Question
Title: How should I change the permissions PRIVATEMSG for users in order them to have the access?
Good day, I've marked read, write and delete the privatemsg for the authenticated users but they don't still have access to the pages such as user/user-id/messages. The access is only granted with "read all" permission. I use privatemsg 6.x-1.5 Thanks.

# Answer
> 0 votes
The normal user interface is at /messages, user/uid/messages is only meant to read messages of other users and is not a full replacement.

6.x-2.x has a feature that allows to move it around but it's relatively complex and I wouldn't necessarly recommend using.

---
Tags: users, privatemsg
---


# Question
Title: How do I make the output of field X look like Y?
I have a field of type X, and it's output is not quite the way I want to it to be. I would like it to look like Y instead. How can I do that?

# Answer
> 2 votes
I usually solve this type of problem by implementing a custom field **formatter**, which is what controls how a field is rendered.

Below is sample code to implement a basic single delta field formatter. It is used on normal "text" fields, and will simple output todays date, with a single setting for in what format to output the date.

Since this particular example does not actually use the field data, it's important to know that you need the field to have **some** value, or Drupal will ignore it.

```
// Declare a new field formatter.
function hook_field_formatter_info() {
  return array(
    'custom_current_date' => array(
      'label' => t('Current date'),
      'field types' => array('text'),
      'settings' => array('date_configuration' => 'm'),
    ),
  );
}

// Form API callback for the formatters settings form
function hook_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    'date_configuration' => array(
      '#type' => 'textfield',
      '#title' => t('Date configuration'),
      '#default_value' => $settings['date_configuration']
    ),
  );

  return $element;
}

// Output a message showing what the current field settings are.
function hook_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  return 'Date config is ' . $settings['date_configuration'];
}

// Actual field output goes under the #markup key. Add a loop instead of the
// leading 0 to support multi-value fields.
function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];

  return array(0 => array('#markup' => date($settings['date_configuration'])));
}

```

---
Tags: entities
---


# Question
Title: how to implement jquery image gallery in drupal theme tpl.php files?
I am new to Drupal 7's theme system. i am creating a custom theme that have image gallery inside it.but i have no idea for implementing jquery image gallery in drupal theme tpl.php files. i searched many tutorials about image gallery in drupal theme. but most of them just show implementation of image gallery using views and gallery related modules. can anybody know tutorials series that show how to add js files in theme tpl.php file from scratch? and what kind of drupal variables are use for gallery purpose.

# Answer
> 2 votes
If you want the bluemasters rotator exactly, you need to copy their javascript and css that apply to the rotator element (image\_reel) and install it in your theme. The following instructions would also be relevant for other slideshow scripts with obvious substituions.

First, you need to add the rotator script from bluemasters to your theme. The name of the file is bluemasters.js and is in bluemasters/js/ in the theme folder.

To install it in your theme, you could just add it as a script tag in your page.tpl.php file in your template, ex:

```
<script type="text/javascript" src="<?php echo path_to_theme(); ?>/path/to/bluemasters.js"></script>

```

There are much better ways of adding this, using drupal\_add\_js and page\_preprocess functions but this is the easiest way to make sure it is loaded on every page.

Next, you're going to need to isolate the css bluemasters is using to create their slider. From their css file, it looks like all of the css for the front page slider is in one block in the file, starting with the comment 'Front-page slider'

```
/*
 * Front-page Slider
 */
.main_view { float: left; position: relative; }

...etc.

```

Grab that and add it to your theme's css file.

If you've got these two files added to your theme correctly, then anywhere the image\_reel class exists (with the following structure) on your pages, their code will convert it into a slideshow. The exact structure (from their demo file) is just a list of links like this:

```
        <div class="image_reel">
            <a href="/bluemasters/node/3"><img src="/bluemasters/sites/all/themes/bluemasters/images/slide-image-3.jpg"></a>
            <a href="/bluemasters/node/2"><img src="/bluemasters/sites/all/themes/bluemasters/images/slide-image-2.jpg"></a>
            <a href="/bluemasters/node/1"><img src="/bluemasters/sites/all/themes/bluemasters/images/slide-image-1.jpg"></a>
        </div>

```

You can add this code in as a block or on a page or in your template directly and it will create the same slider effect.

---
Tags: theming, media
---


# Question
Title: how to change "username" text located in registration form
how i can change "username" text, located in registration form.. i need to change it to "Organization Name" and everywhere of my website "username" text should replace with "Organization Name". How to do it? Thanks

# Answer
The way to modify the user registration form is to add a hook\_form\_alter() function to your theme to change the form variables and add a theme hook to use a custom use-register.tpl.php file. There are numerous tutorials and responses here on stackexchange (for example) that can guide you on this process, but if all you're trying to change is one string, you should try the string overrides module, which allows you to easily replace anything passed through the t() function (ex. "username" --\> "organization").
> 2 votes

---
Tags: users
---


title: max number of content types on drupal

text:
# Question
Title: max number of content types on drupal
i have been handled a drupal site to work on, the problem is its very messy, they were building every single detail as a content type **(using CCK)**, that produce around **150 content type** and **560 database table** ( now you can imagine the mess), and i want some document to convince my team leader that this is a bad approach to follow

if any one could help

# Answer
> 1 votes
560 tables isn't that much (D7 produces a lot more because of one field =\> 2 tables) but 150 content types is *a lot*, that's for sure. This will result in huge caches that Drupal needs to carry around all the time.

I assume that site uses content types to store any kind of data, including internal stuff that isn't displayed?

Using content types for anything that is displayed on the website usually makes sense, you also get a lot of integration for free (e.g. views). However, having a huge amount of content types, doesn't scale well as you found out so you might want to go through your content types and convert some of them to custom tables.

In Drupal 7, it is common to define entities for custom data structures, especially things that are not content (see drupal commerce, search api and so on for examples).

There, is, however, no official or technical limit of content types that you can have. I'd recommend using xhprof to profile the site, if you can e.g. show that the site is using a huge amount of memory because of that, that might be a good argument.

# Answer
> 1 votes
On top of any negative performance effects, it makes it hard for a site admin to manage.

Content types should be used for different types of content. If you need to have slight variations within a certain type of content, use a module like Conditional Fields or Webform Entity.

Recently I saw a good presentation on this idea of Semantic Site Building, perhaps that will help point out mistakes in the site build you've been saddled with.

---
Tags: 7, entities, nodes
---


# Question
Title: Why do Drupal core functions get node object instead of nid as argument?
Most (if not all) of Drupal functions accept $node object instead of $nid as argument, like `node_type_get_name($node)`, so we should first write `node_load($nid)` and send its long output to the functions, whereas they can call the `node_load()` function themselves and reduce number of developers' codes. What's the reason?

# Answer
I think it's to avoid the repetition of node\_load that could occur.

I searched a little in the source and you can see node\_type\_get\_name($node) is called from others functions which also take a $node object argument, node\_promote\_action for exemple

```
function node_promote_action($node, $context = array()) {
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
}

```

It seems DRY to me. Imagine you gave a nid as argument in node\_promote\_action :

```
function node_promote_action($nid, $context = array()) {
  $node = node_load($nid);
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($nid), '%title' => $node->title));
}

```

And then node\_load again in node\_type\_get\_name :

```
function node_type_get_name($nid) {
  $node = node_load($nid); // repetition
  $type = _node_extract_type($node);
  $types = _node_types_build()->names;
  return isset($types[$type]) ? $types[$type] : FALSE;
}

```

With nid as argument, each time a node related function (A) need to process some node's properties (often if not always), they would call node\_load. This would lead to unnecessary repetition when another node processing function (B) is called inside the first (A), just like in the above example.
> 2 votes

---
Tags: 7
---


# Question
Title: Is it possible to run functional tests without creating test tables?
My goal is to speed up functional tests without tweaking the database. Is it possible to avoid the creation of Simpletests setup tables and use existing tables instead? I read this article where the author states :

```
Maybe the answer is Simpletest 2 which allows you to run on a "dirty" environment.

```

So is this "dirty" environement is the answer? If so, how to use it as setup ?

# Answer
> 1 votes
I have found the answer there. But don't do that !

It's better to move the database on a tmpfs folder (it's \> 5x faster), because not only a "dirty" environment does not work, but it will broke your website with a serious error (just happened to me). Hints to tweak the database on this question.

It's there but don't do it :

```
  // for our functional testing, we want to test the pages and code that
  // we've been generating in the real database. to do this, we need to
  // ignore SimpleTest's normal fake database creation and fake data
  // deletion by overriding it with our own setUp and tearDown. NOTE that
  // if we make our own fake data, we're responsible for cleaning it up!
  function setUp() {
    // support existing database prefixes. if we didn't,
    // the prefix would be set as '', causing failures.
    $this->setup = TRUE; // Drupal 7 way
  }
  function tearDown() { }

```

---
Tags: 7, database, testing
---


# Question
Title: Ajax error on dependent dropdown. Drupal 7
I am trying to get the following dependent dropdown to work, however I constantly get the following error. So far could not figure out what the problem is. I was wondering if anyone has had a similar problem and might have the solution for it.

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /?q=system/ajax StatusText: OK ResponseText: stringstring(1) "2" array\[ {"command":"settings", "settings":{"basePath":"\u002F", "pathPrefix":"", "ajaxPageState":{"theme":"bartik", "theme\_token":"Ghiw-ikiaoP9ioC23jfb6h1vvIuA4G\_nb3NBGO0mfEA"}, "overlay":{"paths":{"admin":"node\u002F\*\u002Fwebform\u000Anode\u002F\*\u002Fwebform\u002F\*\u000Anode\u002F\*\u002Fwebform-results\u000Anode\u002F\*\u002Fwebform-results\u002F\*\u000Anode\u002F\*\u002Fsubmission\u002F\*\u000Anode\u002F\*\u002Fedit\u000Anode\u002F\*\u002Fdelete\u000Anode\u002F\*\u002Frevisions\u000Anode\u002F\*\u002Frevisions\u002F\*\u002Frevert\u000Anode\u002F\*\u002Frevisions\u002F\*\u002Fdelete\u000Anode\u002Fadd\u000Anode\u002Fadd\u002F\*\u000Aoverlay\u002Fdismiss-message\u000Auser\u002F\*\u002Fshortcuts\u000Aadmin\u000Aadmin\u002F\*\u000Abatch\u000Ataxonomy\u002Fterm\u002F\*\u002Fedit\u000Auser\u002F\*\u002Fcancel\u000Auser\u002F\*\u002Fedit\u000Auser\u002F\*\u002Fedit\u002F\*", "non\_admin":"admin\u002Fstructure\u002Fblock\u002Fdemo\u002F\*\u000Aadmin\u002Freports\u002Fstatus\u002Fphp"}, "pathPrefixes":\[ \], "ajaxCallback":"overlay-ajax"}}, "merge":true}, {"command":"insert", "method":null, "selector":null, "data":"\u003Cdiv id=\u0022second-select-box-replace\u0022\u003E\u003Cdiv class=\u0022form-item form-type-select form-item-second-select-box\u0022\u003E\u000A \u003Clabel for=\u0022edit-second-select-box--2\u0022\u003EChoose \u003C\u002Flabel\u003E\u000A \u003Cselect id=\u0022edit-second-select-box--2\u0022 name=\u0022second\_select\_box\u0022 class=\u0022form-select\u0022\u003E\u003Coption value=\u00227\u0022\u003ECountries\u003C\u002Foption\u003E\u003Coption value=\u00223\u0022\u003EUniverse\u003C\u002Foption\u003E\u003C\u002Fselect\u003E\u000A\u003C\u002Fdiv\u003E\u000A\u003C\u002Fdiv\u003E", "settings":null}, {"command":"insert", "method":"prepend", "selector":null, "data":"", "settings":null} \]

Here is the code:

```
function form_new_term_step_two($form, &$form_state){

    $first_options = _step2_first_options_select_box();

    $selected = isset($form_state['values']['first_select_box']) ? $form_state['values']['first_select_box'] : key($first_options);
    //var_dump($selected);

    $form['first_select_box']= array(
        '#type' => 'select',
        '#title' => 'How do you categorize the term ?',
        '#options' => $first_options,
        '#default_value' => $selected,
        '#ajax' => array(
            'callback' => 'ajax_step2_select_callback',
            'wrapper' => 'second-select-box-replace',
        ),

    );

    $form['second_select_box'] = array(
    '#type' => 'select',
    '#title' => 'Choose',
    '#prefix' => '<div id="second-select-box-replace">',
    '#suffix' => '</div>',
    '#options' => _ajax_example_get_second_dropdown_options($selected),
    '#default_value' => isset($form_state['values']['second_select_box']) ? $form_state['values']['second_select_box'] : '',
  );

    return $form;
}

/*
 * All the Submit and Callback fucntions
 */
function ajax_step2_select_callback($form, $form_state){

    return $form['second_select_box'];

}

function _ajax_example_get_second_dropdown_options($selected= Null){

    $results =  taxonomy_get_term_by_name($selected);
    $tid = array();
    foreach ($results as $objs){

        $tid = $objs->tid;

           }

    $terms = taxonomy_get_children($tid);

    foreach ($terms as $term){

        $options[$term->tid] = $term->name;

    }

    return $options;
}

```

# Answer
> 1 votes
You need to remove the line

```
'#options' => _ajax_example_get_second_dropdown_options($selected),

```

Then, put your function call and update the #options on some condition. So, something like this:

```
if(isset($form_state['values']['first_select_box'])) {
  if($form_state['values']['first_select_box'] == 'something'){
    //the contents of your _ajax_example_get_second_dropdown_options function here
    //and instead of returning something... just SET #options to your new output.
    $form['second_select_box']['#options'] = 'new stuff';
  }
}

```

Furthermore, most of the time people will not even show the second select box until the first one is filled out with something useful for the second. In that case, you can set the #type of the second select box to 'markup' and then in that above if statement SET the #type to select.

```
$form['second_select_box'] = array(
  '#type' => 'markup',
  '#prefix' => '<div id="second-select-box-replace">',
  '#suffix' => '</div>',
);

if(isset($form_state['values']['first_select_box'])) {
  if($form_state['values']['first_select_box'] == 'something'){
    //the contents of your _ajax_example_get_second_dropdown_options function here
    //and instead of returning something... just SET #options to your new output.
    $form['second_select_box']['#type'] = 'select';
    $form['second_select_box']['#options'] = 'new stuff';
    $form['second_select_box']['#title'] => 'Choose';
  }
}

```

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


# Question
Title: How do I target a specific term or node in a toked?
I am developping a site on a dev server, and I am wondering how to create hyperlinks not depending on the server the site is running on.

I have considered usig `href="node/xx"` and `href="term/yy"` but I would like to use the paths generated by pathauto.

But I cannot include the pathauto url as I am certain my client will change titles before I move the site to its final destination, and I might have to regenerate paths to do that.

So I am wondering if there is a way with tokens. Something like `[node:nid:122]` or `[term:tid:122]`

# Answer
The link node module is doing this for you. Here is a quote about it (from the module's project page):

> Once installed you (or any user who can post) can add an embedded href link to any node using the syntax (where N is a number, and NNN is a node id):
>
> \[node:NNN\]
>
> Parameters follow the part and are comma separated name="value" pairs:
>
> \[node:NNN,title="Original version of the picture"\]
>
> MultiLink supports Link Node, so if someone is viewing in another language it gets converted to \[node:101\] or whatever the correct node is for the translated version automatically.
> 0 votes

# Answer
I would suggest using the Pathologic module and you can link to anything internal (e.g. `<a href="/node/22">` and it will automatically convert the link to the URL alias of node 22 for the current site.
> 0 votes

---
Tags: tokens
---


title: Link field to views pages and nodes

text:
# Question
Title: Link field to views pages and nodes
On my content type I want to allow a content administrator to insert a hyperlink to a page and allow them to define a list of related pages. This works fine for linking to nodes, but I am unable to get Views Pages to list.

I have tried the following options:

* references module - only allows you to reference nodes
* View reference - Not an interface I want to give to a non-techie
* entityreference - also does not allow you to reference views pages
* viewfield - only allows you to *insert* views and the interface is not end user friendly
* linkit with linkit views - could not get "views pages" to list, documentation seemed to imply it was possible

The items are all in my main menu, is there not a module or picker out there that allows you to pick menu items?

# Answer
> 0 votes
Linkit + Linkit views *is* a solution, it allows:

* Autocomplete field to look-up Nodes or Views
* WYSIWYG and link field integration
* allows external links too

**Just note**: the autocomplete lookup requires the "Display name" of your view to be descriptive, as it is used for the lookup not the title, if these are all "Page" you will not find them.

---

What it is not is a node-reference or entity reference, but all I wanted was to have hyperlinks to other nodes.

# Answer
> 0 votes
Maybe View Reference ? Please refer to this page

---
Tags: 7, views, navigation
---


# Question
Title: hook_form_alter - validation function does not get called in Internet Explorer
I created my own function to validate username and password from the login form, and it's working great in FF and Chrome, but does not work in IE 8 and 9.

I'm using hook\_form\_alter to catch the loginform and then I replace the default validation function "user\_login\_authenticate\_validate" with "my\_own\_validation\_function" in the $form\['#validation'\] array.

But for some reason the new validation function never gets called in IE, but I've verified that the default validation function is replaced by printing the $form info, and it all looks great.

I'm not really sure of where to go from here, I've spent way to much on this now ;)

Any help appreciated!

# Answer
The Form API works via PHP and is executed in its entirety on the server. There really should be no question of browsers being involved in the equation. That is, unless you are doing something with JS (or CSS/anything client side) that might affect form input.

I would:

1. Clear all my caches.
2. Ensure that I'm working on the same page, site (and as the same user) in both FF and IE.
3. When you mention "printing the $form info", I assume that you are using the Devel module. If you aren't, you should be. Devel's `dpm()` function is the best way to debug these things by adding diagnostic print statements in each step - the form, the validation hook and the submit hook.
> 1 votes

---
Tags: users, forms
---


# Question
Title: Strange PDOException Error With Computed Field
I have a computed field which is calculating values based on an entity reference field. It works fine when calculating an AVG, but I realized today that what I actually would like is for it to find the most popular result in a column. So I altered the code as suggested here. However, now it's throwing me a PDOException error that (I think, I'm not exactly an expert) is related to the WHERE portion of the query. I'm not sure why it would be doing this. The code and error are included below. Any suggestions?

Old, working code:

```
$entity_field[0]['value'] = "";

$nids = db_query('
    SELECT entity_id
    FROM {field_data_field_review_venue_reference}
    WHERE field_review_venue_reference_target_id = :nid',
    array(':nid' => $entity->nid)
   )->fetchCol();

if (empty($nids)) {
    $entity_field[0]['value'] = "-10";
}

else {
    $entity_field[0]['value'] = db_query('
    SELECT AVG(field_review_payment_value)
    FROM {field_data_field_review_payment}
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
   )->fetchField();
}

```

New, error-throwing code:

```
$entity_field[0]['value'] = "";

$nids = db_query('
    SELECT entity_id
    FROM {field_data_field_review_venue_reference}
    WHERE field_review_venue_reference_target_id = :nid',
    array(':nid' => $entity->nid)
   )->fetchCol();

if (empty($nids)) {
    $entity_field[0]['value'] = "-10";
}

else {
    $entity_field[0]['value'] = db_query('
    SELECT COUNT(field_review_payment_value) AS `Rows`
    FROM (field_data_field_review_payment)
    GROUP BY (field_review_payment_value)
    ORDER BY `Rows` DESC
    LIMIT 1
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
   )->fetchField();
}

```

Error:

`PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE entity_id IN ('16', '17', '21', '22', '30', '31', '32', '33', '34', '35', ' at line 6: SELECT COUNT(field_review_payment_value) AS`Rows`FROM (field_data_field_review_payment) GROUP BY (field_review_payment_value) ORDER BY`Rows`DESC LIMIT 1 WHERE entity_id IN (:nids_0, :nids_1, :nids_2, :nids_3, :nids_4, :nids_5, :nids_6, :nids_7, :nids_8, :nids_9, :nids_10, :nids_11, :nids_12, :nids_13, :nids_14, :nids_15, :nids_16, :nids_17, :nids_18, :nids_19, :nids_20, :nids_21, :nids_22); Array ( [:nids_0] => 16 [:nids_1] => 17 [:nids_2] => 21 [:nids_3] => 22 [:nids_4] => 30 [:nids_5] => 31 [:nids_6] => 32 [:nids_7] => 33 [:nids_8] => 34 [:nids_9] => 35 [:nids_10] => 36 [:nids_11] => 38 [:nids_12] => 40 [:nids_13] => 45 [:nids_14] => 46 [:nids_15] => 47 [:nids_16] => 50 [:nids_17] => 51 [:nids_18] => 52 [:nids_19] => 57 [:nids_20] => 75 [:nids_21] => 79 [:nids_22] => 85 ) in eval() (line 26 of /Applications/MAMP/htdocs/sites/all/modules/computed_field/computed_field.module(466) : eval()'d code).`

# Answer
> 0 votes
Try moving the `WHERE` clause to before the `GROUP BY` statement:

```
$entity_field[0]['value'] = db_query('
  SELECT COUNT(field_review_payment_value) AS `Rows`
  FROM (field_data_field_review_payment)
  WHERE entity_id IN (:nids)
  GROUP BY (field_review_payment_value)
  ORDER BY `Rows` DESC
  LIMIT 1',
  array(':nids' => $nids)
)->fetchField();

```

MySQL queries have to follow a certain format and the `WHERE` clause needs to be before `GROUP BY`, `ORDER BY`, `LIMIT`, etc.

---
Tags: entities
---


# Question
Title: Can node reference be altered to include views pages?
I have a site where 'related pages' is a node reference CCK field for a node. Authors can add related pages (1 or more) to a node with the autocomplete functionality of node reference.

My question is the following: is it possible to extend the CCK node reference field to include non nodes, e.g. views pages, in this case?

# Answer
> 4 votes
You could use a separate viewfield for the related views, and theme it so that the nodereferences and viewfields appear in the same list.

You could also use a link and use a custom widget if you don't wanna type the full path every time.

On a couple of sites I ended up never (or *very* rarely) using a view's page display. Instead I attached the view to a node, and always referred to the view via its node. This was because my advert banner system was based on nodereferences. It's not the most extensible approach, but it worked for those sites.

# Answer
> 2 votes
There are some major differences between a node and a view. The node is some pieces of data (title, CCK, etc), while the view is constructed by querying the database.

That said it would be possible to make a reference to views. I don't think the approach would be to try to extend the node reference field. Instead you would need to create your own type of CCK field. Unless you know your way around CCK, this could very well be a lot more work than you would like.

You also need to note, that views are more complex than nodes, as they have more viewing possibilities. A view can have an endless amount of different displays, so you would need to not only save the view name but also the display.

The solution would probably end up being so technical, that only expert users would be able to use it. Though I'm against using PHP filter in node, an easier solution would be to create a field, where you could put in a PHP snippet to embed the view you want. `views_embed_view` I believe it's called, this is what you would have needed in your cck field formatter anyways.

# Answer
> 0 votes
Just adding another solution as @wiifm was looking to only use the nodereferences as hyperlinks. Linkit module + Links + Linkit Views gives a field with a pretty little search widget as well as a WYSIWYG button + IMCE integration.

One config thing to check in my answer re Views Links (to my own question) on configuration.

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


title: Managing user disk space

text:
# Question
Title: Managing user disk space
I need a mechanism for managing users' storage space. I have multiple content types with file upload fields. Admin should be able to set it globally, or per individual user.

My initial approach is to add a field in the admin configuration menu, for admin to set the default limit, and a field for users for individual space allocations.

When a user goes to create new content, I check their used space to see if they are maxed out. Then when they are about to upload a file, I'll check the file size and see if it will put the user over the limit. If not, I let the upload occur.

The Drupal API gives us a file\_space\_used() function, which gives the total file space used by a particular user, so that's pretty cool.

Am I on the right track?

EDIT AFTER ANSWER: syd asked me to post my script, and I forgot.

```
function mymod_file_validate($file)
{
    global $user;
    $ulimit = 0;    // user limit

    // get the limits per role (I had two to check against, and vals are
    // in megabytes (hence the *1000000))
    if (array_search(HL_ROLE_REG, $user->roles))
        $ulimit = variable_get(HL_VARKEY_REGSPACE) * 1000000;

    if (array_search(HL_ROLE_PREM, $user->roles))
        $ulimit = variable_get(HL_VARKEY_PREMSPACE) * 1000000;

    return (file_validate_size($file, 0, $ulimit));
}

```

# Answer
Drupal does all the work.

I made a call to file\_validate\_size() in my hook\_file\_validate() handler. I also made an admin form to modify each role's allowable space (using variable\_get/set), and it works great.

Next step is to create a table containing non-default values (keyed by uid), and an admin tool to set individual users' allowable space. I'll then update my hook\_file\_validate() handler to check for the user in that table. If not, then check the default.
> 2 votes

# Answer
Probably you should use file\_validate\_size()

```
function file_validate_size(stdClass $file, $file_limit = 0, $user_limit = 0) {
  global $user;

  $errors = array();

  // Bypass validation for uid  = 1.
  if ($user->uid != 1) {
    if ($file_limit && $file->filesize > $file_limit) {
      $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
    }

    // Save a query by only calling file_space_used() when a limit is provided.
    if ($user_limit && (file_space_used($user->uid) + $file->filesize) > $user_limit) {
      $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', array('%filesize' => format_size($file->filesize), '%quota' => format_size($user_limit)));
    }
  }
  return $errors;
}

```

> Checks that the file's size is below certain limits.
>
> This check is not enforced for the user #1. Parameters
>
> $file: A Drupal file object.
>
> $file\_limit: An integer specifying the maximum file size in bytes. Zero indicates that no limit should be enforced.
>
> $user\_limit: An integer specifying the maximum number of bytes the user is allowed. Zero indicates that no limit should be enforced. Return value
>
> An array. If the file size exceeds limits, it will contain an error message.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Simple calculator with predefined coeficient
I would like to have very simple calculator on my page - user should input any number x (days) and the result should be x times y where y is any preddefined coeficient that I define. Is it possible to do in drupal. 6 or 7 version? Thank you

# Answer
> 0 votes
Yes - this is possible, but its not really related to Drupal (at least the way you define it). Its either going to be a javascript calculator that you embed in a page (where the result wouldn't get saved) or a PHP function that processes the results from a form and returns the result on the next page.

Either way, both are beyond the scope of this site but tutorials like this one should give you a start on writing your calculator embed.

---
Tags: views
---


# Question
Title: Wrap comment replies in a collapsible fieldset
I found an article about wrapping all comments (http://scito.ch/content/wrap-comments-collapsible-fieldset), but I just want to wrap comment replies in a collapsible fieldset.

How do I achieve this?

# Answer
Implement hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() and add the collapsible fieldset to the form field. For example:

```
function MODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
    //Create the fieldset
    $form['custom_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('My Collapsible Fieldset'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );

    //Move the field into the fieldset
    $form['custom_fieldset']['comment_body'] = $form['comment_body'];

    //Unset the original field
    unset($form['comment_body']);
}

```

You can set `'#collapsed' => TRUE` if you want the fieldset to be closed by default.

---

If you're looking for a Module based approach, you may want to look into the Field group project.

I'm not sure how well this module will get along with the Comment module though. You may need to implement hook\_form\_alter() in a custom module or in your theme.
> 2 votes

---
Tags: 7, comments
---


# Question
Title: The famous counter module "counter" is marked unsupported
The famous counter module "Counter" is marked unsupported. Is there another good choice for counter?

# Answer
The Visitors module is pretty good option for the counter module.

**Reports provided by the module:**

> 1. View pages that have recently been visited.
> 2. View pages that have been hit frequently.
> 3. View pages count per month.
> 4. View pages count per day of month.
> 5. View pages count per day of week.
> 6. View pages count per hour.
> 7. View pages count per host.
> 8. View access log.
> 9. View user activity report (hits, nodes, comments).
> 10. View referrer list.
> 3 votes

---
Tags: 7
---


# Question
Title: Drupal clean URLs not working from subdirectory
I'm not sure if this belongs here or in serverfault, so feel free to flag it if necessary. I have a server with a drupal installation at /drupal. I want the URL www.example.com to point to www.example.com/drupal. I don't want to change my server root, just do an Apache Rewrite.

```
RewriteRule (.*) /drupal/$1

```

This works, so when I type www.example.com I go to the drupal site. The issue is no other URLs go to the correct spot. So when I type a URL like www.example.com/about, I see the drupal theme but then the content just says

> The requested page "/about" could not be found.

The page www.example.com/drupal/about does show up fine. I've also changed $base\_url to www.example.com. Any idea what could be wrong?

I've also tested that URLs like www.example.com/?q=node/16 work fine, so the problem is just with clean URLs.

# Answer
> 2 votes
Problem in drupal Clean URL, To Enable drupal clean url in subdirectory un comment the following line in .htaccess file.

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

```

for more refer the blog Enable drupal clean url in subdirectory or subdomain

---
Tags: redirection, uri
---


# Question
Title: Controlling file paths in multi domain setup
A site responds to internal.example.com, and external.example.com.

Content editors all use internal. When Drupal generates the cached output, all images are now absolute URLs pointing to an internal domain, making them fail.

How would you handle this?

# Answer
I use the sledgehammer approach and search/replace from template\_process\_html:

```
function foo_process_html (&$variables)
{
  $variables["page"] = str_replace("http://internal.example.com/", "/", $variables["page"]);
}

```

You can also get fancy and use `preg_replace` if you need better control. I typically end up needing this when I move a site from our staging server, which is a subdomain off of ours, onto a client's own domain.

If I were in your shoes, I would think about having an internal theme and an external theme, combined with one of the choose-a-theme-based-on-domain-name solutions. Then you can add preprocess/process as needed to just the external theme.
> 1 votes

# Answer
I think that your best option is to create a *filter* to replace the URL on the fly. While you could replace it with the URL of the external domain, it would be better to replace it with a relative URI instead. There's a dead module that does this which you could adapt or take over for your needs.

The related module list is also worth exploring for other ... novel solutions.

Edit: Further information from the OP suggests that Pathlogic might also be a good fit especially when considering the provided use cases.
> 1 votes

# Answer
One solution could be to manipulate the URL's with hook\_file\_url\_alter, and another option, not file specific, could be hook\_url\_outbound\_alter.
> 0 votes

---
Tags: multi-sites
---


# Question
Title: Fatal error: Class name must be a valid object or a string
A "Fatal error: Class name must be a valid object or a string \[…\] common.inc" appears on every page on the backoffice.

We don't how to reproduce this because it happens suddenly. When I've done a `var_dump()` of `$class`, and `$entity_type`, this is the result I obtained:

```
    string 'user' (length=4)
    TaxonomyTermController
    string 'taxonomy_term' (length=13)
    string 'user' (length=4)

```

The debug code has been added to entity\_get\_controller().

```
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    echo $class;
    var_dump($entity_type);
    $controllers[$entity_type] = new $class($entity_type);
  }

  return $controllers[$entity_type];
}

```

It seems that `$type_info['controller class']` doesn't exist for "User".

This problem is solved when we flush the cache\_bootstrap (via `DELETE FROM cache_bootstrap`) and cache (via `DELETE FROM CACHE`), but this is a temporary solution because it appears again.

It's a big problem for us. Any idea will be really appreciated.

# Answer
The function entity\_get\_info() is responsible for gathering up this data about your entities. I would try to debug that one, and see what goes wrong.

You will want to have just cleared the cache when you do this, or you debug results will not be correct.

Can't think of a better answer to the question that is still generic enough to be useful for someone else.
> 0 votes

---
Tags: 7, entities
---


title: Editing multiple nodes in 1 page

text:
# Question
Title: Editing multiple nodes in 1 page
I want to create a drupal site to record student's grades. Since every student will have a class, I want to make an assignment page that contains all the students' names(belonging to a class) so that I can record their individual grades. I do not want to edit individual nodes form by form. However, since each student's grade is considered a node, I can only list the nodes in a view, which is not editable(unless I use the alpha release of Editable module). This can be done easily in Filemaker but I do not know how to do it in Drupal. I wish to know what is the idea to achieve the goal? I think doing in Views is not ideal. What will you do to achieve this goal?

# Answer
> 2 votes
If you are comfortable with PHP, you could create a form that has all the students in a class and displays the student's name and then their grade.

Rather quickly, you could create a custom module and include several drupal hooks in it. It would start out with something like this:

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

  $items['class/grades'] = array(
    'title' => 'Class Grades',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('YOURMODULE_class_grades_form'),
    'access callback' => 'user_is_logged_in',
  );

  // any other menu items here

  return $items;
}

```

This creates a menu item so that when someone goes to

`www.yoursite.com/class/grades`

they will be shown a form. **NOTE:** *With `access callback` set to `user_is_logged_in`, that means ANY logged in user on your site can do this but I am just trying to show you the broad strokes here.*

We need to get the form, but before we go there, for another broad stroke, you will need to create a view that returns a list of student nodes. In the fields, just return the nid of the node. If you hit preview, we want to see something like 13, 27, 55, 99, or whatever the nids are. In that node, I am also going to assume you have a text field called grade that stores the grade for that student in the class. For this, I will also assume this view is called `just_the_nids`.

Now, let's define that form:

```
function YOURMODULE_class_grades_form() {
  $form=array();

  $result=views_get_view_result('just_the_nids');

  foreach($result as $r) {
    $node=node_load($r->nid);
    $form[$r->nid] = array(
      '#title' => 'Grade for ' . check_plain($node->title),
      '#default_value' => !empty($node->field_grade[0]['value']) ? $node->field_grade[0]['value'] : '',
      '#type' => 'radios',
      '#options' => array(
        'A+' => 'A+',
        'A' => 'A',
        'A-' => 'A-',
        'B+' => 'B+',
        'B' => 'B',
        'B-' => 'B-',
        'C+' => 'C+',
        'C' => 'C',
        'C-' => 'C-',
        'D+' => 'D+',
        'D' => 'D',
        'D-' => 'D-',
        'F' => 'F',
      ),
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Grade'),
  );

  return $form;

}

```

What this does is grab the view you created and loops through it, loading each node and grabbing the title, which I hope is the student's name and then displays the grade of that student with radio buttons. I know we could have returned the title and grade in the view and used it here, but just trying to "show the math" which might help later on :)

At this point, if you saved everything and flushed your menu cache, you could go to the page and see some like this:

```
Jill Doe
 ( ) A+
 ( ) A
 ( ) A-
  .
  .
  .

Doug Drupal
 ( ) A+
  .
  .

[GRADE]

```

However, pressing the \[GRADE\] button at the bottom of the page wouldn't do anything because we haven't declared what it should do other than just submit the form. So we do that like this:

```
function YOURMODULE_class_grades_form_submit($form, &$form_state) {
  foreach ($form_state['values'] as $nid => $grade) {
    if (is_numeric($nid) && !empty($grade)) {
      $node=node_load($nid);
      $node->field_grade[0]['value']=$grade;
      node_save($node);
      drupal_set_message(check_plain($node->title) . '\'s grade set to ' . $grade);
    }
  }
}

```

What this does is go though the form and load each node again and set the grade field to what you clicked on in the form and then save the node back again with just that field changed (along with a perky drupal message telling you what it did :)

Now, what this doesn't do that it should for primetime:

Menu per class (unless you only have one)

Security (every logged in user can do this)

Internationalization (I didn't use t() where appropriate)

CSS Style (it isn't fancy, eg, the radios all go down vertically instead of horizontally, etc)

I assumed A-F grading, and also saved the text, You could get fancy here and store 4.0 for an A+, 3.7 for an A, etc, but right now it saves the actual text of the grade but anyway I hope it might give you some ideas on how to do it.

I also assumed D6, D7 has slightly different field structures.

A lot of information on the ins and outs of all this can be found in the Drupal Form API Quickstart Guide

---
Tags: views, entities
---


# Question
Title: How to change the title of the page dynamically?
I created a basic page in my drupal 7 site.

On that page I have some jquery tabs. When I click on tab1 its content displays and hides the contents of other tabs, and when I click on tab2 its content displays and hide other contents and so on.

So I want to change the title of the page in the content area according to the tab selected. If tab1 selected and its content are showing then title of the page in content area should be changed according to the tab content(for example Tab1) and similarly for others.

Is this possible?

I have tried `drupal_set_title("Tab1")` but it does not change the title of the page. and also it will not help me because it will change the title once and I want dynamic based on the tab selected.

# Answer
You need to add an `onclick()` event handler for all tabs.
Assuming UL LI layout http://jsfiddle.net/k7Gkm/

```
$(".my_tabs").click(function(){
 $("#header").html($(this).html());
});

```
> 3 votes

# Answer
If you are using jQuery UI Tabs:

```
$("#tabs").bind('tabsselect', function(event, ui) {
  document.title = $(ui.tab).text();
}

```
> 1 votes

---
Tags: javascript, 7
---


# Question
Title: How to manage the order of the modules execution?
I have a 2 modules which has javascript files modify the height of an element (through jquery).

module one set the height to 100px module two set the height to 200px

I seems like the module one is fired after module two. I need the js file of module two to be fired after the js file of module one. This is to change the weight of the js files.

I included the js file in the module\_one.info file like this:

`scripts[] = js/myfile.js`

Can I do this?

Should I add the js files in myTheme.info ?

# Answer
You can change the module weight in your system table in the data base. This will reorder the execution of the modules and also the inclusion of js.

You can update the weight via myphp admin or you can do it via a custom modules .install file in a hook\_install. for example:

```
db_update('system')
 ->fields(array(
   'weight' => 10,
 ))
 ->condition('name', 'module_name')
 ->execute();

```

Replace module\_name with the name of the module you would like to delay.

Clear all cache afterwards
> 2 votes

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


title: Update cache after writing data

text:
# Question
Title: Update cache after writing data
I'm writing a custom module to extend the Casetracker module to allow users to update the cases' due date via the comments form. So far I have successfully used `hook_form_comment_form()` to add the date field to the comment form and `hook_comment()` to write the new value to the DB using `drupal_write_record()`.

I'm running into a caching problem though. The updated values don't show up in the node until I `drush cc all`. Is there a way I can tell Drupal to update it's cache to show the new value?

I'm using Drupal 6.26, Casetracker 6.x-1.0-beta9 (part of OpenAtrium).

# Answer
you can use cache\_clear\_all() to clear the caches after you write the new value to the database. it will be best if you can find out the comment's cache id and clear only that one. Unfortunately I don't have any D6 databases on my server to look into the database
> 1 votes

# Answer
You could add the drupal\_flush\_all\_caches() function in order to do a complete cache clear.

But if you know which tables to be cleared you can use cache\_clear\_all('\*', 'TABLE\_TO\_FLUSH', TRUE);. This is better for performance reasons.

Cache\_clear\_all could be confusing because actually, it doesn't clear all caches by default.

```
// Empties cache tables, rebuilds the menu cache and theme registries, and invokes a hook so that other modules' cache data can be cleared as well.
drupal_flush_all_caches

// If called without arguments, expirable entries will be cleared from the cache_page and cache_block bins.
cache_clear_all();

```
> 1 votes

---
Tags: 6, caching
---


title: search form at admin/content

text:
# Question
Title: search form at admin/content
I try to administrate a lot of content in Drupal 7.

How may I add a search form at Content administration page (admin/content)?
I need it so that I can easily find a node when there are hundreds of nodes.

# Answer
> 3 votes
You can use Views Bulk Operations, which allows you to replace that administrative page with a view. As you are using a view, you can add an exposed filter to filter the list of nodes by the title, or any other parameters you choose; the screenshot shows a view that can filter the node list by the author or the state of the nodes.

As far as I recall, VBO comes with an example view that can replace the administration page for the content; you just need to change the URL used for the view, and customize the view itself.

# Answer
> 2 votes
Besides the excellent VBO module, there is another which turns all core admin pages into customizable views, that is, Administration Views module.

---
Tags: nodes
---


title: Which image preset to use?

text:
# Question
Title: Which image preset to use?
I created a new image style with scale and crop effect. When I create a node and apply that image style to the image included with the node, I can see parts of the image are cut out.

This happens specially when the image is large (vertically or horizontally). I need to use an image style which does not cut the image and resizes it properly.

How can I achieve this?

# Answer
> 3 votes
You want to use the "Scale" option, and only set 1 of the variables. Either width OR height. You can leave 1 of them blank. This way the image styles will respect the aspect ratio of your images. I usually only set width, and leave height blank.

Don't use "Scale and crop" as crop will cut parts off your image to make it fit the size you specified.

---
Tags: 7, media
---


# Question
Title: Which modules should I add to Advanced Forum to provide increased functionality?
Drupal 6 Advanced Forum is very capable, but the basic installation doesn't offer many features. For example, by default there is no signature possible.

**What modules/plugins/things do you recommend adding to provide a well rounded set of improved functionality in Advanced Forum?**

For example, Apache Solr is meant to be a very good add-on to provide improved search functionality. There will surely be lots of other modules that you can think of that would be needed to provide some of the features that come as standard in 3rd party software. Which modules would you say are the most useful ones to have?

Edit:

One need of the forum is to support posting from a mailing list. It can do this already, but maybe there are nice features that can be added to improve this. Perhaps something that makes e-mail formatting look better in a forum, if that is necessary.

Anti-spam is important too. I don't know whether there is a single, catch all anti-spam module. Perhaps there are several modules that should be used here.

The forum is important for community building, so plugins that would help there, for example things that make profiles more informative.

I am interested in all sorts of good functionality. I would like to hear about plugins that people suggest because they are useful, even though I haven't referred to them in this post. That is what I am hoping for. I don't know what to look for / what good things to add.

# Answer
While I do think this question is off-topic for this site, I know what you're going through. I recently built a forum with drupal, and I was surprised at how difficult it was to choose a good module to fulfill certain requirements, or even how to find the right ones for the job.

So to help you out, here's some modules I used to add functionality to the forum:
> 12 votes

---
Tags: nodes
---


# Question
Title: How to check how many times a user has logged in?
I want to know how many times a user has logged in until a given date in Drupal 7. Is this possible?

# Answer
I don't think drupal keeps that data as standard. You might want to look at User Stats Module which does it for you.

> Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics are:
> 1. days registered;
> 2. join date;
> 3. days since last login;
> 4. days since last post;
> 5. post count;
> 6. login count;
> 7. user online/offline;
> 8. IP address;
> 1 votes

---
Tags: users
---


title: can't delete pages

text:
# Question
Title: can't delete pages
When I try to delete an article or page, I get this error:

> Notice: Undefined variable: pid in simple\_access\_node\_delete() (line 263 of /home5/piconepr/public\_html/isip/drupal/sites/all/modules/simple\_access/simple\_access.module).
> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'pid' in 'where clause': DELETE FROM {simple\_access\_node} WHERE (pid IS NULL ) ; Array ( ) in simple\_access\_node\_delete() (line 264 of /home5/piconepr/public\_html/isip/drupal/sites/all/modules/simple\_access/simple\_access.module).
> The website encountered an unexpected error. Please try again later.

This is pretty bad because I can no longer delete articles from my main page.

Is there an easy way to make this error go away. I am not an SQL programmer and I hate to think I will have to go into the database and muck around with it.

# Answer
> -1 votes
Try deleting the cache. To do so, go to

Home » Administration » Configuration » Development

And then click 'Clear all caches' button.

Make sure that the user who attempt to delete the page has permission to do so.

---
Tags: nodes
---


title: how to join two field together

text:
# Question
Title: how to join two field together
i have a content type named product. i need to add product like this:

title: product1

description: this is a product

company:a price:100

company:b price:200

company is a node reference field with numbered of values set to unlimited and price is a text field but i don't know how relate price field with company.

if i can't do something like this in drupal 6, drupal 7 help me?

# Answer
> 1 votes
If you use CCK ver 3.x you get the multigroup submοdule. This allows you to create a group of fields like in you case company and price and then create multiple instances of this group.

**UPDATE**

CCK ver 3.x is alpha. However I have used it in production without problems. You could look into the issue queue for bugs in the 3.x version before you use it.

If you are creating a new site I would suggest going with drupal 7. CCK has moved to core in drupal 7 but the functionality of multigroup does not exist. However you can achieve a similar result using the Field Collection module. Looking at this http://oliverdavies.co.uk/blog/2011/08/create-multigroups-drupal-7-using-field-collections or this http://mostrey.be/creating-multigroup-widgets-drupal-7 will find out how.

---
Tags: 6, entities
---


# Question
Title: Drush suddenly stopped working for one site
I have a bunch of sites on my local machine and have been using Drush (v5.4) happily for a long time to administer them.

All of a sudden, with no changes made to one such site, Drush reports these errors:

> Command pm-disable needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run this command.
>
> The drush command 'dis addthis' could not be executed.
>
> Drush was not able to start (bootstrap) the Drupal database. Hint: This error often occurs when Drush is trying to bootstrap a site that has not been installed or does not have a configured database.

Needless to say the site in question is running fine on the local machine with no errors (and is completely installed). Drush works fine for every other site on the machine.

What can cause Drush to suddenly misbehave like this for one particular site?

# Answer
> 1 votes
Drush, being run from the command line might have different permissions than the web server. Essentially your site can work correctly but some files might be in accessible from drush. If you are running into errors you might want to ensure that the group permissions of your entire Drupal site are set correctly by running:

```
chown -R owner:group sites_directory

```

If you run into permission denied errors as the result of running `chown`, run it as `sudo` or contact your system administrator.

# Answer
> 1 votes
I cannot answer why this happens, but I have a site that periodically does this with **drush pm-enable**. I think this site has trouble doing the nightly module update check, and something bad gets cached. A **drush cc all** always fixes it.

---
Tags: drush
---


# Question
Title: Use a contextual filter value in a view referencing a node name/path rather than id
I would like to create a views that has a contextual filter with a node reference.

I'm able to view the contextual filter working when I use the node's id value, but I need to be able to use the alias or name value of that content type. I have people categorized by office (the office is also a content type because it has much more content than a taxonomy would allow). Then using the office location as a contextual filter I'm trying to show the "team" listed for each office.

/office/atlanta/team rather than /office/6/team

# Answer
> 0 votes
Instead of Term: ID you might want to use Term: Name. I believe you can also check a box in the contextual filter options panel to display "Term ID converted to term name".

# Answer
> 0 votes
I'm not sure, but it could be something like

> \[term:vocabulary\]/\[term:name\]

---
Tags: 7, uri, views
---


title: Pass querystring to XSL through module

text:
# Question
Title: Pass querystring to XSL through module
I'm trying to do some fancy navigational work within a large XML sheet, and am generating links with querystrings in my transformation.

What I would like to do is parse the querystring within my .module file, and then pass it somehow to the XSL processor.

Essentially, right now I have (without any error handling at present):

```
/* generate hook */
function _xml_import_generate()
{
  $p = $_GET['p'];

  $path = drupal_get_path('module', 'xml_import');

  $xsl = new DOMDocument();
  $xsl->load("{$path}/xml_import.xsl");

  $xslt = new XSLTProcessor();
  $xslt->importStyleSheet($xsl);

  $xml = new DOMDocument();
  $xml->load("feed.xml");

  return (string) $xslt->transformToXML($xml);
}

```

I can't seem to find any documentation regarding this...but how do I pass `$p` into my XSL transformation?

# Answer
> 2 votes
I think you just need to parse out the query string, and then use `XSLTProcessor::setParameter`:

```
/* generate hook */
function _xml_import_generate()
{
  $p = $_GET['p'];

  $path = drupal_get_path('module', 'xml_import');

  $xsl = new DOMDocument();
  $xsl->load("{$path}/xml_import.xsl");

  $xslt = new XSLTProcessor();
  $xslt->importStyleSheet($xsl);

  $xslt->setParameter("", "p", $p);

  $xml = new DOMDocument();
  $xml->load("feed.xml");

  return (string) $xslt->transformToXML($xml);
}

```

Your parameter should then appears as a `<xsl:param />` in your XSLT.

---
Tags: 7
---


# Question
Title: How can I add the +0430 timezone to Drupal 6?
As you know, Drupal 6 doesn't have the +0430 timezone in the date/time page. I want to add this specific item into timezone drop-down list.

Does anybody know about this core patching? How can I do it?

# Answer
> 0 votes
I found the solution for my question.

Go to modules \> systems

open **system.module**

Then find **\_system\_zonelist** function

```
/**
 * Generate an array of time zones and their local time&date.
 */
function _system_zonelist() {
  $timestamp = time();
  $zonelist = array(-11, -10, -9.5, -9, -8, -7, -6, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1, 0, 1, 2, 3, 3.5, 4, 5, 5.5, 5.75, 6, 6.5, 7, 8, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 14);
  $zones = array();
  foreach ($zonelist as $offset) {
    $zone = $offset * 3600;
    $zones[$zone] = format_date($timestamp, 'custom', variable_get('date_format_long', 'l, F j, Y - H:i') .' O', $zone);
  }
  return $zones;
}

```

All you need is adding 4.5 value to $zonelist array.

The array must be

```
$zonelist = array(-11, -10, -9.5, -9, -8, -7, -6, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1, 0, 1, 2, 3, 3.5, 4,4.5, 5, 5.5, 5.75, 6, 6.5, 7, 8, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 14);

```

# Answer
> 0 votes
I think this looks like a problem in PHP. The timezone is being used by the Date module, and that contains date\_timezone\_abbr(), which uses PHP's timezone\_abbreviations\_list().

Only the keys are stored, and the PHP function is being used. I am afraid there is no way out of this, unless there is a way to convince PHP.

When I tried the following code, I get 4, not 4.5.

```
$a = timezone_abbreviations_list();
echo $a['aft'][0]['offset'] / 3600;

```

---
Tags: datetime
---


# Question
Title: easiest way to implement alternating row colors?
DISCLAIMER,

I am not a programmer.

What would be the easiest way to implement alternating css row colors in a table for a drupal 7 theme? Thanks!

# Answer
> 4 votes
To augment @Clive's answer, drupal also adds a CSS class of "odd" and "even" to each TR element in the default theme table, so you could use them, too, eg:

```
tr.odd { background-color: #ccc; }
tr.even { background-color: #aaa; }

```

These are based on the `$zebra` variable that is available in a lot of templates just for this purpose.

# Answer
> 6 votes
The easiest way would be straight CSS using the `:nth-child` pseudo-selector:

```
tr:nth-child(even) td { background: #ccc; }
tr:nth-child(odd) td { background: #aaa; }

```

The usual caveats apply (i.e. it doesn't work in Internet Explorer \<9)

---
Tags: theming
---


# Question
Title: Getting site-offline message when trying to drupal_bootstrap from command line
I'm trying to bootstrap drupal from a standalone PHP script at the command line from sites/all/modules/mymodule/mymodule.php.

```
<?php
  chdir('/sandbox/mysite/');
  require_once './includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

I'm attempting to run it from the command line, but I get Drupal site-offline when I do (trimmed for brevity):

```
cd /sandbox/mysite
php sites/all/modules/mymodule/mymodule.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Site off-line | Pressflow</title>

```

The site is online and works fine from the browser. DRUPAL\_BOOTSTRAP\_DATABASE is where this fails, since I can bootstrap the DRUPAL\_BOOTSTRAP\_CONFIGURATION and DRUPAL\_BOOTSTRAP\_EARLY\_PAGE\_CACHE phases without a problem. Anyone run into this before? Thanks in advance.

# Answer
> 0 votes
An easy way of writing CLI code for Drupal is implementing your own drush (http://drupal.org/project/drush) commands. Drush itself commes wirh handy example code.

# Answer
> 0 votes
I was running this from MAMP and had to specify the direct path to PHP at the CLI for drupal to bootstrap correctly. It was calling Mac system php, not MAMP.

---
Tags: bootstrapping
---


# Question
Title: Dynamic frontpage image changes every hour
I want to have a frontpage with images changing every hour. As it is the frontpage, the page is cached.
Can this be done with views?
I'm thinking of creating a views block which shows a random image but I'm lost on the refresh every hour part.

# Answer
Inside of views, over in its cache settings, you can choose TIME and then select one hour for the results and output. Then, if you have it show a random image, it will cache that and only select another image after that hour has passed. This of course will be defeated if your page is cached, but if its cache lifetime is less than an hour, it will cache up eventually (I just made a pun lol)
> 1 votes

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


# Question
Title: hook_views_pre_execute() query not running (or being overwritten)
I'm trying to completely overwrite the query that's created by Views UI by using `hook_views_pre_execute()` in a custom module. I know about the new database API and how this function expects a SelectQuery object, but I've also read (in a posting from Lullabot, so I think it's legit) that if you're just writing a single query and don't need to do anything conditional, it's perfectly OK to skip that and just use `db_query()` with raw SQL.

So here's my function - the `drupal_set_message()` line is executing, but the output of the view is still sorted in ascending order, which is what is set in the Views UI. My understanding was that this function was supposed to completely overwrite what's in the UI, so how do I get it to work? (Right now I haven't done anything funky with the SQL except change the order by just to see if it would work. There really is other stuff that needs to be done which justifies using a module instead of the Views UI.)

```
function group_speaker_carousel_views_pre_execute(&$view){
    if ($view->name == 'speakers_carousel')  {
      drupal_set_message("view is {$view->name}");
       db_query("SELECT DISTINCT node.title AS node_title, node.nid AS nid, field_speaker_node.title AS field_speaker_node_title, field_speaker_node.nid AS field_speaker_node_nid,  'node' AS field_data_field_job_title_node_entity_type,  'node' AS field_data_field_company_node_entity_type
      }
FROM {node} node
LEFT JOIN {field_data_field_speaker} field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN {node} field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
WHERE (((node.status =  '1') AND (node.type IN ('speaker'))))
ORDER BY field_speaker_node_title DESC");

    }
}

```

# Answer
The reason nothing's changing is because you're just *running* `db_query()`, not actually assigning it to anything. If memory serves you need to assign your new query to `$view->build_info['query']` (but that might be for Drupal 6).

Also you won't unfortunately be able to use a vanilla `db_query` for this (as far as I know), because Views is expecting a `db_select()` object.

You can test this pretty easily by running the following two statements:

```
// Breaks the view.
$view->build_info['query'] = db_query('SELECT nid FROM {node}');

// Does not break the query (but results are wrong obviously).
$view->build_info['query'] = db_select('node', '')->fields('n', array('nid'));

```

I would look at re-working your query into a dynamic `db_select()` and then assigning it as in the above example, you should get more joy.
> 2 votes

---
Tags: 7, views, hooks
---


# Question
Title: Customizing views output- rewrite output to show an image based on key value
I want to use a views template to customize the output of the gender field on my user profile. The gender field is a select list, and the key values are as follows:

* f (female)
* m (male)
* o (other)

I created a template file, `views-view-field--field-acc-gender.tpl.php`. I have the images saved in my theme's directory. I can write an if statement to check against the key value, but how do I get the value of the field? (This is probably a straightforward question, but I just learned about views templates today.)

I tried the following in `views-view-field--field-acc-gender.tpl.php`:

```
<?php
if ($output == 'M') {
  print 'male';
}
else if ($output == 'F') {
  print 'female';
}
else {
  print 'other';
}

```

However, my view still simply prints out `M` or `F` instead of `male` or `female`.

# Answer
You should be able to access the data from `$row` array from inside the template file. So:

```
$data = $row->field_field_acc_gender;

// This may not necessarily be the correct structure of your field's data.
// So you may want to do print_r($data) or dpm($data) to see correct structure.
$gender = $data[0]['raw']['value'];

switch($gender) {
  case 'M':
    print('Male');
    break;
  case 'F':
    print('Female');
    break;
}

```
> 2 votes

# Answer
Ideally you want to be using a copy of 'views-view-fields.tpl.php'.

Before the foreach loop on the $fields object you can alter the output.

**Example:**

```
   if ( $fields['FIELD_NAME']->content == 'something' ) {
      // do something else...
   }

```

In your example it would be appear you've gone for the 'single field' option.

You might want to just assign some alternative value to $output then print it after your conditionals.
> 0 votes

---
Tags: views
---


# Question
Title: How to direct a specific role to a specific page
This is related to this question:

How do I redirect a user role on login (Drupal 6)?

My biggest problem is that the only rules available as far as I can see are on user login, period, nothing for a specific role. How would I go about setting the redirect ONLY for certain user roles, when using rules?

# Answer
> 2 votes
In rules you could select "when a user logs in" and then as the action, select "custom php code" and fiddle with something along the lines of:

```
if (in_array('ROLE_TO_CHECK', array_values($account->roles))) {
  drupal_goto('PAGE_TO_GOTO');
}

```

ADDITION:

D'oh!

Rules can do this....

1. Select 'Add a new rule'
2. Name it whatever and select 'User has logged in' as the event
3. Add a condition: User has role(s)
4. Select the role you want
5. Add an action.
6. Select Page Redirect
7. Enter the path you want ADDITION: check both Force Redirect and Immediate Issue check boxes
8. Save

---
Tags: 6, rules
---


# Question
Title: "Failed to set field" Problem with SimpleTest, testing a form
With SimpleTests, I want to test a form similar to :

```
  // Textfield :
  $form['fieldset_name']['test'] = array(
    '#type' => 'textfield',
    ...
  );
  // Submit :
  $form['fieldset_name']['submit_button'] = array(
    '#type' => 'submit',
    '#submit' => array('my_module_form_submit'),
    '#value' => 'Submit button',
  );

```

This form is accessed from 'admin/config/my\_module'. So I add the following test in my\_module.test :

```
  function testForm() {
    $path = 'admin/config/my_module';
    $edit['test'] = 'testing field\'s input';
    $this->drupalPost($path, $edit, t('Submit button'));
  }

```

When I run the test, it fails with these errors :

> Failed to set field test to testing field\\'s input
>
> Found the Add button (failed)

Where am I wrong ?

# Answer
Permissions would be my first guess.

Enable debug output in the Simpletest settings and then check if your module is installed and you have permissions to visit that page.
> 1 votes

---
Tags: 7, testing
---


# Question
Title: Best way to store custom values in Drupal 7?
Is there a good (recommended) way to store custom values in Drupal 7? I've looked into variable\_set / variable\_get, but then read a comment suggesting NOT to use those for the purpose that I'm needing (unless I completely misunderstood). Here's the comment that I'm referring to:

http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable\_set/7

"All data created by variable\_set() is loaded from the database at bootstrap. Calling variable\_get() doesn't perform the database request to get you the data, it simply declares the $conf global and returns the variable you've asked for. Therefore, don't carelessly use variable\_set() to store lots of data that you will only use on individual pages or in custom methods. Use your own little table and storage functions for that."

Basically, I'd like a place to store a couple of values, so that I can avoid having to hard code those values within my custom module code. For instance, I'd like to store a current Reporting Year (i.e. 2011), and a current Data Entry Year (i.e. 2012). Is this just something that I'd need to create my own table for?

# Answer
No, there's no need to create your own table for that. Your use case is a perfect example of what *should* be stored in the variables table (in my opinion).

Since the data isn't particularly volatile, and you only have a couple of values, I can't see any benefit to adding a custom table for it.

If you start finding yourself storing a lot of data in variables, for example a single different variable for each node of a certain content type, that's when you need to start looking at a custom table.
> 1 votes

# Answer
If you are just using these to to replace constants in your code, then `variable_set` / `variable_get` is the appropriate thing to use.

It is not the best approach to persist data between pages (eg, emulate a cookie) or to avoid having to make a custom database table.
> 1 votes

# Answer
From what you've said here,

```
$foo=variable_get('YOURMODULE_current_reporting_year', '2011');

```

or

```
$bar=variable_get('YOURMODULE_current_data_year', '2012');

```

isn't going to really hurt anything.

You could even set up a module admin settings page to set these if/when your years change. Now, if your module was going to variable\_set() these all over the place, that would be another story.

Of course, if you are super concerned with the DB, you could also

```
define('YOURMODULE_CURRENT_REPORTING_YEAR', 2011);
define('YOURMODULE_CURRENT_DATA_YEAR', 2012);

```

and then this would work:

```
$foo=YOURMODULE_CURRENT_REPORTING_YEAR;
$bar=YOURMODULE_CURRENT_DATA_YEAR;

```

but you would have to manually change those defines when necessary.
> 1 votes

---
Tags: nodes, database
---


# Question
Title: Hiding Superfish Dropdown on Specific Menu Item
I am working on a Drupal site that has a series of about 2 dozen articles. I have a page called "News" which lists the title/teaser for each article. I would like the menu item "News" to be active as the parent of each article node, but I would like to disable the dropdown menu (No need to have dozens of articles in a dropdown). I am using Superfish and have the dropdown enabled for all other menu items. Is there any way to disable it for a single menu item? Perhaps I need a different menu module?

Any help would be greatly appreciated. Many thanks!

susanhouser

**EDIT**

Here is a screenshot to help illustrate:

http://screencast.com/t/3eyDuK0w

**EDIT02**

I ended up coming across a solution that fit my need (See answer below). Instead of setting News as the parent menu item for each article (I was doing this to generate the class "active-trail"), I used the plugin described in my answer. Thanks for all of the help!

# Answer
> 1 votes
I ended up solving my problem by setting the url pattern for Articles to "news/\[node:title\]". I then used Menu Trails to highlight the News menu item based on the url path.

Now the "News" link will automatically be highlighted when viewing individual articles. Hopefully that helps someone else!

# Answer
> 0 votes
You can configure "Menu Depth" option for that superfish block.

Also you can use css to hide the 2nd level dropdown UL

# Answer
> 0 votes
The easiest way is to do it with CSS. It's dirty, it's not drupal way, but it works.

Get the ID of the `<li>` element of News then put:

```
#id-of-element ul {
  display:none!important;
}

```

The !important bit **may** not work on IE6 though, unless your page is rendered in standards compliant mode.

See this question on Stackoverflow.com, particularly the second answer by Graphain.

---
Tags: routes, navigation
---


# Question
Title: What are the steps to create a custom widget based on taxonomy_select?
I need to create a widget for fields of type "taxonomy\_term\_reference". The widget "taxonomy\_select" is very nearly what I need to build, but needs some modification. I have seen examples that start with a given widget to build a custom version. The function below fails because there is no "taxonomy\_select\_field\_widget\_form" defined. Where is the "taxonomy\_select" form creation code?

```
/**
 * Implements hook_field_widget_form().
 */
function taxonomy_multiselect_add_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $element += taxonomy_select_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

  return $element;
}

```

# Answer
The `taxonomy_term_reference` field type uses the core `options_select` widget and implements `hook_options_list()` to provide the values, the taxonomy module doesn't implement any of the widget code itself.

The `options_select` widget is defined in `options_field_widget_info()` in the code options.module file (inside the field module folder). The form elements themselves are built up in `options_field_widget_form()` in the same file. They're pretty well commented so you should be able to get a good idea of how they work.

I'd also recommend the Examples module if you haven't already got it, it has a field type/widget example module with good sample code and comments.
> 0 votes

# Answer
I'm now trying to customize the core options multiselect with this code:

```
function taxonomy_multiselect_add_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $instance['widget']['type'] = 'options_select';
  $element += options_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

  return $element;
}

```

But my widget now builds a multiple-value table with the default first row being the multiselect. How can I build my own identical version of the multiselect to begin modifying?
> 0 votes

---
Tags: 7, entities
---