title: How to loop over fields from query?

text:
# Question
Title: How to loop over fields from query?
I am trying to create nodes from information extracted from a SQL query by using the following:

```
db_set_active('sage');
$query = db_query('SELECT CLIENT_ID, MASTER_CLIENT_ID, PARTICIPANT_ID FROM sage.CLIENT');
$result = $query->execute();
foreach($result as $record) {
  $node = new stdClass();
  $node->title = (string)$record->participant_id;
  $node->client_id = (string)$record->client_id;
  $node->master_client_id = (string)$record->master_client_id;
}

```

However, from my `echo` statements, I can see that my code never even enters the loop.

I had thought that `execute()` returns me an object of the query to loop over, but I guess I was wrong.

Could someone please tell me how I can loop over the results of my query and get the fields?

# Answer
```
$result = $query->execute()->fetchAll();

```

should do the trick.

There's a lot more info and several more examples in http://api.drupal.org/api/examples/dbtng\_example!dbtng\_example.module/7
> 1 votes

# Answer
Also: `db_query()` does the execute for you. You only need `$result = db_query('SELECT thingie FROM whatever')'` and then loop through the results.

But you really want `db_select()`.

```
$columns = array('CLIENT_ID', 'MASTER_CLIENT_ID', 'PARTICIPANT_ID')
$query = db_select('client', 'c');
$query->fields('c', $columns);
$results = $query->execute();
while($record = $results->fetchAssoc()) {
  $node = new stdClass();
  $node->type = 'your_node_type';
  node_object_prepare($node);
  foreach($columns as $column) {
    $node->$column = $record[$column];
  }
  node_save($node);
}

```

Each $record is an associative array, keyed by the column name, thanks to fetchAssoc(). So you'll have $record\['CLIENT\_ID'\], etc. You'd then add them to the $node object however you want/need to.

Some helpful hints here: http://www.group42.ca/creating\_and\_updating\_nodes\_programmatically\_in\_drupal\_7
> 1 votes

---
Tags: 7, database
---


title: How can I filter search results?

text:
# Question
Title: How can I filter search results?
I need to restrict certain search results from showing up for users and limit them to a specific content-type. This can be either the main search or some sort of custom search since it's the only type of post that will need to be searched on the site.

# Answer
> 2 votes
You have a few options. The quickest solution is to use views and take advantage of its quick and easy, powerful filtering capabilities. Views is a must in using drupal. If I was you and you are expecting to be heavily reliant on search then look into using search\_api and views together to create some nice mashups.

---
Tags: 7, search
---


# Question
Title: Help needed for adding and edit & delete link in a column in a view table
I need to implement views with a table format to display fields for selected content. I would like one of the columns to have edit/delete links that will request perform the desired task for the row selected. I have seen it done on sites, but have not found an example In which to review the view configuration.

Clarification: Each row in a table represents a content node and each column would display a field in the content type. I want to put an edit link that will call up the specific node in that row in the editing form.

# Answer
Could you just add a field with the node ID and rewrite it to reconstruct the url, inserting the node id where applicable (different structures for different entity types)?
> 3 votes

# Answer
There is a module for that which could help you: the editablefields module.

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within the Views module, etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).
>
> This module has been totally re-written for Drupal 6, and it is very much simpler.
> 2 votes

---
Tags: views
---


# Question
Title: Issue with grouping in a view using Views PHP
I posted this a week ago at the drupal.org issue queue for Views PHP, but have not received a single response, so I'm hoping someone here can help me.

I have a view that displays a conference schedule. Each session is associated with a track (taxonomy), and gets a track icon to display. There's also one or more speakers per session (entity references to the speaker nodes). There's one type of session that needs to be associated with all the track types, but we don't want it to have a visual indicator. In order to get the icon to display conditionally, I used a Global PHP field. It prints the icon (if the conditions are correct) and then the session number and title, all on a single line. This works. The view is grouped first by date/time, so all sessions on Wednesday at 10 AM show up under a single heading. This also works. Here's the output code of the Global PHP field:

```
<?php
if(isset($data->field_field_hide_track[0]['raw']['value'])) {
    if($data->field_field_hide_track[0]['raw']['value'] == '0') {

    $image_vars = array(
        'path' => file_create_url($data->field_field_track_icon[0]["rendered"]["#item"]["uri"]),
        'alt' => $data->field_field_track_icon[0]["rendered"]["#item"]["alt"],
        'attributes' => array(
          'class' => array('session_list_track_logo')
        )
      );

    $track_logo = theme('image', $image_vars);
    print "<h3>" . $track_logo . " " . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "</h3>";
    }
    else {
      print "<h3>" . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "</h3>";
    }
}
?>

```

Before adding the Global PHP, it was secondarily grouped by a dummy field that had its output rewritten to concatenate session number and session title. (both individual fields were hidden from display.) This worked, but we couldn't display the icon conditionally.

That's where the Global PHP field comes in. If I group by date/time and then by the php field, it's inconsistent between session records. Sometimes it prints the php field twice, regardless of how many speakers there are. Sometimes it prints it once for each speaker. Sometimes it prints once for the first speaker, and a second time for the next chunk of speakers.

---

**grouped by date/time and session number (both excluded from display); displaying php field**

---

**grouped by date/time and php field (both excluded from display**

---

I've also tried grouping by all possible common fields (date/time, session number, session title, icon, and php field) which gives me such a mess I couldn't even get a decent screenshot of it because a single record doesn't fit on my screen!

This is the desired result:

I'm attaching screenshots of all of these, as well as a mockup shot of the desired result. Can anyone help me out? (Note that the groupBySessionNumber.png screenshot was taken after the Global PHP field was added, and the icon/number/title line is a result of that field.)

# Answer
> 1 votes
Consider using a Computed Field on the Session content type to combine

* the icon (conditionally)
* the session number
* the session title

Then you can use that field for the secondary sort, and leave the Global PHP out of the View. Be sure to store the computed field in the database so that Views can access it.

---
Tags: 7, views
---


title: Dynamic Content Fields

text:
# Question
Title: Dynamic Content Fields
I am new to Drupal. using drupal 7

I would like to have dynamic fields in content type. basically i would like to allow users to add a content and in that content, fields should generate dynamically.

for example if user has select CAR the next field (MODEL) should be generated dynamically according to first one having all the model for that particular car and so on.

i know about "hierarchical select" but its not good for me. conditional fields are still under development.

search a lot but did not come out with any solution. please help.

thanks

# Answer
> 1 votes
Despite your statement in your question, Hierarchical Select is the standard way to approach this sort of need.

There's likely no other stock solution for this, since no one bothered to duplicate HS.

# Answer
> 0 votes
you can let the user create the content-type himself and let him add the fields with the fieldUI.

you'll probably need to put your focus of how to manage the content-types, when should a new one be created, when can an existing be used ..

---
Tags: 7, entities
---


# Question
Title: How do I redirect a form after has been submitted?
I need to upgrade this Drupal 6 code to Drupal 7.

I add a form submission handler to a form, using an implementation of `hook_form_alter()` that executes the following code.

```
array_unshift($form['buttons']['submit']['#submit'], 'MODULE_case_form_pre_submit');
$form['buttons']['submit']['#submit'][] = 'MODULE_case_form_submit';

```

The code for `MODULE_case_form_submit()` is the following.

```
function MODULE_case_form_submit($form, &$form_state) {
  if ($form_state['values']['type'] == 'case_slide') {
    $form_state['redirect'] = 'case/' . $form_state['values']['cid'];
    return;
  }
}

```

# Answer
> 4 votes
There isn't anything different between Drupal 6, and Drupal 7, for the code you are showing, which means:

* `$form_state['values']` still contains the values submitted from the users
* `$form_state['redirect']` is still used to redirect the users to a different page

What changes is that the submission buttons for the node edit form are inside `$form['actions']`.

```
  // Add the buttons.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
    '#value' => t('Save'),
    '#weight' => 5,
    '#submit' => array('node_form_submit'),
  );
  $form['actions']['preview'] = array(
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
    '#type' => 'submit',
    '#value' => t('Preview'),
    '#weight' => 10,
    '#submit' => array('node_form_build_preview'),
  );
  if (!empty($node->nid) && node_access('delete', $node)) {
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 15,
      '#submit' => array('node_form_delete_submit'),
    );
  }

```

# Answer
> 1 votes
Your code looks correct; maybe you need to ensure:

1. The form submission hander is executed, when the form is submitted
2. The condition checked in the IF statement is true

# Answer
> -2 votes
I solved it by using the following code in `hook_node_insert()`. It works now.

```
drupal_goto("content/$title");

```

---
Tags: 7, forms
---


# Question
Title: drupal 7 - drupal_add_js - inline doesn't execute
I made a custom module and I added the following code inside the php tag and also in my hook\_menu function

`drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');`

I can't figure out why it's not firing.

When I look at the 'view source' of the page I do see this:

`<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { alert("Hello!"); });
//--><!]]>
</script>`

# Answer
> 2 votes
Go through this document http://drupal.org/node/171213 It shows how to use Jquery. The syntax for jquery ready function is:

```
jquery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});

```

---
Tags: javascript
---


title: How to remove bullets from drupal menu?

text:
# Question
Title: How to remove bullets from drupal menu?
I have created a drupal menu and added a couple of links. Unfortunately, when displayed, these come with bullets. How can I remove these? I am using the `Precise` theme, but it does not seem to be added by this theme.

# Answer
> 7 votes
This could be default browser styles. It does't matter if they are added by the browser by default or by CSS, the solution is to remove them with CSS.

```
li {
  list-style: none;
}

```

You should create a sub\_theme where you create and add your custom styles.

# Answer
> 2 votes
It can be a tough job to adjust the styling of Drupal 7 menu's. Their nested styling and classnames sometimes make it hard to override, so I came to the conclusion to completely not load the default Drupal styling for menu's in my custom themes. The results are clean pure HTML menu lists which need some custom resetting/styling off-course (primary tabs become a clean list as well!).

```
function YOURTHEME_css_alter(&$css) {
  // remove Drupal menu styling!
  unset($css['modules/system/system.menus.css']);
}

```

# Answer
> 1 votes
I finally replaced my menu with a view where I set the display format to "Unformatted list."

# Answer
> 1 votes
Do as @googletorp said, but add `!important` at the end.

```
li {list-style: none !important;}

```

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


# Question
Title: efficient way to apply content permissions
My site has content type "Department News". There are 10 departments, each one should have permission to create and edit its own "Department News", everybody can view everything.

How to implement it?

My idea is to create 10 roles - one for each department - and the only difference between them will be Create and Edit access to a specific content type.

Then create 10 identical content types, just named differently - and configure permission for the Department-Content matrix.

The question: is it possible to implement it somehow more efficiently, at least without creating 10 content types which are identical, only for the purpose of assigning permissions to them. Best would be also to get rid of the 10 roles and e.g. check additional permission for "Department News" based on a field in user profile.

Duplicating almost identical roles and content types is a burden from maintenance point of view.

# Answer
Have you tried looking into Organic Groups? It seems like the PERFECT solution to your problem. It'll require a bit of work to set up, but the benefits will FAR outweigh the work.

You could have each department set up as a group, and then users can be assigned to those groups. You can then set permissions that allow users to create content but only for their specific group (using OG means that this can be ONE content type).

You'd only need one user role (an organic groups user..you could also have a department admin per department should you want).

You can also do some more awesome stuff from here on out. Just as an example, these departments could then view their own department content - but you can also display all posts from all groups.

There are some REALLY good videos at Modules Unraveled
> 0 votes

---
Tags: 7, users
---


# Question
Title: Passing variables to a theme from a custom module
I have a custom module which initiates the theme hook - passing the $node object as an argument:

```
theme('my_widget', array($node));
```

```
function my_module_theme() {
  return array(
    'my_widget' => array(
      'template' => 'my_widget',
      'variables' => array('node' => array($node)),
    ),
  );
}

```

However, in the 'my-widget' template file, I need to pick up the $node variable. But doing a dpm() on $node returns Null.. - think I may be setting the variable incorrectly, but not sure what's going on. Cheers

# Answer
The correct code is the following one.

* Theme call

```
theme('my_widget', array('node' => $node));

```
* Theme declaration

```
function my_module_theme() {
  return array(
    'my_widget' => array(
      'template' => 'my_widget',
      // This array contains the default values.
      // You should not use a PHP variable.
      'variables' => array('node' => NULL),
    ),
  );
}

```
> 6 votes

---
Tags: theming
---


# Question
Title: create a copy of a field-collection for entity clone
I have a use case where I need to create a copy of an entity (commerce product) that is home to various field collections.

the entity is created by a simple load/save combo:

```
// load entity
$old_entity = commerce_product_load_by_sku($sku);

// copy
$new_entity = $old_entity;

// alter copy so it can be saved as a new entity
$new_entity->status = 0;
$new_entity->title = $old_entity->title . '(COPY)';
$new_entity->is_new = TRUE;
// [...] and a few more unsets (created, revision, copying translations...)

// ->>> missing field_collection clone / exchange of id references in the entity here <<<-

// save entity
commerce_product_save($new_entity);

```

As the field\_collection id stored in the entity remains unchanged, both entities now share the field collection which leads to unwanted effects.

Can someone point me to a reference on how to create copies of field\_collections and get their id's returned, so I can exchange them in the parent entity before saving it? ... or maybe there is an even better way to deal with this?

# Answer
> 4 votes
This has been solved by **chalee** on d.o on the following issue: Integrate node\_clone with field\_collection module.

This is his function that works just fine for my use case:

```
<?php
function clone_fc_items($entity_type, &$entity, $fc_field, $language = LANGUAGE_NONE){
  $entity_wrapper = entity_metadata_wrapper($entity_type, $entity);
  $old_fc_items = $entity_wrapper->{$fc_field}->value();
  if (!is_array($old_fc_items)) {
    $old_fc_items = array($old_fc_items);
  }

  $field_info_instances = field_info_instances();
  $field_names = element_children($field_info_instances['field_collection_item'][$fc_field]);

  unset($entity->{$fc_field}[$language]);

  foreach ($old_fc_items as $old_fc_item) {
    $old_fc_item_wrapper = entity_metadata_wrapper('field_collection_item', $old_fc_item);
    $new_fc_item = entity_create('field_collection_item', array('field_name' => $fc_field));
    $new_fc_item->setHostEntity($entity_type, $entity);
    $new_fc_item_wrapper = entity_metadata_wrapper('field_collection_item', $new_fc_item);

    foreach ($field_names as $field_name) {
        //if (is_array($old_fc_item->{$field_name})){
            if (!empty($old_fc_item->{$field_name})){
                $new_fc_item->{$field_name} = $old_fc_item->{$field_name};
            }
        //}
    }
    $new_fc_item_wrapper->save();

    //Now check if any of the fields in the newly cloned fc item is a field collection and recursively call this function to properly clone it.
    foreach ($field_names as $field_name) {
        if (!empty($new_fc_item->{$field_name})){
            $field_info = field_info_field($field_name);
            if ($field_info['type'] == 'field_collection'){
                clone_fc_items('field_collection_item',$new_fc_item, $field_name,$language);
            }
        }
    }

  }
}
?>

```

Again, kudos goes to **@chalee** \- thanks :)

---
Tags: 7, entities
---


# Question
Title: Style block based on configuration setting
I'm writing a module for Drupal and a bespoke theme. The blocks of the modules either float to the left or the right of the region their in. Currently I do that by hard coding specific css styles, e.g.

```
#block-myModuleName-myBlockName {float:left; background: red;}
#block-myModuleName-anotherBlockName {float:right; background: blue;}

```

I want to be able to set left/right (and maybe something else like background colour). So I've created an admin form that saves a persistent variable, such as `variable_get('myBlockName-left', 0)`.

I can use that in the block content. I can wrap the content in a div that is based on the var such as `<div class="myModulesetToLeft">`, but that will not include the title, and it's a bit messy because it's deeper into the DOM of the block.

Do I need to create a template file for blocks? But that code will need to know what block it is displaying, so that it can check the right variable to know which class to add to the block div.

# Answer
I'd probably just use the Block Class module and assign a classes like `block-left` and `block-right`.

> Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent `<div class="block ...">` element of a block. Hooray for more powerful block theming!
> 1 votes

# Answer
You should really do three things:

1. Instead of using an admin form and `variable_set` / `variable_get`, you should use a theme settings form.
2. You would then make a `template_preprocess_block` in your theme, which reads a theme variable with `theme_get_setting` and sets something in `$variables`.
3. In your block template, use the variable that you set.

If you can accomplish all of this with just CSS classes, then in your preprocess, you can just tack classes onto `$variables['classes_array'][]` and skip the third step.
> 1 votes

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


title: Editing a Custom Block

text:
# Question
Title: Editing a Custom Block
I have taken over the maintenance of a site that was built with Drupal 6.x

Prior to this I have no Drupal experience, so I am rolling up my sleeves and getting stuck into how Drupal works, with vcarying degrees of success.

My problem is this:

There is a menu on the site which I would have presumed was primary navigation, but it turns out to be a block.

I need to edit this menu, but there are no options to do so under blocks, there is a configure button beside it, but this does not allow me to edit its content. There is no delete option shown either, as I notice some blocks have this option and others dont.

Any ideas where I can find the content of this block so that I can edit it?

# Answer
> 0 votes
You get the delete option in the block configuration page for those blocks that have been created using Add Block option (in Admin \>\> Site Building \>\> Block). In your case the menu block in question might have been created programatically using hook\_block or any other means that I'm not aware of and the Delete link might not appear due to the same. Suggest that you identify the code/module responsible for generating the block before you proceed on to anything. Also if you wish to replace this block with something more easily configurable I'd suggest using Nice Menus which I feel is a wonderful module

---
Tags: 6, blocks
---


# Question
Title: Facebook like photo gallery with comments, tag photo, share etc
Is there any Facebook like photo gallery module with comments, tag photo, share option. Please help in this.

# Answer
To annotate images in Drupal *7*: Imagefield Marker http://drupal.org/project/imagemarker

See also: Image Annotations in Drupal 7

Very good multiple image uploader in Drupal 7: Media module http://drupal.org/project/media (Quick way to get this is to create a free drupalgardens.com account and export the whole Drupal 7 code)

Comments are built-in in Drupal 7 for many content types.

Consider also: http://drupal.org/project/disqus (Drupal support for DISQUS a discussion comment system for integration with various social networking sites)

Also: Facebook Comments module: http://beacon9.ca/labs/drupal-7-facebook-comments

I would suggest integrating comments with an existing social network as their authentication policies (particuarly Facebook's for example) can discourage trolls, spam and provide you with a centralised means of managing the comments, as well as spreading awareness of your site as their comments on your site are seen by their friends in their feeds).
> 4 votes

---
Tags: social-network, media
---


title: Form and Table on same page

text:
# Question
Title: Form and Table on same page
I got a Form and a Table displayed on the same page. The weird thing is that when the form is submitted and the page are reloaded (after doing a database SELECT) with $\_POST values, the table is not showing....why?

Here is the code (suppose $tabb2 have correct table data):

```
<?php

function collabinc_menu($may_cache) {
  $items = array();
  $items['admin/reporting/report_details2'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'say_report_details2',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function say_report_details2($values = array()) {
  $output = "";

  if (isset ($_POST['search'])) {
     $output = theme("table", $tabb2);
  }

  $build['content'] = array(
    'this_does_not_matter_too_much2' => drupal_get_form("report_details_form"),
    'this_does_not_matter_too_much1' => array('#markup' => $output,),);

  return $build;
}

```

Please note that both Form and Table are working, and displayed correctly at the same time when not putting the "if (isset ($\_POST\['search'\]))" condition. Also note that the condition is fully working and checked.

Thanks!

# Answer
You can use the Table theme. Example :-

```
$form['data_field'] = array(
'#type' => 'textfield',
'#title' => t('Search!'),
'#id'   => 'search',
'#maxlength' => 1024,
'#description' => t('Search by using tags and free text'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Go!!',
);
...
...
fill $table
...
...
if(sizeof($form_state['input'])!=0) {

$form['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('Empty Rows')
);
}
return $form.

```
> 2 votes

# Answer
It sounds like it might be related to this post: hook\_form being called twice. After the page reloads the form\_state is no longer retained. The solution they suggest:

> Set `$form_state['redirect'] = false` to prevent redirection.
> 0 votes

---
Tags: forms, theming, routes
---


# Question
Title: What options exist for search result weighting (e.g. promoting same score results higher in the results)
I'm impressed with search in core; especially when empowered with the **Search Configuration** module. However I'm skimming the modules in the search category & not seeing anything that allows for arbitrary result weighting, perhaps the sticky bit could be used for this, but I was looking for something more granular; like a specific content type having a specific taxonomy term would float higher in the results.

# Answer
Although Search API / Apache Solr Search Integration are popular modules with more flexible control over boosting, the core Search module allows you to add custom scoring via hook\_ranking().

There is a code snippet in a comment in the documentation referenced above that at least hints how to do the boosting fpr content types. Boosting on a specific taxonomy term might be a little more tricky because the scoring logic is done in the "score" key, which is effectively a SQL clause. Therefore you have to either get fancy with joining a custom table that has some of your custom scoring logic pre-calculated when the node is indexed, or you will have to add you logic directly in the SQL clause to generate it on the fly. The latter could get messy if you have a lot of conditions.
> 3 votes

# Answer
Search\_api together with search\_api\_solr lets you do this as does apachesolr. I find search\_api easier to work with.
> 2 votes

---
Tags: search
---


# Question
Title: How can I make a link to a node obtained from an SQL query?
I'm trying to make a module for a users profile page which shows all of the content of certain types they have created. I have got the query to work and list the results in a block - however I can not get the returned list to contain links to the nodes. Here is my code:

```
function get_articles()
{
  if(arg(0) == 'user' && is_numeric(arg(1)))
  {
    $account = user_load(arg(1));
  }

  $result = db_query('SELECT node.title FROM {node} node WHERE (( (node.uid = :uid) AND (node.status = \'1\') AND (node.type IN (\'article\')) )) ORDER BY `created` DESC LIMIT 5', array(':uid' => $account->uid));

  if($result->rowCount() > 0)
  {
    $list = array(
      '#theme' => 'links',
      '#links' => array(),
    );

    foreach($result as $record)
    {
      $list['#links'][] = array('title' => $record->title, 'href' => $account->name . '/' . $node->title);
    }

    return drupal_render($list);
  }
  else
  {
    return t('This user has no Articles.');
  }
}

```

Thank you in advance to anybody who answers.

# Answer
> 1 votes
```
foreach($result as $record)
{
  $list['#links'][] = array('title' => $record->title, 'href' => $account->name . '/' . $node->title);
}

```

You have $node-\>title in this code, but there is no $node object. The href appears to be the user's name, and then the title of a node? So the link would be http://example.com/johndoe/My Page Title, which doesn't seem right.

Is this what you're trying to do? First, add node.nid to your list of SQL columns

```
foreach($result as $record)
{
  $list['#links'][] = array('title' => $record->title, 'href' => 'node/' . $record->nid);
}

```

You might also look into bypassing the $list array, and the drupal\_render() function, and simply use:

```
$links = "<ul>";

foreach($result as $record)
{
  $links .= "<li>" . l($record->title,'node/'.$record->nid) . "</li>";
}

$links .= "</ul>";

return $links;

```

---
Tags: nodes, database
---


title: Create template pages

text:
# Question
Title: Create template pages
Using Drupal 7 and Clean theme. And my main module is Views. And i want, create template tpl.php file for every page.

I know node id method but don't know how create tpl file for views pages.

Please help, thank you.

# Answer
In the views ui, click on 'advanced' and go to 'theme information'. This gives you a number of suggestions for the template file and what code should be in it.
> 0 votes

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


# Question
Title: Apache Solr Search show only currrent user language
I'm using Apache Solr Search Integration to do the searching on our website, works great except i get results for all the language on the site instead of only the one the user is currently using.

Is there a way to show only nodes that are in the current users language? Either filter it out of the results by a simple check or directly in the query?

I was hoping there would be a hook to alter the results before the pager is created, i got as for as filtering out the other language in hook\_apachesolr\_search\_page\_alter() but thats to late, then you get a pager for 3 pages with only one result.

I also tried Apache Solr Multilingual but that doesn't seem the work really well at the moment for 7.x.

# Answer
One way to do this is to implement hook\_apachesolr\_query\_alter() to automatically filter on the current language. In a custom module called "mymodule", the code snippet would look similar to the following:

```
/**
 * Implement hook_apachesolr_query_alter()
 */
function mymodule_apachesolr_query_alter($query) {
  global $language;
  $query->addFilter("ss_language", $language->language);
}

```
> 8 votes

---
Tags: 7, search, i18n-l10n
---


# Question
Title: Problem in displaying with Embedded Google Docs Viewer module
I'm using Embedded Google Docs Viewer module,everything is ok except when viewing it's showing like this:

How can solve this problem?

# Answer
> 1 votes
Open the `PPTX` file and Save As a `PPT` file. This worked for me to prevent the unexpected symbols in the google docs viewer when trying to embed a `PPTX` file.

# Answer
> 0 votes
Can the PDF be accessed? Is it behind a password? Are the permissions correct on the file?

If you try with another PDF does the same thing happen?

e.g

www.inference.phy.cam.ac.uk/itprnn/book.pdf

https://docs.google.com/viewer?url=www.inference.phy.cam.ac.uk/itprnn/book.pdf

~Mark

---
Tags: 7
---


# Question
Title: drupal 7, how to select multiple servers in LDAP Authorization?
I was using multiple servers i.e one is ADS and the other one is Open LDAP in drupal 7 for the authentication. LDAP Authorization Configuration is showing both the servers with a radio button option, where i can choose only one option. But i need to pick both the option. Please could anybody help me out.

If there is any option. Just am new to Drupal. If there is a option, please share with me. thanks

# Answer
To my knowledge -- unless your LDAP schemas are very similar or you want to write some custom LDAP queries you cannot query 2 ldap sources "at once". Actually in Perl I think you can have 2 sources for a query, but in PHP you can only have server connection ...

So, typically you just waterfall a request through X ldap servers hoping 1 will succeed. I haven't used the drupal 7 LDAP module yet because it was buggy when I was looking at it months ago.

You can do LDAP stuff in drupal with php by hand using user\_external\_login\_register() which I've done in drupal 7 for various LDAP authentication points.

A small random example off of the web.
> 0 votes

---
Tags: commerce
---


# Question
Title: When using Rules to set a value on a taxonomy term reference field, I get choices like "field:0", "field:1", etc. What do these numbers mean?
When I add a "Set a data value" action for my taxonomy term reference field, Rules allows me to choose from the following:

* field-age
* field-age:0
* field-age:1
* field-age:2
* field-age:3

What are these ":0" ":1" etc. fields?

EDIT: These appeared when I changed the "Number of values" for field-age from "1" to "2". However, since I only changed the number of values to 2, why did 4 things appear?

# Answer
It's basically letting you have access to a zero-based array for the different instances of a multiple cardinality field (as I think you've already worked out).

It seems the reason there are 4 shown is just a default; a visual cue to let you know there are more than one possible values for that field.

If you have a field with 20 values you'll still only see `0...3` in the Rules data selector, even though you can use `0...19`.
> 2 votes

---
Tags: taxonomy-terms, rules
---


# Question
Title: Showing term description on terms page that are displayed using views
I am currently using a view to override Drupal's core taxonomy pages. Unlike the core handling of taxonomy pages, views does not display the current term's description. Is there a good way to display a term's description through views or would I need to make a template file for the view?

# Answer
> 1 votes
If understood correctly... simply add the field `Taxonomy: Term description` to your view:

# Answer
> 3 votes
1: Create a view much like this one (It is a term view using the term ID as a contextual filter then showing an unformatted list of the description field):

```
$view = new view;
$view->name = 'catalog_taxonomy_term_descriptio';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Catalog Taxonomy Term Description';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Catalog Taxonomy Term Description';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Taxonomy term: Term description */
$handler->display->display_options['fields']['description']['id'] = 'description';
$handler->display->display_options['fields']['description']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['description']['field'] = 'description';
$handler->display->display_options['fields']['description']['label'] = '';
$handler->display->display_options['fields']['description']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['description']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['description']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['description']['alter']['external'] = 0;
$handler->display->display_options['fields']['description']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['description']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['description']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['description']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['description']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['description']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['description']['alter']['trim'] = 0;
$handler->display->display_options['fields']['description']['alter']['html'] = 0;
$handler->display->display_options['fields']['description']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['description']['element_default_classes'] = 1;
$handler->display->display_options['fields']['description']['hide_empty'] = 1;
$handler->display->display_options['fields']['description']['empty_zero'] = 0;
$handler->display->display_options['fields']['description']['hide_alter_empty'] = 1;
/* Contextual filter: Taxonomy term: Term ID */
$handler->display->display_options['arguments']['tid']['id'] = 'tid';
$handler->display->display_options['arguments']['tid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['tid']['field'] = 'tid';
$handler->display->display_options['arguments']['tid']['default_action'] = 'empty';
$handler->display->display_options['arguments']['tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['tid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['tid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['tid']['not'] = 0;
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'catalog' => 'catalog',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'catalog-taxonomy-term-description';

```

2: Go into your taxonomy term view (I'm assuming you have already edited/overridden this) and set the Header in the Page Settings section to Global: View area. In the settings for that you will be able to select your view description view. This will cause the term description to show up the top of the page while displaying the related nodes below it.

# Answer
> 1 votes
@carsonblack's solution worked for me. Initially it wasn't working, but I just needed to tick the box that says "Inherit contextual filters" - which is found on the Global: View area settings.

---
Tags: 7, views
---


# Question
Title: Restrict comments on nodes of a content type based on user role
I am building a site in Drupal, where there are 2 different types of registered users. Let us call them *basic users* and *premium users*. These could be roles, or groups, or something else.

Authorized users will be able to publish pages with simple content and comments underneath. All pages are viewable publicly, even by non registered users and so are the comments.

Only registered users should be able to post comments.

What I would like is for some pages to allow comments only from *premium users*. So, there would be two categories of pages. Again let us call them *basic pages* and *premium pages*.

The permissions would be as follows:

**Basic pages**
READ: all
COMMENT: *basic users*, *premium users*

**Premium pages**
READ: all
COMMENT: *premium users*

Any help/pointers would be appreciated, as I have limited experience with Drupal.

# Answer
> 3 votes
You can perform a hook\_form\_alter on the comment form in a custom module. This will allow you to change the form so it checks if the current user has a premium role. If the acting user has the premium role the option to submit a comment is displayed. If they do not show a message like "only premium members can comment".

```
MODULENAME_form_alter(&$form, &$form_state, $form_id) {
if ( $form_id == 'comment_form') {
  global $user;
   if (!user_role('Premium'){
    // Form alter here to unset comment form and show "only premium members can comment"
    unset($form['author']);
    unset($form['subject']);
    unset($form['comment_body']);
    unset($form['actions']['submit'] );
    unset($form['actions']['preview'] );
    print "Only Premium members can comment";
  }
 }
};

```

You can look in comment.module for the default code for comments....

# Answer
> 3 votes
The Comment Permissions module might be what you're looking for. Though there is only a Drupal 6 variety. Here is a quote about it (from the module's project page):

> ... enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.
>
> Note that "reply" links below comments may still appear for users without the permission to add comments. This is unfortunate, but I haven't found a workaround. See https://www.drupal.org/node/185855 for more information. Of course, the links can easily be removed in the theme layer.

# Answer
> 3 votes
Just a clean code to complete the Approved answer above:

```
/**
 * Implementation of hook_form_alter
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    // First make sure we are altering the right form
    if ($form_id == 'comment_form') {
        // Keep the form alter clean by moving the logic to a separate function
        _MYMODULE_restrict_comments($form, $form_state);
    }
}

/**
 * Restrict comments in content type based on user role
 */
function _MYMODULE_restrict_comments(&$form, &$form_state) {
    global $user;
    $node = $form['#node'];
    // a custom function to do your logic
    if (_MYMODULE_comments_should_be_restricted($user, $node)) {
        // unset form elements, you can fetch them easily by print_r(array_keys($form));
        unset($form['comment_body'], $form['actions'], $form['author'], $form['subject']); // etc.
        // add a optional message for user.
        $form['no_access'] = array(
            '#markup' => t('You have no access to comment on this content.')
        );
    }
}

```

---
Tags: comments, users
---


# Question
Title: How do I jump to a specific place on a page?
I wish to be able to jump to a specific place on a given page.

I have inserted `<a name="placetojumpto"></a>` into the text of the page, and set the link to the page to be "about\_us/customers/#placetojumpto."

If I type the URL in the address bar it works fine, but when I try use the link generated by Drupal, it converts the "#" to "%2523," so the link becomes "about\_us/customers/%2523placetojumpto" and then fails.

# Answer
> 7 votes
The problem is that you have the #, called fragment, in the path, Drupal escapes it for you, and what you need to do is tell Drupal specifically that you want a fragment in the url.

Example:

```
l('linktext', 'node/1', array('fragment' => 'placetojumpto'));

```

Documentation here: http://api.drupal.org/api/drupal/includes--common.inc/function/l/7

# Answer
> 1 votes
Get rid of the / before the #

So your link will be

`<a href="about_us/customers#placetojumpto">Link here</a>`

Then your link will go to the #placetojumpto anchor on the customers page :-)

# Answer
> -1 votes
This works for me in drupal 7: `<a href="#contact" id="contact">Contact</a>`

---
Tags: uri
---


# Question
Title: How to limit Node refernce field selection to user own nodes?
If there are 3 content types that user can create A, B and C. A is main content, B and C are secondary content types, each time B or C created they automatically have reference to A. My goal is to make possible optionally create reference on C node to B, by displaying check list (when C node is edited/created) with B nodes from same A node. This nodes can have only 1 author and only 1 main A node, so C2 can not be referenced to A1 or B1, only to A2-B2, even if they have same author.

What can be the best way to create such reference filter/pernissions?

Thanks

# Answer
You can create a View of type References, and then configure the Node Reference field to use that View.

So you configure the View to only list nodes that the current user is the author of, and any additional filters you want. That should give you what you want.

Look for this area when you edit the Node Reference field:
> 4 votes

---
Tags: 7, users, nodes
---


# Question
Title: cannot validate custom field widget for user profile field when editing node
I have defined a field widget and set #element\_validate to validate the input. This works fine when I create an account, but when I update the account, the field is not validated and does not even save the changes. It is as though the field doesn't exist

# Answer
> 0 votes
I got around it by attaching the validation in hook\_form\_alter:

```
function referrer_widget_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "user_profile_form") {
        $form["field_who_referred_you"]["#element_validate"] = array('referrer_widget_field_widget_validate');
    }
}

```

---
Tags: 7, entities
---


# Question
Title: Using custom test helpers in your test cases
I'm trying to write test cases for my custom module and in order to speed things along for current and future testing I defined a garbage class that can spit out random data. However the testing module cannot seem to locate my Garbage class. After some debugging I realize that Drupal looks in the registry table to find the class and while my class is defined in the default registry table, simpletest creates it's own custom registry table to run tests which doesn't contain my class or it's location. Is there any way around this or some way to force simpletest to make an exact duplicate of the registry table?

Notes:

* The garbage class is located in a separate file (Garbage.php)
* Yes I do have 'files\[\] = Garbage.php' in my .info file.
* While I could just move the garbage functions into test case itself, I may need to reuse it for other tests later on so having it in a separate class is ideal.

Garbage class

```
    class Garbage {
        public static function getGarbageString(int $i = 1) {
            $return = array();
            for ($j = 0; $j < $i; $j++) {
                $return[$j] = self::_getRandomString();
            }

            return $i == 1 ? $return[0] : $return;
        }

        private static function _getRandomChar() {
            return chr(mt_rand(33,126));
        }

        private static function _getRandomString() {
            $length = mt_rand(1, 255);
            $return = '';
            for ($i = 0; $i < $length; $i++) {
                $return .= self::_getRandomChar();
            }

            return $return;
        }
    }

```

Located in .module file

```
    function getRecord($recordName) {
        return $records[$recordName];
    }

```

Located in RecordTestCases which extends DrupalWebTestCase

```
    public function testGetRecord() {
        $badData = Garbage::getGarbageString();
        $this->assertNull(getRecord($badData), 'Testing get record with bad data');
    }

```

# Answer
If getRecord() and testGetRecord() are methods of the Garbage class, then you have a misplaced } bracket.

Alternately, testGetRecord() will have no idea what to do with $this, since it's not part of a class definition. It would need to be a method of a subclass of DrupalUnitTest, or DrupalWebTest. As-is, PHP will choke on it.
> 0 votes

---
Tags: 7, testing
---


title: Form theming not working

text:
# Question
Title: Form theming not working
Please could someone advise what is wrong with the following? When the page loads it downloads an unknown file type. The form is displayed but not with the template/theming.

The form...

```
function test_form($form, &$form_submit) {
    $form['message'] = array(
            '#type' => 'textarea',
            '#title' => t('Message'),
            '#required' => TRUE,
    );
    $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Send')
    );

    // Get the path to the module
    $path = drupal_get_path('module', 'test');

    // Attach the CSS and JS to the form
    $form['#attached'] = array
    (
            'css' => array
            (
                    'type' => 'file',
                    'data' => $path . '/css/test.css',
            ),
            'js' => array
            (
                    'type' => 'file',
                    'data' => $path . '/js/test.js',
            ),
    );

    $form['#theme'] = 'test_form';
    return $form;
}

```

The theme...

```
function test_theme($existing, $type, $theme, $path) {
    return array(
            'test_form' => array(
        //'arguments' => array('form' => null),
        'path' => drupal_get_path('module', 'test') . '/templates',
        'template' => 'test',
        'render element' => 'form',
            ),
    );
}

```

The directory...

* test
* test/css/test.css
* test/js/test.js
* test/templates/test.tpl.php
* test/test.info test/test.module

# Answer
> 0 votes
It sounds like there is just a problem with the loading of the attached files in your $form\['#attached'\] setting. Are you getting 404 errors from your debugger for the js and css files or is it not trying to load them?

You should try rewriting your form settings with the type as a settings array (if you need it) according to the API documentation

```
$form['#attached'] = array
(
        'css' => array
        (
                $path .'css/test.css' => array('type' => 'file',),
        ),
        'js' => array
        (
                $path .'js/test.js' => array('type' => 'file',),
        ),
);

```

or maybe more simply as:

```
$form['#attached']['css'] = array(
  drupal_get_path('module', 'test') . 'css/test.css',
);

$form['#attached']['js'] = array(
  drupal_get_path('module', 'test') . 'js/test.js',
);

```

---
Tags: forms, theming
---


# Question
Title: Can you create a script to programatically run update.php on multiple drupal sites
We have a multi-site install that uses the same core files but different databases. As of right now, we have over 40 sites. When I do module and core upgrades, I have to login to each site and manually run update.php.

Is there a way to automate this process so that I do not have to spend so much time logging into every multisite, run update.php and clear the cache? If so, what is the exact command to run update.php? I've tried wget and that doesn't seem to work.

# Answer
> 3 votes
I've written a similar script on a 50+ site multisite install. You want to use the command line powertool drush for this, and then run the command

```
drush updb

```

from a shell script, ex:

```
cd /var/www/site1-environment/
drush updb --uri=http://site1.com
cd /var/www/site2-environment/
drush updb --uri=http://site2.com
... etc

```

Of course if all of these sites are in the same multi-site structure than you won't need to repeat the cd command in your shell script.

---
Tags: 7, updating, multi-sites
---


title: Populate nodes with XML data via XSLT

text:
# Question
Title: Populate nodes with XML data via XSLT
I have a Drupal 6 website that needs to populate a page with data from an XML feed. We are considering using XSLT to transform the data into an appropriate format, however in searching the internet for ideas I haven't come up with much.

So far I've found CCK XSLT, which doesn't seem to have much documentation behind it, and Services, which seems to interact only with an XML-RPC server (we would simply be pulling a feed itself, not interacting with a server).

Is there a good way to go about doing this?

(Also, I don't have enough rep to create an XSLT tag. If some kind user would like to retag for me, I'd appreciate it)

# Answer
> 1 votes
The easiest (though probably not the best), is to do something like:

```
// http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_permission/7

function mymodule_permission ()
{
    return array(
        "view mypage" => array(
            "title" => t("View My Page"),
            "description" => t("View My Page"),
        ),
    );
}

// http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7

function mymodule_menu ()
{
    $items = array();

    $items["mymodule_mypage"] = array(
        "title" => "My Page",
        "page callback" => "_mymodule_generate",
        "access arguments" => array("view mypage"),
        "type" => MENU_CALLBACK,
    );

    return $items;
}

function _mymodule_generate ()
{
    $path = drupal_get_path('module', 'mymodule');

    drupal_add_css("{$path}/mymodule.css", array(
        "type" => "file",
    ));

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

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

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

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

```

This is stripped down code I have taken from a custom module I have for displaying a resume maintained in XML format.

---
Tags: nodes, importing-exporting
---


# Question
Title: How to migrate from test environment to production environment?
The migration is from the local environment to the production environment. The production environment has run some time and created a lot of articles.

In order to add new things to my site, I added a custom theme and installed CCK, Views and other modules in my local test environment. Now that the local test environment is finished, how do I migrate it to the production environment, without destroying the content of its database?

# Answer
> 35 votes
This is a non-trivial problem that almost everyone has a different answer for: there isn't a canonical Drupal way to handle staging to production pushes. Dries Buytaert, the guy who runs the Drupal show, made it one of the key initiatives of Drupal 8. Of course, Drupal 7 was just released, so it'll be a while before that bears any fruit.

The problem can be broken out into two separate issues:

* Staging configuration (variables, content types, fields, views, etc.)
* Staging content (nodes, users, etc.)

The former can be mostly handled by the Features module, which will take your site configuration and turn it into a module you can add to your Drupal installation: this way, you can add it to your version control system and not having to worry about it being blown away when you migrate your content.

The latter is really tricky, because on an active site, it's likely the content will change on production even after you've made the initial sync to your development environment. This prevents wholesale replacement of content during staging like you can do with configuration.

Additionally, Drupal doesn't use universally unique identifiers (UUIDs) for content: every time a node or a user is added, the ID increases by one. So what might be node 45 on your development site might be node 90 on your production site.

Unfortunately, I don't have a great solution for this: staging content is a real weakness of Drupal. What I personally do is add content on the production site only. If a client wants to see how the content looks prior to it going live, I'll set up a clone of the production site that's only accessible to the client. Then, once approved, the same changes are then made directly to production.

There's another alternative that gets tossed around: the Deploy module. It's supposed to leverage Services to make staging content relatively painless. But I can't vouch for its effectiveness and it doesn't have a Drupal 7 version.

# Answer
> 7 votes
In our process.

1. We have a shell script that pull the db from prod.
2. We are using Hudson to rebuild our dev/staging branches to sync live and dev branches.

Since we are using Git, every task we are doing has its own branch, then when passed to QA we merge it to master as our staging server for regression testing.

When master is ready we do a test release to our `Release Server` which is a replica of live (configuration, hardware, etc).
3. We use `Feature` module to deploy configurations. Some stuffs are not yet supported by feature so we use hook\_update\_N then run updatedb.php or `drush -vd updb`
4. After release perform Features revert(`drush fra --yes`) to revert all overriden feature.
5. Since we are using Boost(moving to Varnish) and Memcache, we need to clear the cache(`drush cc all`).

We are using rsync to sync our images/video etc...

# Answer
> 2 votes
To Migrate from a XAMPP server to another server, I followed the instructions on this site.

Make sure that you keep the same structure on your production server as you did on your development server. I also had to edit some files in Drupal admin dashboard located at: **admin/config/media/file-system**

Ensure that your *Public file system path* and *Temporary directory* have the correct locations set.

---
Tags: 7, migrations, staging
---


# Question
Title: How do I include custom CSS files in the styles dropdown?
I am trying to include custom *css* file to *ckeditor*.

It doesn't show *css* file in styles drop-down list.

I have included this two lines of code into;

```
 /drupal/sites/all/modules/ckeditor/ckeditor.config.js

 config.extraPlugins = 'stylesheetparser';
 config.contentsCss = 'test.css';

```

Thanks a lot for the help.

# Answer
Have tried going adding the css file via the configuration page?

yoursite.com/admin/config/content/ckeditor/edit/

navigate to the page, edit the target profile and click on the CSS link to expand the configuration pane... you should be able to tell CKeditor what to do from there. I'm not sure if its necessary but you may need to refresh the site's cache before the new files get picked up. hope this helps.
> 0 votes

---
Tags: wysiwyg
---


title: Is there a way to sort by taxonomy?

text:
# Question
Title: Is there a way to sort by taxonomy?
On the the main content page: mysite.com/admin/content we are allowed to sort by a few criteria. Sort by content type, published date etc. but is there a way to sort by taxonomy? It seems like previous versions of drupal could do this. But not so in 7? I know you can create a view to handle this, but i am curious if its possible to accomplish the functionality via the content admin page.

# Answer
There's no way to do it with the default content admin page, short of writing code to alter the form. Vocabularies aren't linked exclusively to nodes in Drupal 7, they can be linked to any type of entity using the field system, so having this functionality wouldn't make sense by default any more.

Creating a View is definitely the right way to go; personally I'd install the Administration Views module which replaces (amongst others) the default content admin page with a View.

The module page says it provides support for filtering by vocabulary out of the box, but even if it doesn't provide sorting you could easily just tweak the View to your own requirements.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Restrict users from creating certain title
I want to restrict the users from creating contents with certain title. I require the following functionality.

**Example :**

1. Prevent users from creating a content with title, say **ABCD**
2. Prevent users from creating a content which has the words, say **ABCD** in the title.

Is there a module for this purpose. I'm new to drupal and I searched drupal.org but couldn't find a module. Thanks in advance

# Answer
> 2 votes
I would look into using a combination of automatic nodetitles, field\_validation and clientside validation. Basically once you have those three installed you can create a new text field on your content type which you will use as the title. In the validation settings for that field you can then set it up to not accept certain rules (see this post). Under the edit section of the content type you can set auto nodetitles to use your new field (and hide the title field) as your title.

# Answer
> 1 votes
**Module Approach**

The Field Validation module may be able to help you validate titles and content.

**Module Setup Details**

*Create a Black List*

You could add a new 'blacklist' of words against a field if you have a specific list. This would knock out the use of **ABCD** as noted in both cases you listed above.

*Use REGEX*

You could use REGEX to validate against one or both of the cases you listed above.

Lullabot has some good introductory information to this module as well.

**Advanced**

If you're looking to get your hands dirty you could add a validation function to any form using hook\_form\_alter().

You can use the Form API Quickstart Guide as an intro into custom validation. Specifically, see the *Validating Forms* section.

---
Tags: 7
---


# Question
Title: code snipped where a form call itself when submiting
I am creating a custom module that I would like to use to display a form, from a module. The form queries a database and displays some information. The database connection is working, and the data has been retrieved successfully. The form has also been displayed successfully, but what I can figure out is how to link all together to have the page displayed again when submitting the form. My code is:

```
<?php

function menu($may_cache) {
    $items = array();
    $items['admin/reporting/report_details'] = array(
        'title' => 'Report: User details by stores',
        'access arguments' => array('access content'),
        'page callback' => 'say_report_details',
        'type' => MENU_CALLBACK,
    );
return $items;
}

// This function should execute the logic if the $_GET variable is set
function say_report_details($values = array()) {
    // The $_GET logic will be somtehing like this
    // if (count($_GET) > 0)
    // Get all the form values from the $_GET wit something like:
    // if (count($_GET) > 0) {
    // $start = mktime(0, 0, 0, $_GET['from_month'], $_GET['from_day'],

    $_GET['from_year']);
    //   $end = mktime(23, 59, 59, $_GET['to_month'], $_GET['to_day'], $_GET['to_year']);
    if ($_GET['store'] > 0) {
        $form = drupal_get_form("report_details_form");
        $output = theme("report_page", $form, $output);
        return $output;
    }

function report_details_form() {
    $form["search"] = array(
        '#type' => 'fieldset',
        '#title' => t('Search params'),
        '#collapsible' => FALSE,
        '#tree' => TRUE,
    );
    for ($i = 1; $i < 32; $i++) {
        $days_opt[$i] = $i;
    }
    for ($i = 1; $i < 13; $i++) {
        $month_opt[$i] = $i;
    }
    for ($i = 2008; $i < date("Y") + 3; $i++) {
        $year_opt[$i] = $i;
    }
    $form["search"]["from_day"] = array(
        '#type' => 'select',
        '#title' => 'Date from',
        '#options' => $days_opt,
        '#default_value' => (($_GET['from_day'] == "") ? date("d") : $_GET['from_day'])
    );
    $form["search"]["from_month"] = array(
        '#type' => 'select',
        '#title' => ' ',
        '#options' => $month_opt,
        '#default_value' => (($_GET['from_month'] == "") ? date("m") : $_GET['from_month'])
    );
    $form["search"]["from_year"] = array(
        '#type' => 'select',
        '#title' => ' ',
        '#options' => $year_opt,
        '#default_value' => (($_GET['from_year'] == "") ? date("Y") : $_GET['from_year'])
    );
    $form["search"]["to_day"] = array(
        '#type' => 'select',
        '#title' => 'Date to',
        '#options' => $days_opt,
        '#default_value' => (($_GET['to_day'] == "") ? date("d") : $_GET['to_day'])
    );
    $form["search"]["to_month"] = array(
        '#type' => 'select',
        '#title' => ' ',
        '#options' => $month_opt,
        '#default_value' => (($_GET['to_month'] == "") ? date("m") : $_GET['to_month'])
    );
    $form["search"]["to_year"] = array(
        '#type' => 'select',
        '#title' => ' ',
        '#options' => $year_opt,
        '#default_value' => (($_GET['to_year'] == "") ? date("Y") : $_GET['to_year'])
    );
    $result = db_query('SELECT taxonomy_term_data.name, taxonomy_term_data.tid FROM
    taxonomy_term_data WHERE vid = 10');
    $strs = array("all" => "All");
    foreach ($result as $store) {
        $strs[$store->tid] = $store->name;
    }
    $form["search"]["store"] = array(
        '#type' => 'select',
        '#title' => 'Stores',
        '#options' => $strs,
        '#default_value' => $_GET['store']
    );
    $form["submit"] = array("#type" => "submit", "#value" => "Show report");
    return $form;
}
function theme_report_page($form, $result = array()) {
    $output = '
    <div id="report_form">
    '. $form .'
    </div>
    <div id="report_result">
    '. $result .'
    </div>
    ';
    return $output;
}

function theme_report_details_form($form) {
    unset($form['search']['from_day']['#title']);
    unset($form['search']['from_month']['#title']);
    unset($form['search']['from_year']['#title']);
    unset($form['search']['to_day']['#title']);
    unset($form['search']['to_month']['#title']);
    unset($form['search']['to_year']['#title']);
    unset($form['search']['store']['#title']);
    $output = "<fieldset>
    <legend>Search params</legend>
    <div class='fieldtitles'>". t('Date From') .":</div>
    ". drupal_render($form['search']['from_day']) ."
    ". drupal_render($form['search']['from_month']) ."
    ". drupal_render($form['search']['from_year']) ."
    <div class='clearing'> </div>
    <div class='fieldtitles'>". t('Date To') .":</div>
    ". drupal_render($form['search']['to_day']) ."
    ". drupal_render($form['search']['to_month']) ."
    ". drupal_render($form['search']['to_year']) ."
    <div class='clearing'> </div>
    <div class='fieldtitles'>". t('Store') .":</div>
    ". drupal_render($form['search']['store']) ."
    <div class='clearing'> </div>
    ". drupal_render($form['submit']) ."
    </fieldset>";
    unset($form['search']);
    $output .= drupal_render($form);
    return $output;
}

function report_details_form_submit($form_id, $form_values) {
    $query = "";
    // This next line is the one we are having an issue right now, as is trowing an
    error due to $form_values is empty for some UNKNOWN reason...
    foreach ($form_values['search'] as $key => $value) {
        $query .= "&". $key ."=". $value;
    }
    return array('admin/reporting/report_details', $query);
}

```

# Answer
Try changing `function report_details_form()` to `function report_details_form(&$form_state)`

You will also need to change `function report_details_form_submit($form_id, $form_values)` to `function report_details_form_submit($form_id, $form_state)`

I would highly recommend reading through the Form API Quickstart Guide for this type of form.

Also, if you are not already using it, install the Devel module so you can access the dpm() function.

From here you can add `dpm($form_values);` to visually debug form variables.
> 0 votes

---
Tags: forms
---


# Question
Title: Modifying only node forms, not forms appearing in blocks?
I have a contact webform in a block in a sidebar that appears on every page.

I also have some webform nodes.

I want to use `hook_form_alter()` to modify the forms that are nodes, not those that appear in blocks.

How can I differentiate between the two in code?

# Answer
**Using hook\_form\_formID\_alter()**

You could use `hook_form_formID_alter()` to target this Webform node specifically.

For example:

```
function hook_form_webform_client_form_429_alter(&$form, &$form_state, $form_id) {
    // Alterations here.
}

```

webform\_client\_form\_429 in this example is found using the `<form id=''>` from the node in the block you want to alter.

**Using hook\_form\_alter for all Webforms rendered in a block**

If the Webform block was created using webform\_block\_view() then $form\['#node'\]-\>webform\_block should be TRUE. Pages on the other hand should be `$form['#node']->webform_block == FALSE`

Try using dpm() from the Devel project to poke around the $form variable for webform\_block specific items.

My assumption would be that you could use:

```
hook_form_alter(&$form, &$form_state, $form_id) {
   if ($form['#node']->webform_block == FALSE) {
      // Alterations
   }
}

```
> 0 votes

---
Tags: nodes, blocks, forms
---


# Question
Title: Always prompt for a shipping address even if there are no shippable products with Ubercart
I manage a site selling online classes. Some classes include shipped items (books, posters, etc); for these classes, the cost of shipping is included in the class price.

Ubercart products are configured as non-shippable, as automated shipping quotes through UPS should not add any additional cost.

I'd like to configure Ubercart (6.x-2.4) to always prompt users to enter a shipping address, without returning an error message when products in the order are not flagged as shippable.

At present, Ubercart will always prompt the user for a shipping address if "Hide shipping information when possible for carts with no shippable items" is unchecked in "Checkout settings." However, it looks like the UPS module will always try to calculate a shipping quote if shipping details are prompted for, regardless of whether items are shippable or not. If this is the case, an error message is displayed informing the user that a shipping could not be calculated.

Is it possible to configure shipping settings to still prompt for a shipping address, while preventing shipping modules such as UPS from returning an error message if no shippable products are configured?

For example:

```
    Order A: (works with UPS shipping module)
         Shippable_product_A  $10 (shipping $5)
         Shippable_product_B  $20 (shipping $8)
         --------------------------------------
         Total order cost: $30 + $13 => $43

    Order B: (does NOT work with UPS)
         Shippable_product_A    $10 (shipping $5)
         Non-Shipped_product    $15
         ---------------------------------------
         Total order cost: $25 + $5 = $30

```

# Answer
The only work around for this is to alter the UPS module yourself or report it as bug, (because in my opinion, this is a bug.)

You could probably write a module that would override the UPS module to circumvent the above suggestions. You have pretty clearly hit the nail on the head though. The problem is not Ubercart but the modules that are interacting with it inappropriately. I know the FedEx module takes into account shipable products, if my memory serves me correctly.

The entire shipping pane should be hidden if there are no shipable items. (That is the point of having that option in the products.)
> 2 votes

---
Tags: ubercart
---


title: Hidding a form element before printing

text:
# Question
Title: Hidding a form element before printing
I want to print only bits of a very big form, my first approach was as follow:

```
function THEME_preprocess_user_profile(&$variables) {
    global $user;
    $account = user_load($user ->uid);
    $variables['user_edit']  = drupal_get_form('user_profile_form', $account);
    $variables['user_edit']['field_about_me'] = 'invisible';
    .....
    $variables['user_edit']['field_some_filed'] = 'invisible';

}

```

This does work to hide certain element, the problem is that there is way more elements i want to hide than elements i want to show, so this process can be tedious..

Would anyone think of a better way to do so ?

**UPDATE :** Ideally i'd like to have a function similar to drupal\_get\_form, but that instead only return a targeted element.

Thanks a lot

# Answer
Either save the elements you wish to print in temporary var, hide all (or unset them), then reassign the saved elements to $vairables array, or use DS module.
> 1 votes

# Answer
if you want to hide elements the appropiate way is to set the `#access` attribute on each element to FALSE, using a `hook_form_alter()`

> '#access'
>
> Used by: All elements and forms
>
> Description: Whether the element is accessible or not; when FALSE, the element is not rendered and the user submitted value is not taken into consideration.
>
> Values: TRUE or FALSE.

Source: http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html/7#access
> 7 votes

# Answer
Remember #access will not consider the particular elements in submit process. we can set #access to false if we want to totally ignore the fields.

In case you want to hide the field with a default value. just pass attribute in form alter:

```
$form[fldname]['#attributes']['style'][] = 'display:none;';

```
> 3 votes

---
Tags: 7, forms
---


# Question
Title: Views pager labels translation per context
Now that I finally have managed to have Views pagers appear, I'm wondering how I could change the strings collection (prev, next, first, last...) per View. That's because in a View that displays items in chronological manner, I would rather see labels like older/newer rather than previous/next. Can this be done somewhere in views template or in template.php? (No jquery here, please :))

# Answer
> 0 votes
Use hook\_pager() in your theme template.

```
function YOUR_THEME_pager($tags) {
  echo "<pre>";
  var_dump($tags);
  echo "</pre>";
}

```

---
Tags: 7, views, i18n-l10n
---


# Question
Title: How to restrict access to content based on roles (multiple levels) and show a public preview?
I'm looking for a reliable solution for the following situation:

1. a membership site with multiple levels of access for users (based on roles, say anonymous, and levels 1 through level 4)
2. need to restrict node view access by role on a per node basis, but allow anonymous access to the teaser (should be possible to show/restrict other fields as well)
3. take performance and flexibility into account

There are several modules that solve most of the problem, but not entirely. I'm looking for recommendations on the combination of modules to use, and whether I'd need to extend any of these with custom code or if just combining contrib modules is feasible.

* Premium content offers the basic functionality, but it seems to only work for the regular body field. Is it still a good option if you want to publically show or restrict other fields? (e.g. restrict the body as well as another text or file field).
* Taxonomy Access Control: I like how you can easily change the access level per node by just changing the assigned taxonomy term. But how would I allow anonymous access to the teaser or other fields?
* Field permissions offers all the granularity on the field level I would need, but I need the option to restrict one field (e.g. node body) to different roles on a per-node basis.
* Or maybe do something with Panels (cf. this answer)?

A solution that plays nice with other modules (e.g. Views) is preferred (I think TAC would qualify here - e.g. filter by taxonomy, maybe use VBO for changing terms...).

How would you do this?

**Update**: I've looked into using Panels; whle I like the flexibility that a Panels-based approach offers, I doubt it's feasible for my use case.

Using Panels, the selection rule would have to be based on a combination of current user's role and node being viewed's term id, so for each selection rule you'd need 2 criteria and the 'All criteria must pass' setting. So each access level (except 'Anonymous') needs two variants: one for the combination of tid + roles that get to view the teaser, and one for tid + roles that get the full node.

Since there are 5 roles to take into account (anonymous + roles A, B, C, D) I'd need 9 page variants. This doesn't feel quite elegant, or would 9 variants be acceptable? (thinking about performance, maintainability etc.).

Another problem is that the Term ID criterium in the selection rule is per Content type, so if I wanted to use this for multiple content types I'd need even more variants. Since I need the 'All criteria must pass' setting for the combination of role and term id, I cannot add term id of two content types in one selection rule.

Another option would be to use PHP for evaluating the selection rule, but that feels like it may be defeating the purpose of using Panels. And code in DB is not a good idea, etc.

So unless I am overlooking a simpler way with Panels, it doesn't seem such a good idea (except maybe with custom PHP for selection rules...)?

# Answer
I would use Panels.

Basically, for all of your **Panel Pages**, you would have two variants.

Each variant would have a **Selection Rule** based on the user role, one for the role and one for not the role.

Then on each, build up the content the way you need. Personally, I would make a custom node view for the restricted view, so you can use the **Node Being Viewed** content piece and just configure it to use the view mode you made.

The reason I recommend Panels is that it makes it easier to change things in the future without needing to get special-function modules to cooperate with each other.
> 6 votes

---
Tags: 7, panels, users, taxonomy-terms
---


# Question
Title: Access imagefield file object during node create/update
I have a content type with an imagefield. I need to get a reference to the file object during node save or update, so I can do something with it.

```
function foo_node_presave($node){
    if ($node->type ==='foo'){
        $filename = $node->original->field_foo_image['und'][0]['filename'];
    }

```

In the above code, $filename isn't populated yet when a new node is being created. It does work during a node update if there was already a file in that field.

How can I get a reference to the file object in a filefield/imagefield in a hook during node creation?

# Answer
> 1 votes
Even if the field hasn't been updated yet you should have access to the `fid` column (the file ID), which you can use in conjunction with the `file_load()` function to get the filename:

```
// Load a file object based on the fid column fo the field.
$file = file_load($node->field_foo_image[$node->language][0]['fid'];

// Get the filename.
$filename = $file->filename;

```

---
Tags: hooks, media, files
---


# Question
Title: Programmatically adding fields to node submission form
I need to add fields to a node creation/editing form programmatically. More specifically, I need to take already-generated form elements from another form and insert them into the node submission form.

That part isn't what's hanging me up though. My problem is that I can't figure out how to make the database hang onto the values submitted via the new field.

For example, the following code (copypasta'd directly from the API Quickstart page) creates a form element inside the existing node form just fine, but when I enter a value and submit the form, the value is not stored.

```
function [mymodule]_form_alter(&$form, &$form_state, $form_id) {
    $form['foo'] = array(
      '#type' => 'textfield',
      '#title' => t('bar'),
      '#default_value' => t('foo'),
      '#size' => 60,
      '#maxlength' => 64,
      '#description' => t('baz'),
    );
}

```

How do I alter an existing form in such a way that the submitted values 'take,' so to speak?

# Answer
I hacked together a way of doing this. I have NO IDEA whether this is at all a good idea, or if I'm doing something blatantly terrible, so any code or ideas here are for information purposes only!

So, here's what I did (for a module called "webformta")

1. On my content type "Answer Key" I added a text field with unlimited multiple values enabled.
2. Inside `webformta_form_alter()` I add my fields:

```
    $form['foo'] = array(
      '#type' => 'textfield',
      '#title' => t('bar'),
      '#default_value' => t('foo'),
      '#size' => 60,
      '#maxlength' => 64,
      '#description' => t('baz'),
    );
 # ... and so forth for all the form elements as I want to add.

```
3. Then, after I add the form elements I want, still inside `webformta_form_alter()`:

```
    $form['#submit'][] = 'webformta_answerkey_submit';

```
4. Next, a separate submit function:

(This appends the responses given onto the ones already in the field without overwriting or deleting the old ones because the `[]` after `$form['#submit']` above adds this onto the `$form['submit']` array instead of replacing it.)

```
function webformta_answerkey_submit($form, &$form_state) {
    $foo = $form_state['input']['foo'];
    $values = $form_state['values']['field_answer_answers']['und'];
    $count = 0;
    foreach ($values as $value){
        $count += 1;
    }
    $form_state['values']['field_answer_answers']['und'][$count]['value'] = $foo;
    $form_state['values']['field_answer_answers']['und'][$count]['_weight'] = $count;
}

```

So, the values entered by your user in as many fields as you want can be stored in an array as one field with many values on the node submission form.

Anyone know if this is a terrible idea for any reason?
> 2 votes

# Answer
Add something like this to your `hook_form_alter()`.

```
$form['#submit'] += array('mymodule_another_submit_handler');

```

Create that function and save your values from `$form_state['values']`.

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

```

Where are they supposed to go? You might try to fire the submit handler of the other form so you wouldn't have to write so much code.
> 3 votes

# Answer
Your code just defines a form element. If you want to put the submitted value into the DB you have add a submitthandler and write appropriate code for it.

Maybe you consider adding a field to this node type as this does all the DB numbo jumbo for you for free. No coding would be required at all.
> 0 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Add an html snippet some within body of the theme using preprocess
I want to add a small html within the body tag of the site. I believe I can use template preprocess for this. I don't want to touch the template files. I am doing this from a module.

# Answer
You should add hook\_node\_view() into your module. See the given example on how to add HTML markup.

```
function mymodule_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

```
> 3 votes

# Answer
You can use `hook_preprocess_page()` for that:

```
MODULENAME_preprocess_page(&$vars) {
  // …
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: What is the difference between rendered entity and content in views 3?
In the **Format** option for a view, the options include **Content** and **Rendered Entity**.

They both offer you a selection of view mode for the content. The former includes some extra options on comments/links.

So what is the point of **Rendered Entity** if it's a single configuration of **Content**?

Suspect I'm missing something!

# Answer
> 19 votes
At a guess...

The "Rendered Entity" format is available so *any* type of entity can be rendered. The "Content" format is only available for nodes, and as such can't be used generically.

Nodes are entities (as are users, taxonomy terms, and a whole host of others provided by contrib modules) and so just happen to be one of the 'items' that the "Rendered Entity" format can handle.

It also happens that Views already implements a format specifically for nodes ("Content"), so it does kind of look like there's repetition; but in reality it's not repetition at all, they're two separate things that just happen to have a bit of crossover in functionality.

---
Tags: 7, views
---


# Question
Title: link next to field to add referenced entity for site editor
EDIT: I want link button in an edit form of a content type like 'store' that says 'add store section'. This link/button should directly go to the edit form that adds a new 'store section' which is pre-configure by me as entity reference. This link would be next to a drop-down list of already available 'store sections'.

First step would be that the link needs to go to the node/add form of contenttypeB. I've heard as a hint that `hook_field()` functions are what I need. Something would have to get the form id somehow and this is where I'm confused, I'm wondering if I need to address the contenttypeB nodeforms hardcoded into my `.module` file? Or do I just need to start doing this by looping through all the fields of the content types and checking whether those fields are an entity reference and then apply it?

I'm still very scared of module development and php as I can stare at code for too long. I'm sort of getting the hook concept a little bit now. Things like `hook_men()` and then how it goes to the callback function I sortof get. Or when it can go to `drup_get_form()` and you fill in the function to build a form, I can dig that.

Just to say what level I'm at.

# Answer
This could be done without a custom module, by using the Markup module.

However, if you are looking for the ability to add a new ContentTypeB that is immediately referenced, the References Dialog module can do this.
> 0 votes

---
Tags: hooks, entities
---


title: Get user object within module

text:
# Question
Title: Get user object within module
I need the $user object within a module am creating. But am not able to get it. I have created a module that extends user object hold more data. Its working fine. I am also able to use this values in theme files. But am not able to get it in any function within a module.

The standard value `$user->name;` or my custom value `$user->data['privacy'];` nothing is available in module.

I tried using this

```
global $user;
$user = $user->name;

```

What is the mistake here? Is it that global is not the right way to get the user object?

# Answer
> 1 votes
You're currently referencing the global `$user` object, then in the very next line you're overwriting it with a string (the username). So your global `$user` object is destroyed, and you will probably be logged out of the site (as well as the code not working as expected).

You're referencing the global user object in the correct way, but by default it isn't fully loaded (i.e. with fields attached, etc). To get the extra data you should use the `user_load()` function like so:

```
global $user;

// Get the fully loaded user object
$account = user_load($user->uid);

// Get the username. Make sure you don't override the global $user object here!
$username = $account->user.

// Get a field value.
$field_items = field_get_items('user', $account, 'field_foo');

```

# Answer
> 0 votes
I had the same problem, and I fixed it with the following code.

```
 module_load_include('pages.inc', 'user', 'user');
 global $user;

```

---
Tags: 7, users
---


# Question
Title: How to create a single image style for both landscape and portrait images?
In a Drupal 7 environment, I want to apply a style to all images within a view. I want every image to be 180px wide & 128px high -OR- 128px wide and 180px high depending on the orientation of the original image.

Can this be done with an image style or do you know any module that would help in achieving this?

# Answer
ImageCache Actions

> Aspect Switcher new 2009-08 - lets you perform different actions or use different dimensions based on whether the image is 'landscape' or 'portrait'
> 2 votes

---
Tags: 7, media
---


title: Avatar upload during register. D6

text:
# Question
Title: Avatar upload during register. D6
It is possible upload a avatar during the registration process? Then save it into the profile.

# Answer
> 1 votes
I haven't used it before but the Register with Picture module sounds like it would do the trick:

> This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.

There are stable versions for both Drupal 6 and Drupal 7. It also has 1600+ installs, is actively maintained and has very few issues in the queue, so I'm assuming it should work great.

---
Tags: users
---


# Question
Title: Taxonomy inline with several category types?
Is it possible for D7 to display several taxonomy fields inline with some separator between them? I want to have a node with 2 category types, say, a song with a Year and a Singer. Now the taxonomy displays in a column:

```
Year: 1999
Singer: Britney Spears

```

And I want it to appear inline with some separator:

```
Year: 1999 |separator| Singer: Britney Spears

```

I've found a similar question but it deals with displaying one multivalued taxonomy field. That's not quite what I want. So where should I look and what I should override to display several types of taxonomy fields inline?

**Update**: after spending 2 days on that I've done it using node.tpl.php and field.tpl.php. It's always better to print your separators outright. Relying on CSS is good but not when there are guys using IE6 out there (I've seen one as late as 2011). Not that I did the best solution ever here (I'm lousy with the code) but still it works and at least does what I want it to do. I did the following:

1) copied node.tpl.php from modules\node to sites\all\themes\mytheme. 2) used $content variable to find all taxonomy fields:

```
$taxonomy_field_names = array();
$all_field_names = array_keys($content);
foreach($all_field_names as $i => $value)
{
    $field_name = $all_field_names[$i];
    $field_type_name = '#field_type';

    //if content contains an array with $field_name and it is an array itself
    //and has an item #field_type of taxonomy_term_reference
    //it is a taxonomy field
    if(is_array($content[$field_name]) &&
        array_key_exists($field_type_name, $content[$field_name]) &&
        $content[$field_name][$field_type_name] == 'taxonomy_term_reference')
    {
        $taxonomy_field_names[] = $all_field_names[$i];
    }
} unset($i);

```

3) hid them to prevent rendering:

```
//hiding taxonomy fields
$count_taxonomy_fields = count($taxonomy_field_names);
for($i = 0; $i < $count_taxonomy_fields; $i++)
{
    hide($content[$taxonomy_field_names[$i]]);
}

```

4) after rendering $content I rendered taxonomy fields:

```
//rendering taxonomy fields
for($i = 0; $i < $count_taxonomy_fields; $i++)
{
    //printing a separator after each of the fields except the very last
    if($i < $count_taxonomy_fields - 1)
    {
        $content[$taxonomy_field_names[$i]]['#separator'] = '•';
    }
    print render($content[$taxonomy_field_names[$i]]);
}

```

5) copied field.tpl.php from modules\field to sites\all\themes\mytheme and renamed it field--taxonomy-term-reference.tpl.php (affects all ). After setting $content\[$taxonomy\_field\_names\[$i\]\]\['#separator'\] at the previous step one can use it as $element\['#separator'\] in field--taxonomy-term-reference.tpl.php:

```
<?php if (isset($element['#separator'])): ?>
<span class="field-item-separator"><?php print $element['#separator']?></span>
<?php endif; ?>

```

6) added the following lines to sites\all\themes\mytheme\css\fields.css:

```
.field-type-taxonomy-term-reference .field-item {
   float:left;
}

```

To people who answered my question I offer my sincere thanks.

# Answer
**Option 1: Pure CSS.** Assuming that you have your Content type's display options are set so that all the taxonomy reference fields are next to each other, you would simply display each of the divs that wrap each taxonomy field as an inline element, then use the \+ selector and :before pseudo-element to add your separator between each field.

These two special selectors are supported in most web browsers, but you might want to check whether they can be used in older browsers your site may need to support.

For example, if each taxonomy field is wrapped with a div having the class "field-type-taxonomy-reference" and your nodes have a div with the class "node-type" wrapping them, your CSS would look something like this:

```
//make the taxonomy fields and their contents display as inline elements
.node-type .field-taxonomy-reference,
.node-type .field-taxonomy-reference * {
  display: inline;
}

//add a pipe separator between two taxonomy fields
.node-type .field-taxonomy-reference + .field-taxonomy-reference:before {
  display: inline;
  content: " | ";
}

```

**Option 2: edit the HTML with a custom field template.** Copy the field.tpl.php file from Drupal core into your theme and rename it field--taxonomy-reference.tpl.php. This would affect all taxonomy reference fields across your entire site, which may not be desirable. You can also implement template\_preprocess\_field() in your theme's template.php to add a new template suggestion for only the nodes (and fields) that you want to have affected by this template. For example:

```
function YOURTHEME_preprocess_field(&$vars) {
  $variables['theme_hook_suggestions'] = array('field__' . $element['#field_type'] . '__' . $element['#bundle']);
}

```

This would allow you to use a field template named field--taxonomy-reference--news-article.tpl.php to affect all taxonomy reference fields on a node type named "new article". One the documentation page for template\_preprocess\_field() you can see a few other variables that are available for you to check (such as field name). You could make multiple fields with different names (and types) across multple node types use the same field template like this:

```
function YOURTHEME_preprocess_field(&$vars) {
  $field_names = array('field_name_a', 'field_name_b', 'field_name_c');

  if(in_array($element['#field_name'], $field_names) {
    $variables['theme_hook_suggestions'] = array('field__inline-style');
  }
}

```

This would allow you to use one template named "field--inline-style.tpl.php" for the fields named "field\_name\_a", "field\_name\_b", etc.
> 4 votes

# Answer
You have a few different options for this.

Option 1: CSS and Node Template -- You can simply use CSS to display the fields inline (e.g., using floats or display: inline-block). Then you can create a template file specific to the node type and print the separator between the two fields.

Option 2: Field and Node Templates -- You could also use the approach described in the answer you linked to in your question and apply it to both fields, making them display inline. Then in a template file specific to the node type you can print both fields, with the separator in between.

Option 3: Use a custom theme function -- You could also use a custom theme function for either the node type or the fields to accomplish the same thing, displaying the fields inline and printing a separator in between.

I suggest going with whichever approach sounds easiest to you. Often times people are more comfortable tackling issue in one manner over another, equally correct, manner.
> 0 votes

# Answer
There is an easier solution for the delimiter, at least: Taxonomy Formatter module: http://drupal.org/project/taxonomy\_formatter

But, here is some theme override code, which you add to your theme.php file:

```
function NAMEOFYOURTHEME_field__taxonomy_term_reference($vars) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$vars['label_hidden']) {
    $output .= '<span class="field-label"' . $vars['title_attributes'] . '>' . $vars['label'] . ': </span>';
  }

  // Render the items.
  $output .= '<ul class="field-items"' . $vars['content_attributes'] . '>';
  foreach ($vars['items'] as $delta => $item) {

    // Set a delimiter, in this case a comma
    $delimiter = ' | ';

    // If the item is the last in the array remove the comma
    if (end($vars['items']) === $item) {
      $delimiter = '';
    }

    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');

    // Output each taxonomy term item, with the delimiter on the end
    $output .= '<li title="Term Description should show here...themephp"  class="' . $classes . '"' . $vars['item_attributes'][$delta] . '>' . drupal_render($item) . $delimiter . '</li>';
  }

  $output .= '</ul>';
  // Render the top-level wrapper element.
  $tag = $vars['label_hidden'] ? 'div' : 'section';
  $output = "<$tag class=\"" . $vars['classes'] . '"' . $vars['attributes'] . '>' . $output . "</$tag>";

  return $output;
}
?>

```

I am not the author of that code (not a PHP programmer), but found it in looking for a similar solution.

In my case, I need the taxonomy term description to show on hover of the term -- so, simply in the TITLE attribute. I need this for both the node display and node form.

If anyone can help me with that, I'd be soooo grateful. I've been researching, experimenting, posting for weeks!
> 0 votes

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


title: Flush cache only for changed pages

text:
# Question
Title: Flush cache only for changed pages
I'm working on a site with Varnish enabled, but I notice that the system clear cache pages, according to the expire configuration, also if pages are not changed. Is it possibile to clear cache only if a page is changed?

Thanks, Sergej

# Answer
You can achieve this by setting a very high default TTL (expire time) and then invalidating the cache only for modified content. The Varnish module and the Cache Actions module are useful tools for that purpose.

Fabian Sörqist, maintainer of the Cache Actions module, has written a detailed article about it here: http://dev.nodeone.se/en/caching-with-varnish-drupal-7-and-cache-actions
> 1 votes

---
Tags: caching, proxies
---


# Question
Title: Pass parameters to Drupal to Return XML data
Is there a module that allows the user to pass the parameters in `POST` or `GET` form, and Drupal will return in XML.

Like I have a view named `table`. `table` has fields named `account_number` and `device_id`. I would like to pass parameters in URL like

`?view=table&account_number=123&device_id=d12`

Then the Drupal would return in XML based on the searching criteria passed in URL.

# Answer
> 2 votes
Exposing Views as XML is one of the features of the Views Bonus Pack module. You would lose your idea of using GET parameters, but you can easily build up other paths, pipe in your parameters, and get output as XML.

This is also something that the Services module can handle, but isn't as tightly coupled with views. This module is very well documented, though. In particular, I suggest reading the REST examples. This is an add-on, Services Views, that may fit your needs, but I have never tried it.

# Answer
> 1 votes
You can also use Views data export. Its very easy to setup. You can as well use the parameters almost the way you wanted - just define the filter on the view.

---
Tags: views
---