# Question
Title: recent forum topics on sidebar of home page, recent articles and forum topics on article pages, recent articles on forum page
I'm having a little trouble finding information to help me figure out what I'm trying to do. Please forgive me, as I am new to drupal's api. I have 3 particular scenarios where I would like a little helpful nudge in the right direction.

1 - I really enjoy having the most recent articles being shown on the front page by default. I would like to know how to have recent forum topics, separate from the recent articles, on the sidebar. Just text would be sufficient. Please tell me this is possible. I've searched for hours looking for some kind of information or maybe a module that accomplishes this.

2 - On the Forum, I would like the exact opposite. I would like the recent articles to be on the sidebar. Just the titles would be sufficient here as well.

3 - On the Article Pages, I would like both recent forum topics and articles on the sidebar.

I'm using the core Forum module, as well as Advanced Forum module. *-Edit*

Are there global variables I can use to achieve this? This, I'm sure, would help others as well with average time on site, and bounce rate.

*--Edit--*

As Dooshta mentioned, this can be accomplished with Views. It's so very easy to use!

Also, I noticed that there were disabled blocks already there for what I was looking for. I've enabled Recent Content for Article Topics, Active Forum Topics, and New Forum Topics. Once I'm done styling them on my local Drupal Installation, I'll post a link to my live site to show an example for this Question!

*--Edit--*

I attempted using the provided blocks, however, I had a problem with a Configure Block link showing up on both provided forum blocks for all roles except admin. After a little research, I seen that it has been a problem for a long time and there's no simple fix. So I decided to use Views instead.

As I mentioned before, Views is absolutely simple to use. I created an Active Forum Topic Block, New Forum Topic Block, and a New Article Block for use on the sidebar. I couldn't configure the Active Forum Topic Block to display the topics in order with last topic commented on first until after creating it, but it wasn't difficult to figure out at all. the page is informative and organized.

If you would like to see how I used Views on my site, go to Strong Local Business. The New Articles don't display on the front page as intended, however you can see them on the sidebar when viewing an article, as designed.

Thanks again, Dooshta!

I hope this question helps others who may want to achieve the same results.

# Answer
Sounds like something that would be easiest to accomplish with the Views module (seeing as you're using the Advanced Forum module you should already have it installed). It allows you to create blocks with the necessary content and then you can just adjust the block settings to get them displayed where you want.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How to override output of checkout page in Commerce
I want to override the output of the order completion page. I need to include custom markup, as well as data from the order. As a matter of personal preference (and for organizational purposes), I'd rather do this in code, in my module, rather than in Rules. Can anyone point me in the right direction?

# Answer
It looks like using `hook_commerce_checkout_pane_info_alter(&$checkout_panes)` or `hook_commerce_checkout_page_info_alter(&$checkout_pages)` would be the best options. There are also hooks that allow you to create your own checkout panes/pages from scratch if necessary (`hook_commerce_checkout_pane_info()` and `hook_commerce_checkout_page_info()`). I would suggest reading more about them here and checking out the specific examples (about page/pane info hook implementations) that you can find in the Drupal Commerce submodule (mostly Checkout) files.
> 8 votes

---
Tags: commerce
---


title: How do relationships work in Views?

text:
# Question
Title: How do relationships work in Views?
This is related to my previous question, How can I make a block that holds all the information about an articles author? I want to make a block that holds all the information about the user who authored the node. I started using Views to make the block, and found the field "Content: Uid" underneath which is described as:

> The user authoring the content. If you need more fields than the uid add the content: author relationship

I was wondering if this could help me to make this block as I've described.

# Answer
> 4 votes
If you add a relationship in the View definition (Third column of the view input form), and select the Content:author from the dialog, you have created a link in the view that exposes data regarding the author. This will give you access to more fields that can be displayed in your view.

Check out the video series, "Taming the Beast" at nodeone.se to get a better understanding of what Views can do.

---
Tags: 7, views, blocks, users, nodes
---


# Question
Title: How might I go about flagging a post or comment containing certain keywords?
I have nodes coming in via FeedAPI and direct user submission, and I've got comments. A client requires me to check incoming nodes against a watch list of keywords. The posts and comments don't need to be blocked, because the watch list is fairly expansive (~1000 words but many are very context dependent). Rather, I need to be able to check the contents of a post or comment against the list and set a flag that triggers a notification to a moderator, who will manually review the content.

Is there a module that can help me with this? Barring a module, I could use a few clues to get me started on this, e.g.

"To check the content on a newly published node or comment, you could do these things."

"To flag based on a hit, you could do this thing."

# Answer
> 1 votes
Look at `hook_node_xyz` (d7) or `hook_nodeapi` (d6) to add code after node save or update.

# Answer
> 0 votes
I hope you are using D6 because most related modules are not released in D7 yet. Here is an overview.

Spam module hasn't been ported yet either. Mollom is more of an automated service solution, don't think you can use your custom word list with it.

# Answer
> 0 votes
Have you looked at the Search ApI for SolR module? I have not worked with it, but I have read a bit on it. SOLR search works on the Apache Database (if that is what you are using) and the module links it into Drupal.

---
Tags: nodes, flags
---


# Question
Title: including jquery.ui 1.6 directly from theme.info
It is possible? because i've tried to include jquery ui library through drupal.org/project/jquery\_ui module (followed instructions in readme.txt) but that library won't show up in source code. What's the problem?

Should i go for jquery\_ui module or i can include that script through .info file?

Jquery ui version = "6.x-1.5" Downloaded jquery ui library 1.6

# Answer
The correct way to include jQuery UI, from README.txt:

In your module, call the following function:

```
jquery_ui_add($files);

```

For example:

```
jquery_ui_add(array('ui.draggable', 'ui.droppable', 'ui.sortable'));
jquery_ui_add('ui.sortable');  // For a single file

```
> 1 votes

---
Tags: 6, javascript
---


# Question
Title: How do I translate empty text of a view?
I have created a view with empty text using PHP code. Now, when I try to translate it through the translation interface (admin/build/translate/search), while I find the string (it show up all the PHP code) and translate it (I did it by adding the PHP code again with the translated strings), when I change the language of my site I see nothing. When I come back to English, it showed up correctly.

Does anyone have any idea?

# Answer
If this view is showing inside of a block then make sure you have the translation "Make this block translatable" is checked, and what ever language you want to translate to is also checked. hope this helps.
> 1 votes

---
Tags: views, 6, i18n-l10n
---


# Question
Title: Views won't handle my pathauto pattern for taxonomy pages
I have two taxonomies on my site that need to be browsable independently using different Views. Therefor I decided to prepend the term paths with the vocabulary name. In PathAuto patter section I have defined:

```
[term:vocabulary:name]/[term:url:path]

```

and the paths look the way I want:

```
vocabname/taxonomy/term/tid

```

however the Views don't work. The pages that are generated for the path

```
vocabname/taxonomy/term/%

```

somehow won't jump in. I see the error that no content has been tagged with this term, whereas the view should display teasers of the children terms.

So, do you think there is a wrong assumption on my side as per the url aliasing process (what occurs first)? Should that work?

# Answer
> 1 votes
OK, so in case someone runs into the same problem. It was my fault. Taxonomy Display works just great. It distinguishes the vocabularies and my PathAuto patterns did not need to be touched. The only thing I had to watch out for was providing default value for the contextual filter in the views responsible for listing final content nodes. Default value should be taken from URL as Taxonomy ID. That's it.

# Answer
> 1 votes
Yes - you're very close on this, but you're right that the pathauto path is not being recognized by views here. To overcome this, you're going to need to add a 'default argument' in your views argument handling code and use PHP code to pass the term id from the end of your string.

It looks like from the version of tokens you are using that you're on Drupal 7 / Views 3, correct? If so, you're going to want to add this under

Contextual Filters --\> Content: Has taxonomy term ID --\> Provide Default Argument --\> PHP Code

and then in the php code section add this code:

```
$path = isset($_GET['q']) ? $_GET['q'] : '';
$path = explode('/', $path);
return $path[3];

```

This gets the current path as an array and returns the 3rd element, or the TID and passes it to your view.

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: Is it possible to hide the title of a block in a region to render it separately from the content?
I'm styling a custom region for the "Active Forum Topics Block" that's included with Drupal. can I hide certain elements in region--\[name\].tpl.php like as it is done in node.tpl.php?

This is part of my node.tpl.php:

```
    // We hide the elements now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    hide($content['field_image']);
    hide($content['links']['#links']['node-readmore']);
    hide($content['links']['#links']['comment-add']);
    hide($content['field_tags']);

```

I would like to do this if it's possible in region--forum\_topics.tpl.php (example name "forum\_topics"):

```
    hide($content['???']);

```

I don't know what the proper way is, for region.tpl.php. If this is possible, what can I put between brackets to hide the title of the block? If there is a documentation page I can see for more than just the block title, can you please link it?

# Answer
> 3 votes
It might be easier to do this in the block.tpl.php file (using `$block->region` to determine the region) as you have the title printed out separately from content there.

In your test environment you can also use stuff like these to get a better overview of complex variables (will help you with issues like this):

```
drupal_set_message('<pre>'.var_export($content, TRUE).'</pre>');

function print_r_html ($data) {
  ?><pre><?php print_r($data); ?></pre><?php
}

```

# Answer
> 0 votes
You can always use hook\_block\_view\_alter to hide the title, you can do something like this

```
function MYMODULE_block_view_MODULE_DELTA_alter(&$data, $block) {
  if arg(xx) = xx {  // detemine the path is a forum topic path
    $data['subject'] = xxx;   // change subject
    // or you can:
    unset($data['subject']);
  }
}

```

ps: MYMODULE is your module name, MODULE\_DELTA is block id. Hope it helps.

---
Tags: 7, theming
---


# Question
Title: How to prevent the user profile page of a blocked user to show up?
When a user is blocked the (core) user profile is still accessible. I would rather show a message "this user profile has been removed".

I could write an exception into the user-profile.tpl.php. Is there a better way?

# Answer
> 2 votes
You should be able to implement hook\_user\_view in a custom module.

First create a page which contains your preferred content (e.g. "This user profile has been removed"). Let's call this node/1337 for now.

Secondly, you want something along the lines of the following:

```
function mymodule_user_view($account, $view_mode, $langcode) {
  if ($account->status == '0') {
    drupal_goto('node/1337');
  }
}

```

There are other parameters you can pass to drupal\_goto if you wish (such as HTTP response code) - check out the API for more info :-)

# Answer
> 0 votes
You can try to alter the page callback of user profile page, change the access callback to point to your custom function that determine whether a user is blocked.

---
Tags: 7, users
---


title: Node count for taxonomy terms

text:
# Question
Title: Node count for taxonomy terms
How can I display the node count values for taxonomy terms with sorting the result list in descending order of node count?

# Answer
> 42 votes
1. Create a taxonomy view
2. Add node group in relationship
3. Add term name and node nid fields for display
4. Enable aggregation in "Other" section (Use aggregation: Yes)
5. Click nid field settings icon, choose group type "count".

Find the export of views that worked for me.

```
$view = new view;
$view->name = 'term_node_count';
$view->description = 'Displays node count values for terms';
$view->tag = '';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'term_node_count';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'nid' => 'nid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'nid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
);
$handler->display->display_options['style_options']['override'] = 1;
$handler->display->display_options['style_options']['sticky'] = 0;
/* Relationship: Taxonomy: Node */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 0;
/* Field: Taxonomy: Term */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = 1;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* Field: Node: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
$handler->display->display_options['fields']['nid']['label'] = 'Count';
$handler->display->display_options['fields']['nid']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['nid']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['nid']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['nid']['alter']['trim'] = 0;
$handler->display->display_options['fields']['nid']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['nid']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['nid']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['nid']['alter']['html'] = 0;
$handler->display->display_options['fields']['nid']['element_label_colon'] = 1;
$handler->display->display_options['fields']['nid']['element_default_classes'] = 1;
$handler->display->display_options['fields']['nid']['hide_empty'] = 0;
$handler->display->display_options['fields']['nid']['empty_zero'] = 0;
$handler->display->display_options['fields']['nid']['link_to_node'] = 1;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$translatables['term_node_count'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('node'),
  t('Term'),
  t('Count'),
  t('Block'),
);

```

# Answer
> 25 votes
All the previous answers were very helpful.

I wanted to get a table so I could let the user sort by Term or by count.

To do this I:

1. Relationship \> Taxonomy term: Content with term
2. Use aggregation: Yes
3. Field \> Content: Nid
4. Aggregation type for Nid = Count DISTINCT

# Answer
> 12 votes
To get a taxonomy node count correctly for taxonomy terms you need to do the following:

1. In Fileds: add **Taxonomy term: Name**
2. In Relationships, add a **Taxonomy term: Content with term**
3. Add a *contextual filter* for **Taxonomy term: Name**

3a. Choose **'Display a summary'**

3b. Choose **'Display Record count with link'**. Also set base path if you want the taxonomy page to be linked correctly.

# Answer
> 5 votes
The key is that you have make sure you've ticked the "aggregation" check box in the advanced option of the view.

# Answer
> 4 votes
Add an argument (renamed 'contextual filter' in the latest Views) for taxonomy terms, and choose 'Display a summary'. Then, choose to display 'Number of records'.

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


# Question
Title: Using ImageField to add an inline image (save thumbnail, and when clicked open with colorbox)
Here is **what I usually do in my websites**:

* Have an option for adding image in the WYSIWYG editor of my choice
* User can upload the image
* User can resize the image in the WYSIWYG editor
* Have the Image Resize Filter enabled for the Input Format
* When user resizes the image, it automatically saves the thumbnail and adds a lightbox/colorbox related attribute so that the image is opened using one of these libraries.

What the problem is now? I have come across a "not very tech-savvy" customer that is displeased with the way that the images are added right now as he cannot grasp any of the regular concepts for images.

Based on his description I reached to the conclusion that **I need to implement the following workflow**:

1. A straightforward filefield (imagefield) where he can press the "Browse" button and then the "Upload" button.
2. He will then write his text in the "Body" field and that's it.

**My Requirements**:

1. I don't mind if he cannot see the image when he is editing the node
2. Only one image will be allowed per node
3. I want to pre-edit the image's vspace, hspace and alignment (e.g.5px 5px left)
4. I would also like if I could use the Image Resize Filter for the uploaded image so that only a thumbnail appears in the actual node (teaser and full view) and the original image appears in a colorbox
5. I don't mind if I will have to edit the node.tpl.php or any other theme file
6. ***It's needed that the image is added with the body of the node (e.g. at the start of the text)***

**What I've tried so far**:

I have watched the MustardSeed video for Image Resize Filter along with ImageField Insert module (now it's called Insert) but there are some complex steps in there that my customer cannot comprehend (e.g. adding Vspace, Hspace, Alignment or even manually resizing the image). I would like to give my customer as few options as possible.

# Answer
If you enable core File and Image modules you can add image upload fields to different nodes/entities and create image styles (to get thumbnails). The number of allowed image uploads can also be set. The image uri will be available in the node.tpl.php file which means you will have full control over how it appears. Here's example code showing about how it could look like in the node.tpl.php file (with colorbox module 'Colorbox load' enabled - alternatively just use javascript):

```
<?php if (!empty($node->field_image['und'][0]['uri'])): ?>
  <?php
  $full_img_url = file_create_url($node->field_image['und'][0]['uri']);
  $thumbnail_url = image_style_url('thumbnail_style', $node->field_image['und'][0]['uri']);
  ?>
  <a class="colorbox-load" href="<?php print $full_img_url; ?>"><img src="<?php print $thumbnail_url; ?>" alt="Image" /></a>
<?php endif; ?>

```

The code is not tested so there might be mistakes, but it should still be helpful. You'll have to set the image field hidden via 'manage display' or unset/hide it in the template file otherwise you'll get a duplicate printed with $content.
> 1 votes

---
Tags: 7, media
---


# Question
Title: CCK Select List widget with "Add another item" functionality?
With certain field types that are set to unlimited you get an "Add another item" button that lets you create as many fields as you need. If you set a field with a Select List widget to unlimited it instead gives you a select list box that has ctrl click functionality for selecting multiple.

I want to know if there's a way to make a Select List widget that is set to unlimited instead show a regular select list, and an "Add another item" button that creates further select lists.

# Answer
> 2 votes
Try one of these modules

---
Tags: 6, entities
---


# Question
Title: How do you programmatically modify a programmatically created content type?
I'm creating a Drupal 7 site that has many content types which are defined programmatically. It is quite likely that, after launch, I will be required to slightly modify some of the content types. During development, whenever I need to make a change, I just uninstall the module, make the changes in code, and reinstall it. In a production environment where the data needs to be kept stable, this is clearly not acceptable.

How can I modify one of my existing content types programmatically? Also, how would I apply this update?

# Answer
1. http://api.drupal.org/api/drupal/modules--field--field.crud.inc/function/field\_update\_field/7
2. http://api.drupal.org/api/drupal/modules--field--field.crud.inc/function/field\_update\_instance/7

Open WWWROOT/profiles/standard/standard.install (starting from line 199) Profile install creates basic content types (like Article and Basic page)
> 2 votes

# Answer
What are you changing slightly? If you are just adding a field to a type, all that is doing is creating another database entry, and any preexisting content will just have nothing in that field until edited again, so you could just do that either through your module or through the menus. However, if you are changing field names, well that's a whole 'nother story in itself.
> 1 votes

---
Tags: nodes
---


# Question
Title: How can I make a block that holds all the information about an articles author?
I would like to add a block into the side bar of all article nodes that contains a mini profile of the user who authored the article. I was wondering if there is an easy way to do this. Thanks

# Answer
Checkout the Author Pane module as well.

> Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.
> 3 votes

# Answer
You should investigate the Views Module. Watch the series at Nodeone.se regarding using the views module called "Taming the Beast" to learn how.
> 3 votes

# Answer
Implement a custom Block or use PHP filter. Find the current node via drupal\_get\_destination. Once you have the node fetch the uid of the creator/editor and do a user\_load to get the full user record.

In a similar way you could also implement an author pane plug-in.
> 2 votes

# Answer
If you really must use a block, you might want to try the eva module. However, if you are open to other solutions, there are a couple of other things to consider.

For sophisticated relationships between different elements on the page, I would recommend trying out panels. Panels seem a little intimidating at first, but it is easy to put, say, the article content in one panel, and user information in another. Try it out; a little experimentation can go a long way.

Finally, if you just want something really quick and easy, make a node-article.tpl.php in your theme, and drop in some code similar to the following:

```
<?php if ($submitted): ?>
<span class="user-info">
  <?php $account = user_load($uid); print theme('user_picture', $account); ?>
  <span class="blog-author"><?php print l($account->name, "users/" . $account->name); ?></span>
  <!-- See also: http://highrockmedia.com/blog/how-create-custom-date-format-better-theming-drupal-views -->
  <?php if (!$teaser) { print format_date($created, 'custom', '<\d\iv \c\l\a\s\s="\d\a\t\e\b\l\o\c\k"><\d\iv \c\l\a\s\s="\m">M</\d\iv><\d\iv \c\l\a\s\s="\d">d</\d\iv><\d\iv \c\l\a\s\s="\y">Y</\d\iv></\d\i\v>'); } ?>
</span>
<?php endif; ?>

```

The snippet above shows the user profile picture, the user's account name, and a fancy calendar date that the article was posted on; just add css and stir.
> 1 votes

---
Tags: 7, blocks, users
---


# Question
Title: Month and year to display based on content post date
I have a magazine blog that I am creating in Drupal 7. I have the date displayed in the upper right hand corner (JAN 2012). How could I have this display work dynamically based on the post date of the article shown or current month if on the main view (blog) landing page? Each blog landing page is a view so the content is filtered that way. I two custom content types to help filter content and custom field created on each as the publish date to push and pull content based on the month. I need to use that publish date field as the date. How do I tap into that field for the date I need?

# Answer
You haven't explained the context of this date. Is it representing results coming out of views like "this post was 5 days ago" or do you just want todays date on the upper right?

This will print the current date on your theme template.

```
<?php
echo date('Y M D');
?>

```

Share some more info on what this date is giving the user exactly; Drupal has some very helpful code for this kind of thing, such as format\_date().
> 2 votes

---
Tags: 7, datetime
---


title: math functions inside views 3

text:
# Question
Title: math functions inside views 3
On my commerce site I give free shipping for users with total order over €100. Now I would like to create a view that would say, "spend \[x\] euros more to get free shipping," where *\[x\]* is simply `100 - $total_order`.

Is there a way to accomplish this in Views, or do I need to use PHP?

# Answer
It really all depends on where $total\_order is defined/declared etc. You might be able to use the http://drupal.org/project/computed\_field module to do the math and just rewrite the field with the text "spend \[field\] euros more...." to do it, or, if that doesn't work, or adds too much complexity, just create a views template for the field that does the math in php there and displays the field.
> 3 votes

---
Tags: views
---


title: How can I back up my Drupal site?

text:
# Question
Title: How can I back up my Drupal site?
My site crashed the other day, and I was wondering if anyone could tell me how I can back up my site, so that if something ever goes wrong again, I could still have a working copy of my site.

# Answer
Try the Backup and Migrate module:

> Backup and Migrate simplifies the task of backing up and restoring your Drupal database or copying your database from one Drupal site to another. It supports gzip, bzip and zip compression as well as automatic scheduled backups.
> 4 votes

---
Tags: 7, backups
---


# Question
Title: How can I limit the number of chars/words in a long text field to 3000?
I would like to limit the amount of text that my users can input in a text field. I want it to be a text area so I made a field called "Solution" then I made it a type "Long Text" and a widget type of "Text Area." I would like to limit the number of characters that the user can post to 3000 characters. Is there an easy way to do this?

# Answer
> 10 votes
The Maxlength module does that.

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


# Question
Title: How can I create a custom page with a different template?
I want to have a page (e.g. the one at http://example.com/mypage) shown as a blank page. How can I use a different template for that specific page, to show it as a blank page?

# Answer
You can use a different template for a page by suggesting a new template file that will be used.

This can be done in a theme, by writing its `template_preprocess_page()`, or in a module by implementing `hook_preprocess_page()`.

```
function template_preprocess_page(&$variables) {
  if (arg(0) == "node" && arg(1) == "1") {
    array_unshift($variables['theme_hook_suggestions'], "page--custom-template");
  }
}

```

This code is for Drupal 7; for Drupal 6 you need to replace `$variables['theme_hook_suggestions']` with `$variables['template_files']`. In the case you are using it in a module, `template_preprocess_page()` needs to be renamed `mymodule_preprocess_page()`, where "mymodule" is the short name of your module.
Instead of using `arg()` you can also use `request_uri()`, but the output returned from this function is similar to "/dr72/devel/php?render=overlay&render=overlay" when Drupal is installed in a subdirectory of the web server's root directory. `request_uri()` doesn't change an alias into the canonical path; supposing that example.com/node-1-title is an alias for example.com/node/1, in my test site, the function will return "/dr72/node-1-title" while `arg(0)` and `arg(1)` would return, respectively, "node" and "1" (the first two elements of the path).
> 4 votes

# Answer
If you want to implement this in code, within a custom theme or module, you need to look into template suggestions.

If you want a ui-based solution, there are a few modules that assist in having custom themes for specific themes/sections of your site. See themekey module, custom page module and page theme module for a few modules that do this.

Personally, I would opt for a template suggesion in a custom module.
> 1 votes

# Answer
```
function yourTheme_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    if($node->type == "mypage") {
      $vars['theme_hook_suggestions'][] = 'html__mypage';
    }
  }
}

```

then we can access to this page from : http://yoursite.com/?q=mypage or in clear url mode : http://yoursite.com/mypage/
> 0 votes

---
Tags: theming, 7
---


# Question
Title: Preprocess custom CCK fields and print image URL in TPL file
I want to preprocess a image field and later print it in my rss.tpl file and I'm currently using drupal 6.

This are the following codes I've tried in the template.php file but no luck :(

```
$vars['image'] = $field_uppdrag_logo;

```

&

```
/*$vars['image']=$node->field['field_uppdrag_logo'][0]['value'];

```

&

```
$vars['image'] = $node['field_uppdrag_logo'];*/

```

My tpl file:

```
<?php
// $Id: views-view-row-rss.tpl.php 3296 2009-05-27 23:08:21Z tim $
/**
* @file views-view-row-rss.tpl.php
* Default view template to display a item in an RSS feed.
*
* @ingroup views_templates
*/

?>
<item>
<title><?php print $title; ?></title>
<link><?php print $link; ?></link>

<description><?php
$description = html_entity_decode($description, ENT_QUOTES, "ISO-8859-1");
print strip_tags($description);
?>
</description>
<image>
<?php print $field_uppdrag_logo[0]['view']; print $image; print $field_uppdrag_logo;
?>
</image>
<?php print $item_elements; ?>
</item>

```

How exactly do I accomplish this?

# Answer
Try the below:

```
$vars['image'] = $node->field_uppdrag_logo[0]['value'];

```
> 1 votes

# Answer
I have found some useful codes but none seems to work for me... it only prints the directory but not the filename...

```
<img src="<?php print $node->field_image[0]['filepath'] ?>"
alt="<?php print $node->field_image[0]['filename'] ?>" />

```

.

```
print theme_imagefield_image($node->field_image[0]);

```

Cant understand why this would work for everyone else but not me...
> 0 votes

---
Tags: 6, theming
---


title: Faceted search and panels

text:
# Question
Title: Faceted search and panels
I'm using Faceted Search module and i was trying to change a display of search result with Panels.

I've enabled `search-node` page in `admin/build/pages` and added a variant with URL selection rule set to `search/results/*` but it looks like nothing happens. I'm still seeing default results page instead the one which uses Panels.

Am i doing something wrong? Does anyone have any tips?
Thanks in advance

# Answer
> 0 votes
Try removing the selection rule. If the page is active and has a variant, I would expect it to work without a path selection rule.

---
Tags: 6, panels, search
---


title: List nodes within a date range

text:
# Question
Title: List nodes within a date range
I am looking for a solution which displays node list within the date range. Requirement is to display events from today to next 6 days group by date. I have a content type "Agenda" with a date field enabled. So the display should look like:

> 2 Jan 2012
> -- 8:00 AM Agenda A
> -- 9:00 AM Agenda B
> 3 Jan 2012
> -- 8:00 AM Agenda C
> -- 9:00 AM Agenda D
> 4 Jan 2012
> -- 8:00 AM Agenda..
> -- 9:00 AM Agenda..
> 5 Jan 2012
> -- 8:00 AM Agenda..
> -- 9:00 AM Agenda..
> 6 Jan 2012
> -- No events scheduled
> 7 Jan 2012
> -- No events scheduled

I tried with the Views module and the Calendar module also, but I don't want to display in calendar style format, and I need to display only these 6 days (now +6 day), not the entire month view. Other styles are not fulfilling my requirement.

Here I have display 6 dates and display node/event associated with its otherwise display "No events".

Could you please suggest something?

# Answer
I'm assuming you know how to filter the view to get the nodes based on the date and date + 6, but are having troubles grouping them together on output by date.

I see you are using D7, but to do this in D6, you would add the date field twice in the view and override one of these with a template to output just the day in question and group on that now simplified field.

A good article on that is http://drupal.org/node/388140 which shows you how to do it by month; to do it by day just change the date function to include it as well.

I would imagine D7 is very similar, and that this helps out.
> 3 votes

# Answer
I agree with Jimajamma's answer, since we have done something similar in DT.

We needed day of the week and time of day

Basically, we had two date fields in our view, one we altered the date format to show only the time, the other one we altered to show only the day of the week. (You can do this in the settings for the field.)

We then altered the Format settings of the view by clicking the settings link next to fields under the FORMAT header and grouped the results by the field showing the day of the week.

Finally, we excluded from view the field showing the day of the week (to avoid duplicated entries in the view)

Also, on one final note, to ensure that we did not get duplicate entries on the view, we used the distinct function. You can do this by

Expanding the "Advanced" section of the view admin

Clicking on "Settings" next to Query settings- this is under the OTHER header

Checking the box for "Distinct"

Hope this helps!
> 1 votes

---
Tags: views, 7, theming
---


title: Prevent Category Pages from Generating

text:
# Question
Title: Prevent Category Pages from Generating
I have a website that is generating /category pages and /taxonomy archive type pages, with a list of posts containing a certain taxonomy term. I do not have a template for this page and they seem unnecessary/duplicate content. Is there any way to prevent them from being created?

category/region/all/boston?page=2&region=DEFAULT /taxonomy/term/14/”?page=19&region=DEFAULT

link to one of these pages http://nyc.thedelimagazine.com/taxonomy/term/14/%E2%80%9D?page=19&region=DEFAULT

# Answer
> 1 votes
If you *really* want to prevent the URLs from existing at all, you could probably unset the paths using a hook\_menu\_alter. I would be careful with that though, as it might have unforseen consequences. The creating module may in some way depend on the paths existance.

I don't know where the category paths comes from but I guess the answer will be the same as for the taxonomy ones.

My solution would be to take over the URL with Page manager, and simply pass the user a redirect to the front page. (Or a 404, if you prefer). Note that I'm talking about "Page manager" in Ctools, *not* Panels. The two modules are often confused and their names interchanged.

---
Tags: taxonomy-terms
---


# Question
Title: How to correctly remove a module in a staged environment?
Some modules have deïnstallation routines. Which typically remove databasetables for that module, variables from the variable table and locales introduced by that module. These routines live in the `.install` of that module.

Therefore, they cannot be ran without that module being present. So here are our current steps. My question is: can this be done simpler and more effectively? Say I remove foo\_bar module.

1. In the RCS, prepare a new release, where:
    * All css and theme-overrides that use or build on top of- foo\_bar are removed.
    * All css and theme-overrides for modules depending on foo\_bar are removed.
2. Push that release to acceptance. Test the deïnstallation (from admin/modules) with a very recent copy of the production database.
3. If all goes well, deploy the new codebase to production, and deïnstall foo\_bar and its dependencies there. This will invoke the uninstall in the various modules, cleaning up the database.
4. In the RCS (git), prepare a new release where the code is actually removed.
5. Deploy that to acceptance where we test if nothing accidentally depended on this (some ugly modules or theme functions include files directly from other modules. Most notably CSS, JS or image-files).
6. If accepted, deploy new release to production. **production now has a clean database and a clean codebase**.

Problem that I can't see how to solve, is that this always needs two releases. Since in Drupal a release requires the site to be offline, this means two times downtime just to remove one module. It also requires two release procedures, which, in professional hosting environments can be very expensive, time-consuming or frustrating.

If we remove the module from codebase in the first iteration, we cannot run the uninstall hooks, keeping many lint in the database; not just a few tables, but mostly variables and locales. If we don't remove the module from codebase, that means the codebase will grow with stale, unused code; this gives no performance overhead, but does make maintaining the code harder and harder.

How do you deal with this?

\[edit: added note about deployment being a tough procedure, often\]

# Answer
> 7 votes
Be very careful about keeping your database and code in sync; as you mention in your question, the modules to be uninstalled need to stay in the code base until their uninstall hooks are run on the live database. This is a limitation of Drupal that a git pull workflow alone is not going to solve.

I would recommend that instead of attempting to adjust your process, you instead look for ways to reduce the downtime required to process your updates. I would recommend setting up a ying / yang multisite staging environment to solve this problem. n.b. I have not used the scripts contained in the preceding link; you may wish to set things up differently, following the same idea that you can *swap* your live and stage sites during deployment.

Continue to follow the same procedure you outlined in your question with the following adjustments:

a. Sync from dev to stage (yang) as usual. Test by doing an uninstall of the modules to be removed followed by code removal, etc. Git workflow notes: create a tag or note the hashid of the different states of your code: all modules in place prior to uninstall, code modules removed, your overrides & c. removed, etc. as needed. Perhaps only two references are needed.

b. When testing is complete and accepted, restore the code on stage (yang) to the state of live (ying).

c. Prepare the live (ying) site for update by disabling any user's ability to change content on the system. An sql update to the permission table will usually do here. At this point, users will still be able to read content on the live site, but will get a permission denied error if they try to update content. (If you are cool, perhaps you could change the permission denied handler to print an appropriate notice that the function is temporarily unavailable).

d. Now push the live (ying) database back to stage (yang) database, excluding the permissions table from the update.

e. Repeat step a. again. If you have your hashtags handy, it should be easy to restore to the state where the modules to be removed exist, run the uninstall hooks on the database, and then advance back to the state of the code where your items from step 1 are merged back in.

f. You are now ready to swap ying and yang. Do this by adjusting your Apache configuration directives. Note that if you do an `/etc/init.d/apache restart`, some connections may be dropped, but `/etc/init.d/apache reload` will allow for a clean swap.

g. Live is now 'yang'; the permissions table is unmodified here, so users can create content. If you automate steps e. and f., the time unavailable should be very low.

h. Push live (yang) back to stage (ying), both code and database -- or push from dev, as needed. You now have a clean environment ready for your next iteration.

---
Tags: nodes, deployment
---


# Question
Title: Request parser best practices for Services 3.x
When you create a service endpoint you can enable various request parsers (application/json, application/x-www-form-urlencoded, multipart/form-data...) How should I decide whether to send the request using JSON vs form-data?

Most of the "node create" examples I've seen do something like this (I think this uses form-data):

```
    //create a node
    $node_data = array(
                      "title"=>"DHC Tool 01",
                      "type"=>"item",

                      "status"=>false, //ensure unpublished
                      "language" => "und", //lanugage neutral
                      "field_webpage"=>array(
                                              "und"=>array(
                                                            0=>array("url"=>"http://berkeley.edu",)
                                                           )
                                             )

                     );

  // Use JSON
  // $node_data = '{"title":"Tool Unpublished 10","type":"item","status":false,"language":"und","field_webpage":{"und":[{"url":"http:\/\/berkeley.edu"}]}}';
    $options['data'] = http_build_query($node_data, '', '&');
    $response = drupal_http_request($base_url . '/node', $options);

```

Is there any advantage to sending the node create request using JSON?

How would the above code be modified to use JSON?

Thanks!

# Answer
> 1 votes
This code will send a request encoded as JSON:

```
function toolreq_test_create() {
  $base_url = 'http://example.com/dirt';
  $options = toolreq_service_login(); //this yields $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
  if (!is_array($options)) {
    print "error<p>";
    return;
   }

   //create a node
   $node_data = array(
     'title' => 'DHC Tool 03',
     'type' => 'item',
     'status' => FALSE, //ensure unpublished
     'language' => 'und', //lanugage neutral
     'field_webpage' => array(
       'und' => array(
         0 => array('url' => 'http://berkeley.edu',)
       )
     )
   );

   //use json
   $options['headers']['content-type'] = "application/json";
   $options['method'] = 'POST';
   $options['data'] = json_encode($node_data);
   $request = drupal_http_request($base_url . '/node', $options);
   if ($request->error) {
     print ("Error doing http request");
     print '<pre>' . var_dump($request) . '</pre>';
   }
   else {
     print ("Success doing http request");
     print '<pre>' . var_dump(json_decode($response->data)) . '</pre>';
   }
 }

```

When considering the best format for your request keep in mind:

---
Tags: services
---


title: How to join tables with hook_views_data

text:
# Question
Title: How to join tables with hook_views_data
I have two tables activity and activity\_map. I need to join both the tables by aid. Below is my code for hook\_views\_data. Base table is working fine including custom text handler. But I do not see the joined table(activity\_map) fields (entity\_id, entity\_type) either in fields section nor in arguments or filters. Am I missing anything?

```
  <?php

    /**
 * Implements hook_views_data
 */
function activity_teamie_views_data() {
  $data['activity_teamie']['table']['group'] = t('Activity');
  $data['activity_teamie']['table']['base'] = array(
    'title' => t('Activity'),
    'field' => 'aid',
    'help' => t('Activity feed item')
  );
  $data['activity_teamie']['aid'] = array(
    'title' => t('Activity ID (aid)'),
    'help' => t('Activity ID'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric'
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric'
    ),
    'sort' => array(
      'handler' => 'views_handler_sort'
    )
  );
  $data['activity_teamie']['template'] = array(
      'real field' => 'template',
      'title' => 'Activity',
      'help' => 'Text describing the activity',
      'field' => array(
        'handler' => 'activity_teamie_handler_field_activity_text',
      ),

  );
  $data['activity_teamie']['data'] = array(
    'title' => 'Data',
    'help' => 'Data array',
    'field' => array(
      'handler' => 'views_handler_field',
    ),
  );
  $data['activity_teamie']['created'] = array(
    'title' => t('Created'),
    'help' => t('Created timestamp'),
    'sort' => array(
      'handler' => 'views_handler_sort_date'
    )
  );
  $data['activity_teamie']['updated'] = array(
    'title' => t('Updated'),
    'help' => t('Updated timestamp'),
    'field' => array(
      'handler' => 'views_handler_field_date',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date'
    )
  );

  /* ACTIVITY MAP */
  $data['activity_teamie_map']['table']['group'] = t('Activity');

  // Join with the {activity} table
  $data['activity_teamie']['table']['join'] = array(
    'activity_teamie_map' => array(
      'left_field' => 'aid',
      'field' => 'aid'
    )
  );
  $data['activity_teamie_map']['aid'] = array(
      'title' => t('Aid Map'),
      'help' => t('Aid Map'),
    'field' => array(
          'handler' => 'views_handler_field',
  ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric'
  ),
      'argument' => array(
        'handler' => 'views_handler_argument_numeric'
  )
  );
  $data['activity_teamie']['entity_type'] = array(
    'title' => t('Entity type'),
    'help' => t('Entity type of the associated entity'),
  'field' => array(
        'handler' => 'views_handler_field',
  ),
    'filter' => array(
      'handler' => 'views_handler_filter_string'
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string'
    )
  );
  $data['activity_teamie']['entity_id'] = array(
    'title' => t('Entity ID'),
    'help' => t('Entity ID of the associated entity'),
  'field' => array(
        'handler' => 'views_handler_field',
  ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric'
    )
  );
  return $data;
}

```

# Answer
```
$data['activity_teamie']['table']['join'] = array(
  'activity_teamie_map' => array(
    'left_field' => 'aid',
    'field' => 'aid'
  )
);

```

You actually want to join the other way round.kk

A general tip, try to think of some kind of similar join relation in Drupal core and look it up in views/modules/$module.views.inc

```
$data['activity_teamie']['entity_id'] = array(

```

Isn't `entity_id` part of `activity_teamie_map`?
> 4 votes

---
Tags: 7, views
---


title: Simple node access control for users

text:
# Question
Title: Simple node access control for users
Users have 'edit own content' permission for content type 'diary'. When viewing own diary node, I would like to present a simple checkbox to 'make private'. Then only that user can view the node.

I've looked at some options for doing this:

1) Write a module that uses hook\_node\_access() - overkill?

2) Perhaps an existing content access module provides a useful hook?

3) Create a 'private yes/no' field, then use Editablefields module to expose it on view. Then use theming layer to hide if set to 'yes'. - clunky?

I'm learning to write simple modules so perhaps a good learning opportunity here, but not sure where to start.

# Answer
I think you should create the field as suggested in 3 regardless of which method you choose for authorizing users to view content. Your first suggestion seems reasonable. I would personally opt for method two, and use the Page Manager in Ctools. PM is a tool however, and as such requires both understanding and configuration to do what you ask. Your third option, hiding in the theme, seems wrong however.
> 2 votes

---
Tags: 7, users, hooks
---


# Question
Title: How to make a node reference field that can also behave as a text field if no reference exists
I'm looking for a flexibly way to allow a user to input a a field, but also to have that field be a node node reference if the the node reference already exists. In other words, lets say I have a content type called dog, each dog has a node reference for favorite toy, if the toy exists, this field should be a node reference, otherwise the user should be allowed to fill it in. Conceptually I can think of two way to do this. One way, is just to make it a field, and then somehow link to another node if it exists. The other is to make it a node reference, and perhaps somehow auto - create the node when the user fills it in.

Recommendations? (using drupal 7)

# Answer
instead of node references you could use term references and then use the Autocomplete Deluxe module to have the user select existing terms or add new terms.

Actually, they there is support for references with Autocomplete Deluxe for References.
> 2 votes

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


title: How do I set a table header in Views 3?

text:
# Question
Title: How do I set a table header in Views 3?
How exactly do I get a table header to appear above the table? In views-view-table.tpl.php I can see a `<thead>` section, but what causes it to actually get rendered?
Where do I specify the column header text? I tried various options in the settings page, but to no avail.

# Answer
> 11 votes
The title can be defined from the Main views form. Each column of the table is associated with a field. If you select the field you can "add label" by selecting the checkbox and providing a name. The Label will appear in the header of the table.

---
Tags: 7, views
---


# Question
Title: How to save the "user agent" in the Drupal logs?
when going through the log files it would be really helpful to know if an error was caused by a real user or by a bot.

Is there a way to save the "user agent" string (browser name) to the drupal log?

# Answer
Using hook\_watchdog, you can manipulate all, or some of your log messages. You can find the user agent string in the super-global $\_SERVER\['HTTP\_USER\_AGENT'\]. This way you could for example prepend all "notices" with the user-agent, and all errors with both user-agent and remote IP.
> 6 votes

# Answer
Please note that there's no guarantee on the level of truth of the user-agent as it's really easy to change for a bot creator (and a browser user as well). Thus, depending on the type of bot and whats its owner is trying to do, you might or might not be able to see if it's a bot just using the User-agent.

Typically, when I try to emulate a real average user through a script, I make sure my bot looks like a Firefox user as much as possible but on the other hand, when a crawling bot (such as the Google bots) visits your website, I think it tries to be identied as a Google bot.

Then, depending on what you want to detect, user-agent might or might not be what you should look for.
> 2 votes

---
Tags: 7
---


# Question
Title: How to always show Poll results on most recent poll block?
I want to make a block that shows a poll that shows the results and with a link to vote to that particular poll. It seems that the default most recent poll shows the results if the user doesn't have the right to vote and the voting options if it has the rights...

How can I control this?

# Answer
From memory you can configue poll blocks using the Views module. At any rate, using Views you will be able to create a new block that displays votes. You can then add a footer to the block with a link to the poll node so users can vote.

There's plenty of documentation about using Views:

http://drupal.org/project/views
> 2 votes

---
Tags: blocks, rating, polls
---


# Question
Title: Why does the Webform disappear after changing Submit button text in Form settings?
I have created a **Webform** page called "Quick Quote".

It is working fine in the website. But when I change the "**Submit button text**" to a new value in `Advance Settings >> Form Setting` configuration, then the entire form (i.e Quick Quote page) disappears.

Why does it disappear, and how to enable it?

# Answer
Difficult to know what's going on based on the limited information you've provided, but it could be permissions. If you don't have permissions to view the webform then you won't see it.

The scenario you've described might occur if you are configuring the webform while logged in, then testing it while logged out (or in another browser) as an anonymous user that does not have permissions to view.
> 0 votes

---
Tags: 6, webforms
---


# Question
Title: drupal single page Error 324 (net::ERR_EMPTY_RESPONSE)
I am having a problem I really can't figure out. I am running a drupal mobile website using mobile tools and I have also boost installed on drupal. Now the mobile website works fine on m.domain.fr BUT ONE page doesn't work. It returns a Error 324 (net::ERR\_EMPTY\_RESPONSE) but all other pages ar ok. This page is a view and I can access it just as expected in Views Editor, I have normal preview, but i can't access this page from web.

Any help would be welcomed.

Thanks

# Answer
I finally found the source of the problem, it was a unsupported PHP function in the view template. As I replaced this function, the page worked normally.
> 0 votes

---
Tags: views, 6
---


# Question
Title: .info file is not loading the JavaScript code
I added the references to some JavaScript files, in my .info file, hoping that they would be output by the `$scripts` variable in my header. I cleared the cache, and they are still not there.

```
$Id$
name = site
base theme = boron
core = 6.x
engine = phptemplate
; We do not have a Left sidebar.
;regions[left] = Left sidebar
; We do not have a right sidebar.
;regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer
scripts[] = sitename/sites/all/themes/custom/jivamukti/js/jquery.nivo.slider.pack.js
scripts[] = sitename/sites/all/themes/custom/jivamukti/js/scripts/jquery-1.6.1.min.js

```

I put the JavaScript in the root of the themes folder I am using, instead of /js, and now it is output in this function in my header:

```
jQuery.extend(Drupal.settings,…);

```

How do I just get it to display inside the `<script></script>` tags?

# Answer
The file path should be relative to the theme directory not the root directory; try it with `js/jquery.nivo.slider.pack.js` instead of `sitename/sites/all/themes/custom/jivamukti/js/jquery.nivo.slider.pack.js`.
> 5 votes

# Answer
Go to "Administrator \> Site building \> Themes"; select the theme, save again, and refresh.
> -1 votes

---
Tags: 6, theming, javascript
---


# Question
Title: Administrator's approval required after published node has been edited
After editing, any published node needs administrator's approval like comments. How can I do this with Drupal 6?

# Answer
> 2 votes
Use the Rules module to create a rule that sets a node to unpublished when it is saved. You might also want to have a look at the Moderate module.

# Answer
> 1 votes
Unfortunately, Moderate is Drupal 5 only. Another alternative is to use the built in revisioning system. Set it up so that any edits create a new revision that does not get published (this is in the settings for the content type). Set the `publish revisions` permission so that only administrators (or whatever your admin user role is) can publish a newly created revision.

You might want to follow that up with an view that shows recent unpublished revisions so that an admin can see the most recent page changes.

Using Oswald's answer, and content that gets edited will become unpublished, and therefore not be visible by users who cannot view unpublished content. With this method a user will be able to carry on viewing the unedited post until the new revision is published.

Check this page for more info on revisioning in Drupal.

---
Tags: 6, comments
---


# Question
Title: How do I use form_set_error() the right way?
In my Drupal 7 module, I have a form and its validation handlers. I call my form from a field.tpl.php with `print render(drupal_get_form('my_form'))`; it works as expected.

The problem is in case of wrong input value.

It requires two incorrect submissions before displaying the error message: The first time, there is red border around my wrong input, and the second time, the error message is displayed (with the red border).

So, what's the right way to use `form_set_error()`?

# Answer
Form builders are not supposed to be called inside a template file, as they are being called too late. When you are calling `render(drupal_get_form('my_form'))`, the code that renders the error messages has been executed, and the eventual error messages reported from the validation handler are saved in the current session from drupal\_set\_message(), which is called from `form_set_error()`.

The code to print the error message is in the page.tpl.php file.

```
<?php if ($breadcrumb): ?>
  <div id="breadcrumb"><?php print $breadcrumb; ?></div>
<?php endif; ?>

<?php print $messages; ?>

```

The code in `drupal_set_message()` that saves the messages to show is the following one:

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

    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
      $_SESSION['messages'][$type][] = $message;
    }

    // Mark this page as being uncacheable.
    drupal_page_is_cacheable(FALSE);
  }

```
> 6 votes

# Answer
You should be looking at form\_set\_error instead

if you have an element like this:

```
function my_custom_module_form() {
  $form = array();
  $form['my_element'] = array(
    '#type' => 'textfield',
    '#title' => 'My Text field',
    '#default_value' => 'Some default text.',
  );
  return $form;
}

```

in your validation callback function do this if you find that the values in `$form_state['values']` aren't valid

```
function my_custom_module_form_validate($form, &$form_state) {
  // Do some checking on $form_state['values'], if you don't like it.
  form_set_error('my_element', 'This is the error message that will be displayed.');
}

```
> 9 votes

---
Tags: 7, forms
---


# Question
Title: Drupaliest way to remove login and registration page descriptions
How to remove the descriptions from log in and registration page ?

I need to remove the description from the fields which are listed in the images.

These are both log in and registration page.

How can i do this?

# Answer
> 9 votes
you write a hook for user login form alter, then you can set the #description to null. you need something like this:

```
function YOURMODULE_user_login_form_alter(&$form, &$form_state) {
    $form['name']['#description'] = '';
}

```

---
Tags: 6, users
---


# Question
Title: How do I automatically get the "Automatic alias" option checked for the content type?
I have the Pathauto module, and I want to have the 'Automatic alias' checkbox selected by default for the new content types I create.

Is there a way to obtain this?

# Answer
> 2 votes
After you define the pattern of the content type path, it will be checked automatically when you add the node of that content type.

The path is admin/config/search/path/patterns.

---
Tags: path-aliases
---


# Question
Title: How to add a class for forgot password link?
I need to add a class for the forgot password link. How can I do using Drupal?

This is the actual link:

```
<a href="/user/password" title="">Have you forgotten your password?</a>

```

My expected link is this one:

```
<a href="/user/password" class="my_class" title="">Have you forgotten your password?</a>

```

How can I achieve this, without using jQuery?

# Answer
> 2 votes
```
/**
 * Implementation of hook_form_alter
 */
function login_register_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
       $form['#validate'][] = "login_register_validate";
    break;
  }
}

```

Just call the validate function:

```
/**
 * To add my_class in the forgot password link
 */
function login_register_validate($node, &$form) {
  // to add class in the forgot password link
  $_SESSION['messages']['error'][1] = 'Sorry, unrecognized username or password. <a class="my_class" href="/user/password" title="">Have you forgotten your password?</a>';
}

```

And it's done..

Here my fear is weather this is a right way ?

Expecting for comments..

# Answer
> 2 votes
Why don't you create a custom block in "admin/structure/block/add," and then add that link with that class into the block? Place the block where you want to place it. It should still fulfill the same requirements.

# Answer
> 1 votes
```
a[href="/user/password"] {
//css
//goes
//here
}

```

is another quick way of accomplishing something similar in most modern browsers.

# Answer
> 0 votes
You can access it using a CSS selector such as the following one:

```
#user-login a {
}

```

You can use jQuery to add the class:

```
jQuery('#user-login a').addClass('my_class');

```

---
Tags: 6, navigation
---


# Question
Title: How do I add a node add link ( for a different content type ) in the node add form (drupal 7)
I'm overriding the node add / edit form using panels. One of the fields that I have added is using the auto complete widget (it is a node reference field). I also want to add a link underneath the autocomplete field to add a new node (one of the referenced nodes). I'm wondering if there is a way to add this link.

If it's not possible within panels, perhaps it is possible someone can give me an idea of how to add this sort of link to node add form using templates.

# Answer
Thanks for the answers, not sure the question was really clear. I ended up doing it by adding "custom content" to the panels pane, I then just switched the options to html and made and html link to the other nodes add / edit page. I know this is not the most elegant solution, but it was really quick and easy.
> 0 votes

# Answer
The module your are looking for is References dialog.

Also, you can use contextual administration. It's a more general approach, that won't put the link exactly where you want, but is much more flexible on the other hand. It allows you to use the same rule set as Panels, such as "Selection rule: Node type", for example to node/add/\[other-type\]. Fits like a glove together with Panels.
> 2 votes

---
Tags: 7, forms, panels, navigation
---


title: Tokens as a boilerplate?

text:
# Question
Title: Tokens as a boilerplate?
Is there a Tokens module that allows for simple boilerplate embedding? For example, embedding `[notification 3]` into a node would correspond to an admin setting(`notification 3 = "Hello World"`). You would then have "Hello World" embedded into all nodes with `[notification 3]`.

# Answer
There is a module that replace some tokens accepted from the Token module (or implemented using `hook_token_info()` and `hook_tokens()` in Drupal 7) in the body of a node, the Token Filter module.

> Token Filter is a very simple module to make token values available as an input filter.

There is then the Token Node Tokens (TNT) module that allows to define new tokens without implementing a module.

> TNT (Token Node Tokens) is a very simplistic module that allows you to create arbitrary tokens without having to create a custom module (i.e. /node/add/token). This was primarily created for use with the tokenize module so that through the UI a user could create tokens for use with CCK.

Unfortunately, this module has been declared unsupported, but looking at its code, you could create your custom module for doing the same thing.

An alternative is the Custom Tokens module.

> It gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.
>
> Versions 7.x-1.x and previours relied on PHP evaluation to build custom tokens.
>
> The new 7.x-2.x relies on input filters. While still allowing for PHP tokens through the D7 core PHP filter module, administrators can permit only HTML or plain text custom tokens.
> 6 votes

---
Tags: tokens
---


title: Changing cck form field options

text:
# Question
Title: Changing cck form field options
i'd like to dynamically change the option labels of a cck form field in the edit node form.

i allready found ou, that i can't do this in hook\_form\_alter, since the cck fields aren't in the form object at this time. so i added a after\_build function. in this function, i'm trying to set the option labels like this:

```
function _mymodule_after_build($form, &$form_state) {
   $form['field_product_alternativtitle']['value']['#options'][1] = "foo";
   $form['field_product_alternativtitle']['value']['#options'][2] = "bar";
   $form['field_product_alternativtitle']['value']['#options'][3] = "meh";
   return $form;
}

```

This, however doesn't change the output of the form in any way. I guess this is logical, since my function gets calles **AFTER** the **BUILD** of the form.

so my question is, how can i achieve my goal?

# Answer
> 3 votes
I would check a couple of things.

1. For sanity, make sure that your after\_build function is being called by adding a drupal\_set\_message().
2. The labels will only change in the Edit form if your values are literally '1', '2' and '3'. Once you save the form, however, drupal will save the original value, not your new label.

```
function mymodule_after_build($form, &$form_state) {
  $form['field_some_options']['value']['#options'][1] = 'hiyo';
  return $form;
}
```

# Answer
> 0 votes
I believe that you also have to set the default value. if your trace out the entire array

```
 drupal_set_message('Options'.'<pre>'. print_r( $form['field_some_options'], TRUE) .'</pre>');

```

you will see a parameter called default\_value. I believe that you have to set that to your desired option. In my experience, the best thing to do is add a validation function by adding this

```
function yourmodule_form_validate($form, &$form_state) {
    }

```

and also adding this

```
$form['#validate'][] = 'yourmodule_form_validate';

```

to your hook function

then trace out the array in your validate function as well. This way you can compare the state of the array when the form builds, and after it is submitted to exactly what is changed, you can then st those value in code.

---
Tags: entities, 6
---


title: Panels selection rule node author

text:
# Question
Title: Panels selection rule node author
I was wondering, I have a panels using the "Node template", is there a way to have "node author" as a selection rule, now I only have "node type".

I'm using Drupal 7.9.

# Answer
Under the "Contexts" tab for your page variant, add a relationship to Node:author. This will expose the available fields from the author for your use.

However, What are you trying to do? You might be better off to define what you want in Views and then set up a node page variant to display the view for you.
> 1 votes

# Answer
Just an fyi, in case you are attempting to override the node edit form using panels, and selection rules, you may have to use the dev version of ctools. I was banging my head against the wall for a while trying to figure out why certain selection rules where not displaying. Once i replaced ctools with the dev version, everything worked fine
> 0 votes

---
Tags: panels
---


# Question
Title: Site gone offline after aborted mysql restart
After trying new my.cnf, restarting mysql took to long (apparently due to some incompatible commands in the experimental config) , so I restored to my original my.cnf and restarts mysql successfully. But now I see that the site has gone off line. I tried the 'desparate' solution, i.e. issued:

```
UPDATE variable SET value = 's:1:"0";' WHERE name= 'site_offline';
DELETE FROM cache WHERE cid = 'variables';

```

but had no effect. Then I changed my database admin credentials. then, to possibly counter a corrupted table, I tried to repaire the database (MyISAM enginge) using

```
mysqlcheck -uroot -pPASS --auto-repair --optimize --databases MYDB

```

I also rebuilt the file permissions on the server.

No cure either.

I'd seen before that the site went offline on whim, but now this seems to become persistent. really appreciate your help to overcome this nasty problem.

# Answer
> 1 votes
It sounds like your database is broken. Drupal can't work without a database, and will display site offline if it can't connect to the database. If you fix your database, (And the data is still intact) Drupal should work fine.

For questions about databases you should go to dba.stackexchange.com

---
Tags: database
---


# Question
Title: Path configuration in media gallery module
I am using Media gallery module to create gallery and pathauto module to generate URL.

For a gallery page I use this pattern for URL

```
photo-gallery/[node:title]

```

When user will click on any photo. I am showing that image on different page.

But I am not getting way to set path for page where the single image will be displayed.

Automatic it generates URL like this

```
/media-gallery/detail/356/460

```

Is there any way around this? Any help will be appreciated.

# Answer
> 5 votes
The solution that Letharion posted will work fine, but making integration with path auto is a better solution like (s)he writes.

Doing this in not that hard, but it can be a bit tricky to do the first time.

To do it you need a few steps.

1. First you need to implement `hook_pathauto` in order to get the setting for how the alias should look like. Here you can give info about which type of token can be used for path replacements etc.
2. Second you need to create a function which can be used to generate an alias. It should look something like this.

```
function foo_pathauto_update_alias($file, $op, array $options = array()) {
  module_load_include('inc', 'pathauto');
  $path = media-gallery/detail/' . $file->bid . '/' . $file->fid
  pathauto_create_alias('aug_product', $op, $path, array('file' => $file));
}

```

Path auto is based on entities. So you need to be able to generate the path from a single entity. In this case the file that's created. By using the above function structure you can use a single function and utilize it for bulk updates as well as regular updates while keeping path auto functionality intact.
3. Lastly you need to call your update function when file is created or updated. This will handle path alias creation. Doing it this way, you can also get path auto to update path alias if the data is changed and the alias should be different, if you want to do so. There is settings for this in the path auto module.
4. For bonus you can choose to create a bulk update function, that will enable you to the alias for any file created. It takes a bit of work, but should work nicely.

Note doing it this way, it will be a good idea to use the file entity module, as it allows you to handle files like entities, which fits path auto a lot.

# Answer
> 2 votes
Media-gallery registers the "media-gallery/detail/%node/%file" path, meaning you can add an alias onto it.

Upon saving the gallery, you could with a form\_alter create path aliases for each gallery image, which should solve your problem.

```
function hook_form_ID_alter($form) {
  foreach($form['images'] as $image) {
    path_save(array('sources' => $image->path, 'dest' => 'pretty-url'));
  }
}

```

A cooler solution would be direct pathauto integration, but I'm not knowledgeable enough to tell you what is required to get that working.

---
Tags: 7, uri, media
---


# Question
Title: How to noindex comment/reply in Drupal 7
I use Drupal 7, and I am trying to use the "noindex" meta tag to prevent http://example.com/comment/reply/43/738 from being indexed by search engines.

The comment/reply page is being indexed, even though I've used the following role in robots.txt:

```
Disallow: /comment/reply/

```

In which template file will I need to incorporate "noindex" meta tag for /comment/reply/ pages?

# Answer
> 7 votes
You can use any of this code in robots.txt:

```
User-agent: *
Disallow: /*comment

```

This will neglect every URL that contains *comment*.

You can also use the following, to neglect every URL containing */comment*.

```
User-agent: *
Disallow: /comment/reply

```

```
User-agent: *
Disallow: /comment

```

After you do this, check whether it is working or not by using the Google Robots.txt checker.

# Answer
> 4 votes
In your theme's template.php, or in page.tpl.php, you can check the page's url to see if the page is a comment page, then add code that will insert the meta tag.

You can do this in the template.php function YOURTHEME\_preprocess\_html(), or insert it somewhere near the top of page.tpl.php. The code to add would be something like this:

```
    <?php
      $element = array(
        '#tag' => 'meta',
        '#attributes' => array(
          'property' => 'robots',
          'content' => 'noindex',
        ),
      );
    drupal_add_html_head($element, 'robots');
?>

```

See drupal\_add\_html\_head().

# Answer
> 1 votes
**Update**: the following works, it prints `<meta name="robots" content="noindex,follow" />` in the head section of all pages accessed via a path starting with `comment`. This is to work around the fact that a page like comment/3 internally carries node/nid as arguments, as jmarkel pointed out above.

```
<?php
function metarobots_comment_help() {
  $url_components = explode('/', request_uri());
  if ($url_components[1] == 'comment') {
    $elements = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex,follow',
      ),
    );
   drupal_add_html_head($elements, 'robots');
  }
}

```

With the aid of a helpful comment on the arg function.

Hopefully this will eventually be addressed by Meta Tags module - there's a feature request, but it's not yet clear if the module author wants to support this.

---

\[My previous comment\] I just wanted to add that using robots.txt is not the answer - as you already noticed, links keep appearing in the search results despite using `Disallow: /comment`. This is expected, since robots.txt tells the bot not to crawl those pages, but it doesn't tell Google not to index it. As explained on SEOmoz Robots.txt and Meta Robots Best Practices for Search Engine Optimization:

> In most cases, meta robots with parameters "noindex, follow" should be employed as a way to to restrict crawling or indexation.
>
> Block with Robots.txt - This tells the engines to not crawl the given URL but tells them that they may keep the page in the index and display it in in results.
>
> Block with Meta NoIndex - This tells engines they can visit but they are not allowed to display the URL in results. (This is the recommended method) So the noindex meta tag you're after is indeed what you need.

---
Tags: comments
---


title: Forum CMS for user?

text:
# Question
Title: Forum CMS for user?
I've had a Drupal 7 site for a few months and I'm planning to create another site with a different topic. It will either be a "forum site" or a "wiki site", I have't decided yet.

For both of the options what CMS or Drupal modules would you suggest:

1. Are Drupal's forum modules sufficiently good for an advanced forum site? Or, which system do you recommend for a Drupal familiar person?
2. Is it possible to create wiki sites with Drupal? If not, which system do you suggest?

# Answer
Picking your software before you select the style of the site is, in my opinion, putting the cart before the horse.

Depending on the details of your final specification Drupal is likely capable of all you'll need, but it might not be the best tool for the job. You might be happier with a MediaWiki for a wiki site, or any one of the dedicated forum systems for a purely forum site.

Develop your goals and specs first, then determine the best tool for the job.
> 6 votes

# Answer
Drupal has an advanced forum module which works very nicely, right out of the box.
It gives you a nice set of default themes up front.

Drupal also has a wiki installation profile that will preconfigure your Drupal site as a wiki.
> 5 votes

---
Tags: 7, nodes
---


# Question
Title: Use the Services-3.x node resource to create a new *unpublished* node
Is there a way that I can force a node to be unpublished by using the node resource?

Requirement: Site A defines a content type 'item' which is published by default. Site B needs to create 'item' nodes on A, and these auto-created nodes should be unpublished.

```
function toolreq_test_create() {
$toolreq_endpoint = variable_get("toolreq_endpoint", "");
$options = toolreq_service_login();
if (!is_array($options)) {
    print "error<p>";
    return;
}
//create a node

$node_data = array(
                      "title"=>"DHC Tool 04 dev",
                      "type"=>"item",
                      //"status"=> FALSE, //ensure unpublished
                      "status" => 0,
                      "language" => "und", //lanugage neutral
                      "field_webpage"=>array(
                                                  "und"=>array(0=>array("url"=>"http://berkeley.edu",)
)
)
);

//use json
$options['headers']['content-type'] = "application/json";
$options['method'] = 'POST';
$options['data'] = json_encode($node_data);
$request = drupal_http_request($toolreq_endpoint . '/node', $options);
}

```

Since the node table's status field is the mysql INT type (with a default of 1), I would think that I could pass status=\>0 in the above code, but doing that results in a *published* node. I have tried passing 0 using both JSON and x-www-form-urlencoded data.

If I use status=\>FALSE and use JSON, the node is created as unpublished, but I think that this is equivalent to inserting '' in the node.status field which results in a mysql warning:

```
mysql> INSERT INTO `bamboodirt`.`node` (`nid`, `vid`, `type`, `language`, `title`, `uid`,
`status`, `created`, `changed`, `comment`, `promote`, `sticky`, `tnid`, `translate`)
VALUES (NULL, 21, 'item', 'und', 'sql insert test', '0', '', '0', '0', '0', '0', '0', '0',
'0');
Query OK, 1 row affected, 1 warning (0.03 sec)

mysql> SHOW WARNINGS
+---------+------+----------------------------------------------------------+
| Level   | Code | Message                                                  |
+---------+------+----------------------------------------------------------+
| Warning | 1366 | Incorrect integer value: '' for column 'status' at row 1 |
+---------+------+----------------------------------------------------------+

```

I would live with that warning, but my webhost's mysql is less permissive and I get a real error (durning node\_save() I think) on that server:

"SQLSTATE\[HY000\]: General error: 1366 Incorrect integer value: '' for column 'status' at row 1"

(Here's the thread over at Pantheon http://help.getpantheon.com/pantheon/topics/json\_node\_create\_works\_on\_localstack\_fails\_with\_error\_500\_on\_pantheon.)

Is there a way that I can force a node to be unpublished by using the node resource, or do I need to write my own resource?

# Answer
> 3 votes
Try setting the 'status' field to `TRUE` or `FALSE` instead of `0` or `1`.

---
Tags: services
---


# Question
Title: How to change conditions of views filters programmatically?
I have a view with a node type filter. I want to change it in some conditions. How do I change this filter in `hook_views_query_alter()`?

# Answer
You specifically ask for altering the View programmatically, and that certainly is possible. I will however suggest an easier way. With Views 3, you can group your filters. This way, you can achieve the effect you are asking for by adding two separate groups of filters.

Group 1: Node:type == \[type\]

**OR**

Group 2: User:role == \[role\] **AND** Node:type == \[other\_type\]
> 2 votes

# Answer
You should be able to alter the content type by User roles by creating a view definition with two pages (or blocks) setting the filter for the content type and another for the user:role. I am using views 3 in D7, but the filters should be in your versions as well. If you are not familiar with Views, check out the video series "Taming the Beast" at nodeone.se.
> 1 votes

---
Tags: views
---


title: Enforce unique constraint on a field

text:
# Question
Title: Enforce unique constraint on a field
For a content type (place), on creation, as the user is entering the name field, I would like to check the previous records for that field. If there is a match, I will present it to the user to prevent duplicate entries. is there way to do this?

# Answer
Check out the Unique field module.

> This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.
> 1 votes

# Answer
In D7 you could also implement your "place" as a taxonomy and then use a "auto tagging" widget. As users type in the place name they see similar names that are already entered. That would prevent miss spellings.
> 1 votes

---
Tags: entities
---


# Question
Title: How do I allow other files in the root directory of my site to be accessible?
Alright so I've noticed that the `.txt` files in the root directory of my Drupal install are accessible just using `http://drupalsite.com/SOMETHING.txt`, but when I try to add other `.txt` files, I get a 404 when I try to access them from the browser. I've even set these files to have exactly the same user:group and permissions as the `.txt` files that I *can* access, and I've tried restarting Apache, but nothing seems to work.

The reason I need this is because I want to use Majestic SEO, which requires you to place a `.txt` file at the root of your website.

# Answer
> 1 votes
I use Site verification for tasks like this, although it may not work for this particular case. IIRC it tried the module for a Majestic .txt file, and it added some dummy content for the text file, which the Majestic service did not accept (the file has to be empty). So I uploaded the file directly to the Drupal root via SFTP. I just checked that website, and the Majestic .txt loads normally. I don't see any reason why you would get a 404, other than that the file is indeed not present. I don't think Drupal is to blame, because if the file is present, Apache will serve it. Only if it's not present Drupal starts doing stuff.

So, unless you have done something in .htaccess it should work, and I only have a silly suggestion: double-check that the file is in the correct folder, copy the file name from that directory and paste it in the browser to check.

# Answer
> 0 votes
I am not sure I've got exactly what is happening straight, so my explanation may have the details a little off... Browsers are very fussy about opening files due to security risks for users. In Drupal, any file that you want to open must be uploaded to the site using file\_save (permanent location), or file\_save\_upload (temporary location). This process is similar to uploading image files. I have not researched exactly what is happening, but suspect that the file identity is then added to the database and allows Drupal to handle it properly. I am adding files using a custom module function. There may be modules that can do this for you if the Majestic SEO does not load them.

---
Tags: .htaccess
---


# Question
Title: Suggest a new template file for a page node view
I have a site which has two main views, a men's blog and a women's blog, both with their own content types, mens-blog-post and womens-blog-post. The problem I am facing is that they share the same page--node.tpl file (node page view, default file:page.tpl not node.tpl), but need to have different content (e.g. other relevant views in the sidebar region). I need to suggest two new template files called page--node--mens-blog-post.tpl.php and page--node—womens-blog-post.tpl.php based on content type.

Here is my attempt:

```
function force_preprocess_page(&$vars){
 if ($vars['content']->type == 'mens-blog-post') {
  array_unshift($vars['theme_hook_suggestions'], 'page__node__mens_blog_post');
 }
 if ($vars['content']->type == 'womens-blog-post'){
  array_unshift($vars['theme_hook_suggestions'], 'page__node__womens_blog_post');
 }
}

```

Can anyone help me clean this up and make it work? I am looking for any solution that works so I am open to other ideas.

# Answer
> 0 votes
I ended up using context (http://drupal.org/project/context) to swap out the content based on the content type. Big thanks to gilzero on my other post... sorry for the mess won't happen again.

# Answer
> 7 votes
To use a different template file for the node being shown, you need to add a new suggestion in `$variables['theme_hook_suggestions']` (Drupal 7), or `$variables['template_files']` (Drupal 6). In both the cases, the variable is an array.

In a module, the hook to implement is `hook_preprocess_page()`.

```
function force_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    if ($variables['node']->type == 'mens-blog-post') {
      array_unshift($variables['theme_hook_suggestions'], 'page__node__mens_blog_post');
    }
    elseif ($variables['node']->type == 'womens-blog-post') {
      array_unshift($variables['theme_hook_suggestions'], 'page__node__mens_blog_post');
    }
  }
}

```

If you have a module called force.module, then your code is correct. The same code can be used for a theme whose short name is force; in this case, in its template.php file you add a `force_preprocess_page()` function.
In Drupal 6, your theme needs to also have the default template file (page.tpl.php), or the custom template is not going to be picked up. I didn't check if this is still valid in Drupal 7. (The only time I created a theme that was using a custom template file was in Drupal 6.)

I would rather check the variable `$variables['node']` is not empty, as `hook_preprocess_page()` is called for every page served from Drupal, including the ones not associated with any node.

# Answer
> 2 votes
I would use Panels instead of a suggestion.

1. Active the "node view" page
2. Create two variants, with
    1. One selection rule for "mens-blog-post"
    2. Another selection rule "womens-blog-post"
3. Add "Node content" to a region.

Done.

Relevant video tutorials here: http://dev.nodeone.se/en/learn-page-manager first four videos should get you started :)

---
Tags: theming
---


# Question
Title: In Drupal 7, how can I include a CSS file only when the front page is being viewed?
I'd like to include a particular CSS file only when the front page is being viewed, since it only applies to the front page, and it's a relatively large file. I know that the solution will involve using drupal\_add\_css(), but I'm not sure where in my theme's `template.php` file this would go. Is there a particular hook within my theme that I should be implementing to use this? Thanks.

EDIT: I essentially have the code down, I'm just not sure what hook is available to my theme files to implement. The actual code will look something like...

```
if (!strlen(request_path())) {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/front.css');
}

```

# Answer
Try this:

```
function mytheme_preprocess_page (&$variables)
{
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/front.css');
  }
}

```

See template\_preprocess\_page and drupal\_is\_front\_page for more info.
> 10 votes

# Answer
The CSS Injector module allows you to do just that.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How a field collection item is linked to a node
I was looking through the database for a field\_collection\_item, but am still confused how it is actually linked to a node.

field\_collection\_item has 2 fields item\_id and field\_name

It seems item\_id uniquely identifies a field collection item and field name is the machine name of the field\_collection. Where do I find a table that links entity\_id's (field collections) to nodes?

# Answer
> 3 votes
If you check admin/structure/field-collections, you will find the machine name of you collections in the first column. Prepend the machine name with "field\_data", just like any other field, and you will find a table with an "entity\_id" column. In my case I have a collection called field\_coworkers, and with

```
SELECT entity_type, entity_id FROM field_data_field_coworkers;

```

I can find the entities, that the fields are attached to.

---
Tags: entities
---


# Question
Title: db_query() to retrieve the image path using the fid
In Drupal 7, I'm trying to retrieve the image path for a given fid.

If I am running a query such as the following, that is fine and dandy and returns a bunch of numbers that relate to the images on each row.

```
$query = db_query("Select s.field_swatch_image_fid as fid from {field_data_field_swatch_image} s");

foreach ($query as $row) {
  $swatch_fid => $row->fid .'<br />';
}

```

However, the table contains no information as to how to retrieve the actual image. Does anyone know the secret to pull the actual image URL into the foreach loop, or is there some sort of render function that needs to be run on the fid values? I'm guessing it is easy, but I can't seem to find any documentation on this.

Also, if I wanted to apply a style to the images, would that be a necessary step if the style was already set on the field image itself, and if so, what would be that process?

EDIT: here is the full query. I was doing it manually because I have to retrieve the value and send a json object back to jquery and then render it in jquery. But this is kindof the start to a different and larger question.

```
Declare database variables to be used in the database call
 - so far this was easier than looking at all the giant field names Drupal creates in the database
 - hoping to rewrite the query in the new improved drupal 7 style soon

*/

  $swatchcolor = "field_data_field_swatch_color";  // sc - swatch color data table
  $color = "field_swatch_color_value";
  $states = "field_data_field_state"; // s the table that holds the swatch's reference to the state
  $state = "field_state_value";
  $swatchref = "field_data_field_swatch_ref"; // sr - swatch reference target table
  $target = "field_swatch_ref_target_id";
  $imagetable = "field_data_field_swatch_image"; // swatch image ref
  $parent_ref = "field_product_ref_target_id";
  // If a swatch has not been selected, run this query and select all colors as options

  if($swc == '') {

    $query = db_query ("Select n.nid AS nid, n.title AS title, s.$state AS state
        FROM {node} n
        INNER JOIN {$swatchref} sr ON sr.$target = n.nid
        INNER JOIN {$states} s ON s.entity_id = sr.entity_id
        WHERE (s.$state IN $theregion)
        GROUP BY title");

  } else {

      $query = db_query ("Select n.nid AS nid, n.title AS title, sc.$color AS color, s.$state AS state
        FROM {node} n
        INNER JOIN {$swatchcolor} sc ON sc.entity_id = n.nid
        INNER JOIN {$swatchref} sr ON sr.$target = n.nid
        INNER JOIN {$states} s ON s.entity_id = sr.entity_id
        WHERE (sc.$color = '$swc') AND (s.$state IN $theregion)
        GROUP BY title");

  }

```

---

EDIT!! Here is how the image path was integrated into the json output:

```
 $json = array();
        foreach ($query as $row) {

        // get the image fid

          $fid = $row->thefid;
          $file = file_load($fid);
          // $file = str_replace('public:\/\/', '', $file1);

        // create the output as an array
          $jsonelement=array(

             'title' => $row->title,
             'path' => $file->uri,
             'style_name' => 'swatch'

            );
              array_push($json,$jsonelement);
        }

            // encode to json
            $jsonstring = drupal_json_encode($json);

            //output the json string
            drupal_json_output($jsonstring);

```

# Answer
> 9 votes
There is no need for manual queries.

You can load a file using `file_load($fid)`, and then the path is in `$file->uri`. It might look a bit stringe ('public://something.jpg'), but that's a so called stream wrapper, and it works just fine with plain PHP file functions.

It's not exactly clear to me what you are trying to achieve; if you want to render an image field from a node/user/..., there are better ways to embed title and things like that, but this would work if you really just have a field. (That you are trying to query the field data table suggests otherwise, though.)

```
<?php
  $file = file_load($fid);
  $variables = array(
    'path' => $file->uri,
    'style_name' => 'your_style_name',
  );
  print theme('image_style', $variables);
?>

```

---
Tags: media
---


# Question
Title: Change default language from the database?
I have made a stupid mistake:

I installed the .po for another language and set it as default (instead of English) even though I did not install/configure all the prerequisites. Now, each time I try to access my website, it goes into an endless loop and I can no longer access its configuration panels.

How can I reset the default language back to English? Is there any file to configure or database entry to change?

# Answer
> 8 votes
In the setting.php file used by your site, add the following lines:

```
$conf['language_default'] = (object) array(
  'language' => 'en', 'name' => 'English', 'native' => 'English',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

```

This will force Drupal to use English as default language. Once you removed the language files for that language, remove those lines from the settings.php file, or Drupal will always use English as default language, indifferently from what you set from the setting page.

The same trick works also for Drupal 6.

---
Tags: i18n-l10n
---


title: List of authors of articles in a view

text:
# Question
Title: List of authors of articles in a view
I am trying to create a page which lists the users who are an author of a node type of article.

I figured I would approach it by creating a view based upon article. So the view started out listing all articles. Then I set up a relationship to users where the user is the author of the article, and in the fields, I just have it output the author's name (user name).

Now I have a list of all of the authors, but it repeats. So you see John Smith a hundred times, if he wrote 100 articles.

How do you make it so that John Smith only shows up once? If I could edit the mysql, I would just use group by uid (so the user only shows once), but in drupal views, it will list that author as a heading for a group, and then list all the articles he was in (so in my setup, it would show his name followed by a listing of his name many times).

This is in Drupal 7

# Answer
> 2 votes
you are almost there. Just set "Use aggregation" to yes. Also, make sure there is not other field in "sort criteria".

---
Tags: views
---