# Question
Title: How to handle Dev and Production servers having different file structure
I know you are not supposed to do this, but for reasons beyond my control the location of my web root is different on my Dev and my production server. As a result everytime I copy the database from my production server to my Dev server, all of my modules become confused and point to the wrong file location. What is the recommended way to handle this?

# Answer
If you are using Drush you can run the following commands to fix the module path problem, if you are using multisites then make sure you are in the `sites/mysite.com` directory (this must not be a symlink) before running these commands.

**Drupal 6**

```
drush eval "module_rebuild_cache();"
drush cc all

```

**Drupal 7**

```
drush eval "system_rebuild_module_data();"
drush cc all

```

(though as I've not tested I'm not sure this is needed on Drupal 7 anymore)

If Drush is new to you then here is the description from the Drush project page:

> Drush is a command line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those of us who spend some of our working hours hacking away at the command prompt.
> 3 votes

# Answer
The Alternative to the Drush approach, in the case you can not run Drush on your server, I have found to solutions for this sort of issue (when moving the modules to another directory):

1. Go to /admin/build/modules and hit the submit button.
2. Run update.php

While Drush is probably preferable, it's not always possible to have setup on your live hosting.
> 0 votes

# Answer
Absolutely essential to change the dev. server to be the same as the production server.

If you don't there will come a day when you wish you had...

Even if it is outside of your control I'd recommend making a good case to however is in charge to change the development server.
> 0 votes

# Answer
When necessary, I mimic the production server file structure using symlinks.
> 0 votes

---
Tags: caching, files
---


title: Base url issues and subdirectories

text:
# Question
Title: Base url issues and subdirectories
I have a drupal site at http://example.com and a development version of the same site at http://another.example.com/subdir. When I'm working on the development version, content that references /sites/default/files/ - such as images - doesn't work because it needs to include the '/subdir' part of the path. Setting `$base_url` doesn't work because that uses the `BASE` element's `href` attribute which doesn't affect urls beginning `/` if the `href` includes a subdirectory.

What's the best way of including the subdir in the image references? Do I need to resort to a server rewrite?

# Answer
> 4 votes
There are two things you can do here in order to try and make you site more portable.

In your templates:

* Always use `l()` for *all* links (even JavaScript links)
* If you need to reference an image in the theme use:

```
<img src="<?php echo $base_path . drupal_get_path('theme', 'themename'); ?>/logo.png" />

```

In your content:

* You do not really have a way in order to preserve uploaded content URL's unless using some form of file manager which do not create absolute links, but much rather links that get sent to drupal that redirect to the file
* If the above is not going to work for you then a modification of the rewrite rules for the drupal site sitting under the subdir is required to basically rewrite all URLs requested that start with sites/default/files/(.\*) rewritten to subdir/sites/default/files/$1

And the apache mod\_rewrite rule may look like the following.

```
# Redirect all files requests to a subdir
RewriteRule ^/?sites/default/files/(.*) /subdir/sites/default/files/$1 [R=301,L]

```

# Answer
> 1 votes
The module Pathologic can help you with this.

# Answer
> 1 votes
If you have any flexibility over the domain of development site at all, we've found that everything just works if you use:

example.com -\> production

dev.example.com -\> development

Your sites dir will work as /sites/example.com in both cases. You just need to modify your base\_url to match the domain.

---
Tags: uri
---


# Question
Title: Ubercart: Change the product display form label "SKU"
How would you change the display of SKU? (Which hook manages the product-node display?)

I need sku to output to display "Model #". on a product node page

Drupal Version 6.2x

# Answer
> 2 votes
Try String Overrides module.

# Answer
> 0 votes
Showing SKU and changing its label
Recommend to use "kulvik" user comment.

---
Tags: 6, hooks, ubercart
---


title: Drupal caching prevents cookie read

text:
# Question
Title: Drupal caching prevents cookie read
On one of my production sites I wrote a jQuery stylesheet switcher. It drops a cookie when a selection is made and uses php to select the corresponding stylesheet on pageload which overrides styles. All is great until I enable performance caching mode, whereby the cookie is ignored on each pageload. Obviously this isn't the desired effect and I can see why this is occuring: being that the pages are cached and no longer truly dynamic with respect to loading what's seen as a 'dynamically' changing stylesheet. You can change the stylesheet however upon returning to a page the initial style is applied. Just for reference I have coded the php into each page template (page-front.tpl.php and page.tpl.php) and the javascript is located in my scripts.js. The php is basically just a couple of if else statements.

Due to a large volume of traffic I have to enable caching on the site, however ideally would like to retain this style-switcher functionality. Is there a method of making an exception to the caching rule for this or will I have to disable the switcher? Would packing it into a module help?

Thanks in advance :)

# Answer
> 2 votes
I think you have have a hard time doing this with caching, since you want to create two versions of the same page.

I haven't tried this, but it should be possible to let your style.css not be an actual css file but a drupal callback that returns the styles based on the cookie. You would need to include the "stylesheet" as you would do styles for IE. You wouldn't be able to cache this, but if you really need to performance, you could do it in a php file and skip the drupal bootstrap.

An alternative option would be to let the js itself execute the styles, based on the cookie.

None of these options are ideal, but they should work.

# Answer
> 2 votes
Would it be possible to create only one version of the page? Include ALL the styles on every page (probably not ideal, but not the end of the world unless they're huge), and then use JavaScript to, say, add a body class depending on the value of the cookie?

Alternatively I like googletorp's idea of the stylesheet being a callback and not a .css file.

# Answer
> 2 votes
Using a cookie to select a cache\_page variant using memcache: http://drupal.org/node/942914. We use this for GeoIP targeting.

Using a cookie to select a mobile theme if the user is on a mobile device: http://drupal.org/node/361832#comment-4110568. Don't use this, gave some help out at one of the local SeaDUG meetings.

---
Tags: 7, caching, javascript, cookies
---


# Question
Title: Where is the best place to insert additional logout functionality?
To insert additional logic when a user logs off one might look at `function user_logout()` in user.pages.inc. This code being in a core module, you should not edit it, but works very well... for example by adding the following code to the top of the 'user\_logout()' function...

```
$last_run = variable_get('cron_last', 0);
if(time() - $last_run > 86400) {
    include_once './includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    drupal_cron_run();
    drupal_flush_all_caches();
    watchdog('user', 'cron set to run and cache to be cleared on user logout', array('%name' => $user->name));
}

```

... I get the cache cleared and cron run if cron has not run in the last 24 hrs. Okay, not ideal for cron but that's another issue.

Where is the best place to add this little snippet? I could simply implement my own logout menu item... but I'm not keen on that solution.

Thanks in advance.

# Answer
> 9 votes
Instead of modifying core, you can implement `hook_user()` in a custom module. Then you can check the `$op` parameter to see if it equals "logout". This code will run whenever a user logs out, regardless of what menu item or link they click to log out.

---

Note that this is different between Drupal 6 and 7. This question was tagged Drupal 6, but if you're using Drupal 7, or plan to later, be aware that this hook was replaced with `hook_user_logout()`.

# Answer
> 0 votes
Might want to check out the Poor Mans Cron module.

---
Tags: 7, caching, cron, users
---


# Question
Title: How can I transfer node and comment records from Drupal 6 to Drupal 7?
Is it possible to export particular nodes and comments in Drupal 6 and import them in Drupal 7? I do not want to copy the whole database and then upgrade it, but be able to move particular records.

# Answer
You could look into using the Migrate module. Although I haven't used it myself, I know that many have been using it to move content from a Drupal 6 website into a Drupal 7 website. Be aware that it is an advanced module that has no UI (that I'm aware of). It integrates with Drush and allows you to create migration scripts and run them from the command line.
> 5 votes

---
Tags: migrations
---


# Question
Title: Ubercart Marketplace - Where is the ImageField for users?
Using Drupal 6

The Imagefield is configured for products. The imagefield appears for admin but not for users. How do I get the imagefield to appear for users who are authorized Ubercart Marketplace sellers? Any help is appreciated!

Andre E.

# Answer
It sounds like you need to check the permissions (/admin/user/permissions).

If you have field level permissions then you'll want to look for your CCK imagefield for your product images under the heading "content\_permissions module." Ensure that the "view field\_YOURIMAGEFIELD" permission is checked for all users.

Also if you're using imagecache on your product images there is also a permission for that as well.

Just for general knowledge the super admin user (user 1) completely bypasses the site permissions even if the super admin is assigned a role. It's a good idea to create a new user and create a new role to assign it to. Then use this user instead of 'admin.' We create a role called 'Site Architect.'

Hope that helps!
> 1 votes

---
Tags: 6, ubercart
---


# Question
Title: Multiple axis voting system (star rating)
I tried Multiple Axis Voting System using Drupal FiveStar and Computed Field, but I am not able to understand the below 2 points:

1. Add a node reference field to the voting node type, make the targeted node type selected.
2. Setup the voting(aka.review) node type, add all needed field and fivestar fields for multiple axis voting. Remember set the "target" option to #3 field.

May anyone help me understanding this?

# Answer
> 3 votes
I think you can try Rate.

> This module provides flexible voting widgets for nodes and comments.
>
> Administrators can add multiple widgets. By default, there are 6 widget types to choose from.

# Answer
> 4 votes
The idea behind this technique, is to have a node that can be reviewed, and then create review nodes that contain the votes.

The first step you list, requires you to add a node reference field on the review node, where you can select nodes of the type that can be reviewed. That will enable uses to select what they are reviewing.

The second step is to setup fivestar for the review node. You need to add the axis that should be voted on, and which users will be able to set when creating the node.

---
Tags: 6, rating
---


# Question
Title: How do I control the "more" link from a views content pane to point to a biblio filtered page
I'm using Drupal 6. I'm trying to create a view pane that lists three biblio items matching a particular term, and then offers a link to more items filtered using the same term. Biblio allows me to access these items nicely using `biblio/term/term_name`. Is there a way to control the `more` link provided by views so that it points to this location?

# Answer
A simpler solution for this is to edit the display footer, set its input format to PHP and print the link yourself like:

```
<?php

  $term_name = 'TERM_NAME'; // set term name depending on how you filter for it
  print l('Read more', 'biblio/term/'. $term_name);

?>

```

if you are using arguments to filter the terms, then you can access the argument(s) like so:

```
<?php
  $view = views_get_current_view();
  $arg0 = $view->args[0]; // or whatever index the term name has
?>

```

Otherwise you need to use a custom module and figure out one of the hooks Views implements (e.g. `hook_views_pre_view()`)
> 3 votes

# Answer
You can select the "Rewrite output of this field" option on the More Link field and use the replacement tokens available to rewrite the url to your desired location. I believe some fields just give a "Show More Link" option. In that case, disable that option. Then add a Link field and use the rewrite tokens to craft the URL you want to send users to.
> 0 votes

---
Tags: 6, views
---


title: Ubercart: Attributes?

text:
# Question
Title: Ubercart: Attributes?
I've got an existing cart and the inventory has separate products for different weights and they're separate entries. I want the varying weights to be combined and searched by attributes. What's the best way to do this with ubercart.

I'm using drupal 6 ubercart 2.

# Answer
Ubercart 2.x has built in support for creating product classes with attributes. See the documentation for more information
> 2 votes

---
Tags: 6, ubercart
---


# Question
Title: How to proceed towards MySQL performance testing for Drupal?
We have lots of Drupal sites installed on our server. Some of the sites do have lots of views and blocks configured on it. Occasionally, one of such Drupal site (with lots of views and contents) suddenly becomes unresponsive or very slow. But rest of the Drupal sites with less contents appear to work fine during that time. We have to restart MySQL database in order to bring unresponsive Drupal site back to normal. We were thinking of setting up a periodic MySQL restart using cron.

This periodic restart option do not appeal to me very much. I want to find the cause of this problem. I suspect that it is mostly because of MySQL, but still it is a guess.

I am not experienced in the server performance issues. What is the best way I should tackle this problem? How can I confirm that it is a MySQL problem and not because of other? If it is a MySQL problem, what basic steps I should take to solve it?

# Answer
I second the recommendations of the DBTuner and Devel modules. I also agree that you should avoid restarting Mysql whenever possible. It builds up a bunch of caches in RAM and will have to start all over if you restart. You should make sure your mysql is using at least my-huge.cnf or better. This thread at Drupal.org http://drupal.org/node/85768 has some info about tuning Mysql for better performance. Always test your my.cnf changes on a dev server because Mysql config changes often break the server without warning or explanation.

Also, make sure PHP has a good amount of RAM. PHP delays can give the appearance of slow db server if you're only looking at the site in a web browser. You want it to have memory\_limit = 32M or greater (I usually do 64-126M). You don't want it crazy high though because that can start to have a negative impact on Apache's performance.

There is also a High Performance group here http://groups.drupal.org/high-performance . This is a good place to poke around.
> 4 votes

# Answer
First tool, that can be used, is Devel \- it will show there's long calls have been made.
And there's many tools for perfomancing and tuning mysql in internet.
> 4 votes

# Answer
I think if you ever need to restart MySQL regularly, especially scheduled, then there is a problem.

How often does this unresponsiveness occur? Do you have ssh access to the machine? Can you access the MySQL prompt and do 'show processlist;' ?

I suspect it is a locked table issue if a query is taking a long time.
> 3 votes

# Answer
I found the dbtuner module to be very helpful. It even suggests and provides an easy way of indexing specific fields. Give it a shot.
> 2 votes

# Answer
Next time this happens do a `SHOW FULL PROCESSLIST` in phpmyadmin/mysql. It will show what queries are running; what tables are locked and for how many seconds the query has been running for. Once you know the query, it's a lot easier to figure out whats wrong.

I'm slightly biased, but dbtuer is a pretty sweet tool for finding slow queries in views. Devel rocks for finding all slow queries.
> 2 votes

# Answer
If you're using version 7, some performance tips can be found at this post.
> 2 votes

---
Tags: performance
---


title: Configuring SSL

text:
# Question
Title: Configuring SSL
I'm using Drupal 6 and already set the SSL Certificate (with my own Certificate Authority) configuration of my apache server, and added the following redirection in Drupal **.htaccess** file.

```
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^test/home https://localhost/test/home [R=301,L]

```

When I try to access http://test/home it redirects to https://test/home correctly, but it shows a 404 error.

> Not Found
>
> The requested URL /test/home was not found on this server.
> Apache/2.2.9 (Ubuntu) PHP/5.2.6-2ubuntu4.6 with Suhosin-Patch mod\_ssl/2.2.9 OpenSSL/0.9.8g Server at localhost Port 443

Moreover, the secure pages module doesn't allow to enable secure pages.

Is there any configuration problem? Please guide me.

# Answer
I'm assuming you're hosting this on your own server? I had the same issue. It ended up being a problem with my Vhost definition in Apache. There are separate vhost definitions for http and https access (I'm not an Apache ninja, so this may not be the most efficient way, but it worked). Make sure your SSL vhost is pointing to the same directory as your normal vhost. It seems like its trying to pull your site from a different directory on your server.

After you check that, click the link in "If this test has failed then go here".

Also, you shouldn't have to use an .htaccess rewrite if you're using the Secure Pages module.
> 5 votes

# Answer
There are separate vhost definitions for 80 and 443 as Chaulky points out. Apache setup is a little more complicated when dealing with SSL. Your vhosts should be something like this:

```

<VirtualHost *:80>
  ServerAdmin webmaster@example.com
  ServerName www.example.com
  ServerAlias example.com
  DocumentRoot /var/www/drupal6

  <Directory /var/www/drupal6>
                Options -Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

  ErrorLog /var/log/apache2/error_example.com.log
  CustomLog /var/log/apache2/access_example.com.log combined
  ServerSignature On

  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel warn
</VirtualHost>

<VirtualHost *:443>
  ServerAdmin webmaster@example.com
  ServerName example.com
  ServerAlias www\.example\.com
  DocumentRoot /var/www/drupal6

  <Directory /var/www/drupal6>
    Options -Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>

  ErrorLog /var/log/apache2/error_example.com.log
  CustomLog /var/log/apache2/access_example.com.log combined
  ServerSignature On

  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel warn

  # Put SSL stuff in here
</VirtualHost>

```

So you have one for port 80 and one for port 443.

Check your ports.conf to make sure that you have something like:

```

  Listen 443

```

Unless you have a good reason not to, I would ditch the securepages module altogether and just run the entire site in SSL mode. By the look of the rule in your .htaccess, that's what you're trying to do anyway.

If you wanted to redirect all non-secure traffic to secure, you could use this version of the non-secure vhost:

```

<VirtualHost *:80>
  ServerAdmin webmaster@example.com
  ServerName www.example.com
  ServerAlias example.com
  DocumentRoot /var/www/drupal6
  Redirect / https://www.example.com

  ErrorLog /var/log/apache2/error_example.com.log
  CustomLog /var/log/apache2/access_example.com.log combined
  ServerSignature On

  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel warn
</VirtualHost>

```

Bit of a long one, sorry, but hopefully this is what you're looking for!
> 4 votes

---
Tags: 6, ssl
---


# Question
Title: Loading a specific node revision for view
I am trying to load a specific revision for viewing by the end user. Drupal 7.

I have the following in my .module ;

```
function mymodule_node_load($nodes, $types) {
  if ($nodes[821]->vid != 5928) {
    $nodes[821] = node_load(821, 5928);
  }
}

function mymodule_node_view($node, $view_mode, $langcode) {
   $node = node_load(821, 5928);
}

```

If I dpm/var\_dump the node after doing this, its perfect and is the correct revision but when it comes to rendering, the page chooses the older revision. So something is happening between these functions and the page rendering. What is it? And how can I stop it?

Thanks in advance, much appreciated.

**EDIT** Anybody know if there is a hook load order chart somewhere? That would be super handy.

**EDIT #2** It seems that even the node.tpl.php has the correct revision but what is displayed is not the correct revision ... See image (body\['und'\]\[0\]\['value'\] != what is displayed.)

**EDIT #3** Ok, so I worked out how to do it (code below) its an awful solution and its because of this that I am going to have a look at the Workbench module because I think it might just do what I need. Thanks for all the help!

```
/**
 * Implements hook_node_view_alter().
 */
function mymodule_node_view_alter(&$build) {
  $latest_revision = _get_latest_published_revision($build['#node']);

  if ($latest_revision) {
    $build['#node'] = node_load($build['#node']->nid, $latest_revision);
    node_build_content($build['#node']);

    $build['body'] = $build['#node']->content['body'];
  }
}

```

# Answer
What mongolito404 says is right; `hook_node_load()` and `hook_node_view()` are not thought to be used to alter the fields already loaded of the node object.

As the documentation reports, they should be used to add additional information.
The documentation of those hooks contains the following sentences:

> This hook should only be used to add information that is not in the node or node revisions table, not to replace information that is in these tables \[…\]. \[**hook\_node\_load()**\]

> The module may add elements to $node-\>content prior to rendering. \[**hook\_node\_view()**\]

If you really want to show a different revision of a node basing on some conditions, you could implement hook\_menu\_alter() to alter the menu callback that handles `node/%node`, and replace it with your own menu callback that verifies which revision of the node should be shown, and shows it.
> 1 votes

# Answer
I think you have misunderstood the usage and intent of `hook_node_load`. What you do is changing the revision ID (vid) after the node has been fully loaded. Same for `hook_node_view()`, you are not supposed to replace `$node` in there, but add additional content to render to `$node->content`.
> 1 votes

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


# Question
Title: I created a view of a page and a block, but cannot find either. Where are they?
I created a page view, but when I type in the address for it, it shows "Page not found". When I try to put the block where I want it to go, it doesn't show up, not even under disabled blocks. What step did I miss?

# Answer
> 5 votes
Did you click on Save button for views?

# Answer
> 0 votes
Are you sure you associated an URL with the view, or you are typing the correct URL?
If the URL requires a parameter (e.g., the node ID, the user ID), it is possible you entered a value that is outside the range of the possible values; for example, if the parameter is the node ID, and the higher node ID is 500, when you use 510 for that parameter, you would get a "not found" error message.

---
Tags: 7, views, blocks
---


title: WSOD on administration pages

text:
# Question
Title: WSOD on administration pages
Here are the facts:

* Made a clean install of Drupal 6.20
* Installed and enabled Admin Menu module

From this point on I can't access any `admin/*` page however I can access to both `node/*` and `user/*`...

PHP log:

```
No entries

```

Apache error log:

```
No entries

```

Apache access log:

```
127.0.0.1 - - [10/Mar/2011:16:22:16 +0000] "GET /drupal_testes/ HTTP/1.0" 200 5771
127.0.0.1 - - [10/Mar/2011:16:22:14 +0000] "GET /drupal_testes/admin HTTP/1.1" 200 -

```

DB table watchdog:

```
Nothing serious...

```

And that's all, for a single access to `/drupal_testes/admin`...
Disabling admin\_menu (at the system table) does work. Also, as a side note, when I go to `admin/build/modules` and try to enable Admin Menu again the page will take forever to load and end in a WSOD.
After that if I go to `drupal_testes/node` the admin\_menu is active and working, except for the `admin/*` pages.

I'm aware of WSOD Walkthrough but none of the reasons seems to apply this case..
Any idea why can this be happening?

---

**Edit #4**

* Exactly the same behaviour when installing Token

**Edit #5**

* Installing CCK, which in theory is much heavier than Token or Admin Menu, presents no problems.
* Flushing the `cache_*` tables changes nothing.
* Increasing php.ini `memory_limit` didn't make any difference...

---

Although the problem is solved by disabling the offending modules, the goal is to have them active and working properly...

# Answer
> 4 votes
If you just started a new site / doesn't contain any data yet as you seem to indicate in your question, it may be faster to reinstall Drupal than search for the source of the WSOD.

---

Otherwise, you could have a look in the database directly:

* first, check the **watchdog table**: it may have error messages that don't show up in Apache and PHP logs
* then, **empty the caches** by truncating every table named `cache_something`
* then if you're sure this module is the one that caused the problem, you can **edit the list of enabled modules** in table `system`: find the module in the list and change its `status to "0"`

But if you make any modification directly in the database, make sure to save a backup first, just in case ;-)

# Answer
> 1 votes
Make sure your PHP memory limit is set to 32 MB (or greater), and that you have output buffering enabled.

# Answer
> 0 votes
I don't know if this is what is happening in your case, but a BOM signature present before the starting `<?php` is difficult to be seen. I had a problem with a module, and it came out that the WSOD was caused by the BOM signature added by the editor I was using, which then didn't show when I edited the file with my usual editor. I then discovered that the editor was set to add the BOM signature by default.

There are also some Unicode characters that have a purpose similar to a space, but they are not show on some editors. This happened to me too, and I was not able to understand the reason of the WSOD until I didn't post the content of the file in a forum, and used Firefox to see that forum page.

---
Tags: 6, wsod
---


# Question
Title: Display the title of related nodes from taxonomy in block
How can I display the title of related news in a block shown in node page?

For example, I create the content type "news", and add "news" nodes that have taxonomy terms taken from the same vocabulary; now I want to show the list of the related node basing on the taxonomy terms associated with the nodes.

How can I display this bock only for "news" nodes?

# Answer
If I understand your question correctly, you can just use Views to accomplish this.

To display a block that lists other node titles with related taxonomy terms:

1. Create a Block View
2. Add the field `Node:Title` (make it link to its node)
3. Add the argument `Taxonomy: Term ID`
4. Configure this argument as follows:

> * Check `Provide default argument`
>     * Select `PHP Code`
>     * Add the following code:

`$node = node_load(arg(1));
if($node) {
if ($node->taxonomy) {
foreach($node->taxonomy as $term) { $terms[] = $term->tid; }
return implode('+',$terms);
}
else {
return;
}
}
else {
return;
}`

> * Check `Allow multiple terms per argument`
>     * Check `Reduce duplicates`
5. Now you need to add the second argument in order to exclude the current node from the list. Click \[+\] button of the arguments section.
6. Select `Node:Nid`
7. Set the "Action to take if argument is not present" to `Provide default argument`
8. Set the "Default argument type" to `Node ID from URL`
9. Check `Exclude the argument`
10. Save your view

You can customize this however you like, such as filtering to a specific content type (ie "News"), can filter by post date, sort by: post date, random, etc.

For a whole discussion on this see http://drupal.org/node/65375

(Sorry for the poor code formatting, not sure how to format code inside a blockquote and list)
> 3 votes

# Answer
The context module will help you with that. With it you can show blocks on selected node types, views etc.
> 2 votes

# Answer
To create a list of related terms, Laxman's answer is the better way. To show this list only at content type news you can use the Context module as said in googletorp's answer.
> 0 votes

---
Tags: taxonomy-terms, blocks
---


# Question
Title: How to order a node's taxonomy terms hierarchically?
Are the terms in a node's taxonomy array ordered hierarchically by default?

If not, what is the most efficient way to do so?

# Answer
No they are not ordered hierarchically by default...

In order to do it yourself you could take a look at the following functions: taxonomy\_get\_parents() and taxonomy\_get\_children().

Here is a great article with nice examples: http://davidherron.com/content/improving-navigability-drupal-taxonomy-hierarchies
> 5 votes

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


title: Distributing nodes across drupal sites

text:
# Question
Title: Distributing nodes across drupal sites
I'm investigating how to create a scalable drupal system where nodes can be shared across different sites. In order to support future growth, it is likely we will need to "plug in" more servers/sites into the network.

I was thinking that this would be best achieved with a central site for storing the master records, users, and permissions, and then the slave sites would hold copies of these where relevant. Not all sites will need all the nodes, only those that are linked.

Alternatively, the central site could store which site has the master record. That might make it easier to grow. Thinking of node id's, the end solution needs to cater for the fact that these numbers could easily hit the millions.

It may be a crazy idea and maybe Drupal is not the right platform for this too.

Any ideas?

UPDATE: The concept is similar to that of sharding and map reduce (my basic understanding that it), yet my biggest concern are the node id's. If the system hits the number of users/groups/nodes we are looking at, we could hit the nid int limit and experience performance issues well before that point too. So a distributed model seems to be the best direction.

# Answer
Normally with drupal you would not have several databases each with their own fragment of the database, and combined you have a whole site.

With **drupal 7**, drupal now supports database masters and slaves from within the application. What this means now is say you need 3 database servers to support your sites non-functional requirements (availability, performance etc), you can now add:

```
<?php
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb1',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver1',
);
$databases['default']['slave'][] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb2',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver2',
);
$databases['default']['slave'][] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb3',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver3',
);
?>

```

This definition provides a single "default" server and two "slave" servers. Note that the "slave" key is an array. If any target is defined as an array of connection information, one of the defined servers will be selected at random for that target for each page request. That is, on one page request all slave queries will be sent to dbserver2 while on the next they may all be sent to dbserver3.

The above is straight from the docs ;)

I would recommend the above approach as this is a *supported* configuration, if you decide to create your own custom drupal schema or load splitting algorithm - you now have to support it.

With **drupal 6** \- you are pretty much forced to use pressflow. Pressflow is a performance based fork from the drupal code base that tries to keep 100% API compatibility with drupal. Lullabot wrote an awesome article on database replication with pressflow 6.

It turns out lullabot released their views 3 slave query module on github as well, fork away!
> 4 votes

---
Tags: performance
---


title: Altering Nodecomment $links

text:
# Question
Title: Altering Nodecomment $links
I am trying to alter the "reply" links added to Nodecomment comments when the nodes are listed beneath the topic. The problem I have is that I want users to be restricted to the inline submit form, but Nodecomment is adding links to the standalone reply page.

While trying to ovveride the links using hook\_link\_alter(), I ran into an issue with Nodecomment comments are treated much like regular comments in that hook\_link\_alter() doesn't seem to be run on them. Here is an example:

```
/**
* Alter module links.
*
*/
function mymodule_link_alter(&$links, $node) {

    // This is an example of altering links that works as expected
    if (isset($links['comment_add']) && node_access('create', $node)) {
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'title' => t('Link altered'),
        'href' => 'http://example.com',
      );
    }

    // This is an example of altering nodecomment links failing.
    // When rendering a list of topic replies, the comment_reply link
    // will not be altered.
    if (isset($links['comment_reply']) && node_access('create', $node)) {
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'title' => t('Link altered'),
        'href' => 'http://example.com',
      );
    }
}

```

I am looking for solutions which can (ideally) be packaged in the site's custom module rather than theme.

# Answer
> 2 votes
Reading the documentation for hook\_link\_alter() I find the following sentence.

> Perform alterations before links on a node or comment are rendered.

The hook implementation you are using is missing the last argument: the definition of the hook given by the documentation is `hook_link_alter(&$links, $node, $comment = NULL)`.

Looking at the code of comment\_render(), which is the function that renders all the comments of a node, you can notice that `hook_link_alter()` is invoked right after the data is loaded from the database (and after `hook_link()`, of course).

```
if ($comment = db_fetch_object($result)) {
  $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
  $links = module_invoke_all('link', 'comment', $comment, 1);
  drupal_alter('link', $links, $node, $comment);

  $output .= theme('comment_view', $comment, $node, $links);
}

```

`hook_comment` is invoked from theme\_comment\_view().

```
if ($visible) {
  $comment->comment = check_markup($comment->comment, $comment->format, FALSE);

  // Comment API hook
  comment_invoke_comment($comment, 'view');

  $output .= theme('comment', $comment, $node, $links);
}
else {
  $output .= theme('comment_folded', $comment);
}

```

`hook_comment()`, which is invoked with a call to `comment_invoke_comment()`, is not called for comments that are not visible.

The implementation of `hook_link_alter()` you created should at least check which comments it is altering, if it is supposed to alter only specific comments. At least, it should check the last parameter (`$comment`) is not `NULL`; if that happens, the hook is invoked to alter node links, which is not what you want as you need to alter comment links.

# Answer
> 0 votes
If they are rendered like Drupal comments why don't you use hook\_comment()?

Here's a kick-start:

```
function mymodule_comment(&$a1, $op) {
  if ($op === 'view') {
    // $a1 is the comment object
  }
}

```

---
Tags: 7
---


# Question
Title: How to output form element values as text?
On a node edit form, I want to make certain fields be non-editable by all users but the values stored in them to be visible on the form. My thought was to just print them out as text instead of in an HTML form element. What is the best way to accomplish this?

To provide some context, these values are populated via a migration and should not be edited on the site.

# Answer
> 4 votes
Changing a form field to a markup element creates problems if the form field is checked by a form validation handler or a form submission handler: `#markup` elements are not passed in the `$form_state['values']` array, which contains the current values associated with the form fields (and which is the array used by the form handlers—both the validation and the submission handers). This method works for form fields that use `#element_validate`, as `#element_validate` is also used from the `#markup` form fields.
If you are sure there aren't form validation handlers that check the value of the form fields you want only to show, then you can adopt this method. As third-party modules could add form validation handlers for those fields, I would not suggest to adopt it, if not in the case the form fields are created by a custom module you created, and no other developers will alter the form fields added by your code (or alter the form created by your code).

Using `#attributes` to make a field read-only is not a secure method (as Berdir pointed out); to be sure the form field values are not altered, you should compare them with the value contained in the form before it shows (which means to check the values contained in the `$form` array). This method has still problems with the form validation handlers (and form submission handlers) because other modules will act as those values are not read-only; only your code will act like as those values are read-only. The other reason to not adopt this method is that is "easier" to add the `#disable` attribute to a form field.

Another method is to change the form field type to `#hidden`. If you choose this method, then you need also to render the form field value using `#prefix`, and `#suffix`.

```
$form['field']['#type'] = 'hidden';
$form['field']['#prefix'] = '<strong>' . t("Field title: ") . '</strong>' .
  check_plain($form['field']['#default_value']);

```

As side note, if those form fields don't need to be visible to users, but they must be present in the `$form_state` array because other modules (including the one that created the form) implement form handlers, then you can change the form field type to `#value`.

# Answer
> 1 votes
You can use the `yourmodule_form_alter` to change fields `#type` from textfield to markup.

---
Tags: forms
---


# Question
Title: How to determine if the current page is a search results page?
How can I determine from within a module or theme if the current page is an Apache solr search results page?

# Answer
> 6 votes
If you're trying to determine from a module then you can check if the page is the search results page via the path arguments using the arg() function.

```
if (arg(0) == 'search') {
  TRUE
}
else {
  FALSE
}

```

# Answer
> 2 votes
From a theming point of view you could simply use

```
<?php if ($search_results) : ?>
    <!-- Do this on search results pages -->
<?php endif; ?>

```

`$search_results` should only return true if you are on a search results page.

If you're looking into styling the results themselves you might want to look into search-result.tpl.php

# Answer
> 0 votes
If you are looking to find if solr has been searched you can use the apachesolr\_has\_searched() function.

This won't indicate if you are on a search results page, as once you start using solr views the definition of a search results page is fuzzy, but it can tell you if a solr search has been performed.

Just for reference apachesolr\_static\_response\_cache() will give you solrs' response, and apachesolr\_current\_query() will give you information on the query.

# Answer
> 0 votes
To verify if a page is a search page, you should verify the first path element of the current URL is `search`, and the second path element is the name of a module that implements `hook_search()`. (I used a temporary variable, and added extra parentheses just to be make the code more readable.)

```
$bool = ((arg(0) == 'search') &&
  ($module == arg(1)) && module_invoke($module, 'search', 'name')
);
if ($bool) {
  // The page is a search page returned from apachesolr.module.
}

```

In the specific case, considering that you want to verify if a page is a result page returned from apachesolr.module, the code can be simplified as follows:

```
if ((arg(0) == 'search') && (arg(1) == 'apachesolr')) {
  // The page is a search page returned from apachesolr.module.
}

```

The reason the generic code can be simplified is that you know the name of the module, and that module surely implements `hook_search()`.
The generic code verify the value returned by `hook_search()` when the last parameter is equal to `"name"` because there are modules that implement `hook_search()` only partially. At least that what I discovered when I was debugging the code of OpenSearch Feed.

# Answer
> -1 votes
In case you are talking about a theme or module you could check the current URL/path if it begins with "search".

---
Tags: 7, search
---


# Question
Title: Does it make sense to develop a fantasy sports management system by creating or extending entities?
I am considering building a fantasy sports management system with Drupal. The system will need content, so that's taken care of with the standard Drupal system. However, does it make sense (or even possible) to create new entities that represent players, teams, leagues, stat-lines, etc?

I have built systems like this in the past (.NET) and it's difficult for me to wrap my mind around the idea of combining content nodes with players, teams, and stats. There are many fields that are exclusive to each type of node/entity and the sheer volume of players and stat data will push the node tables to crazy levels.

I haven't messed with Drupal 7 entities (which I believe abstracts nodes, users, and taxonomies), but I'd like to hear opinions if this concept is possible.

# Answer
> 2 votes
Regarding the nodes table getting large: if you have a lot of nodes, the node table will be large. If you have a lot of players and store them in their own table, then the players table will be large. If you have a lot of data objects, you have a lot of data objects. So, now that the obvious has been said, the question arises as to how much content will be stored in nodes that isn't player content? If you expect a lot, you could argue for normalizing the players out of the node table. On the other hand, keeping everything in one node table gives you quick and built-in access to all the functionality that comes with CCK and Views. From my own experience, Mysql can handle literally millions of rows in a single table without much effort.

**Edit:** On the other hand, you can make a good argument that if these nodes will have a lot of fields that are inherently Player attributes, it would be faster to store all that data in one table than making a lot of joins to bring in the CCK fields. The trade off would be you'd need a lot more development time.

# Answer
> 3 votes
Drupal 6 has a module called League Site that might be useful to have a look at... I don't think it has been ported to 7 yet but it has an awful lot of functionality for league sports right out of the box.

# Answer
> 2 votes
I'm actually building a similar fantasy sports game thingy using Drupal and I gotta say I don't regret it one bit. The main advantage as far as I'm concerned is being able to abstract tons of the heavy-lifting by using standard Drupal functionality and then using custom modules to glue things together when necessary and add extra stuff.

Using nodes and node references helps organize your game and makes interacting with and manipulating the data much easier and using views for example makes finding what you want and displaying it a million times easier too.

Do it! It will give you a huge productivity boost and if you know your way around a couple hooks you should be able to fill in the blanks for stuff Drupal won't give you that easily.

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


title: Building a Web App using Drupal

text:
# Question
Title: Building a Web App using Drupal
I'm looking at building a Web Application on the Drupal framework. Does anyone know of an existing drupal profile installation that has this viewpoint?

For example, I've been building features for Open Atrium and I'm familiar with some of the concepts and modules this contains. However, Open Atrium does not really satisfy the concept of clients having a profile and creating projects with subscriptions.

So in essence, I'm looking for a package similar to Open Atrium, but satisfies a web application development. Think of it more as building web tools like Basecamp or Freebooks, but using a base platform to get there.

Any ideas?

# Answer
> 2 votes
Creating your own install profile doesn't need to be a big project in itself, especially for Drupal 7, that has simplified making install profiles. Features also helps a lot, making it easy to save settings, content types, views etc in a module.

All you really need to do in the install profile is to

* Enable modules
* Save settings
* Enable blocks (maybe)
* Create content (maybe)

I suggest that you build your own install profile that fits your needs, instead of trying to find one. You could start out with how it's done in Open Atrium, and just edit it to fit your needs.

# Answer
> 0 votes
In my opinion, building web apps with drupal is not really a good idea, but it depends upon the size of the application that you will be seeing in the end.

If you can clarify what kind of web application we might be talking about then I can give a more suitable answer.

---
Tags: installation-profiles
---


# Question
Title: "Node: Created day" mismatched, not reflecting the actual created day
Views Version: 7.x-3.0-alpha1

I was trying to create a blog archive view, like blog/yyyy/mm/dd, where blog/2011/03/10 is supposed to display all posts created on 2011, March 10th. However, the page **blog/2011/03/10** actually displays all posts created on **2011, March, 11th**, one day advanced to the supplied day argument.

How to reproduce the bug:

1. clean install, enable modules.
2. create blog content type, generate dummy contents.
3. create a view:

```
  * Arguments:
        o Node: Created year
        o Node: Created month
        o Node: Created day

  * Path: blog

  * Filters
        o Node: Published Yes
        o Node: Type = blog

```

The year, month arguments show correctly, **just the day is wrong, always one day prior to the day argument.**

Can anyone point me to what went wrong?

# Answer
Actually had this bug, but with views 2 on drupal 6, and instead of going forward a day, our view was going backward a day.

Have you tried updating to --dev to see if the issue still exists? I know a lot of patches have been committed since that alpha was released.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to expand the fieldsets in node-add form?
When I am adding new node by `admin/content/node-type/story`, there are a lot of settings ordered by groups: *Submission form settings, workflow setting, comment settings*. But all these fieldsets are all by default collapsed.

My question is: how to make them all default to expanded?

# Answer
> 4 votes
I believe you have one of two options...

1. In Code: Have a look at hook\_form\_alter() and modify the applicable field groups to be `$form['the_form_fieldset']['#collapsed'] = FALSE;`
2. In UI: Modify the CCK types form. Go to your content types, click manage fields on the one you want and then select the 'Manage Form' tab.

Hope that helps!

# Answer
> 0 votes
Apart from implementing `hook_form_alter()` to collapse the form fieldsets present in the node edit form, you can also install and use the Fieldset helper, which is a module that remember the status of the fieldsets, and restore it every time the page containing them is viewed; this means that if you collapse a fieldset, that fieldset will be always shown as collapsed.
As alternative, you can install Override Node Options that, as secondary feature, it also allows selected field sets to be set as collapsed and/or collapsible.

---
Tags: 7, forms
---


title: Can I use simple XML to feed views?

text:
# Question
Title: Can I use simple XML to feed views?
I want to use the power of views to handle my data which comes from simple xml representing just a grid resp table

```
<list>
  <listpos id="12312">
    <foo>attr1</foo>
    <bar>attr bar</bar>
    ...
  </listpos>
  <listpos id="124412">
    <foo>attr 2</foo>
    <bar>attr barxy</bar>
    ...
  </listpos>
  ...
  ...
</list>

```

So the main task is to display that table sortable, exclude some columns, filter and search etc.

Is this possible with views? It would be handled by a plugin i guess? Or are plugin only for output? (I know of the json, atom etc plugin / modules.)

I also tried the feeds module plus xml / xpath parser and let the importer create the nodes so a view can display them. But I have to delete them anyway after user logs out because it's sensitive data and should not be kept on the webserver.

And what about combining this data with other sources i.e. join with a node table?

# Answer
> 2 votes
There is a module for this: XML Views.

# Answer
> 2 votes
The best way to do this would be

1. Write a module using simple XML library that extracts data from the xml
2. Store that data into nodes
3. Use views to show that data

Advantages Using this approach

1. No overhead of reading the xml again and again for visitors
2. Say if XML structure changes, you won't have empty or error in your view

In my experience parsing XML every time is very expensive.

> But your case is different as xml data is sensitive and needs to be erased from the server every-time, a user logs out.

So creating nodes and deleting them is not a very smart step.

The best way would be to create a custom module using simple xml library and to not use views at all. Store that data in temporary table, show them using your custom module or custom sql query then using the user hook deleting the table and xml, as the user logs out.

# Answer
> 1 votes
That's not entirely true. Views can use handlers which do not rely on SQL. http://drupalmodules.com/module/entityfieldquery-views-backend is an example of a module which purports to do something like that. I'm sure there are some other ones. http://developmentseed.org/blog/2009/feb/05/extendr-flickr-and-views is an interesting case study of something similar as well.

That being said, it's probably not a simple task.

# Answer
> 0 votes
If you want views to access your XML data, you would need to store it in a database. All that views really does, is to create SQL for you, and provide some different theming functions for outputting the data.

There are some modules that can help you with this. Since you have custom data, the data module is probably the best fit. This would keep the data in a custom table.

You could create a cron job, to delete entries older than x hours/days to make sure you don't store the data permanently. It's a bit cleaner this way and the best option I can think of.

---
Tags: 7, views
---


# Question
Title: Printing a content pane with Printer, Email and PDF versions Module
I'm trying to determine how to add a content pane with an argument to a custom tpl.php file that is adding some other things to the print version. I've done this before with a block, adding in the region that I needed to print out with the block, but in this case I don't think I can just print out "content\_bottom" etc.

# Answer
> 1 votes
Example code taken from Programmatically display panels page

```
$node = node_load(array('type' => 'panel', 'title' =>'Your Node Page Title'));
$panel_node=node_view($node, FALSE, TRUE, FALSE);
print($panel_node);

```

---
Tags: theming, panels
---


# Question
Title: How do I allow users to determine which other users can edit their content?
I'd like to let users specify which other users may edit their content. Basically a user would be able to create a piece of content, which they are then allowed to edit but no other users can edit (accept "admins"). This is all standard Drupal stuff so far and very easy. But now I'd like to let the user give permissions to other specific users to edit the content they created. So, the "creator" can now assign "editors", letting other users edit the content the original user created.

In case this isn't quite clear yet, here is a use case...

A site sells subscriptions which allow privileged users to create a Project on the site (Project in the sense of a software development project). The user who purchased the subscription can now create nodes of various content types that make up the content of the Project. But since no one likes to work alone, they can invite others to their Project. The invited users can edit any content created by the user who purchased the subscription.

So... how do I allow a user to specify certain other users which can edit his/her content and give those selected users edit permissions on all nodes created by the original user?

# Answer
Node access user reference worked for me, and was quite easy to use from the users perspective.
> 3 votes

# Answer
I would suggest looking at ACL too. It provides an API that allows you to configure which users have access to which nodes. The also mentioned Content Access module provides a User Interface on top of that, which is however targeted at administrative users I'd say. So it might not work well for what you plan to us it.

It shouldn't be that complicated to write a custom user interface for your specific use case on top of ACL, however.
> 2 votes

# Answer
You can use Content Access \+ ACL, but carefully read instructions.
Also i can recommend Rules modules, there you can control flows of node and it's access (but you should have "little" knowledge of php).
> 1 votes

---
Tags: nodes, users
---


# Question
Title: Remove specific stylesheets from a given page
Adding a stylesheet to specific pages is easy: implement `hook_preprocess_page()`, call `drupal_add_css(...)` and set `$vars['styles'] = drupal_get_css()`.

---

But what is the proper way to *remove* a stylesheet (or in my case, all "media=screen" stylesheets) for a specific page, without interfering with the caching system ? (e.g. not some regex applied to the output)

You can't just do `unset($vars['css']['screen'])` because `$vars['styles']` has already been generated at this point and there exists no `drupal_remove_css()` function.

# Answer
> 8 votes
This seems to be the cleanest way, in `hook_preprocess_page()`:

```
$css = drupal_add_css();
unset( $css['screen'] );
$vars['styles'] = drupal_get_css($css);

```

---
Tags: 7, theming
---


title: Force all links to be absolute

text:
# Question
Title: Force all links to be absolute
I've a custom module I'm sending the content of node and views by email. The module first render the node/view and wrap the results around common template.

But when my views and node content are build, they contain links are relatives. I'm looking for a way to force these links to be absolute (ie. with domain and protocol).

The url() and l() functions can be used to output absolute links, but I don't see a way to force this behavior on all links. I'm planning to process the content as an HTML string to extract all links and complete the URL when required. But this doesn't seem very efficient.

Is there another way to ensure absolute URL ?

Here is the code used to render the content for nodes and views:

```
//For nodes
$node = node_build_content($node, FALSE, FALSE);
$node->body = drupal_render($node->content);
unset($node->teaser);
node_invoke_nodeapi($node, 'alter', FALSE, FALSE);
$content = $node->body;

//For views
$content = $view->preview($display_id, $arguments);

```

# Answer
> 3 votes
Have a look at this module: Pathologic

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.

# Answer
> 0 votes
How about adding the BASE tag to your page.tpl.php:

```
<base href="http://www.yourooturlhere.com/" />

```

See: http://www.w3schools.com/tags/tag\_base.asp

---
Tags: 6, uri, navigation
---


# Question
Title: What are effective optimization techniques for Views 3?
I have been doing a bit of profiling on a site I am working on which extensively uses views.

Views takes up about 2/3 of the processing time even with the views caching on. Are there best practice ways to speed up views, or things which are known to cause performance hits.

I should add that the views are solr views, so this is a question mostly about the views architecture rather than optimizing queries.

Have tried using APC, but it didn't change the execution time much.

# Answer
> 2 votes
You first should find out where the performance bottleneck is.

* Is it the executing of the query
* Is it the rendering of the view
* Is it a specific function

See http://drupalperformanceblog.com/drupal-xhprof-profiling about the article.

Once you have the problem it's possible to fix it. You wrote that you had enabled views caching: Which kind of caching output or query cache?

# Answer
> 2 votes
*Using advance caching techniques will not only improve query intensive views but will improve overall performance of the website.*

But the above can be a separate issue.

First try to indentify the problem as stated by @Daniel Wehner. Then again also look at the issue queue of the view3 to see it has any conflicting module, that is slowing down the query.

Also disabling some modules and trying to see the performance difference can help you identify the culprit. It has happened with me. A facebook module was making my views very slow and the page rendering time was awfully high.

---
Tags: views
---


# Question
Title: List outline of books related to another book by a node reference field
I am using the book module with four content types: A, B,C and D.

A is the content type for child pages and the rest are allowed in book outlines.

I also have a node reference field in A that allows users to select nodes of type A related to the one they are creating.

I am trying to use views to display all the nodes that are related to a certain type A node and also display the outline of these related nodes.

E.g. viewing Book A.1 related topics and their outline:

* Book A.1
    + Book A.2
        - Page A.2.1
        - Page A.2.2
    + Book A.3
        - Page A.3.1
        - Page B.3.2
        - Page C.2.2

I have gotten as far as displaying all the related nodes to a certain node but I am not being able to display their outline.

Any help/critics appreciated.

# Answer
> 1 votes
Have you tried views to create the outline.

A simple custom module will also do the trick and then you can use the generated result to show in the block as outline. In my opinion this is the best and fastest possible way to do your job.

---
Tags: 7, views
---


title: Customising field container

text:
# Question
Title: Customising field container
I've created a cck field formatter. The field outputs uploads from filefield into embedded iframes that link to google docs for display. It currently outputs:

```
<div class="field field-type-filefield field-field-documents">
  <div class="field-items">
    <div class="field-item odd">
      <iframe src="http://docs.google.com/viewer?url=http://example.com/2011/sites/example/files/session/documents/brighton_online.doc&embedded=true" style="width:470px; height:296px;" frameborder="0"></iframe>
      <p><a href="http://example.com/2011/sites/example/files/session/documents/brighton_online.doc">Download the document</a></p>
    </div>
    <div class="field-item even">
      <iframe src="http://docs.google.com/viewer?url=http://example.com/2011/sites/example/files/session/documents/sample.pdf&embedded=true" style="width:470px; height:296px;" frameborder="0"></iframe>
      <p><a href="http://example.com/2011/sites/example/files/session/documents/sample.pdf">Download the document</a></p>
    </div>
  </div>
</div>

```

I would like to edit the html outside the contents of the .field-item. Is it possible to do this in the module or do I have to create a custom theme tpl for it?

# Answer
You should override the field template content-field.tpl.php to do that. The default template is usually found in /sites/all/modules/cck/theme/content-field.tpl.php.

Be aware that this will override the template for every field that is rendered, not just your custom formatted fields. In theory, you can build logic into the template that switches its output depending on the field type. However that is a bit of a hack; IMHO, all html output that is specific to your formatter, should be generated by the formatter itself and should stay inside div.field-item. Imagine that all formatters would start overriding content-field.tpl.php - that would create a mess because you never know which module is going to 'win' the override battle.
> 1 votes

# Answer
I'm often using the excellent module Custom Formatters for this kind of purpose. Simple and clean.
> 2 votes

# Answer
**Edit**: I see 2 other answers have been posted while I answered. In this case, the most you can take from here is using Semantic CCK.

The easiest way to do this is to use the Semantic CCK module. It allows you to override the markup per field without additional templates.

However if you want to keep it all in your module, then you need to implement to have hook\_theme() implementation that returns the definition for content\_field and return the needed markup.

Your hook\_theme implementation would looks something like this:

```
mymodule_theme() {
  return array(
    'content_field' => array(
      'arguments' => array('element' => NULL),
    )
  );
}

mymodule_content_field($element) {
...
}

```

You can also use hook\_theme\_registry\_alter()
> 1 votes

---
Tags: 7, entities, files
---


title: What is the URL to set the admin theme?

text:
# Question
Title: What is the URL to set the admin theme?
The URL to change the admin theme isn't the same in Drupal 7 compared to 6. What is the new URL?

# Answer
> 10 votes
Its at the bottom of the 'Appearance' page (admin/appearance), in the section labeled 'Administration Theme'.

---
Tags: 7, uri
---


title: How do I get backslashes to save?

text:
# Question
Title: How do I get backslashes to save?
Everytime that I type a backslash into a textbox on my drupal site (in content editors, administration pages, you name it; I mean *any* textbox), it gets filtered out before it reaches the module code.

So I end up typing something like this:

> This is just some content with an \n or a directory structure like C:\Program Files\whatever

And it gets converted to this on save:

> This is just some content with an n or a directory structure like C:Program Fileswhatever

This really makes it hard to edit content on my D6 site; anyone know a fix for this?

Related issues:

This is on admin pages; so filters aren't used.

# Answer
> 6 votes
This sounds like it may be a `magic_quotes` issue. If at all possible, disable this in your PHP configuration. Instructions on how to disable them are on the PHP website. If this is enabled on a live, shared server and you don't have access to the PHP configuration then I would highly recommend looking for a new host. The `magic_quotes_gpc` option has been deprecated in PHP 5.3, and will likely be removed very soon.

Magic quotes provide a way of escaping incoming input, and have been frowned on for quite a while in favor of validating input properly in your application, which Drupal does.

---
Tags: 7, nodes
---


# Question
Title: Is possible for a module to know when one of its blocks is being output on the dashboard, and change the content of that block?
Drupal 7 has a new core module (dashboard.module) that allows users with the right permissions to add blocks defined from third-party sites to the dashboard, which is shown as overlay on the current page.

Is it possible for a module that implements blocks to know when the block is being rendered on the dashboard?
The idea would be to change the content of the block, and make it smaller (for example).

# Answer
> 2 votes
Looking at the code of dashboard.module, I found the following function:

```
/**
 * Implements hook_block_list_alter().
 *
 * Skip rendering dashboard blocks when not on the dashboard page itself. This
 * prevents expensive dashboard blocks from causing performance issues on pages
 * where they will never be displayed.
 */
function dashboard_block_list_alter(&$blocks) {
  if (!dashboard_is_visible()) {
    foreach ($blocks as $key => $block) {
      if (in_array($block->region, dashboard_regions())) {
        unset($blocks[$key]);
      }
    }
  }
}

```

dashboard\_is\_visible() is the function that returns `TRUE` when the dashboard is visible, and dashboard\_regions() is the function that returns an array containing the list of the regions contained in the dashboard.

Those are the functions that allows to a module to know when its blocks are being rendered in the dashboard. The only problem is for the module to know to which region its blocks are associated, as the block object is not passed to the hook\_block\_view(). Drupal 7 uses new hooks, hook\_block\_view\_alter() and hook\_block\_view\_MODULE\_DELTA\_alter(), whose second parameter is the block object. Implementing one of these hooks is possible to alter the block basing on the fact the block is being rendered in the dashboard, or not.

Supposing that `mymodule` is the module short name, and `test_block` is the delta value, the module should use the following function:

```
/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function mymodule_block_view_mymodule_test_block_alter(&$data, $block) {
  if (dashboard_is_visible() && in_array($block->region, dashboard_regions())) {
    // The block is rendered in the dashboard.
  }
}

```

# Answer
> 2 votes
You could check the url argument that the block is displayed on and then if it matches an expected pattern i.e. /dashboard then you can alter the contents of the block. This solution only really works if you've coded the block yourself.

Update: This method will still work, although I'm not familiar enough drupal 7s dashboard module to comment further. The only thing I would suggest is to output page variables and see if there is anything set by dashboard module.

---
Tags: 7, blocks
---


# Question
Title: hook_preprocess_page: "node_load() + node_page_view()" versus "%node + node_page_view()"
A basic node (nid "123") exists and a module registered two paths using `hook_menu`:

* `first/%node`
* `second`

---

Both page callbacks use `node_page_view($node)` to display a fullpage view of the node, except the second callback additionally uses `node_load(123)` to get a reference to `$node`.

Therefore `http://localhost/first/123` and `http://localhost/second` look the same as far as the user is concerned.

---

However `hook_preprocess_page` receives the `node` variable only with the first path, therefore **Drupal obviously does something beyond `node_load` when it sees a `%node` wildcard, any idea what it is so that `hook_preprocess_page` receives the reference to `$node` in both cases** ? (because handling everything internally in the second path produces much more friendly urls than redirecting to the first path from the second).

Example:

```
<?php

/**
 * Implementation of hook_preprocess_page().
 */
function mymodule_preprocess_page(&$vars){
    if (@isset($vars['node'])) echo '<h1>[mymodule.module] Node is defined</h1>';
    else echo '<h1>[mymodule.module] Node is NOT defined</h1>';
}

/**
 * Implementation of hook_menu().
 */
function mymodule_menu(){
    return array(
        'first/%node' => array(
            'title' => 'First callback',
            'page callback' => 'mymodule_page_first',
            'page arguments' => array(1),
            'access callback' => TRUE,
        ),
        'second' => array(
            'title' => 'Second callback',
            'page callback' => 'mymodule_page_second',
            'access callback' => TRUE,
        ),
    );
}

/**
 * Page callback for url "http://localhost/first/123".
 */
function mymodule_page_first($node){
    echo '<h1>[mymodule.module] Function mymodule_page_first</h1><pre>';
    var_dump($node);
    echo '</pre>';

    return node_page_view($node);
}

/**
 * Page callback for url "http://localhost/second".
 */
function mymodule_page_second(){
    $node = node_load(123); //the ID of an existing node

    echo '<h1>[mymodule.module] Function mymodule_page_second</h1><pre>';
    var_dump($node);
    echo '</pre>';

    return node_page_view($node);
}

```

(Source of file `mymodule.module`)

---

My best/only hope so far is to dig in the source of `node_page_view` and all functions it consequently triggers until I find what happens between the moment `node_page_view` is called and the moment the `module_invoke_all` which triggers the hook is called.

# Answer
When `mymodule_preprocess_page()` is invoked for the "first/%node" path, it gets the node object because the path is associated with a node from the module.
Drupal cannot associate a node object with a path like "/admin/content/node" (Drupal 6 path) because the path doesn't contain any reference to a node ID which is marked as node ID. Which node object should Drupal return for such paths, considering a Drupal website can contains hundreds of nodes?

Your question is "how can Drupal associate a node object in one case, but not in the other one?"

The answer is in the template\_preprocess\_page() code, which the function executed before the template page.tpl.php is rendered.
In that function, you will find the following code:

```
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

```

The default parameters for menu\_get\_object() are `$type = 'node', $position = 1, $path = NULL`, which means `template_preprocess_page()` is asking for the node object that is associated with the placeholder in position #1, which is the value returned, for example, from `arg(1)`.

Looking at the source of `menu_get_object()`, you will notice that the code being executed is the following:

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

```

Using the default arguments, the function will verify the loading function associated with the route item #1 is `node_load()`. If the loading function is that, then it will return the value returned by the loading function to the calling function (in our case, `template_preprocess_node()`).

To automatically get a node object, your menu callback should use a path like "second/%node" (which would be compatible with the default `menu_get_object()` arguments). The only problem is that for such paths the node ID needs to be passed; if the URL is http://example.com/second, Drupal will show a 404 error page, as the placeholder require parameter that must be passed.
To resolve this problem, the module should define two menu callbacks: one associated with "second", and one associated with "second/%node". The first menu callback would not get a node object, while the second would get the node object (and `mymodule_preprocess_page()` would get it too).

As alternative, you should change the code of `mymodule_preprocess_page()` to something similar to:

```
/**
 * Implementation of hook_preprocess_page().
 */
function mymodule_preprocess_page(&$vars){
  // Check if the page being served is one of the pages handled by the module.
  if (arg(0) == 'first' || arg(0) == 'second') {
    if (isset($vars['node'])) {
      // The page is a node page.
    }
    else {
      $vars['node'] = mymodule_load_the_default_node();
    }
    // …
  }
}

```
> 3 votes

# Answer
When Drupal sees the '%node' wildcard in the url it knows the argument is referencing a node id, so automatically sets the `$node` variable for you, making it available in `hook_preprocess_page`. In your "second" menu callback, you should set the `$vars['node']` variable. That way you can use it `hook_preprocess_page`.

Reference: http://drupal.org/node/224170
> 1 votes

---
Tags: 7, routes, theming
---


title: CCK Field with two values?

text:
# Question
Title: CCK Field with two values?
Is there a way to have a CCK Field have two values for one input?

For example, a field called 'Sodium' and two values, '190mg' and '8%'- first being the amount, second being % of daily value.

If not, whats the best way to achieve this?

Edit:

The best solution I am looking for would be sets of Fieldgroups, and each row having 3 inputs. Label | value (required) | value (optional) - so, Sodium | 190mg | 8%

# Answer
Take a look at the CCK multi group options, which are only a part of CCK 3.0+. This functionality allows you to combine multiple base fields into one field grouping. See http://drupal.org/node/119102 for the *long* history on how this came about.

I actually can't find good documentation on using it, as CCK 3.0 is still only in Alpha, so unfortunately you'll just have to play around with it some.

The other option is to write your own CCK field type, in which there is no issue creating multiple inputs for one field. The upshot is that you can definitely achieve this using your own custom field, the downsides are you are writing custom code (which is nice to avoid) and it's not as flexible as the multigroup options built into CCK 3.0
> 7 votes

# Answer
So you want to combine two cck fields in one, in a way?

You could use two seperate fields 'sodium mg' & 'sodium %' - and add a computed field, so you can combine the values of those two fields into one field, 'sodium values' for example.

Some more info about the Computed Field module to make such computed field possible (from its project page):

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!
> 3 votes

# Answer
I might be missing something but the easiest thing would be to enter the whole string "Sodium | 190mg | 8%" into the text field and then parse out the values at the theme level to do whatever you need to do - putting it in table, making a graph, etc. Underneath the text field put an example, problem solved. No alpha required.
> 2 votes

# Answer
You can add all the data you want to a single CCK field, but you need a CCK type that supports this.

With CCK you can specify, how the data store should be (field\_settings), how the form for inputting should be (widget) and how the field should be renderen (formatters).

You're not quite clear on how you want things, but the easiest thing to do, would be to create a have a single input/storage, and use a custom formatter to display the single value as two, based on some regex or similar.

You could also make your widget, that would create a custom form for the field and how the data should be stored. If multiple values is setup for the field, you could use `delta` to separate the values. This requires more in depth knowledge of the inner workings of CCK, but would give you better data control.

The documentation on doing all of this is very limited, but looking at other modules will give you an idea on how to do it.
> 1 votes

# Answer
The module that allows you to achieve this in Drupal 6 is called Multigroup, and it is part of CCK 3.x, which has an alpha release. This module allows you to add multiple fields to a fieldset, and then presents the fieldset in the familiar 'add another' manner that CCK uses for multi-value fields.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How To Place One Forum Topic in Many Forums
I have a forum system created with D6 and the Advanced Forum module. I would like to have a special forum topic posted in all the forum sections that describes the site rules and how to use the various forum features. It would be perfect if this could be done using a single node that appears in all forums at once because that way all the comments would be contained in a single discussion.

# Answer
I've answered my own question. I used the Rules module (http://drupal.org/project/rules). That thing is GREAT!

First I created my topic that I wanted to show in all forums. Let's call it node/10.

Next I created a topic with the same title in all of the other forums, but the body content just reads, "REDIRECT". Let's call these nodes 11-16.

Then I created a new Triggered rule with one IF and one DO.

IF uses an "Execute custome PHP code" statement which checks the node id to see if it is one of the REDIRECT pages, like so...

```
return in_array($node->nid, array(11, 12, 13, 14, 15, 16));

```

When IF returns true, DO immediately executes a System \> Page redirect to node/10.

So far, so good.
> 2 votes

---
Tags: 6, nodes
---


# Question
Title: Drupal 7 Views Contextual Links edit Nodes and Fields
I created some Views with Drupal 7 and also installed the module Contextual Links. It helps me to edit Views and Blocks. But for non-admin users like Editors etc. it would be great to even edit Nodes or Fields with Contextual Links.

So I hover a Field there should appear a Edit Link.

I couldn't find any detailed settings for Contextual Links.

Please tell me how to set this up.

# Answer
> 2 votes
At the moment, contextual links for the node are displayed only when you choose "Unformatted" as style and "Node" as row style. I already posted a feature request to allow adding contextual links when the row style is "Fields".

---
Tags: 7, nodes, navigation
---


# Question
Title: How can I use conditional logic to not display a <div> in page.tpl.php based on node id?
I'm using a theme that has regions not supported by Panels' "Disable Drupal blocks/regions" settings. I've tried to remove the using an if statement in PHP, but either my PHP syntax is wrong or I'm not using the correct Drupal variables. Right now the section looks like this:

```
<?php
    if ($node->nid != 51) {
        echo '<div id="left">';
            { if ($left) { print $left;}
        echo '</div>';
 ?>

```

I have a feeling I'm not nesting the second if statement correctly in PHP though.

# Answer
If you're trying to hide the left sidebar when viewing node 51, this is not the right way to do it. Edit the block visibility settings for the blocks in the left sidebar so they are hidden when the path is 'node/51'. Then in your template you can do this:

```
<?php
  if ($left) {
    print '<div id="left">' . $left . '</div>';
  }
?>

```

This will hide the entire div#left when there are no blocks in the left sidebar.
> 8 votes

# Answer
I think that altering the visibility settings for all the blocks shown in the left sidebar is the correct way to hide the left sidebar.
If, for any reason, you need to hide the left sidebar from code (for example, because you need to hide the left sidebar in specific conditions that are not the URL of the currently show page), then what you can do is implementing `hook_preprocess_page()`, which is invoked before the page template is rendered. That hook is allowed to alter any variable that is passed to the page template.

```
function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->nid == 51) {
    // The left sidebar will not be shown.
    $variables['left'] = '';
    // …
  }
  // …
}

```

The hook can check more complex conditions are verified, including verifying that some node fields have specific values, which is not possible when changing the block visibility settings, if not writing PHP code that is then passed to `eval()` from the block module (in such cases, it is better to put that code into a custom module).

The reason you are getting an syntax error is that the code contains a curly bracket that doesn't match a closing bracket, and there is a missing closing bracket.

```
if ($node->nid != 51) {
  echo '<div id="left">';
    /* This bracket is extra. -> */ { if ($left) { print $left;}
  echo '</div>';
} /* <- This bracket is missing in the code you reported. */

```
> 3 votes

---
Tags: 7, theming
---


# Question
Title: What is the equivalent of theme_menu_item in Drupal 7?
I know that in drupal 6 exist: **theme\_menu\_item**, but in drupal 7 there is not. Is there any replacements so that I modify the output for main system menu ?

Actually I want to do a kind of filter of the menu items depending some criteria, which I will set in the function.

# Answer
Looking at the function that called the theme function `theme_menu_item()` (menu\_tree\_output()), and comparing it with the Drupal 7 version of the same function, I can say that the equivalent of `theme_menu_item()` is theme\_menu\_link().
> 5 votes

# Answer
The theme\_menu\_item() function has been replaced by theme\_menu\_link(). For details on this change, and all other changes made to the theme layer between Drupal 6 and 7, see the Converting 6.x themes to 7.x page. There is also a corresponding module conversion page.
> 4 votes

---
Tags: 7, routes, theming
---


# Question
Title: Add custom permission to specific module "group" on permissions page
Using a custom module, how can a permission be added to a core/contributed module "group" on the permissions page without hacking the core/contributed module?

Example:

# Answer
> 3 votes
As already said, it would not be a good idea to list a permission implemented by a module together the permissions implemented by another module; it would difficult for users to find the permissions implemented by, for example, custom\_module.module, when it is listed together the ones implemented by user.module.

If you really need to change the order used to list the permissions (but then, is it really necessary), then I would suggest to change how the list of permissions is shown: instead of listing them basing on the module implementing it, you could list them basing on different criteria.
To do this, you would need to:

Is it worth doing it? It could be, depending on your customer.
Considering that the first official release for Drupal 7 has been released, and the code for Drupal 7 would change, it is probably not worth doing it. I would rather try to understand why the customer wants to change the order of the permissions listed in the administration page, and explain the reason why changing it is a bad idea; if the customer insists the code needs to be implemented for their own purposes, then I would make him understand that the code should be rewritten when the site passes to Drupal 7, and it is not worth spending time for such changes, when it is possible to use the same time to implement something that it is really necessary.

# Answer
> 2 votes
There's no hook\_perm\_alter and those permissions are grouped by module, so likely th way would be to get in there would be with hook\_form\_alter on those forms (there's is per role permission forms along with the main one; not sure if they are using the same form\_id).

Should still define the permission via yourmodule\_perm so anything else can know the permission exists.

Personally, I'd advised against it; let your permission by where it would be so there's no "I installed this module and can't find the permission! oh, why was the permission under a different module?!!"

# Answer
> 1 votes
There are two ways to accomplish what you ask for.

Either through `hook_form_alter` or by overriding the form's theme function: `theme_user_admin_perm`.

For a standard contrib module, this wouldn't be a good idea, as people tend to look for a module's permission by browsing for it's name. If your module does some alterations to the standard user permission flow, it might not be a bad idea to show the added permission along with the default ones from the user module.

---
Tags: 7, users
---


# Question
Title: Is it better to use the latest version released 1 month ago, or use the older but still supported version?
I am going to create a new website: Is it better to use the latest major version recently released, or the previous still-supported version? For example, if Drupal 9 were released one month ago, should I use Drupal 9, or Drupal 8, or Drupal 7?

# Answer
> If all the modules you need works on D7, I see no reason to not use it.

That pretty much sums it up. In some more simple projects we are using D7 already. Anything complex, without the budget to invest in helping develop the D7 versions of the modules required, we are still finding ourselves starting in D6.

Worth noting, anything you start in D6, make sure the maintainer intends to create a D7 version and, if not, you have the ability and budget to do so yourself. Sooner or later you'll need to migrate, so select your modules with care.
> 20 votes

# Answer
If all the modules you need works on D7, I see no reason to not use it.

So a round of quick testing should probably help you out, provided you know which modules you will use.
> 8 votes

# Answer
The major advantages to dev in 7 vs. 6 in my opinion are:

1. Drupal 7 has better out-of-the-box accessibility best practices rolled-in (see: http://groups.drupal.org/node/116744)
2. When Drupal 8 comes out (whenever that may be), Drupal 6 will no longer be supported. If all the modules and functionality you need are (or soon will be) available in 7, you'll save yourself the hassles of having to upgrade your site if you start with 7.
3. Drupal 7 abstracts out the back-end database, so now SQL Server and other back-end databases can be used instead of just mySQL and PostgreSQL. Now that Oracle owns mySQL, that has caused some angst as to what its future will be. Plus if you develop a site for a larger corporation and might need to port it over to "their" backend database, you're theoretically buying some wiggle room with 7.
4. It's shiny and new and I'm guessing that most devs will want to develop modules and themes for 7 going forward, so 6 will not get the fancy new add-ons that will be coming out for 7.
5. It'll be a faster and easier to get started as you won't have to install a slew of modules just to get the base functionality that 7 already has.
6. See #4
> 5 votes

# Answer
If you're uncomfortable with the differences between alpha, beta, dev, RC (and don't know how to use drush) etc then I'd be wary of moving to Drupal 7.

Most modules are still in active development will have multiple releases - the version you launch site with will likely be out of date quickly.

that being said, I LOVE D7 and haven't found many issues with module support :D
> 2 votes

---
Tags: 9
---


# Question
Title: How can a module verify one of the update pages is shown?
What should a module do to verify if Drupal is updating the database tables to avoid to output a message when one of the update pages are being shown (or to avoid to do any superfluous task during the update)?

The module I am referring to is a custom debugging module that does some tests at every requested page, and outputs the result using `drupal_set_message()`.

# Answer
> 4 votes
devel.module has a function called `devel_silent()` that does some very comprehensive checking. I might replicate this in your own module.

```
function devel_silent() {
  // isset($_GET['q']) is needed when calling the front page. q is not set.
  // Don't interfere with private files/images.
  return
    function_exists('drupal_is_cli') && drupal_is_cli() ||
    (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'ApacheBench') !== FALSE) ||
    !empty($_REQUEST['XDEBUG_PROFILE']) ||
    isset($GLOBALS['devel_shutdown']) ||
    strstr($_SERVER['PHP_SELF'], 'update.php') ||
    (isset($_GET['q']) && (
      in_array($_GET['q'], array( 'admin/content/node-settings/rebuild')) ||
      substr($_GET['q'], 0, strlen('system/files')) == 'system/files' ||
      substr($_GET['q'], 0, strlen('batch')) == 'batch' ||
      substr($_GET['q'], 0, strlen('file/ajax')) == 'file/ajax')
    );
}

```

You can probably simplify this a bit to just the part that is checking for 'update.php' and the `$_GET['q']` checking.

```
    strstr($_SERVER['PHP_SELF'], 'update.php') ||
    (isset($_GET['q']) && (
      in_array($_GET['q'], array( 'admin/content/node-settings/rebuild')) ||
      substr($_GET['q'], 0, strlen('system/files')) == 'system/files' ||
      substr($_GET['q'], 0, strlen('batch')) == 'batch' ||
      substr($_GET['q'], 0, strlen('file/ajax')) == 'file/ajax')
    );

```

# Answer
> 1 votes
Basically, check the path. If the path is /admin/update\* or whatever, don't run your code. Check out drupal\_get\_destination().

---
Tags: 7
---


title: Customising the first item in a view

text:
# Question
Title: Customising the first item in a view
As a block on my homepage I'm trying to output:

```
<ul>
  <li><a><img><p>Node 1</p></a></li>
  <li><a>Node 2</a></li>
  <li><a>Node 3</a></li>
  <li><a>Node 4</a></li>
</ul>

```

where each \<li\> represents a node, and the image/text supplied by CCK fields attached to each node.

Currently, I'm using a block view to output nodes 2-4, and an Attachment view to present the first node as outlined here: http://www.agileapproach.com/blog-entry/the-views2-attachment-display

The problem is my output ends up more like this:

```
<div class="attachment attachment-before">
  <div class="view view-homepage-news ..">
    <div class="item-list">
      <ul>
        <li class="views-row ...">
          <a><img><p>Node 1</p></a>
        </li>
      </ul>
    </div>
  </div> <!-- /.view -->
</div>
<div class="item-list">
  <ul>
    <li class="views-row ..."><a>Node 2</a></li>
    <li class="views-row ..."><a>Node 3</a></li>
    <li class="views-row ..."><a>Node 4</a></li>
  </ul>
</div>

```

I can probably bend that output suit my purpose, but it will involve a lot of templating and configuration. I'd also like to avoid using CSS and/or JavaScript to modify the output, unless that's my only option.

Given this, what's the easiest way to get the output closer to what I need it to be?

Edit: here's some rough php code I'm using in the customfield php code field (based on Jeremy French's suggestion: Here's the code I'm using in my PHP Code customfield:

```
<?php
  ++$static;
  if ($static == 1) {
    $nd=node_load($data->nid);
    $img_path = imagecache_create_path('news_image_thumbnail', $nd->field_image[0]['filepath']);
    print '<a><img src="' . $img_path . '"><p>Node 1</p></a>';
  } else {
    print "<a>Node $static</a>";
  }
?>

```

# Answer
You could do something with views\_customfield.

You add a php field, get it only to display the markup you want (no containing elements) and output a value only for row number 1.
> 5 votes

# Answer
I personally use preprocess functions to do this, something like the following:

```
function HOOK_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'VIEW_NAME' && $vars['view']->row_index == 1) {
    // Do stuff here.
  }
}

```
> 8 votes

# Answer
I'm not sure if I'm understanding your question correctly, but I believe you could use Semantic Views module for this. If you set the Style under Basic Settings to Semantic Views, you'll then have an option under the Semantic Views settings to set a "first class attribute", which will help you target the first list item in your view in your theme's style.css file.
> 6 votes

# Answer
The easiest solution is with a custom template. It doesn't need to be a lot of work though. With the theming information available in the views interface you can see what template you need to change. All you need to do, is to add some code to print the extra items for the first node. Views will loop through each row, so should be easy.
> 4 votes

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


# Question
Title: How to increase the width to the Omega sub-theme more than 950 usable pixels
I have created a new sub-theme of the Omega theme (version 7.x-2.1) in Drupal 7.

But I want to use 970 usable pixels instead of 950 pixels as the sub-theme offers in "Default container width".

How can I do this? Shall I change the 960.css file from *themes/omega/omega/css/960.css* or shall I overwrite the 960.css file form my sub-theme? What you suggest?

# Answer
> 4 votes
My guess would be not to touch to the original theme and create a new one where you can override without touching anything to the original.

Now, I can't help any more, I never used that theme and Drupal 7 yet.

# Answer
> 3 votes
Finally I have followed the advice of @Polzme and @Chaulky and I have created my own sub-theme and I modified there the style.

As for my specific requirement this was:

```
.container-12, .container-16, .container-24, .container-32 {
    width: 970px;
}

.container-32 .grid-1, .container-32 .grid-2, .container-32 .grid-3, .container-32 .grid-4, .container-32 .grid-5, .container-32 .grid-6, .container-32 .grid-7, .container-32 .grid-8, .container-32 .grid-9, .container-32 .grid-10, .container-32 .grid-11, .container-32 .grid-12, .container-32 .grid-13, .container-32 .grid-14, .container-32 .grid-15, .container-32 .grid-16, .container-32 .grid-17, .container-32 .grid-18, .container-32 .grid-19, .container-32 .grid-20, .container-32 .grid-21, .container-32 .grid-22, .container-32 .grid-23, .container-32 .grid-24, .container-32 .grid-25, .container-32 .grid-26, .container-32 .grid-27, .container-32 .grid-28, .container-32 .grid-29, .container-32 .grid-30, .container-32 .grid-31, .container-32 .grid-32 {
    margin-left: 10px;
    margin-right: 10px;
}

```

---
Tags: 7, theming
---


# Question
Title: Custom default value for Webform's select options component
I use Drupal 7 with Webform 7.x-3.9.

I have created a new component from type "select options". I also have chosen to display it as a listbox and I've populated it with a few strings from the type "**safe\_key|Some readable option**" as expected. Here's an example :

1|Mr.

2|Ms.

3|Miss

Everything works perfectly well and the behavior is the following :

* If I select this component to be mandatory, the display will be "-Select-"
* If I don't select this component to be mandatory, the display will reflect the first string from the "Options" text area. In my example, it will be "Mr."

Now, imagine I want to have "Ms." but don't want to change the order. Nowhere I see this possible. Unfortunately, the "Default value" textfield is only used for tokens...

Any idea ?

# Answer
All you need to do, it to put the key value into the default value field, in this case 2, to make `Ms.` the default value of the form. This is what the default value if used for.
> 2 votes

---
Tags: 7
---


title: Save order data in a plain text file

text:
# Question
Title: Save order data in a plain text file
Just like the order data can be sent via email, I want to save the order data in a plain text file in a specific directory on the same server as the drupal installation.

Is it possible? How can I achieve this?

# Answer
> 3 votes
Saving a file should be a fairly simple job with PHP. If you want to do it when an order is completed, you could make a conditional action for it, or use one of the hooks that's invoked when the order is completed.

If you have an concrete problems on how to do this, you should refine your question.

If you want to save the mail sent, this would hold the order info, you could create a custom module and use hook\_mail\_alter to get the mail text:

```
/**
 * Implements hook_mail_alter().
 */
function my_module_mail_alter(&$message) {
  if ($message['id'] == 'uc_order_action-mail') {
    $message_text = $message['body'];
    // Code to save text as txt file here.
  }
}

```

By default the mail sent with ubercart is a HTML mail, so you might want to create your own text instead.

Whatever you do, you shouldn't alter Drupal or any of the modules, you should create your own module(s) that make the alteration. If you are new to Drupal development, you should read the developer guide.

---
Tags: emails, ubercart
---