# Question
Title: How to define and use an external database connection in a custom module
I'm developing a module that will rely heavily on external database queries. Is there a best practice for defining and using an external database connection throughout a module?

This page tells me how to make the connection, but not where to put it in a module (specific hook?) so I only have to define it once. Also, is it always necessary to do "db\_set\_active('YourDatabaseKey');" or can I pass an argument that will set the db to use? I'm using Drupal 7.

# Answer
There's no particular place to put this code (hook or module), you just put it where you need it.
So it should go just before your queries on the other database and just after to set back the default DB.

If all your module will rely on the external DB just put it a the beginning of the first function called for your module and at the end of the last function.

Of course every one of your function should be executed on the external DB and nothing must have to query the default database without switching back.

This following code would fail:

```
db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

$node = node_load(123); //This would fail on the external DB.

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();

```

You should switch back and forth:

```
db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();
$node = node_load(123); //Query made on the default Drupal DB.
db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();

```
> 8 votes

# Answer
You will have to add into `settings.php` located at `/sites/default/` in following syntax

//Drupal 6

```
$db_url['default'] = 'mysql://db_user:password@localhost/db_name';
$db_url['external'] = 'mysql://db_user2:password@localhost/db_name2';

```

//Drupal 7

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'db1',
      'username' => 'user1',
      'password' => 'pass',
      'host' => 'host1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'extra' =>
  array (
    'default' =>
    array (
      'database' => 'db2',
      'username' => 'user2',
      'password' => 'pass',
      'host' => 'host2',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

And after these settings you can use db\_set\_active() to switch between databases.
> 3 votes

---
Tags: 7, database
---


# Question
Title: How to have html not just sitename or logo in site heading block? (via subtheme or preferably editing WITHIN drupal)
Can someone give examples of using html not just a text string or logo graphic in the header for a site?

I ask because I'd like to use several web typography fonts to make a logp rather than a bitmap.

**Update**

Editing "editing WITHIN drupal" - would be nice, sorry to adjust question. Thanks for your answers so far.

# Answer
> 4 votes
Keep it simple. Just disable the logo in your theme settings and use a block in it's place. You can throw anything you want in there.

Just place a block using Drupal UI into the header region of your theme. No coding, no template files creating/hacking is needed.

# Answer
> 2 votes
This is an area I am just getting into so I do not have a complete answer. Are you looking to replace the site name text and style it?

The location of the text will vary according to the theme you are using. If you do not have firebug, I suggest you get it. It is an add-on that works with firefox browser and is essential for figuring out where things are. If you right click on the site name you can "inspect element" to find out what region name and css class is styling it.

You can place whatever text you want in a block and define a css type for styling it.

You can also do it programmatically. The text will have to be inserted in the php code file page.php.tpl. If you are not familiar yet, the php.tpl files actually construct the html code for a page when the request for the page is made. There are others, besides page but odds are that is where the code is. The style of the text can be redefined using css files.

# Answer
> 2 votes
All the action takes place in page.tpl.php, there you have the following variables

> * `$logo`: The path to the logo image, as defined in theme configuration.
> * `$site_name`: The name of the site, empty when display has been disabled in theme settings.
> * `$site_slogan`: The slogan of the site, empty when display has been disabled in theme settings.

which are used for rendering your site identity.
You can alter this tpl either directly (if it's your own theme) or by creating a subtheme.
There you put all your fancy HTML:

```
<div id="header">
  <div class="section clearfix">
    <!-- new HTML instead of Drupal's -->
  </div><!-- /.section -->
</div><!-- /#header -->

```

---
Tags: 7, theming, blocks
---


# Question
Title: Webform: states dropdown vs textbox plain text in case of other country autoswitch?
How can I make a webform so when a user selects the country US it will show the states in a list with a mandatory select from list and when other countries it will show Province as textedit also mandatory.. i don't want to mess arround with Jquery and hide the controls resulting into multiple fields

# Answer
> 0 votes
If you're not fond of installing a pretty big module as location, have a look at conditional fields which allows you to do what you need.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

So set up a select list of counties and if US is selected show the "states list" that would be hidden otherwise.

# Answer
> 0 votes
addressfield module does that perfectly.

What I don't like about it is that it will also show "address 1&2" fields. You can hide those with css. When you output the field it will show the complete address. You can also hide the parts you don't need with css.

---
Tags: webforms
---


# Question
Title: How can I programmatically insert date field values?
I have a bunch of values from a .sql export that are in the datetime format (same format that date fields take in the DB). I'm creating nodes using these date values. How can I insert these values into the date field?

I tried:

```
$node->field_data_field_date['und'][0]['field_date_value'] = $datetime_value;

```

but it didn't seem to work. Any ideas? Thanks!

# Answer
> 9 votes
If your field's name is `field_date` you should access it by using

```
$node->field_date['und'][0]['value'] = $datetime_value;

```

And if it has an "end" date you have to set its `value2` property.

Try to install devel, create a node for the content type you want to use and go to the devel tab `node/123/devel` to explore its object.

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


# Question
Title: Create a View with Previous Next and Return to Parent options
ok so I've currently sorted this out using raw PHP and mySQL queries but it feels like a hack and I'd like to Drupalafy it if possible. not sure if it would be quicker or not, but would certainly be easier to manage in the long run.

I have a list of node thumbs on a front page, ordered into Tax based groups. Click any of these and you are taken to that nodes page and you can next/previous though all the other nodes in that Tax group. there is also a link to take you back out to the front page (of which there could be many, as this is based on a higher level tax term).

I'll try and show an example.

```
Tax top 1.
  tax sub 1
  tax sub 2
Tax top 2
  tax sub 3
  tax sub 4

nodes 1,2,3 are in Tax sub 1
nodes 7,8,9 are in Tax sub 2
nodes 4,5,6 are in Tax sub 3

Main page 1 shows nodes 1,2,3 under heading Tax Sub 1, and 7,8,9 under Tax Sub 2,
main page 2 shows nodes 4,5,6 only under heading Tax Sub 3.
Click though to a node say 5, and you will have a
Next take you to node 6
Previous to node 4
Home/back to Main page 2.

```

hope that makes senese. you can see it in action on this site. www.martynazoltaszek.com

So my question is can I do this using I guess Views? I've tried but cannot elicit the control I want completely.

edit: the nodes can be in any sort order so I guess I require the nid to be carried though to the view of a single node, and from that work out what would be next previous.

# Answer
These are rough suggestions, have you tried custom pagers and eventually views slideshow for the previous/next links ?

For the back link, you can call your views with an URL parameter and build a footer link using this parameter (somewhat do the "destination" parameter).
> 2 votes

---
Tags: views
---


# Question
Title: Module or template mod for making development site look different from live site
When I have my development and live site open in the same browser I sometimes mix them up because they look the same. What tricks do you all use to distinguish them?

# Answer
The Environment Indicator works well for that. It works best with a local\_settings.php file, in my experience.
> 2 votes

---
Tags: 7
---


title: Drupal Database Relationships

text:
# Question
Title: Drupal Database Relationships
I would like to know why there are no relationships been built between tables in Drupal Database.

I was just going through the Drupal database structure and wondering why haven't any relationship been created.

any explanation would be appreciated. one of the main thing that i was reminded was that, mysql database engines could be a limitation.

# Answer
> 4 votes
Quite a vast topic among many reasons:

* MyISAM doesn't support foreigns keys and Drupal used this as a default engine until D7 (which now use InnoDB as default if available).
* Schema now support foreign keys so you can benefit from this in documentation.
* Enforcing FK in Drupal would be quite a challenge (Damien Tournoud - one of Drupal most prolific core contributor - stated: *Drupal is far from being able to use foreign keys properly*).

---
Tags: database
---


# Question
Title: During updating translation: Fatal error: Maximum execution time of 240 seconds exceeded
I've tried to install a second language to my Drupal7 site. It can be done either by automatically or manually translation. I tried both but I got into the following issue at halftime:

> Maximum execution time of 240 seconds exceeded.

I tried to set higher values in php.ini:

```
default_socket_timeout = 240 (it was 60)
max_input_time = 360;
max_execution_time = 360;

```

I using local WAMP and Drupal7 installation. Port 8888.

I need help with configuration or another way to install it.

# Answer
> 3 votes
Open sites/all/modules/l10n\_update/l10n\_update.locale.inc; at line 28, change the code to the following one:

```
drupal_set_time_limit(840);

```

It will increase the execution time and will work. The original code set the time limit to 240.

# Answer
> 0 votes
Make sure you restarted your server (apache) to let the changes take effect.

---
Tags: i18n-l10n
---


# Question
Title: How to setup birthdate field with optional values
I want to have a "birthdate" field for my users. It should be optional to enter a year or a date. If a year is selected I want to display the age. If a date is entered I want to show the birthdate.

If I use the date field and make it optional I can have empty default values. However, as soon as I enter a year it requires the date and month too and vise versa.

Any solutions?

# Answer
I would define 3 optional selects:
\- Year (`now()` to `now()` \- 100)
\- Month (1-12)
\- Day (1-31)

Then in a hook\_node\_validate() I would check if only the year is provided or a full date. Also don't forget to verify if the date is valid (like Feb, 31...) using `checkdate( int $month , int $day , int $year )`.

Then create a field template to either display the age or a birthdate.
> 1 votes

---
Tags: 7, datetime
---


title: FileDepot module help

text:
# Question
Title: FileDepot module help
I am using FileDepot module, and I wanted some help in this. I wanted the authenticated users to create their own folder, and upload their files. They can upload files, but they cannot create their own folder. How do them give them the permission to create their folder?

I found a feature like LOCK. What is this lock feature basically used for?

# Answer
> 2 votes
I think the lock feature is to indicate that you are editing the manuscript. When you are ready editing, and have uploaded the next version, you can unlock it.

---
Tags: 7, files
---


# Question
Title: How to attach a field to an entity programmatically?
Is it possible to attach a field to an entity programmatically?

I want to create a new entity, say vehicle, which has radio buttons defined for the brand of the vehicle. I would like this field to not be able to be deleted or modified via the UI.

# Answer
Yes, it is possible, the function is field\_create\_instance(). If the field was not created before, you will need to create it with field\_create\_field() first.
> 5 votes

---
Tags: 7, entities
---


# Question
Title: How to remove the "Close comment thread" button in Open Atrium?
On my casetracker nodes in Open Atrium, the `atrium.module` inserts a "Close comment thread" / "Reopen comment thread" button. What's the simplest way to remove this button, without having to modify `atrium.module`?

# Answer
> 2 votes
A quick look at atrium.module, specifically function atrium\_preprocess\_node(), shows that the "Close comment thread" is only shown when the user has the right to update the node (`node_access('update', $vars['node'])` returns `true`). That means that you can hide the button by taking away that permission.

Alternatively, you could implement hook\_form\_alter in a custom module and set $form to an empty array when $form\_id equals 'atrium\_comment\_thread\_toggleform, or (but this may be tricky) implement `THEMENAME_preprocess_node(&$vars)` in your theme's template.php and alter $vars\['post\_object'\] to take out the form again.

---
Tags: 6, theming, distributions
---


title: How to build a dynamic menu structure

text:
# Question
Title: How to build a dynamic menu structure
I'm building a module for which I want to create two dynamic menus: one main menu with each menu item being a group name that the user belongs to (the groups come from a different database) and a secondary menu with a fixed set of menu items that manipulate specific properties of the group selected in the main menu (for example show group members).

What would be a good approach to do this? I found this question that shows how to create a menu within a module, but I'm not sure how to tackle the dynamic part of the menu items. Each user can have a different main menu, depending on the groups the user is part of, and the secondary menu items need to pass the group id of the selected main menu item. Next to hook\_menu, I suppose I need to do something with wildcards, but I've never worked with those in menus so I'm not sure.

I would like to be able to use the menus as a source for primary and secondary menus in different themes, so I'm flexible with changing the site appearance by selecting another theme. I'm using Drupal 7.

# Answer
> 2 votes
I found a way to do this, but I'm still interested to know if this is the right approach (and if bad things will happen with a very large number of groups and users).

Both menus are created using hook\_enable in the install file of the module (the development module is an excellent example on how to do this).

Like I say in my comment, I don't think you can create dynamic menu items so I'm creating a menu item for each group (when a group is added, I need to do a menu\_rebuild). To determine if the menu item should be visible for a user, I created an access callback that checks if a user is part of that group. This callback will be called with every page request, so it will always work.

The secondary menu works with a wildcard and a to\_arg function. For example, a menu item is set as $items\['pmenu/%get\_groupid/grouppage'\] and in the function get\_groupid\_to\_arg($arg) I'm extracting the groupid from the path with arg(1), which is returned (for details see hook\_menu and the Menu example). The secondary menu items also use the same access callback to check if the user may see the menu item.

Finally I had to apply a fix for the theme, because the corresponding primary or parent menu item (group) would not be set as active if a secondary menu item was selected. I'm using Marinelli and applied the patch in comment 14 of this issue. That didn't quite work, so I changed it a bit to only look at the path when checking for a parent as described in comment 16.

---
Tags: 7, routes, hooks
---


# Question
Title: Why don't menu tabs show for a view generated page?
Why don't menu tabs show for a view generated page? Viewing my site as an administrator I see menu tabs above content pages for view, edit, and Devel (I have the developers module turned on). When I generate a view page, the menu tabs are not displayed. I have viewed video tutorials and they are present on a view page. The view is working and generating the correct page. Is there a setting somewhere?

Added Question: OK hansag answered my initial question below, so let me rephrase the question. The problem is I have created 3 pages in the view each with menu tabs assigned. The paths for each are:

default tab page= materials/% page 2 = materials/%/general page 3 = materials/%/scope

There is a contextual filter that takes the % value and finds articles with an attached taxonomy term. The view page works since the placing a URL such as materials/termname finds the correct articles and displays them.

Why don't the menu tabs show?

# Answer
> 3 votes
Those tabs are used for node editing. When you create a "page" from the views module it is general collecting a series of nodes on the page, so it is not displaying the single node tabs.

You might consider using this module. Block Edit

It generates view/edit tabs for blocks and views.

Hope this helps!

# Answer
> 1 votes
I have found another answer as well.

In my example above, I had more than one tab defined, so even though the standard tabs such as "view" or "edit" did not show up, my additional tabs should have.

What I have found is that the menu tabs appear to only work if the path begins with 'user', 'comment, or perhaps a couple other key terms. I was using 'materials' as the path root and this excluded the display.

I have posted an issue for the views module although I am not certain this is them or core. Hopefully they can expand the functionality of the menu tabs to fit with path naming schemes of users.

---
Tags: views, routes
---


title: Featured Content block inside node

text:
# Question
Title: Featured Content block inside node
I'm using Drupal 7 and trying to include the Featured Content block between the write up and the comments, i.e. I want it inside a node.

I tried the method explained here, but am not getting the block appear.

This is the code I've used in my node.tpl.php

`$block = module_invoke('featured_content', 'block_view', '1');
print render($block);`

The featured content block's URL contains this:

admin/structure/block/manage/featured\_content/1/configure

Any suggestions? What could I be missing out?

# Answer
> 1 votes
As suggested in another post, I used this code:

```
$block = block_load('featured_content', '1');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
print $output;

```

This worked perfectly!

---
Tags: 7
---


# Question
Title: How do you move a file/image reference attached to a current node to a different node?
I found this previous question, but I'm struggling to adapt it to what I want to accomplish.

How can you take a file/image that is attached to one node, and move it to another or create a new node and attach it there?

# Answer
> 1 votes
I can't recommend this as finished code, and I certainly can't vouch for it's safety/usability, but I was able to accomplish this with:

```
<?php
function testymod_node_presave($node){

    if($node->type == 'image_gallery'){
        $nl = $node->language;//to shorten lines

        if(isset($node->field_image,$node->field_image[$nl],$node->field_image[$nl][1])){
            //Leave the first file, but move all the rest to indidivual nodes of their own
            for($i=1;$i<count($node->field_image[$nl]);$i++){
                $tmpNode = new stdClass();//Create a node object

                $tmpNode->uid = $node->uid;

                //Use the current node data
                $tmpNode->type = $node->type;
                $tmpNode->title = $node->title;
                $tmpNode->language = $nl;

                //Set some defaults
                node_object_prepare($tmpNode);

                //Add the file
                $tmpNode->field_image[$nl][0] = (array) unserialize(serialize($node->field_image[$nl][$i]));//Only way I know to do a deep clone

                $tmpNode = node_submit($tmpNode); // prep for saving

                node_save($tmpNode); // Should have an nid now
            }
            //Remove attachments from the original
            $node->field_image[$nl] = array_slice($node->field_image[$nl], 0,1);
        }

    }
}
?>

```

I may try to develop this into a usable module with a switch in the content type to enable it for a given content type, but I'd need to figure out how to automatically copy any relevant fields over as well.

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


title: How to autofill webform from GET vars?

text:
# Question
Title: How to autofill webform from GET vars?
I need to make a form that autofills itself with some values that I give from the GET or POST params

I have an emailing that is personalized for each user so when they click on a link or a submit form they will view that webform autorefilled with their data

I'm using Drupal 6.19 and Webform 6.x-3.4

# Answer
> 10 votes
Webform has GET support built-in, see: Setting Default Values from the URL.

For POST you have access to `%post[key]` or you can retrieve `$_POST` and set your values using `hook_form_alter()`.

> Webform allows several special values to be used as defaults when configuring a component. The special placeholders are commonly called tokens. The tokens Webform supports include:
> %username
> %useremail %site
> %date
> %server\[key\]
> %session\[key\]
> %get\[key\]
> %post\[key\]
> %request\[key\]
> %profile\[key\]

Working with Default Values

# Answer
> 1 votes
The prepopulate module does it for GET arguments.

---
Tags: entities, webforms, ajax
---


# Question
Title: Joomla to Drupal module - migrating issues
Notes: Drupal 7.x. Joomla to Drupal module version 1.0 ALPHA3

I was playing with the Joomla to Drupal module, which is currently in alpha. I had imported some 100 content items from a Joomla install using this tool. However, making changes to some of the content was producing errors, so I decided to start fresh; I deleted all of the imported content.

I then attempted to redo the import, however, it threw additional database entry related errors stating that it was unable to overwrite tables.

I decided to start anew by disabling and then removing the module and its related tables all together; logged into mysql and removed tables `joomla_categories` `joomla_content` `joomla_sections` and `joomla_users` as well as the joomla directory under `../sites/all/modules`.

I proceeded to reinstall the module, and went to configure it; all of the settings were intact i.e. database name, password, etc. from the previous install (caching?).

I go to perform the import, and a database error shows up stating that the `joomla_users` table does not exist. I log back into mysql and notice that the module did not recreate the joomla\_ database tables.

Isn't the module responsible for creating these tables? Can anyone see what I may have done wrong in my process? If the module doesn't create the tables, what does?

# Answer
> 1 votes
From the sounds of it, the module was not uninstalled correctly. You should first disable the module, then when the modules page reloads, uninstall it. During the uninstall process is when hook\_uninstall() is run and the database tables and any saved variables (from the variable table) should be deleted.

If you didn't uninstall the module correctly, Drupal never performed these actions, and therefore still believed the module was installed. Since it believed the module was already installed, the database tables would not be created.

For more information regarding uninstalling modules see the article: Uninstalling Modules

---
Tags: 7, migrations
---


title: Location of core theme functions?

text:
# Question
Title: Location of core theme functions?
Where can i find the core theme function code (D7)? I would like to use the table theme function as a template for a new theme function I'm writing.

Arnold

# Answer
> 4 votes
Check out the API Docs on Drupal.org. There you will be able to find the description on how to use the functions as well as the actual code of the function. For your use, here is theme\_table(). The actual function is in "includes/theme.inc, line 1631" as stated in the `theme_table()` documentation page.

# Answer
> 3 votes
Have a look at themeable functions in the API and more generally you can search for theme\_.

---
Tags: theming
---


# Question
Title: Error on views page. Any idea what this means?
Uncaught exception thrown in session handler.

> PDOException: SQLSTATE\[08S01\]: Communication link failure: 1153 Got a packet bigger than 'max\_allowed\_packet' bytes: UPDATE {sessions} SET uid=:db\_update\_placeholder\_0, cache=:db\_update\_placeholder\_1, hostname=:db\_update\_placeholder\_2, session=:db\_update\_placeholder\_3, timestamp=:db\_update\_placeholder\_4 WHERE ( (sid = :db\_condition\_placeholder\_0) AND (ssid = :db\_condition\_placeholder\_1) ); Array ( \[:db\_update\_placeholder\_0\] =\> 1 \[:db\_update\_placeholder\_1\] =\> 0 \[:db\_update\_placeholder\_2\] =\> 173.8.158.117 \[:db\_update\_placeholder\_3\] =\> Wpw4khR1syd0trFnNVSUxDsOs\_MtPQ

That gibberish at the end beginning with `=>` goes on for dozens of pages dumped directly onto the page. Any idea what to look into?

# Answer
> 0 votes
You likely need to bump up max\_allowed\_packet in your MySQL instance. That query is likey trying to store a large amount of data. I have never seen this at runtime, though. I have only had problems with this variable when trying to restore backups.

---
Tags: 7, views
---


# Question
Title: Possible to have 2 contextual filters with "or" rather than "and"?
I would like to create a view that shows all nodes created by the currently logged in user OR where the currently logged in user has commented on.

D6 had a views\_or module but it's not ported to 7.

Are there any simple solutions?

# Answer
> 4 votes
OR is built in Views 3 (see this issue) with a rather pleasant interface.

But for what you need, you can do this with a single filter: "Content: User posted or commented - *Display nodes only if a user posted the node or commented on the node.*"

Views 3 AND/OR filter interface:

---
Tags: 7, views
---


title: Importing Feeds into an entity?

text:
# Question
Title: Importing Feeds into an entity?
I am trying to create a store using Ubercart. like most other things on my site, I have a large amount of data stored on a csv file that I downloaded out of PHPmyAdmin from another site (the clients original site), which I need to upload into my new site. I am trying to upload them as products, but the problem is that things like the "List Price", the 'cost", the "sell price", and "SKU" number are entities, and those fields don't show up in the feeds importer. is there a way to import feeds into an entity as well as a field?

# Answer
> 1 votes
In Drupal 7 you can acheve this using the Commerce feeds module. Also check this tutorial.

I couldn't find anything similar for Ubercart; maybe back-porting the Commerce feeds module is the only way to go.

---
Tags: 7, ubercart, feeds, entities, importing-exporting
---


# Question
Title: Access to $content['links'] from page.tpl.php in D7
I understand how to print node fields and custom fields in the page.tpl.php files but how would I go about adding the $content\['links'\], (or I suppose $content\['comments'\], but I am really just looking for the links) like it is in the node.tpl.php?

I took a look at the node object and I don't see it in there. I would like to ultimately have the node links printed in two places, and one of the places is easiest to access from the page.tpl.php.

# Answer
> 2 votes
Well it looks like it can be pulled off with (in the page.tpl.php files):

```
$links = node_view($node);
print render($links['links']);

```

Anyone know if there is a better approach?

---
Tags: nodes, theming, 7
---


title: Article Page "View"

text:
# Question
Title: Article Page "View"
How do I make a View for the Article nodes that are created through the standard Article content type in Drupal 7?

I feel like I should make a Page View, but then it's wanting a URL, which should already exist from the Article node. I'm not sure how to properly hook it all together with Views

# Answer
Views comes with a default view that emulates the Drupal core frontpage. Just enable it and specify a path (e.g. /articles). This URL has nothing to do with each nodes URL, this is just the URL of the page view where to access the "list" of most recent articles.
> 1 votes

# Answer
I suspect you are struggling with the same concepts I have wrestled with as I have started using Drupal in the past couple months.

I was under the impression that a view took over the display of some content and substituted itself for the original. Every item has a path including a view. If you want to have a view display an article or group of articles, you give it a path and tell it what you want through the filters display settings and sorting options. You can also pass information through the path by making part of the path a variable eg. example.com/my\_stuff/%. You would then provide subcategories of 'my\_stuff' to replace the % in the URL. By setting up a contextual filter in the view, you tell it how to interpret the information in the path in the variable position. Getting all parts of the context filter settings correct will take a little time and the video series "taming the Beast' at nodeone.se helps a great deal.

There is also a module called page manager/panels that will intercept the path you enter in the URL and take control of its display. If your article had a path of my\_stuff/my\_article, you could set up a panel to intercept that URL and do almost anything you want including re-routing to another page display, controlling the manner it is displayed and what else is added n blocks on that page display, or even send information about the article to a view that is not available from with Views to generate a more refined view result. Panels is not necessary to begin, but after you master views, you may be interested in how Panels enhances View capabilities and webpage design.

I struggled with several misconceptions as I started out and there is little info to help, so feel free to ask for clarifications. I'd be happy to help.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How do I change the global site url when serving Drupal from behind a reverse proxy?
I want the site name to be the FQDN instead of the machine's internal name (ie: localhost), especially in tokens. I'd like to be able to change the value once (like say in an env var) so it shows up any time the site's url needs to be used, say in automated emails.

aggravating factor: we're using IIS7

# Answer
> 4 votes
inside settings.php:

```
global $base_url;
$base_url = 'http://my.domain.name';

```

---
Tags: tokens, iis, proxies
---


title: Error messages are not translated

text:
# Question
Title: Error messages are not translated
We have successfully build a multilingual Drupal website, the only thing that isn't being translated yet are the error messages.

We have the default Drupal 6 contact form on the website. All the field labels are translated correctly including the "Send" button.

However, when someone just tries to submit the form without completing the fields, the error message always show in English.

# Answer
> 2 votes
I just had to download the translation file of the language and it was fixed by importing it through the "translate interface" area of the Drupal backend.

---
Tags: 7
---


# Question
Title: How to display add node form below the view in Drupal 6?
I have a very similar functionality to stackoverflow - i.e. I have a a view that display question and below it there are answers (seperate nodes references). The user can comment on both the question and answers. Below it I would like to display a form that is used to add another answer by the user. This node will simply create an 'answer' node and display it above (just as stackoverflow) How can I add such a form below the view?

# Answer
> 1 votes
You should check Form Block module. This block can be placed in any region beside your view.

---
Tags: views, 6, nodes, forms
---


# Question
Title: How to implement question/answer functionality with following feature?
I would like to create a question/answer website using Drupal7, where a user can ask a question and other users can answer that question. This one is very simple to implement in Drupal 7. But what additional feature i want is when a user asks a question he will set the expiration period also by choosing from a select list (5Days, 7Days and 15Days etc). Within this duration the STATUS of the question should be shown as "OPEN for Answer". After this period, the STATUS should be changed to "Finalizing Best Answer" automatically and now no new answer can be submitted by any user and after the best answer is selected by the asker, the STATUS should change to "CLOSED" automatically. But the asker of the question can change this STATUS at any time from "OPEN" to "CLOSED" even befor the expiry set by himself, but he can not change any other field of the question form once a question is published. How should i implement this type of functionality in my content type? Please provide your views for this type of functionality. Thanks!!

# Answer
Well, while the Answers module does not support this entirely, it does provide some helpful functionality. (FWIW, this has been an open feature request for some time. I haven't gotten around to it ... but if you end up implementing it, I would love to integrate it.).

In particular, the Answers module allows you to programmatically "lock" questions, meaning additional answers are not allowed. You can also extend the module with the Best Answer module (which, naturally enough, enables question authors to select a Best Answer). The Best Answer module already provides an administrative setting which, if set, means that questions are automatically locked after the question author selects a Best Answer.
> 2 votes

# Answer
What about Rules? Assuming your answers are comments to a node, you can set something like "when a user publishes a comment to nodes of this content type, update its expiration field to (field + x days)".

To add a state "open" or "close" Flag is your way, that integrates well with Rules too.

Hope it helps
> 1 votes

---
Tags: 7
---


# Question
Title: How to use views contextual filter default argument "Taxonomy term id in url"
I am following the guide http://www.metachunk.com/blog/adding-related-content-view-drupal-7 to make a related content block. I have 2 taxonomies that my content is tagged with. But the contextual filters are not working.

I think it is because the path is node/\[nid\] and does not contain a taxonomy term id. How can I fix this so that views can figure out what terms a node is tagged with? Should I provide the default argument another way?

# Answer
Have you figured this out? If so could you share your answer?

I do not think the problem is that the path follows any pattern. As long as you create a path that identifies the location of a term and you configure the contextual filter correctly. eg. example.com/whatever-you-want/any-term will work as long as the view path is example.com/whatever-you-want/%. The 'any-term' must be a term in a vocabulary defined for the contextual filter and validation must be set to identify it.
> 1 votes

# Answer
Youre probably better off using panels to populate the view pane/block with the correct context (term id) but you can also delegate views to do this for you using the information you have (nid) and adding a relationship in views. Depending on if youre trying to list the terms or items mathicn the terms it is done slightly differently but this shoul dget you headed in the right direction. Good luck!
> 0 votes

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


title: Pass arguments to hook_form_alter()

text:
# Question
Title: Pass arguments to hook_form_alter()
I have two login boxes on the same page and, I would like to integrate different behaviors to those based on some arguments.

I'm calling myself the forms with `drupal_get_form('user_login');`. I would like to pass a variable to the form:

```
drupal_get_form('user_login', $myvar);

```

And then be able to get it from a `hook_form_alter()`:

```
function mymodule_form_alter($form, $form_state, $form_id, $myvar) {
  // some code here
}

```

But i can't find a way to do this.

# Answer
The passed arguments are kept in `$form_state['build_info']['args']`. You can find a documentation of the $form\_state structure here: drupal\_build\_form().
> 9 votes

---
Tags: forms, users
---


# Question
Title: Select List, 'Other" option text field, any text written in textfield 'Illegal Value' error is given
In one of my content types, I have an option for a select list with pre-defined values. I have the 'other' field configured, so when selected a text field displays to enter the 'other' information.

However whenever a user enters information into the text field and attempts to save the form, an "Illegal Value" error is displayed.

I went in and looked at the configuration and could not see anything wrong. Any ideas?

# Answer
> 1 votes
Are you using http://drupal.org/project/select\_or\_other ?

Is the field set as required? Take a screen pic of the config for the field.

---
Tags: 6, entities, nodes
---


title: Limit items in shopping cart

text:
# Question
Title: Limit items in shopping cart
Is there a way to limit users on my site to buy only 2 items from a list of products? Am using Drupal 7 with Commerce module and Rules. I added a new rule to when adding or removing and item from the shopping cart, it would check if the total quantity is bigger than 2, then it would remove the last element like this.

> **Event** Before adding a product to the cart
>
> After adding a product to the cart
>
> **Conditions**
>
> Total product quantity comparison Parameter: Order: \[commerce\_order\], Operator: \>, Quantity: 2
>
> **Actions**
>
> Remove an item from a list
>
> Selected list: commerce-order:commerce-line-items

and the item to remove is

> commerce-order:commerce-line-items:2

Sadly its not working, and I really need your help. thanks

# Answer
> 1 votes
I had a similar problem: I had to check for certain conditions before adding an item to the cart (not after adding). And if the condition is not met the item should not be added.

The only way i could resolve this is by adding a **"Execute custom PHP code"** action with the code:

```
drupal_goto('any_path');

```

This doesn't look very correct but its the only thing that worked for me.

---
Tags: commerce
---


# Question
Title: Can the Views Module assign a value to the <title>
Can the Views Module assign a value to the and/or $title variable?

More specifically, I would like the Views Field: "Content Title" to be the $title.

# Answer
I found a place in the Contextual Filter that lets me set the page title based on the Node ID's URL parameter.

I set options that met my needs in "Context Filters \> Content: Nid." Within the Nid options, there are several options for providing a filter value and for overriding the title.
> 4 votes

---
Tags: views, 7
---


title: Commerce View oddities?

text:
# Question
Title: Commerce View oddities?
hi I'm trying to create a new Cart view which will simply show Items Total, Cost total and checkout links. I wanted to keep the Default view in place as a fall back, so I cloned it to work on it, but then I noticed my new clone view has a **Save** button attached to the footer\* which isn't there on the original. Also the original is labelled as Display **Master**, which I've not sen before and dont believe I have access to create such a type.

The footer is set to **Commerce Line Item: Line item summary** and investigating all the options that come with this, none seem to control this Save button.

Can anyone help me out with these two oddities? show some info on the altered screen shots below.

cheers.

# Answer
> 1 votes
That is because the summary area handler triggers Views Form (even when there are no actual form elements in the view), which renders the Save button. Once Views 7.x-3.0-RC2 gets released the following patch: http://drupal.org/node/1256302#comment-4909962 will be committed to Commerce, solving the problem. So update Views to the latest -dev, apply the Commerce patch, and you should be good.

# Answer
> 2 votes
The master page is always present in a defined View, although it may not be visible. To toggle its visibility on and off go to the views list page and select the 'Settings' Tab. Check or uncheck the "Always show Master Display" checkbox.

When you begin a new view and generate the a page or block, the hidden master is also being completed. It serves as the template for any new pages or blocks you create without cloning. I keep the master display visible and will use it as the template for views with many alternate displays.

---
Tags: commerce
---


# Question
Title: is it a security hole to verify an uploaded supposed-to-be-zip file as a zip with zip_open()?
Question's subject is pretty much it.

I have an upload widget on a custom content type that is for users to provide a zip file.

I want to verify the file they provide is indeed a zip file, and take appropriate action if not. However, first I need to know if it's safe to pass an unknown file type to zip\_open(), probably using the ZIP\_CHECKONS flag for extra integrity checks.

edit: just realized ZIP\_CHECKONS is not exposed in php. :(

Is this a safe way to verify a file is a zip file?

# Answer
> 3 votes
That seems reasonable to me. I would probably place the file in a temporary directory first and then use zip\_open on it in that location.

You may also be able to use OS level commands (which come with their own risks) to verify the integrity of the file without actually unzipping it.

Are you going to store the zip files as zip files after being uploaded? Doing so presents additional issues since zips can be used to contain lots of files that may or may not be appropriate. You may want to get a list of the contents of the file to automatically include in your field so people downloading them will know if the file contents are valid. You could also integrate with something like http://drupal.org/project/clamav to scan all the files that are uploaded.

---
Tags: files, security
---


# Question
Title: An AJAX autocomplete textfield in Drupal 7 doesn't work in Chrome
An AJAX autocomplete textfield in Drupal 7 works in Firefox, but doesn't work in IE and Chrome. The following error appears:

> ```
> An AJAX HTTP error occured. HTTP Result Code: 200 Debugging information follows.
> Path: http://localhost/drupal/en/example/autocomplete
> StatusText: OK
> ResponseText: {"admin":"admin","alex":"alex","apple":"apple"}
>
> ```

```
function clubform_menu() {
  $items['example/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function _module_name_autocomplete($string) {
$matches = array();
$return = db_query("SELECT name FROM users where lower(name) like '".$string."%' LIMIT 10");
  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->name] = check_plain($row->name);
  }
  // return for JS
  drupal_json_output($matches);
}

...
        $form['editclub']['club_name'] = array(
          '#title' => t(''),
          '#type' => 'textfield',
          '#description' => t(''),
          '#autocomplete_path' => 'example/autocomplete',
          '#weight' =>15,
          '#size' => 30,
         );
...

```

The output in Firefox is the following:

# Answer
> 4 votes
I found out what causes AJAX error! When I turn on any module with UTF-8 encoding, it causes the error; when I change the encoding to ANSI or to UTF-8 without BOM, everything works. This encoding problem happened only in Google Chrome; in Firefox all encodings work well.

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


title: Forum access based on role

text:
# Question
Title: Forum access based on role
I cant figure out to hide forum sections based on role. I only want clan leaders to see the clan leaders section, squad members to see their own squad section etc. I already have the roles set up, but I can't figure out how to restrict access to container/forum based on those roles.

Someone mentioned the taxonomy access control module. But that seems *really* overyly complicated for what I want to accomplish.

# Answer
> 2 votes
Not sure what version of Drupal you are using, but have you looked at the Forum Access module? For D6 there is a stable release and the D7 version is in Beta. The module is also very straight-forward

From the module's page:

> This module changes your forum administration page to allow you to set forums private. You can control what user roles can view, edit, delete, and post to each forum. You can also give each forum a list of users who have administrative access on that forum (AKA moderators).
>
> This module requires the ACL module in order to function. The D7 version also requires the Chain Menu Access API module.
>
> Forum Access is compatible with the core Forum module, Advanced Forum, and Content Access, Domain Access as well as all other well-behaved node access modules.

---
Tags: nodes
---


# Question
Title: How do I take payments via Ubercart and distribute them to vendors?
I'm working on a site that needs to take custom payment and remit a part of it to one or more vendors that are determined by the products purchased (the vendors essentially create the products themselves in the shop). I have seen Ubercart Marketplace as a possibility for this, but it's rather old. However, it's the closest to what I need. Should I go with it or is there a better, more fully-integrated solution in Drupal (that uses Ubercart) that I should investigate?

# Answer
> 2 votes
This is outside Ubercart, but it's definitely possible with Drupal!

For this demonstration, I will use a point system. Let's say 100 points = $1.00.

Drupal 7 method:

1. Create a content type, called Products.
2. Install a Drupal module, called Entity Reference and add an Entity Reference field to the Products content type, select users. This will allow you to reference the product to vendors.
3. Create another content type, called Points. Also add an Entity Reference field to it, and select type as users, to reference users. In addition, add a decimal field (amount).
4. Install another Drupal module, called Rules
5. Create a rule that would, after a certain time (30 days, etc...) from the sale date, create a Point node with that User referenced and add the commission earned.
6. Create a rule, that would unpublish the Point node anytime the payment is withdrawn.

Another option is to use the Relation module. It's more work and still in early stages.

By creating a Point node for each commission, you're leaving all records of transactions. I would never overwrite the old commission value with new commission, i.e. $user-\>payment = $user-\>payment + 10. It will mess things up.

You can still use Ubercart with this, as it uses Drupal's entity/field structure. Simply skip #1 and use Ubercart's product content type.

# Answer
> 2 votes
I would recommend that you go with Ubercart Marketplace for Drupal 6.x, especially if you need vendors to create their own products and have their own set of permissions to edit products, publish products, ship to vendors and/or get sales reports. I've used Ubercart Marketplace with some of my own customizations and patching (especially in the payment and reports area) but overall it does the job and in my opinion it will take a lot more if you build this functionality from scratch or try to bundle several other modules.

If you need to automatically split the payment as you get orders then take a look at Amazon Flexible Payments which lets you splits payments and has a very flexible API to do whatever you need.

---
Tags: 6, ubercart
---


title: What does testing a patch mean?

text:
# Question
Title: What does testing a patch mean?
In drupal.org issues when someone creates a patch, in attachment table there is a column named *Test result* which has a value like `FAILED: [[SimpleTest]]: [MySQL] 32,869 pass(es), 2 fail(s), and 0 exception(es).` and in *operations* column a link to *re-test*

What does re-testing mean? And what's meaning of the line `FAILED: [[SimpleTest]]: [MySQL] 32,869 pass(es), 2 fail(s), and 0 exception(es).` ?

(I'm not sure this is specific to Drupal)

# Answer
> 8 votes
In Drupal.org, for projects that are enabled, patches in the issue queues are passed to a test server, which executes the following steps:

* It creates a Drupal site
* It copies, and installs the module for which the patch has been written
* It applies the patch being tested
* It runs a set of SimpleTest tests, which has been written by the maintainer of the project wrote for his own module, to verify the patch doesn't introduce any problem

Once the tests are done, the test server reports to Drupal.org the result, which is then shown in the issue where the patch is attached.

This is what essentially happens. I didn't mention all the details, such as:

* The Drupal site is created before to run every test
* The test server executes also its own tests to verify the created Drupal site is running correctly
* The test server periodically executes tests to verify it is running correctly
* The Drupal version, and the version of the module that needs to be installed are taken from the issue itself; if the issue is for version 6.x-1.0 of a module, then the test server creates a Drupal 6 site, and installs the version 6.x-1.0 of the module, to which it applies the patch found in the issue report

---
Tags: community-official-site, version-control
---


# Question
Title: Ubercart - moving uc_order-customer.tpl.php to my theme folder makes emails sent twice
Ive copied uc\_order.tpl.php to my them folder as well as uc\_order-customer.tpl.php which ive used to remove a few fields from the customer's notification email.

The problem is that now the same email notification is being sent twice at the same time, to the same email address.

If I remove the files from the theme folder, the problem goes away, but of course I need to modify the template and i wont want to hack core.

Thanks

# Answer
> 2 votes
Updating to the latest module version fixed this.

---
Tags: theming, ubercart, emails
---


title: Set multiple domain for one language

text:
# Question
Title: Set multiple domain for one language
I am running a d6 website with i18n and I have multiple domain on it working very fine. Now I want to add another domain but for an existing language so what is the best solution for that.

In fact, this additionnal domain is for the mobile version of the website and because menus depends on language domain selection, I cant' get my menus using the mobile domain but the default domain, that's why I want to add another language but I can't :)

Maybe there is a simpler solution?

Thanks

# Answer
> 0 votes
I would rewrite second language domain to the "primary" one in settings.php Something like

```
if ($_SERVER['HTTP_HOST'] == 'newlang.example.com') {
  $_SERVER['HTTP_HOST'] = 'lang.example.com';
}

```

---
Tags: 6
---


# Question
Title: Customise message notifications in Drupal 7
I'm using organic groups with Drupal 7 and members receive email notifications when new content is posted to their group.

However I can't find a way to modify:

```
Email subject: New post in group
Email message: Hello [user], There is a new post called...

```

Which template or database entry do I need to modify?

# Answer
OG7 Uses the Rule module for sending email notifications. See admin/config/workflow/rules/reaction/manage/rules\_og\_group\_content\_notification
> 4 votes

---
Tags: 7, organic-groups, emails, notifications
---


# Question
Title: Mandatory Group / Autosubscribe in Drupal 7
I'm using organic groups for a community website which notifies members when a new article is submitted to their group.

However I would like ALL members to receive notifications when the admins publish articles to the site.

There are 2 ideas on how I think this could be done:

1. Autosubscribe all users to receive notifications when articles are posted (to no group) by the admins
2. Have a 'General' group that all members automatically join on signup

I have seen a module for Drupal 6 which address idea 2 but so far I have not found any solution on Drupal 7.

# Answer
You can use rules to do this (As OG7 uses rules for everything else).

1. Create new Rule
2. Add New Action
3. React on event: After saving new content
4. Add condition
5. Data Selector node:author
6. Choose whatever role is admin
7. Add Action
8. Send email to all users of role
9. Select whatever roles
10. Fill in your message with applicable tokens

You can also check out the notifications and Messaging framework or the new Newsletter module for D7. These are better for allowing users to control which notifications they receive and can subscribe and unsubscribe themselves.
> 2 votes

---
Tags: 7, organic-groups, notifications
---


# Question
Title: How do I direct link a view to a taxonomy menu?
I have created a vocabulary with over a hundred terms on three levels (parent/child/child) and used Taxonomy Menu to create a custom menu. Selecting a menu item brings up a default menu page with the description and a list of teasers of content that has the vocabulary term in a field. I would like it to use a view to manage the content display. IS there a way to direct the menu items to a view? I cannot find a way to change the link generated by the taxonomy menu module.

Edit to clarify the question: Taxonomy menu generates a user defined menu block that will call up the taxonomy term selected. Unfortunately it locks the path (so it can regenerate the menu from the vocabulary if it changes). I am looking for a way to generate the menu but change the path to display the view rather than the term page offered by taxonomy menu.

# Answer
If I understand well your question, I think that you can show your menu with the `Expose Filter` fature of Views:

first add the filter related with your taxonomy:

then select the type of your menu (for example: dropdown) to expose:

and finally, you can expose these filter to visitors, to allow them to select terms to see just the content related:

I hope I have understood, and that information be useful. Here is an example of the view with results according a selection:
> 2 votes

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


# Question
Title: How can I display multiple taxonomy terms on a node?
I have a Drupal6/Ubercart setup. My products are categorised with taxonomy but we have a requirement that products can be placed into multiple category hierachies. For example, one product might be in:

```
Homeware
   Kitchens

```

and

```
Kitchens
   X Kitchen Range

```

The other requirement is that when displaying the product, the heading should show the breadcrumb of the hierachy as well as the category name. This would be dependent on how the user got to view the product. If they went through the menu Homeware \> Kitchens, this would be the breadcrumbs/heading displayed and vice versa.

How could I achieve this?

# Answer
If you want a product to show up in multiple categories you simply enter all terms from the category vocabulary in the product edit mode. The hierarchy you need to build up in the menu system not in the vocabulary.
> 1 votes

---
Tags: 6, taxonomy-terms, ubercart
---


# Question
Title: Include a PHP file located in the home directory in a module
How can I include a PHP file located in my Drupal's home directory from a module?

# Answer
Drupal 7 defines the constant `DRUPAL_ROOT`, which contains the name of the directory where Drupal is installed. It is used from Drupal functions, such as module\_load\_include() in a way similar to the following one:

```
if (function_exists('drupal_get_path')) {
  $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
  if (is_file($file)) {
    require_once $file;
    return $file;
  }
}

```

In your case, you should use the following code:

```
require_once DRUPAL_ROOT . "/$filename";

```

The variable `$filename` contains the name of the file to load.
> 8 votes

# Answer
If I understand well, according my test is not needed indicate any path, just with the name of your file that is in your home directory. For example I have a file called `testfile.php` in my home directory, then from my module inside `sites/all/modules` I can use:

```
include ('testfile.php');

```

I hope information be useful.
> 4 votes

# Answer
~~I would use API module\_load\_include()~~.

**Edit** : This API is meant for including PHP file located in module's directory.
> 0 votes

---
Tags: files
---


# Question
Title: What does Contextual Filters (in Views) serve for?
I was playing with filtering content using views but seems I can't make them work the way I want : to display the articles of an edition based on the latest issue no. (or latest issue date) on the frontpage. I figure out this can be done using contextual filter but don't know how.

My content types are:

editions: edition\_no, edition\_date, edition\_title article: title, body, edition\_no.

Many thanks for help.

# Answer
Contextual filters in Views 3 replaces the 'Arguments' of Views 2.

It's best used with paths as outlined in this video: http://nodeone.se/blogg/learn-views-with-nodeone-part-19-contextual-filters-with-paths.

By the sounds of it, the filtering of your view could do the same job.
> 5 votes

---
Tags: views
---


# Question
Title: Can I creat a View output using the root path?
just need a simple task. I need to change the homepage based on a view.

If I edit the path inside view settings something like /home it works. But if I try to use the default site root path it displays:

```
Display "Page" uses a path but the path is undefined.

```

That means I am forced to set up my site homepage to www.domain.com/home

Can someone help?

# Answer
> 2 votes
Your view will need a path set, in this case 'home' and then within your site's **Site Information** settings just set 'home' as the *Default front page* (for Drupal 7 got to http://www.yoursite.com/admin/config/system/site-information).

When you access the URL of your site you will see your View, setting the homepage menu link to '' will also direct users to your homepage without adding '/home' to the URL.

---
Tags: views
---


# Question
Title: How do I prevent the feed aggregator creates blank nodes when cron is run?
I've recently taken over the management and development of a Drupal 6 site and one of the problems plaguing this installation is that blank nodes authored by "Visitor" keep popping up.

I've narrowed the issue down to the RSS aggregator and it seems like the nodes are being created when this runs durring the cron job. Has anyone seen this before? If so how do I go about fixing this? If not, does anyone have an idea where to look in order to resolve this?

# Answer
Take a look at the Scheduler module. It creates blank nodes if you have some crappy nodes in scheduler table.
> 0 votes

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


# Question
Title: Image field unlimited values doesn't save just the first image..the others disapear on save
I have a weird problem that appeared with my latest drupal installation I have a content type with some image fields that have an unlimited value (I can upload more images to the same field) When I press SAVE only the first image remains saved..the other ones..don't No error is given.. Nor on screen nor on logs..

my drupal version is 7.8 memory limit 96M Apache/2.2.13 (Unix) mod\_ssl/2.2.13 OpenSSL/0.9.8g PHP/5.2.11 with Suhosin-Patch Mysql 5.1.38

# Answer
Seems to be that is a bug from Drupal fixed in the last release (7.9) according the release note.
> 1 votes

---
Tags: entities, media
---


# Question
Title: node-NAME.tpl.php doesn't override the node template. I've cleared theme registry
I'm using Drupal 7.8, and I've tried the same thing I did with Drupal 6, making a custom layout for a node type.

I've copied node.tpl.php, and renamed it node-NAMEOFTHENODETYPE.tpl.php, altered the template, uploaded it to the theme folder. Surprisingly, Drupal 7 doesn't take it: It shows the default node layout.

Can anyone tell me what I am doing wrong?

# Answer
You mispelled the filename. Drupal 7 now uses double dashes (*--*); your file needs to be node--NAMEOFTHENODETYPE.tpl.php.
> 7 votes

---
Tags: 7, nodes, theming
---


# Question
Title: Module is enabled but none of the hooks work
I have created this simple module (named "youtube"):

```
echo 'outside function';

function youtube_view($node, $view_mode) {
   echo 'inside function<br />';

    return $node;
  }

```

I can only see the echo outside of the function. I've tried numerous hooks and I can't get any of them to work. The only thing different is that I am a new user to Drupal 7 and this is created on a multi site.

My structure for this module is:

sites/customsites/modules/youtube

And the site can see it fine as I have enabled it in the backend.

Do you have any idea on why this happens?

# Answer
> 3 votes
Hook implementations are cached in Drupal 7. After adding a new hook, you need to clear the cache for example using the devel block or `drush cc all`.

Also, hook\_view() is not actually a hook. It is callback that is only invoked for the module which provides the given node type.

---
Tags: 7, hooks
---


title: How can I debug an email function?

text:
# Question
Title: How can I debug an email function?
I'm using flag\_friend module and want to customize the email that is sent after a friend request is made.

What's the best way developing code for email functions like this where you can't just reload the page to see your changes?

I would have to go back, remove the friend request and create a new request to trigger the next email, then wait for the email to arrive.

# Answer
You could write an automated test with SimpleTest.

Takes quite a bit of initial effort but once you have it, it is a matter of a few seconds to re-run your test.

Simpletest also automatically intercepts sent mails and you can then get them directly in the test with `$this->drupalGetMails()`.

See for example How do I write automated tests for a Drupal site?
> 3 votes

---
Tags: 7, emails
---


# Question
Title: My 960 grid system has wider columns that standard. 55px instead 40px for 16 columns
I was surprised to discover my website is wider than is supposed to be.

I am using Drupal + Omega Theme that uses 960 grid system.

The total width of the site is 1180 instead 960.

The columns are wider:

* **On 16 columns options: they are supposed to be and 40px they are 55px**
* **On 12 columns options: they are supposed to be 60px and they are 80px.**

The gutter is 20px and is ok.

What is the problem?

# Answer
> 2 votes
On wide screens, Omega (or in fact: its base theme 'Alpha') will switch to the wide lay-out. You will find the css for it in alpha/css/grid/alpha\_default/wide/alpha-default-wide-16.css and alpha/css/grid/alpha\_default/wide/alpha-default-wide-12.css.

This responsive behavior can be controlled from the Omega theme settings page.

---
Tags: theming
---


# Question
Title: What is $delta for in Field API hook_field_widget_form?
d.o defines it as such:

> $delta The order of this item in the array of subelements (0, 1, 2, etc).

So that you can use it as an index into the $items array, but i can't seem to wrap my head around when the $items array would have more than one element.

# Answer
> 1 votes
See the answer to my question re; delta field in views. I got an answer for $delta as well.

---
Tags: entities
---


# Question
Title: How to create a table without uninstalling and reinstalling the module?
I have a module and an installation file that is used to create a table.

According to my requirement, I need to add an another table in the same install file. I know that by using `hook_schema()` we can create n number of tables.
But we need to uninstall and reinstall again to create the tables. If I use this, my existing data will be lost, so I am not supposed to do this.

Is there any way to create a table without uninstalling and reinstalling the module?

# Answer
This link answered my question: Updating tables: hook\_update\_N() functions.

For example:

In Drupal 7:

```
<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_7101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  db_create_table('mytable2', $schema['mytable2']);
}
?>

```

and in Drupal 6:

```
<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_6101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  $ret = array();
  db_create_table($ret, 'mytable2', $schema['mytable2']);
  return $ret;
}
?>

```
> 4 votes

# Answer
hook\_install() is called only when the module is first installed; after that, `hook_install()` will be called only if you first uninstall the module.

When you are updating a module, you need to implement hook\_update\_N(), which runs all times the module is updated. At the same time, the implementation of hook\_schema() needs to be updated to include all the schema used from the module, for who installs the module for the first time.
> 0 votes

---
Tags: installation
---


title: Will a version 6.x module work in v7.x?

text:
# Question
Title: Will a version 6.x module work in v7.x?
Is it possible that an older version of a module works when it has not been upgraded to 7 or is it a lost cause to try?

# Answer
The module versions must match the core version to work. Drupal 6 modules will not work on Drupal 7.
> 3 votes

# Answer
Without updating a module to Drupal 7, the module will not work on the new Drupal version.

The first reason is that Drupal 7 looks for a line containing "core = 7.x" in the .info file of the module; if the file doesn't contain that line, or contains a different version ID, such as 6.x, the module will be reported not to be compatible with Drupal 7.

Even if you would edit that file, the module could not still work, depending from the implemented hooks. If the module is implementing a hook that has been renamed in Drupal 7, it will not work; the same is true if the arguments of the hook have been changed. For example, `hook_nodeapi()` has been replaced from a family of hooks, whose name is generally `hook_node_$op()`, where `$op` was the parameter passed to `hook_nodeapi()`. Finally, in few cases, a hook that was already used in Drupal 6 has changed purpose in Drupal 7; an example of this is hook\_hook\_info() that in Drupal 7 defines which files are used from a module to implement its hooks, while hook\_hook\_info() was used in Drupal 6 to define the triggers to which the users could associate actions.

There are also hooks that have not been renamed, or for which the parameters didn't change, but it's rare that a module just uses those hooks.
> 2 votes

# Answer
A large portion of the Drupal 7 API has changed from the Drupal 6 API, so it is unlikely that a module will work as-is. It is still possible, though, for some small modules to not use any changed functions.

Note that you can't take a D6 module and just plunk it into a D7 installation anyway. The core version is specified in the modules's .info file.

Would I try this? No.

If a module hasn't been ported to Drupal 7, then it is likely that it either isn't needed or it isn't being maintained anyway (which is a warning sign).
> 0 votes

---
Tags: 7
---


title: Disable link on username in comments?

text:
# Question
Title: Disable link on username in comments?
How can I disable the link on authenticated an authenticated user's name in the comment submission form in Drupal 6?

# Answer
I just tested this out, not sure if it is the best way, but it works. Create a really simple custom module and implement hook\_form\_FORM\_ID\_alter().

**YOURMODULE.info**

```
name = YOURMODULE
description = Description of YOURMODULE goes here...
core = 6.x

```

**YOURMODULE.module**

```
<?php
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  $form['_author']['#value'] = $form['author']['#value'];
}

```

Place these files in a directory named YOURMODULE, inside contrib modules directory. Then enable the module.

(Be sure to replace YOURMODULE with the name you choose to give to the module everywhere it occurs.)
> 1 votes

# Answer
Everything you need to make this change can be found here: Three tips for comment theming in Drupal

Note: While this article is written for Druapl 5, it will work fine under Drupal 6 as well.
> 0 votes

---
Tags: 6, users, navigation, comments
---


# Question
Title: How to create a suggested content view using Flag and Flag Terms modules?
I am using Flag and Flag Terms modules to allow users tagging the content and taxonomy terms they like or dislike.

How do I create a view or a block that shows and sorts content based on tags assigned to, the way that prioritizes tags the current user subscribed for ?

Set up as in my previous question: How do I set up user's "Favorite Tags" and "Ignored Tags" tag subscriptions?.

# Answer
I just tried it out. I need to add it to my site too and the 50 points bounty was enough incentive to move it up on my list ;-)

After installing flag and flag\_terms you create a new flag and select "Taxonomy terms" as the "Flag Type". Configure the text options, select a vocabulary (or many), permissions and select the "Display link on taxonomy term pages" checkbox.

Then view a few terms on the standard term page and flag them using the new link.

Then create your view for content from your selected "vocabulary". The trick is that you have to add the "Content: Taxonomy terms on node" relationship first. Only then can you add the "(term) Flags: termflag (by current user)" relationship and select your "term flag" you entered previously. If you "require this relationship" it will only show you nodes where the term has been flagged.
> 3 votes

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


# Question
Title: Not getting along with the form API tutorial
I am using Drupal 7, and I want to build a form. I tried to follow the tutorial in "Pro Drupal 7 Development"; I created a .module and .info file, which are supposed to work, I activated the module, and now I don't find the form.

How can I see the form in the front end, or at least at the back end? Is there a URL Drupal is giving to this module? How can I see it?

# Answer
Use hook\_menu().

```
function YourModuleName_menu() {

 $items['testform'] = array(
   'title' => 'Test form',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('your_form_function'),
   'access arguments' => array('access content'),
   'type' => MENU_CALLBACK
 );

 return $items;
}

```

Access the page from example.com/testform, where example.com is your site address.

You can also create a block from your form to access it.
> 2 votes

---
Tags: forms
---


# Question
Title: Drupal 7 - better navigation for Pages in custom menu
I have several custom menus that link to Pages in my Drupal 7 site. One custom menu is called Announcements. When I visit a Page that is linked in the Announcements menu, I would like to display in the sidebar the other links that are in the Announcements menu. I don't want to have to create a menu block for Announcements and manually maintain a list of nodes on which to show the menu block, to make it show only on the Announcements pages. How can I dynamically list links from the custom menu that links to the current page?

**It would also be nice if...**

* I have a page called News Archives on which a menu block is displayed for the Announcements menu as well as some other menus. It would be nice to have a custom breadcrumb for any Page linked in the Announcements menu like 'Home \> News Archives \> \[the current page\]'. I have the Custom Breadcrumbs module installed, if someone can think of a way to use this for this purpose.
* The Pages in a given menu don't have any pattern to their URL, or hierarchy. Many of them are just off the root site, e.g., `http://mysite.com/page_linked_in_announcements_menu`. Is there any way to dynamically change a Page's URL alias to reflect which custom menu it belongs to? So on the edit page for a Page, the URL alias might be "blah", but it's linked in the Announcements menu, so I can access it at `/announcements/blah`. Then if I moved "blah" to My Other Custom Menu, its URL would automatically become `/my-other-custom-menu/blah`, without me having to edit the URL alias by hand.

*This is a cross-post from Stack Overflow because I didn't know how to port the question over.*

# Answer
This best approach in this regard can be a single multi level menu along with Menu Block module.

Top level menu form main navigation to sections while first level children appear as section items menus. Menu Block configured with 2nd level items chooses second level items siblings of current active item.
> 1 votes

# Answer
For the automatic menu items, there is a nice little module called Auto Menu. Unfortunately the port to Drupal 7, is still in progress.

I found that you can get the same results using Node Auto Term and Taxonomy Menu.

As to the URL pattern, you should use pathauto, they have many tokens you can use. For example you could setup a taxonomy for each menu custom menu (if you do this you won't need to create the menu manually because the Taxonomy Menu module can do it for you). You can use the token for that taxonomy in the pathauto urls, and then setup pathauto so that it changes the node's path when there is changes (it won't do this by default, it will keep the first set path).

Wit this setup if you change the taxonomy for the node you would see the url change and the menu item created on the correct menu.

\**update: I would use Breadcrumb Menu for breadcrumbs.
> 0 votes

---
Tags: routes, uri, navigation, 7, breadcrumbs
---


# Question
Title: How to add 100 contributed modules into git repository fast?
I use a git repository, and Drush to manage Drupal projects.

What I would like to do now is to add more then 100 contributed modules to the git repository to keep track on these modules as well.

If I am forced to add contributed modules manually, I have to do the following steps over 100 times:

```
drush dl <contributed module name>
git add .
git commit -m "<contributed module name> <contributed module version> imported"

```

I would like to avoid or limit this manual task. Is there any automated way to do this?

# Answer
> 2 votes
You can use submodule on if you want keep tracking all latest commit for each project, but that means that your project can have development code from one of these modules.

Or, you can also download all your 100 modules with Drush and just do a `git add .` in the parent directory (git add all files recursively).

# Answer
> 0 votes
I wrote a short bash script (below) that simplifies this process a bit but is not perfect.

Can someone suggest a more flexible solution ?

```
function drush_dl_add_commit()
{

    dr_module=${1}
    dr_version=${2}

    drush dl "${dr_module}-${dr_version}"
    git add .
    git commit -m "${dr_module} (${dr_version}) imported"

}

drush_dl_add_commit profile2 7.x-1.0
drush_dl_add_commit progress 7.x-1.0
drush_dl_add_commit purr_messages 7.x-2.0-beta2

```

How to automatically select the latest stable module version so the following would work without errors/warning messages ?

```
drush_dl_add_commit profile2
drush_dl_add_commit progress
drush_dl_add_commit purr_messages

```

---
Tags: 7, drush, version-control
---


# Question
Title: What is the suitable file permission for 'files'?
I have written this small bash script to rebuild D6.22 file permissions:

```
#!/bin/bash
cd /path/to/drupal

chown -R bob:www-data .

find . -type d -exec chmod u=rwx,g=rx,o= {} \;
find . -type f -exec chmod u=rw,g=r,o= {} \;

cd /path/to/drupal/sites

find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
find . -name files -type d -exec find '{}' -type f \; | while read FILE; do chm$
find . -name files -type d -exec find '{}' -type d \; | while read DIR; do chmo$

chmod -R 777 /path/to/drupal/sites/default/files  #bad idea??
chmod -R 755 /path/to/drupal/tmp

echo "Permissioin rebuild is done!"

```

Of course prior to executing the script 'bob' should have been added to www-data group using

> usermod -G www-data bob

I know that a security-aware admininstrator should avoid giving 777 permission to web server, however when I assign 755 to files, users can not upload image/avatars and I get a warning that says sites/default/files/pictures/picture is not writable.

So what alternative permission do you use for 'files' (and works)?

Thanks

# Answer
> 4 votes
This really depends on how you have Apache configured.

I almost always run Apache in prefork mode. When I do this, I

```
chown -R apache.apache sites/default/files
find sites/default/files/ -type d -exec chmod 755 {} \;
find sites/default/files/ -type f -exec chmod 644 {} \;

```

This lets Apache write to that directory. Note that the owner/group depends on the setting from httpd.conf.

When I use FastCGI, then I use the user that Apache runs as.

The main key is that your files/ directory is owned and writable by just Apache, and that the rest of the files in docroot are owned and writeable by someone else, and not writable by Apache. Normally this is the user I run drush as.

One quirk has to do when drush runs things that write to this directory, like bam-backup.

Then I will add my drush user to the Apache group, and do

```
chown -R apache.apache sites/default/files
find sites/default/files/ -type d -exec chmod 775 {} \;
find sites/default/files/ -type f -exec chmod 664 {} \;

```

so that drush can write to files, but Apache can't write to the rest of docroot.

---
Tags: files, security
---


# Question
Title: How to show only oldest and newest node in Drupal views?
I want to create a view that only shows the oldest and newest node of a certain content type what is the easiest way to do this?

Thanks

# Answer
How about creating a contextual filter in view, and take a look at the below image to select any of these creation dates?

Afterwards, filter your content type as in the following image:
> 2 votes

# Answer
Reader beware: this is probably a bad idea. But I couldn't resist.

```
function example_views_query_my_view_name_alter(&$view, &$query) {
  $query->addExpression("ABS(nid - (SELECT MAX(nid) + MIN(nid) FROM {node} WHERE type='mynodetype') / 2)", 'horrificorder');
  $query->orderBy('horrificorder', 'DESC');
}

```

(Of course add a node type filter and display only two items in the Views UI.)
> 1 votes

# Answer
I guess that you can build two displays, one to show the oldest and other to show newest, and one to show (in each display) only one item per page without pager (in "Pager settings" of your view). Then, you can pull/show/embed these two displays where you need.
> 0 votes

# Answer
"...I needed these on the same view so I can make a calculation..."

Getting calculations generated from Views results will take php coding skill and a knowledge of how Drupal is generating and displaying a page.
> 0 votes

---
Tags: views, blocks
---


# Question
Title: How can I set variables only once per block?
I have a block module that displays some data taken from XML. That module has multiple (approx. 7) blocks, each of which displays a different "view" of the same XML. Each block can be positioned independently on the page, but all of the blocks are displayed at once and all of the blocks use the same data.

Since the XML parsing code runs inside the block\_view() hook, it runs once for every block.

My problem is that the XML parsing is expensive in terms of time (not hugely so, but easily \>95% of the total module runtime), and this is a page that I want to run as fast as possible.

How can I move the XML parsing out of the block\_view() hook and run it once per page view? Is there another hook that will let me set some global variables or something like that?

```
function my_module_block_info() {
    $blocks[0]['info'] = t("My Module: block one");
    $blocks[1]['info'] = t("My Module: block two");
    $blocks[2]['info'] = t("My Module: block three");
    ...etc (~7 blocks total)...
    return $blocks;
}

function my_module_block_view($delta = '') {
    $parsed_stuff = parse_some_xml();
    switch ($delta) {
        case 0:
            $block['subject'] = t('Blah');
            $block['content'] = block_0_html($parsed_stuff);
            break;
        case 1:
            $block['subject'] = t('Yada');
            $block['content'] = block_1_html($parsed_stuff);
            break;
        case 2:
            $block['subject'] = t('Etc');
            $block['content'] = block_2_html($parsed_stuff);
            break;
        ...etc (~7 blocks total)...
    }
    return $block;
}

```

# Answer
You can use static caching in your parse\_some\_xml function. Some people consider this a cleaner, less evil solution than using global variables (but I will not get into that discussion here).

With static caching, your my\_module\_block\_view() would remain the same, but your parse\_some\_xml() would look like this:

```
function parse_some_xml() {
  static $parsed_xml;
  if (!isset($parsed_xml)) {
    // Do the actual parsing here, and store the data in $parsed_xml
  }
  return $parsed_xml;
}

```

See A Beginners Guide to Caching Data to learn more about static caching.
> 3 votes

# Answer
You can use hook\_init() to setup a global variable.

```
function my_module_init() {
  global $parsed_stuff;
  $parsed_stuff = parse_some_xml();
}

```
> 1 votes

---
Tags: 7, blocks
---


title: Testing Batch API usage with Simpletest

text:
# Question
Title: Testing Batch API usage with Simpletest
I've written a module that reads a csv of user records and imports them into Drupal 6 using the Batch API. The Batch API operations callback basically just does a user\_save(). It works fine when I test it manually. I'm now writing a SimpleTest to verify it.

What I've found is that when I run my test (which extends DrupalWebTestCase), it actually creates new users in my primary Drupal's tables, rather than into the "simpletest" prefixed tables. I suspect this has something to do with the combination of SimpleTest and the Batch API.

Has anyone experienced this before?

SimpleTest 6.x-2.11 Drupal 6.22

Edit: Adding a very simple test case that duplicates the problem. After running the SimpleTest, my primary Drupal site will have 3 new users (u1, u2, u3) created in it. The test will fail, because no users will be created in the 'simpletest\*' prefixed tables.

Module code:

```
function user_import_batch($user_data) {
  $batch = array(
    'title' => t('Importing users'),
    'operations' => array(
      array('userimport_process', array($user_data))
    ),
    'progress_message' => '',
    'finished' => 'userimport_finished',
  );
  batch_set($batch);
}

function userimport_process($user_data, &$context) {
  // Initialize
  if (empty($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($user_data);
    $context['results'] = array();
  }

  // Process max 20 users at a time
  $processed = 0;
  while ($context['sandbox']['progress'] < $context['sandbox']['max'] && $processed < 20) {
    $index = $context['sandbox']['progress'];

    // create user
    $account = user_save('', $user_data[$index]);

    $context['sandbox']['progress']++;
    $processed++;
  }
  $context['sandbox']['import_object'] = serialize($Import);

  // Finished yet?
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

```

Simpletest code:

```
class ImportTestCase extends DrupalWebTestCase {
  protected $privileged_user;

  public static function getInfo() {
    return array(
      'name' => 'User Import Test',
      'description' => 'Test',
      'group' => 'User Import Test',
    );
  }

  public function setUp() {
    parent::setUp();

    // Create and log in our privileged user.
    $permissions = array(
      'administer users',
    );
    $this->privileged_user = $this->drupalCreateUser($permissions); // user id 3
    $this->drupalLogin($this->privileged_user);
  }

   public function testAddUsers() {
     // import 3 users
     $user_data = array(
       array(
         'name' => 'u1',
         'mail' => 'u1@example.com',
         'pass' => 'password'
       ),
       array(
         'name' => 'u2',
         'mail' => 'u2@example.com',
         'pass' => 'password'
       ),
       array(
         'name' => 'u3',
         'mail' => 'u3@example.com',
         'pass' => 'password'
       ),
     );

     user_import_batch($user_data);

     // verify that the users have been created
     // this will fail, as the users will be created in the host site that is running the SimpleTest
     $imported_count = db_result(db_query('SELECT count(uid) FROM {users} WHERE name LIKE "u1" OR name LIKE "u2" OR name LIKE "u3"'));
     $this->assertEqual(count($user_data), $imported_count, 'Imported users appear in users table. Found ' . $imported_count);
   }
}

```

# Answer
> 1 votes
Running batch API in tests should work just fine, although there is an issue with the testbot.

Make sure you are always using curly braces for your tables, that's the usual issue when something like this happens. So for example `SELECT * FROM {node}`.

Edit:

Two things wrong with your code, as written in the comments.

1. You are not calling batch\_process() in your code, so the batch is never executed within the tests.
2. My initial answer was not 100% correct. You can not trigger batch runs directly within your test code. A batch requires direct interaction with the browser and it is not possible to run tested batches (simpletest is already running as a batch run). What you need to do is create a test module, implement hook\_menu() with a page callback and then call batch\_set()/batch\_process() there.

---
Tags: 6, testing, batch-operations
---


# Question
Title: Using form elements for various forms in Drupal 7
I am building a site with several forms that partly contain identical building blocks (for example a fieldset 'payment details'). Ideally, I would like to design my form elements separately and then inject them into each form. My idea was to create functions with &$form as parameter, as in the following code:

```
function payment_details(&$form) {
  $form['payment_details']['amount'] = array(
    '#title' => t('Payment Amount'),
    '#type' => 'textfield',
  );
}

```

I then call the function in my form definition.

```
transaction_form() {
  // ...
  payment_details(&$form);
  // ...
  return $form;
}

```

While the approach leads to the desired result, Drupal gives me the following warning:

> Deprecated function: Call-time pass-by-reference has been deprecated in drupal\_load() (line 1100 of C:\Wamp\www\paradise\includes\bootstrap.inc).

Maybe anyone can give me a better way to reach my goal? At least, can you guys advise on how to fix this problem? I understand from various forum posts that this is a PHP related issue, and that it can be more or less ignored for development. Do you agree?

# Answer
> 2 votes
Your function already accepts the $form variable by reference (`function payment_details(&$form)`) so you don't have to pass the $form element by reference when calling that function. Just use `payment_details($form);` in your form builder and you should be fine. Passing by reference is deprecated in recent PHP versions, so that's why you get a warning.

---
Tags: 7, forms
---


# Question
Title: Migrating files from multiple paths with the migrate module
I am trying to take a bunch of files and turn them into nodes that link to those files in my system. Now when I say a bunch I am talking about thousands, if not tens of thousands of files. So I need a way to do this which includes using multiple directories as the source. Mainly one directory with multiple sub-directories to recurse through.

So I decided to go with the migrate module. In my module setup that creates the migration script I have a schema declared for an intermediary table. This table will hold all of the path information for each file I want to import.

I then (in the install function hook) loop through the image directory recursively and gather a list of file names and paths. Then I stick the information into the intermediary table. This table is what I then import from.

The only problem is that when mapping the file fields I am unable to figure out how to get it to get the source path from each entry. It seems to want me to specify a flat path where all the files will reside and that won't work.

Is there a way to get it to get the full source path from the intermediary table?

This is using Drupal 7 and Migrate 2.2.

Here is the mapping information I am trying. The jpg\_uri field is where that source path should be coming from (I just can't seem to figure out how to make that happen).

```
$jpg_arguments = MigrateFileFieldHandler::arguments('',
  'file_fast', FILE_EXISTS_RENAME, NULL, array('source_field' => 'jpg_name'),
  array('source_field' => 'jpg_filename'), array('source_field' => 'jpg_filename'));

$this->addFieldMapping('field_image', 'jpg_uri')
     ->arguments($jpg_arguments);

```

# Answer
> 2 votes
I believe you need to pass `NULL` as the first argument to `arguments()` instead of `''`.

```
$jpg_arguments = MigrateFileFieldHandler::arguments(NULL, 'file_fast', ... etc);

```

---
Tags: 7, files, migrations
---


# Question
Title: How is it possible that neither if nor else branch gets executed here?
I'm developing one of my first drupal modules and stuck here:

```
$maxexp = db_result(db_query("SELECT max(expiration) FROM {uc_roles_expirations} WHERE UID=%d and rid=%d", $uid_befizeto, 4));
dpm('DB query finished');
dpm('me = '.$maxexp);

if($maxexp) {
   dpm('True branch');
 } else {
   dpm('False branch');
 }

```

This is a snippet from `mymodule_nodeapi`'s case 'insert'. My problem is that I do not understand why do I see the following messages after saving a node:

```
DB query finished
me =
Node blah saved successfully

```

I simply do not understand if there is no error, how it is possible that I cannot see `True branch` or `False branch` among the messages..

# Answer
It was a character encoding problem in the source file. I changed the encoding in my favorite text editor, and the code started working.
> 1 votes

---
Tags: 6, database
---


title: CSS reverted on cache clearing

text:
# Question
Title: CSS reverted on cache clearing
I am using D7 with Panels and Panels Everywhere enabled and using the Versatile Theme. I have changed the default versatile.css file to have the page-content div be 960px instead of 1020px. All of the regions are % that are created using the Builder Flexible layout since the site is still under development.

Every time I clear the cache the css at -- /sites/default/files/ctools/css/ad57ff1546b4e3e493a0d16eb09e3ad9.css reverts back to 1020px.

Seeing if anyone knows how to keep this from happening?

/\* found out what I was doing wrong. 1020 was the default width that was still being used at the General page of Variant even though I changed the default setting in the Panels Mod.\*/

# Answer
found out what I was doing wrong. 1020 was the default width that was still being used at the General page of Variant even though I changed the default setting in the Panels Mod.
> 1 votes

---
Tags: panels, chaos-tool-suite
---


title: Theme a Page Node Not All Page Nodes

text:
# Question
Title: Theme a Page Node Not All Page Nodes
I have a page of node type: Page with the name 'latest'. I was looking at a module that lets me arse about with the comments form and things and i was wanting to add some code just to that one page. Not change all the Page content type.

Im sure i added something to my template, a preprocess thingy to achieve this before. Im using Drupal 6. Could anyone point me in the right direction? thanks.

I'll go see if theming a node is the same but ive a feeling from past experience i have to add something. Knowing me ive probably still got the preprocess thingy in there. ill go check.

# Answer
I believe you are looking for template suggestions, see Drupal 6 Template Suggestions, one of the Drupal provided theme suggestions will do it for you.

I think the one you are looking for is page-node-\[node-id\].tpl.php

Alternatively you can create your own theme suggestions, see Working with template suggestions

Edit: It depends on what you want the code to accomplish if this answer is correct or not, if it's something related to display then templates may be correct, but if it's data manipulation then you may be better off with template\_preprocess\_node

Alternatively if you want to execute arbitrary code not directly related to just the theming of the node, I think you would use hook\_nodeapi or hook\_view
> 5 votes

---
Tags: theming, 6
---


title: Programmatically validate a node?

text:
# Question
Title: Programmatically validate a node?
I am programmatically creating many nodes. Obviously they have to be valid before storing them. Such `$node` objects have CCK fields mixed with custom fields.

Because the validators only set a `form_set_error()` and hardly ever return the validation-result, I have to go trough the form-api in order to know if a node is valid, or so it seems.

I call `node_validate()`, then `form_get_errors()` (which, in turn calls `form_set_error()`).

There appear to be several problems with this approach:

* `form_set_error()` sets a message with `drupal_set_message()`; for stuff like cron (a session-less user), this adds orphaned persistent error-messages to the database (they will never be printed, hence never deleted).
* the returning array of errors is created to be used in a multidimensional form array. Especially with CCK-fields, I have to dig quite deep in order to find the actual error.
* I just want to store a node, so I am not interested in a user-faced form; using the form API just feels wrong.

Is there a simpler, more elegant method?

# Answer
There aren't any other ways, as the hooks that the modules need to implement to validate a node are `hook_validate()` (if the module implements a content type) and hook\_nodeapi('validate') (for all the other modules). Those hooks get a `$form` parameter, and are supposed to call form\_set\_error() in the case there is a validation error.

The easier way to find if there are errors set for a form is to use `form_get_errors()`, which returns the array with all the errors set with `form_set_error()`, the function that is also called from `form_error()`.

In the case more than one node is validated, you would need to call `form_set_error(NULL, '', TRUE)` before `node_validate()`, and then get from `form_get_errors()` the array containing the error messages; if this is empty, there are no error messages.

```
form_set_error(NULL, '', TRUE);

// node_validate() call.

$errors = form_get_errors();

if (!empty($errors)) {
  // Some module reported an error.
}

```

Alternatively, you can use the following snippet to verify no module reported an error, after you call `node_validate()`:

```
if (!empty($_SESSION['messages']['error'])) {
  // Some module reported an error.
}

```

Before calling `node_validate()` from the cron task, you would need to set `$_SESSION['messages']['error']` to an empty array; in that way, you are sure the errors reported in the array are caused by the node validation hooks.

`$_SESSION['messages']` is the variable used from `drupal_set_message()` to store the messages passed to the function.

```
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
  if ($message) {
    if (!isset($_SESSION['messages'])) {
      $_SESSION['messages'] = array();
    }

    if (!isset($_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type] = array();
    }
    // …
  }
  // …
}

```
> 5 votes

---
Tags: 6, forms, nodes
---


title: Import LoginToboggan settings

text:
# Question
Title: Import LoginToboggan settings
Is it possible to import the LoginToboggan settings to a feature ? Logintoboggan doesn't seem to have an api either

# Answer
> 0 votes
You'll want to use the strongarm module. That will expose the variables that logintoboggan stores it's settings in to features. When building your feature it will add an option for "strongarm: variables" to the edit components section. You will need to know the actual internal variable name. You can get that by either looking at logintoboggan's code or from the field names in the settings page's html source.

---
Tags: 7, users
---


# Question
Title: Can I run bulk update for URL aliases at command line?
I have over 30,000 nodes, and bulk update is painfully slow. Is there another way to run this?

# Answer
> 3 votes
You can also use Drush for the bulk update, see this article.

# Answer
> 1 votes
I would look at the code of the path\_alias module and then optimize that. It's probably slow because it runs some checks before updating each node. If you are sure about your naming structure you might be able to an optimized query.

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