# Question
Title: How to make radio buttons required and have a possible default value
I have a set of radio buttons. I first check the database to see if one of the options has already been set for the user and if so add it to `$attending`. If none have been set I don't want a default value. I thought I could achieve this by setting `default_value` to `false`. The problem I have is that when setting `default_value` to `false` and I submit the form without selecting an `attending` option, Drupal does not give me an error saying I didn't select an option for that radio group. How do I set a default value to nothing so that Drupal gives an error when I try to submit without selecting an option?

```
$form['attending'] = array(
  '#type' => 'radios',
  '#title' => t('Will you be attending?'),
  '#options' => array(
    '1'   => t('Yes'),
    '0' => t('No'),
  ),
  '#required' => TRUE,
  '#default_value' => isset($attending) ? $attending : false,
);

```

# Answer
> 3 votes
I'm not sure exactly why this happens; maybe `FALSE` is being cast to an integer in the validation, being evaluated as `0`, and becoming an acceptable selection (your value for "No" being `0`).

Fortunately you can use `NULL` instead:

```
'#default_value' => isset($attending) ? $attending : NULL

```

---
Tags: forms
---


title: Migration data from Tridion to Drupal

text:
# Question
Title: Migration data from Tridion to Drupal
I've been tasked with migrating a Tridion based website to a Drupal installation. (It's more of a rebuild really)

I was wondering if any of you have any experience with migrating the data from Tridion in a such a form that I could use it in Drupal. I have never worked with Tridion and don't know the first thing about it (the documentation does not seem to be open?).

So my question to you is: What is the best/easiest/most reliable way to import the data from a Tridion driven application in to a Drupal application? (I would seriously prefer not to do it manually.)

Any general tips you might have are also much appreciated.

# Answer
> 3 votes
There are a number of api/integration points for SDL Tridion, depending on your version you have:

SDL Tridion 2009 and previous -\> TOM (Tridion Object Model) a COM+ API you can use in a .NET project.

SDL Tridion 2011 -\> TOM (as before) or the SDL Tridion Core Service (.NET web service)

I'd recommend using these APIs to extract the information you need from Tridion into XML data in the structure that makes it easy for you to work with.

You can then use something like the services module http://drupal.org/project/services to process and import your XML.

Also maybe of use... SDL Tridion is a component based CMS and content is based on a specific **Schema** items. A schema is likely to translate to a drupal **content type** pretty well, but if you're trying to achieve the sort of flexible layout that you can get from SDL Tridion (page/component templates) you'll likely need to be using the Panels module.. or something similar.

Let me know if you need some more information.

# Answer
> 2 votes
I can't tell about Tridion, but I'm sure there is a database of some sort.

As soon as you're talking about data migration, you have to consider the Feeds module.

Feeds can eat many data formats, XML and CSV for instance, so it's just a matter of exporting your data in a smart way.

---
Tags: migrations
---


# Question
Title: create relation between two nodes using the relation module
I am using the relation module and i don't like the way the default relation blocks work(entity collector and relation add blocks).

SO I'm trying to write my own block for creating relation. I have a form which has two text boxes, where the user selects two different end points between which the relation has to be made. he then clicks on submit and the relation has to be created.

coming to the relation module, i see that it doesn't have an API for use. Also i looked at the existing relation creating blocks(entity collector and relation add), they load entities and not nodes. Can some one explain me how i load all the entities available. Also is there a way where I can get the entity from the node id ?

Thanks.

# Answer
I have a module that uses Hierarchical Select to give users a nice looking UI to create relations from.

Below is an excerpt of how I create the relation.

```
  $tid = 1; // A term id.
  $node = node_load(1);
  $relation_bundle = 'a_type_of_relation';

  $endpoints = array();
  $endpoints[] = array('entity_type' => 'taxonomy_term', 'entity_id' => $tid);
  $endpoints[] = array('entity_type' => 'node', 'entity_id' => $node->nid);

  $new_relation = relation_create($relation_bundle, $endpoints);

  if ($rid = relation_save($new_relation)) {
    drupal_set_message(t('Relation created'), 'status', FALSE);
  }
  else {
    drupal_set_message(t('Creating relation failed'), 'warning', FALSE);
  }

```

Adding more useful validation and messages is left as an exercise to reader, as that will be very context sensitive.
> 1 votes

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


# Question
Title: How to add a css class to the nodes in the front page according to taxonomy of each node in drupal 7?
in the front page, I have displayed multiple nodes (article) in the teaser view, each article has taxonomy.

I want to theme each node teaser according to the taxonomy it has, I think it can be done in the theme\_preprocess\_html(&$variables, $hook), for example

```
function theme_preprocess_html(&$variables, $hook) {
  if ($variables['is_front']) {

    // something here, but I don't know what to do
  }
}

```

the first step is how to find all the nodes in the frontpage, the second is to get the taxonomy of each node, the third is to add the specific css class to each node according to the taxonomy of each node

Does any have suggestions?

# Answer
Supposing that "field\_tags" is the taxonomy field for which you want to use the taxonomy term values, you could use the following code.

```
function theme_preprocess_html(&$variables, $hook) {
  if ($variables['is_front']) {
    $terms = array();

    foreach ($variables['page']['content']['system_main']['nodes'] as $nid => $array) {
      $items = field_get_items('node', $array['#node'], 'field_tags');
      foreach ($items as $tid) {
        if (!isset($terms[$tid]) && ($term = taxonomy_term_load($tid))) {
          $terms[$tid] = drupal_html_class($term->name);
        }
      }
    }

    if (!empty($terms)) {
      foreach ($terms as $class_name) {
        $variables['classes_array'][] = $class_name;
      }
    }
  }
}

```
> 2 votes

# Answer
an easier way could be with views - you can create / enable a view that will replace the homepage. there you can add the taxo as a hidden field and use it in the class setting of the row
> 1 votes

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


# Question
Title: add block to front page as a new section
I want to add block to front page as a new section On ours website, but I didn't succeed, please can you help me to do it? I used views to create it but when i create it doesn't show in blocks.

website: www.awene.com (is a kurdish website in iraq) designed by drupal 6.

Best regards

# Answer
Do you have a section available to add the block to or do you need to add a section to put the block in? To add a new section you'll need to edit the .info file for your theme and add the new section definition there. Also you'll need to modify the active page template for your homepage adding a new section to the template file. Then you can define where the block will appear and in the block config you can define that it only appear on the `<front>` page if that's the desired result.
> 1 votes

# Answer
You need to first specify what region the block will be displayed in (most likely the Content region, I'm thinking in your case). This can be done by going to the Blocks administration section. Save once you've specified the appropriate region.

Then you need to configure the block. On the same page, find the entry representing your block and click Configure (it should be off to the right). Scroll down to the bottom, select the radio button "Only the listed pages" and enter "" in the big text area. Click "Save block". That should get the appropriate block into the appropriate region.

Afterwards though you'll need to use CSS to style the block correctly, but that's not really in the scope of this question.
> 1 votes

---
Tags: blocks
---


title: SQL Views Taxonomy

text:
# Question
Title: SQL Views Taxonomy
I have an SQL querry that creates a comparison table based on taxonomy and am wondering if it is possible to recreate using Views??

If a node has a taxonomy it selects the node tile and 'Y' else 'N' A sample of the SQL code is:

```
enter code here

select a.title AS SOFTWARE,
COALESCE((select 'Y'
from taxonomy_index b, taxonomy_term_data c
where c.tid = b.tid
and c.vid = 3
and b.tid = 17
and a.nid = b.nid), 'N') AS 'Results Recorded',
COALESCE((select 'Y'
from taxonomy_index b, taxonomy_term_data c
where c.tid = b.tid
and c.vid = 3
and b.tid = 13
and a.nid = b.nid), 'N') AS 'Free Trial'
from node a
where a.type = 'Software'

```

Many Thanks Julie

# Answer
Building this query in Views impossible, but you can use PHP code (for example, views\_php, views\_customfield, viewsphpfilter) or just templating fields in Views for making dynamic calculations.
> 0 votes

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


title: Linking to files inside Drupal

text:
# Question
Title: Linking to files inside Drupal
I've been asked to create an intranet at work and thought I'd look at Drupal to get this done. What they want to have is a few blogs, a calendar, a forum as well as a link to all of the documentation that staff are required to be able to access to do their jobs, such as a phone list (in .xls format) and a ton of .pdf files that contain policies and procedures.

I have D7 installed on a 2008R2 server, the same server that contains all of the data. This server doesn't face the internet, so security doesn't have to be too deep.

Anyway, how would I create my site in Drupal so that I can point to the directories on the file server (which everyone can access to read)? I'm ok with a directory listing, it doesn't have to be fancy.

I had explored creating a directory inside of my site then having the files sync between the data drive and the www data store. I looked into having the site tie into our AD infrastructure but it's going to be setup so only a few can add to it and everyone else can read. The forums will be for certain staff (5 or so) to be able to bat around ideas.

# Answer
> 2 votes
I'm not sure what kind of answer you are looking for ...

If you just want these files stored remotely, but accessible from drupal you may want to look at these modules:

I actually have a similar criteria on a site. Serve pdf file listings from a non-drupal directory to allowed users -- essentially a simple directory listing. Here is how I did it in D7 with a bit of custom coding.

1. I make a symlink from a remote filesystem into like DRUPAL\_SITE\_DIR/sites/default/files/REMOTE\_MOUNTPOINT
2. Make a custom module that uses something to scan for files and show them to the enduser. You can use D7 file\_scan\_directory if you like, I actually opted for Symfony's Finder Component. The advantage to Symfony's finder is things like "show files of X size", "sort by something" or doing more complex search filters (which I will need) or truely different types of remote files (FTP, S3, etc). Example code for a module poorly named "views\_fs" can be found in this public Gist.

Hope this info helps.

---
Tags: files
---


title: Teaser view doesn't show image field

text:
# Question
Title: Teaser view doesn't show image field
I've added an image field in a content type, and set the 'Field Settings' -\> 'number of values' to unlimited, which means users can upload unlimited images for this field.

Then I build a view for this content type and expose the image filed to the view. What I'd like is to expose only image in teaser view, and all images in the full view.

I use a template preprocess function

```
function MYTHEME_process_field(&$vars) {
  $element = $vars['element'];
  // Field type image
  if ($element['#field_type'] == 'image') {
    // Reduce number of images in teaser view mode to single image
    if ($element['#view_mode'] == 'teaser') {
      // something might be wrong here
      $item = reset($vars['items']);      // not working
      $vars['items'] = array($item);      // not working
    }
  }
}

```

In debugging this function, this 2 lines

```
  $item = reset($vars['items']);
  $vars['items'] = array($item);

```

It doesn't seem to work because the image field in the content type can have multiple images.

# Answer
I just tested that exact code in Drupal 7 and it's working perfectly! The full view displays two or more images and a view of teasers just shows one image per node.

HOWEVER, I did notice the following: if you're just in the process of building a view the **Preview** below the view does not display the final output correctly. The Preview in the view of teasers shows multiple images per teaser, but if you just go ahead and hit 'save' and then test your view (by going to its link if it's a page), you'll see that it actually displays correctly.

Does that end up working for you?
> 2 votes

---
Tags: media
---


# Question
Title: Extending EntityFieldQuery's method finishQuery doesn't work as supposed
Extending EntityFieldQuery's method finishQuery with the following code causes query return nothing:

```
class ClientEntityFieldQuery extends EntityFieldQuery {

  public function finishQuery($select_query, $id_key = 'entity_id') {
    $select_query->leftJoin('field_data_field_date', 'o', 'client_event.eid = o.entity_id');
    $or = db_or()
      ->condition('o.field_date_value', time(), '<')
      ->isNull('o.field_date_value');
    $select_query->condition($or);

    // Call parent method
    parent::finishQuery($select_query, $id_key);
  }
}

```

But when I copy the contents of finishQuery to the extended class (see below), the query works fine. So why does it not work when altering $select\_query in the extended class and then calling parent::finishQuery($select\_query, $id\_key)?

This works:

```
class ClientEntityFieldQuery extends EntityFieldQuery {

  public function finishQuery($select_query, $id_key = 'entity_id') {
    $select_query->leftJoin('field_data_field_date', 'o', 'client_event.eid = o.entity_id');
      $or = db_or()
        ->condition('o.field_date_value', time(), '<')
        ->isNull('o.field_date_value');
    $select_query->condition($or);

    // This is copypaste from EntityFieldQuery's method finishQuery
    foreach ($this->tags as $tag) {
      $select_query->addTag($tag);
    }
    foreach ($this->metaData as $key => $object) {
      $select_query->addMetaData($key, $object);
    }
    $select_query->addMetaData('entity_field_query', $this);
    if ($this->range) {
      $select_query->range($this->range['start'], $this->range['length']);
    }
    if ($this->count) {
      return $select_query->countQuery()->execute()->fetchField();
    }
    $return = array();
    foreach ($select_query->execute() as $partial_entity) {
      $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
      $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
      $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
      $this->ordered_results[] = $partial_entity;
    }
    return $return;
  }

}

```

# Answer
I think it's because you're not returning anything from the function.

The code for the base `finishQuery()` function returns at the very least an empty array; at the moment your function isn't doing that.

The fix might be as simple as changing the last line to:

```
return parent::finishQuery($select_query, $id_key);

```
> 1 votes

---
Tags: 7, entities, database
---


# Question
Title: Prevent caching some selected parts of a html page
I've written a small block in php (used drupal) and have enabled caching because the page contains several static images. But I don't want contents of the block to be cached.

Tried to use **Cache\_Lite** but it's not working. So is there a way to restrict some parts of the page prevent being cached?

thanks in advance...

# Answer
> 0 votes
Checkout ESI. In short you need to AJAX load that block if you don't wish for it be be cached for logged out users.

---
Tags: caching
---


# Question
Title: Adding temporary field to form to print ID's
When writing modules, especially in the "hook\_form \_alter" hook, I find myself in the same situation many times:

I want to control some $form fields and I'm searching the field ID, the right attribute convention, etc.

I'm trying to print all the fields and their attributes to the output page so I could do that every time I need information about a form fields.

1. How can I print all the fields complete attributes?
2. I need to stick it temporarily in the page - how can I send the details to the page (I don't know what are the fields ID's...)?

# Answer
> 0 votes
Devel \- Helper functions for Drupal developers and inquisitive admins.

Add in hook\_form\_alte function `dsm($form);` and refresh your form page, you will get message with structured info.

---
Tags: forms
---


title: broken handler for custom handlers

text:
# Question
Title: broken handler for custom handlers
I'm using Drupal 7 with views 3.

I have defined a custom handler for a field and is working on my development machine. When I revert same view in live environment I am getting issue of broken handler, even the handler class s present.

Thanks in advance for your help.

# Answer
I have fixed this issue by using hook\_views\_data\_alter(). Earlier the custom handler for the select field was defined in hook\_views\_data().
> 0 votes

---
Tags: 7, views
---


# Question
Title: How can I remove the header n the node/add/[content_type] pages
I have a content type 'Numbers' and on the `node/add/numbers` page there is a header that says 'Create Numbers.'

I would like to remove this header from the page. I've searched in `node.tpl.php` with no success. I'm thinking that this is a job for a `HOOK_form_alter()` but I'm not sure what needs to be altered in the form.

# Answer
This may not be a good solution but it works. Put the below code in template.php preprocess\_page in your admin theme.

```
if(arg(0) == 'admin' && arg(1) == 'numbers') {
      $vars['title'] = "";
}

```

Where `number` is the node type.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to add a specific menu item in Panels?
I am using Drupal 7. I made use of panels to partition the look of a page. I would like to know whether it is possible to add "A specific menu item" in the panels? I have used node templates to generate this page. I have 6 menu items(main menu), i want only one of them to be present in the panels.

Thanks in advance.

# Answer
To the best of my knowledge, Panels can only interact which *whole* menues.

One option is using Menu block to slice a menu into pieces, exposed as blocks. I don't think menu blocks however can pick *one* item, though I haven't looked at all the advanced options.

If you just want a single menu item, can you just emulate the markup?
> 2 votes

---
Tags: 7, panels
---


# Question
Title: Drupal won't validate required field when disabled
I have a content type with required field in it. If the field is disabled then Drupal won't verify it. (it is being verified if not disabled). How can I verify that the field has a value even if it's disabled?

**More details:**

For some of the users I set the value by Prepopulate and disable the field (by implementing the hook `hook_form_alter`).

I still want to prevent the user from messing with the URL. For example: he can take the "new content" link I've created for him that looks like:

```
/node/add/my_type?edit[field_to_set]=12

```

and remove the URL query:

```
/node/add/my_type

```

I thought that if he would do it, he won't be able to save the form because of the required field (which is disabled) - but Drupal won't verify it.

# Answer
> 1 votes
According to the API docs of \_form\_builder\_handle\_input\_element disabled fields are ignored, you can try using #access instead.

You can try adding your own handler after that of prepopulate and check if a (valid) value is entered, if not redirect the user or display a message

```
function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
  $form['#after_build'][] = 'MY_MODULE_prepopulate_after_build';
}

function MY_MODULE_prepopulate_after_build($form, &$form_state) {
  // check #value
  if (empty($form['field_to_set'][0]['#value'])) {
    drupal_set_message ('You altered the URL', 'error');
    drupal_goto ();
  }
  // if #value is set, set #default_value as well
  if (empty($form['field_to_set']['und']['#default_value'])) {
    $form['field_to_set']['und']['#default_value'] = $form['field_to_set']['und']['#value']
  }
  return $form;
}

```

---
Tags: forms
---


# Question
Title: Added js file is not working nor throws it any errors
I add a js file with form\_alter and #attached. Everything works fine.

```
    function ganzech_form_alter(&$form, &$form_state, $form_id) {
      switch ($form_id) {
        case 'anbieter_node_form':
          $form['#attached']['js'] = array(
            drupal_get_path('module', 'ganzech') . '/ganzech.js',
            );

          break;

      }
      return;
}

```

http://jsfiddle.net/KuqHT/3/ (click the first Checkbox to see what it does) This works even on jQuery 1.4.x. My Drupal has 1.5.2 You can see the file here: http://www.fsd-vss.ch/sites/all/modules/custom/ganzech/ganzech.js

I have it included on my form in `node/add/anbieter` The HTML on that node looks like this

```
<div class="form-item form-type-checkboxes form-item-field-kantone-und">
  <label for="edit-field-kantone-und">Kantone <span class="form-required" title="Diese Angabe wird benötigt.">*</span></label>
 <div id="edit-field-kantone-und" class="form-checkboxes"><div class="form-item form-type-checkbox form-item-field-kantone-und-Ganze-Schweiz">
 <input type="checkbox" id="edit-field-kantone-und-ganze-schweiz" name="field_kantone[und][Ganze Schweiz]" value="Ganze Schweiz" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ganze-schweiz">Ganze Schweiz </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-AG">
 <input type="checkbox" id="edit-field-kantone-und-ag" name="field_kantone[und][AG]" value="AG" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ag">AG </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-AI">
 <input type="checkbox" id="edit-field-kantone-und-ai" name="field_kantone[und][AI]" value="AI" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ai">AI </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-AR">
 <input type="checkbox" id="edit-field-kantone-und-ar" name="field_kantone[und][AR]" value="AR" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ar">AR </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-BE">
 <input type="checkbox" id="edit-field-kantone-und-be" name="field_kantone[und][BE]" value="BE" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-be">BE </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-BL">
 <input type="checkbox" id="edit-field-kantone-und-bl" name="field_kantone[und][BL]" value="BL" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-bl">BL </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-BS">
 <input type="checkbox" id="edit-field-kantone-und-bs" name="field_kantone[und][BS]" value="BS" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-bs">BS </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-FL">
 <input type="checkbox" id="edit-field-kantone-und-fl" name="field_kantone[und][FL]" value="FL" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-fl">FL </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-FR">
 <input type="checkbox" id="edit-field-kantone-und-fr" name="field_kantone[und][FR]" value="FR" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-fr">FR </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-GE">
 <input type="checkbox" id="edit-field-kantone-und-ge" name="field_kantone[und][GE]" value="GE" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ge">GE </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-GL">
 <input type="checkbox" id="edit-field-kantone-und-gl" name="field_kantone[und][GL]" value="GL" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-gl">GL </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-GR">
 <input type="checkbox" id="edit-field-kantone-und-gr" name="field_kantone[und][GR]" value="GR" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-gr">GR </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-JU">
 <input type="checkbox" id="edit-field-kantone-und-ju" name="field_kantone[und][JU]" value="JU" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ju">JU </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-LU">
 <input type="checkbox" id="edit-field-kantone-und-lu" name="field_kantone[und][LU]" value="LU" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-lu">LU </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-NE">
 <input type="checkbox" id="edit-field-kantone-und-ne" name="field_kantone[und][NE]" value="NE" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ne">NE </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-NW">
 <input type="checkbox" id="edit-field-kantone-und-nw" name="field_kantone[und][NW]" value="NW" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-nw">NW </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-OW">
 <input type="checkbox" id="edit-field-kantone-und-ow" name="field_kantone[und][OW]" value="OW" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ow">OW </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-SG">
 <input type="checkbox" id="edit-field-kantone-und-sg" name="field_kantone[und][SG]" value="SG" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-sg">SG </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-SH">
 <input type="checkbox" id="edit-field-kantone-und-sh" name="field_kantone[und][SH]" value="SH" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-sh">SH </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-SO">
 <input type="checkbox" id="edit-field-kantone-und-so" name="field_kantone[und][SO]" value="SO" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-so">SO </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-SZ">
 <input type="checkbox" id="edit-field-kantone-und-sz" name="field_kantone[und][SZ]" value="SZ" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-sz">SZ </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-TG">
 <input type="checkbox" id="edit-field-kantone-und-tg" name="field_kantone[und][TG]" value="TG" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-tg">TG </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-TI">
 <input type="checkbox" id="edit-field-kantone-und-ti" name="field_kantone[und][TI]" value="TI" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ti">TI </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-UR">
 <input type="checkbox" id="edit-field-kantone-und-ur" name="field_kantone[und][UR]" value="UR" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-ur">UR </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-VD">
 <input type="checkbox" id="edit-field-kantone-und-vd" name="field_kantone[und][VD]" value="VD" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-vd">VD </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-VS">
 <input type="checkbox" id="edit-field-kantone-und-vs" name="field_kantone[und][VS]" value="VS" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-vs">VS </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-ZG">
 <input type="checkbox" id="edit-field-kantone-und-zg" name="field_kantone[und][ZG]" value="ZG" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-zg">ZG </label>

</div>
<div class="form-item form-type-checkbox form-item-field-kantone-und-ZH">
 <input type="checkbox" id="edit-field-kantone-und-zh" name="field_kantone[und][ZH]" value="ZH" class="form-checkbox">  <label class="option" for="edit-field-kantone-und-zh">ZH </label>

</div>
</div>
<div class="description">Wo liegt das Einsatzgebiet der Firma?</div>
</div>

```

Can it be, it has something to do with `jQuery(this).is(':checked'));`? But why is my pastie working even with jQuery 1.4.x and why I don't get any Errors if its that?

# Answer
> 0 votes
It was the JS file. Not working:

```
jQuery('#edit-field-kantone-und-ganze-schweiz').bind('change', function ( ) {
     jQuery(':checkbox').attr('checked', jQuery(this).is(':checked'));
});

```

working:

```
jQuery(document).ready( function() {
jQuery('#edit-field-kantone-und-ganze-schweiz').bind('change', function ( ) {
     jQuery(':checkbox').attr('checked', jQuery(this).is(':checked'));
});
});

```

# Answer
> 0 votes
Try to use it like this:

```
$form['#attached']['js'] = array(drupal_get_path('module', 'ganzech') . '/ganzech.js' => array('type' => 'file'),);

```

This way is clearly specified that it is a file.

And of course please check for the name of the module. Some type errors could always mess with your code.

---
Tags: 7, forms, javascript
---


# Question
Title: How do I get the views pager to display (after adding an view header)?
I'm using the standard views implementation of taxonomy term pages, ok I've added a view header display, but beyond that, it's a stock Views 3 view.

It apparently has a pager set, but it's not showing up. Once upon a time it was there, now it's not. It was my client that noticed \*blush\*. Yes there are enough results in the query. Have tried Mini and Full versions, but nothing seems to create any HTML that resembles a pager.

It seemed to happen after adding another simple view in the header.

# Answer
To save you wading through the comments which led to this answer, here it is in summary:

The problem was that the 2nd view included in the Header of the main view **also had a pager on it**.

Two solutions:

1. Views can cope with having more than one pager, with a bit extra config: you have to set the **Pager Id** field on one of the Views Displays to an integer not in use by other views/displays on that page (e.g. 1 instead of 0).
2. In my case I realised that the attached header view **did not actually need a pager** (it was only ever going to display one result - the description for the taxonomy term), and I should have selected "show fixed number of results" instead of a pager option. Changing this fixed the problem.

Hope this answer is useful for someone else getting stuck!
> 2 votes

---
Tags: 7, views
---


# Question
Title: RSS Feeds: Using Aggregator (Drupal Core) vs Feeds module - which has more features and is more reliable?
RSS Feeds: Using Aggregator (Drupal Core) vs Feeds module - which has more features and is more reliable?

It looks like Feeds has more features. Is this true? and is it more reliable?

# Answer
Answering my own question, I would be inclined to say Feeds module, on the basis of:

* more integration with other Drupal entities allowing more possibilities for manipulation of the content
* extensibility - ability to extend with extension modules that parse the XML content of the feed to re-purpose it. e.g. rather than a text list of youtube videos, the actual videos themselves embedded into the page
* standard api for extensions
* well supported and active in drupal 7
> 2 votes

---
Tags: 7, feeds
---


# Question
Title: How do I define a Drupal variable using phpmyadmin?
According to this issue, I need to drupal\_weight\_select\_max to 1000 in my Drupal installation. It suggests several methods:

1. Use Drush (Not an option for me as it's on shared hosting)
2. Define it in a module (Beyond my skillset)
3. Define it in settings.php (which seems to break my site. i.e. site doesn't load and I get WSOD)

If this can be done in phpmyadmin, can you please tell me in plain english, step-by-step how I can do this?

# Answer
> 5 votes
The variables are stored as serialised PHP strings so adding one to the database manually might just be a pain. You can do it quite easily though, just follow these steps:

1. Download and install the Devel module
2. Navigate to http://mysite.com/devel/php
3. Put this code in the textfield:

```
variable_set('drupal_weight_select_max', 1000);

```
4. Press the 'Execute' button.

If you do want to do it directly in PHPMyAdmin you can get away with a running a single query:

```
INSERT INTO variable (`name`, `value`) VALUES ('drupal_weight_select_max', 'i:1000;')
  ON DUPLICATE KEY UPDATE `name` = 'drupal_weight_select_max', `value` = 'i:1000;';

```

and then flushing your caches.

# Answer
> 0 votes
* find table variable
* check if the variable is not there yet (column name)

+ yes : edit it
    + no : add a new record
* new record :

+ name : drupal\_weight\_select\_max
    + value : i:1000;

# Answer
> 0 votes
This comment closer to your, just open phpmyadmin, locate your database on left side, click *SQL* button on the top, and paste SQL code from comment:

```
UPDATE variable SET value = 'i:1000;' WHERE name = 'drupal_weight_select_max';

```

Click *Run*.
Then you should clear your cache, for this run clearing cache in Drupal in Performance section or do manually:
Locate *Cache* table, click Operations, and click on *Empty the table (TRUNCATE)* link.

But you should be sure that this variable exists in *variable* table. For this, click on *Variable* table, click *Search* button on the top, enter **drupal\_weight\_select\_max** on *Value* for *Name* row and click *Go*.
If table exists, running SQL or updating located row will enough (clear Cache of course), otherwise click Insert and enter values that provided in comment: **drupal\_weight\_select\_max, i:1000;**
For inserting, clearing cache doesn't need.

# Answer
> 0 votes
This doesn't really answer the question, but it is incredibly easy to add a field to the site information page to set a variable, so it can be easily edited. All you need to do is add this hook to a custom module.

```
function HOOK_form_system_site_information_settings_alter(&$form, &$form_state, $form_id) {

  $form['site_information']['fieldname'] = array(
    '#type' => 'textarea',
    '#title' => t('Field Title'),
    '#default_value' => variable_get('fieldname', ''),
    '#description' => t('Field description'),
    '#required' => TRUE,
  );

}

```

Which would arguably be the correct way of adding a sitewide variable.

---
Tags: 7, database
---


title: How do I disable ajax on file fields?

text:
# Question
Title: How do I disable ajax on file fields?
I'm having some problems where using `drupal_get_form()` breaks the upload/remove functionality of a file field when it's processed with ajax. It seems this may be a core issue (http://drupal.org/node/1526300) but I haven't found a solution that works for me yet.

I've noticed that the form degrades gracefully when ajax is disabled in the browser and the file field works correctly.

I would like to just disable ajax for this form but I don't see how. I don't see any `#ajax` elements in `hook_form_alter()` or `hook_field_widget_form_alter()`.

# Answer
> 11 votes
You can force the buttons to submit normally by unbinding the javascript events using something like this in a form alter:

```
// Disable ajax upload for file field
drupal_add_js("jQuery(function() { jQuery('#edit-field-image :submit').unbind(); });", 'inline');

```

It would be nice if there was a way to not have the javascript bound in the first place by manipulating the `$form` (or something else).

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


# Question
Title: How can I add context (or distinguish between contexts) to translations with t()?
I have made a custom address handler for the Addressfield module which uses the word "state" (for the geographic state/province). However, I'm also using the Revisioning module, which uses the word "State" to describe the state of a piece of content.

Unfortunately, to translate this into Japanese, I need two different words for "State"; how can I get two different strings to appear on the translate interface screen?

(I know I could just re-write "State" in revisioning to something like "Revisioning state" but I'd like to know if there's a way to handle this without altering the strings.)

# Answer
Yes, you can pass a context to t(), see the third parameter, $options. However, you can only do this in the source code, which means that it is often not helpful. Might be possible in your case, because it's your own code.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Alternate to field_get_items() ?? CCK fields reconstriction?
After a long quest, finally I got the solution for splitting $content in Drupal 7 in node.tpl.php.

Previously i was using i was using :-

```
print $node->field_name['und'][0]['value'];

```

Which was giving a warning :-

```
Notice: Undefined offset: 0 in include() (line 24 of C:\xampp\htdocs\drup\sites\all\themes\myCustomTheme\node.tpl.php)

```

Now I am using the function below which works fine with no errors

```
$output= field_get_items('node', $node, 'field_name');
$output = $output[0]['safe_value'];
print $output;

```

Now the problem is I have more than 50 fields on the page , I don't think it would be efficient to call field\_get\_items('node', $node, 'field\_name') function 50 times.

Whats the alternate ? OR should I strict to the field\_get\_items function OR should I strict to the print $node-\>field\_name\['und'\]\[0\]\['value'\]; which I heard is not good to use in Drupal 7 as und is undefined. This though solves my problem but gives irritating warnings.

# Answer
First off, `'und'` is the value of the LANGUAGE\_NONE constant, which is used for the content not associated to a particular language. Not all the fields have a value for that, and if you are trying to access it, you get a PHP warning.

For example, for taxonomy terms, the array structure could be one of the following.

* tags
* other taxonomy terms

If you need to get the field value that would be used for the currently used language, you can just use `field_get_items()`. Its code cannot be optimized, as it needs to determinate the language used for the field.

```
function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) {
  $langcode = field_language($entity_type, $entity, $field_name, $langcode);
  return isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : FALSE;
}

```

Even the code for field\_language() cannot be much optimized. You could avoid multiple calls to field\_valid\_language(), but that is the only thing you can do.

If you have your own code to decide which language should be used for the fields, you can access the field data directly, without using `field_get_items()`.
> 2 votes

# Answer
You can install the EntityAPI module and use a meta-data wrapper to ease accessing Node fields. I believe it loads the object once and just references the field data when you want it.

You can also try the field\_extract module.

I believe Drupal's `entity_load()` and default Drupal object caching makes your concern of calling `field_get_items()`, or the entity API or field\_extract a non-issue as the node is retrieved once and then that cached node data is re-used for the lifetime of the page.

Give both a looksee; your mileage may vary.
> 0 votes

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


# Question
Title: Make blog available to authenticated users only
I have a site which lists some events in a block using the agenda module. I have this set to be the main content (eg taking up the center of the page). This is the only content I would like general visitor to see.

I would like to use the same site to have a private blog which is only available to logged in users.

Is there a way I can restrict viewing of the blog pages to anyone not logged in?

I have tried simply removing the view content permission but this causes other issues!

# Answer
> 1 votes
Would the 'Content Access' module be what you are looking for?

http://drupal.org/project/content\_access

Using this you would be able to set your Blog content type to be viewable only by registered users.

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


# Question
Title: How to add a custom read more link in views?
I have used views to create a page to look like the below screen shot. I have used trim to limit the description of the body to 200 texts. I have added "Link" and have termed it as "Read more". Is it possible to change the "Link" text in our webshop as "to shop"? I want this change to happen only for that specific item. For the rest it should be "Read more"

# Answer
Probably going about it the wrong way, you could either set a custom text field on your node called 'Link text' then output that as a field and check 'Link this field to its node' in views.

Or you could use the 'Link' field type contrib module, then output that as a field, this will allow you to set custom text as the link label, but you will also need to supply the link itself. But this will allow more flexibility.
> 2 votes

# Answer
The Views UI does not offer if'fing. And - frankly - I almost gave up using the Rewrite options, as I noticed I'm more productive with tpl files. If you want to alter the link depending on some context, try using row theming then.

1. Add a field named `Taxonomy Term: Term ID`. Make sure it outputs raw, without any classes, wrappers, and stuff
2. In the Theme Information section: pick a theme tpl file that suits you, put it on server and rescan template to make it recognized.
3. Put your field where you want: `print $fields['tid']->contents`
4. In the PHP code, make a variable that will form the link text depending on the context you wish
5. Build the link using the l() function, using the variable as the first parameter. The url for terms is 'taxonomy/term/$tid'. I don't remember if the l function replaces it with alias, if not, use drupal\_get\_alias\_path on the url, to have an aliased link.

That should work.
> 1 votes

---
Tags: views
---


title: Usage of i18n and multi-site?

text:
# Question
Title: Usage of i18n and multi-site?
I beg you to make it clear for me, can i share tables in multisite installation with different databases and which ones?

If i am to use i18n on multisite, what is the best way to do that. Thanks a lot in advance.

# Answer
> 0 votes
As i understood you almost cant use common tables on multi-site installation - i\`ve been checking them one by one. First i configured all of sites - only the main site (from which tables were shared) could switch languages and translate nodes. On the others there were no switcher showing and translated nodes were not linking.

Maybe you can some, but still you got to have everything identical (starting from content types and endind with nodes)

Maybe i am wrong.

---
Tags: i18n-l10n, multi-sites
---


# Question
Title: Is it possible to use jQuery on filters (B.E.F.) in a view?
I am trying to add some special behaviours with jQuery to input type checkboxes in a view (using better exposed filters). Ideally i need to make inactive all checkboxes when one of them is clicked. I\`ve written a script but it did not do anything. So i added a simple another code via drupal\_add\_js in template.php just to see whether it would be working:

```
jQuery('input#myid').click(function(){
alert("clicked");
});

```

it didn\`t work and i am asking is it possible to use jQuery on checkboxes in a view? Thanks in advance!

# Answer
The right way to write jQuery in drupal 7:

```
(function ($) {
  Drupal.behaviors.functionname = {
    attach: function(context, settings) {
      // some code, with $
    }
  };
})(jQuery);

```
> 0 votes

---
Tags: javascript, views
---


# Question
Title: How to edit Media module`s display profiles?
I can\`t find where can i edit media module profiles. There are no any link in admin section.

# Answer
> 0 votes
They are to be edited on file-types page in Structure: admin/structure/file-types

---
Tags: 7, media
---


title: Force Image module to regenerate thumbs

text:
# Question
Title: Force Image module to regenerate thumbs
I am using the Image module along with ImageGallery to make galleries in Drupal 6. I now have some 'holes' in my gallery where Image can't find the thumbnails, so they need to be regenerated. How do I force that to happen? Have tried clearing caches and running update.php, but I still have the holes. Am I missing something?

# Answer
Probably the easiest way is to just go to the ImageCache Styles page and re-save the style. Don't make any changes just hit save.

You could also just delete all the thumbnails out of the image\_styles folder in your files/ directory.
> 2 votes

---
Tags: 6, media
---


# Question
Title: Which tables can i share in multilingual multi-site installation?
I have a multi-site installation with different databases. I've shared i18n\_; language; locale\_ tables. On the main installation several languages work just fine. But on the others sites which i am trying to use also with multilingual settings i can't get language switcher appear whatever i try. They don't want to use prefix between nodes. Translated nodes are connected but there's no way to switch between them. Please could you give advice which tables am i able to use to have shared translations without problems?

# Answer
As i understood you almost cant use common tables on multi-site installation - i\`ve been checking them one by one. First i configured all of sites - only the main site (from which tables were shared) could switch languages and translate nodes. On the others there were no switcher showing and translated nodes were not linking.

Maybe you can some, but still you got to have everything identical (starting from content types and endind with nodes)

Maybe i am wrong.
> 0 votes

---
Tags: 7, i18n-l10n, multi-sites
---


# Question
Title: Hide dates in the present in .tpl.php files
I've got a content type (Events) and they have event dates. Some of them have multiple dates, some of them haven't. But I want to hide the dates which are in the past.

Obviously, February 15th and April 18th are already passed. How can I hide them?

When I do `var_dump($content)` in the tpl, all I got is this:

```
<span class="date-display-single">15 February 2012 - <span class="date-display-start">14:00</span> to <span class="date-display-end">16:30</span></span>

```

So it looks like I can't filter in PHP since it's already converted into HTML. Any idea how I can filter this?

**EDIT: screenshot of my date section**

# Answer
Presuming you are using the Date module. In the Manage Display settings for the content type, modify the setting for the Date output and put 'now' in the 'starting from' box.
> 2 votes

# Answer
Maybe you could use a regex on it to get the date out? Parse that date with the strtotime() function to compare it to today's date? Then just add a class to the span and hide it with css or get the entire row out of the array.

The regex could look like this:
`/(<span class="date-display-single">)([0-9]{1,2}\s[a-zA-Z]*\s[0-9]{4})\s(.*)/`

The second group should be your date and you can use the first and third group to reconstruct the line + the extra css class.
> -1 votes

---
Tags: 7, datetime, views
---


# Question
Title: Can't figure out how to set a context with t()
This is a follow-up to this question on setting contexts using t().

I am attempting to set a context using t().

I am trying to set the *context* for the translation of **State** to *geo*. My code looks like this:

```
$format['locality_block']['administrative_area'] = array(
  '#title' => t('State', array('context' => 'geo')),
  '#size' => 10,
);

```

This doesn't give any errors but it also doesn't create the translation unit with the context, either. Any clue what I'm doing wrong? (It's probably something obvious; I'm not good with PHP.)

# Answer
The second argument of the `t()` function are the replacements and not options.
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: How to programatically resize image and respect aspect ratio when saving a node
I was wondering if there is an api call that lets me resize an image and respect the aspect ratio. Right now I am using `image_resize` to successfully resize an image to a given width and height but it ignores aspect ratio and distorts the images. Is there an api call that will allow me to do this and maintain original aspect ratio?

# Answer
> 1 votes
`image_scale()` will do this if you just provide a width or a height rather than both.

# Answer
> 1 votes
This is again a case where using code seems to only come up for the sake of it. This doesn't even involve the use of a module : everything needed is in core and manageable via the UI :

Go to `admin/config/media/image-styles/list` (provided the Image module is enabled), choose a style or create one and you can then use it in Views or in `admin/structure/types/manage/your_ct/display`.

---
Tags: 7, media
---


# Question
Title: Make a separate list of selected content
Hi I am very new to Drupal. I want to make a restricted list of contents to show in a view. By default a view of certain content type brings all of the contents in it which I don't want. How can I accomplish this?

# Answer
> 0 votes
You can use Nodequeues to accomplish this really effectively.

---
Tags: views, nodes
---


title: How can I hide the taxonomy term icon?

text:
# Question
Title: How can I hide the taxonomy term icon?
By default, taxonomy terms on a node display with a tag icon:

What's the easiest way to get rid of that icon? Just use `hide($content['fieldname']);` in my node template and rewrite it the way I want? Or is there a config option somewhere that I've missed that would let me turn it off?

# Answer
> 2 votes
I am almost sure it\`s generated by your theme with css. So you can use firebug to find this line and delete background and padding of this element.

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


# Question
Title: How to delete a module from the Modules menu?
I have installed a few modules that I don't use at all. I can't find any option to uninstall them. How do I do it? Is there a separate module to do it?

# Answer
> -2 votes
Not sure about a separate module for this, but you can just delete the module folder in your `sites/all/modules` folder. Works for me every time.

# Answer
> 3 votes
The module uninstall page in Drupal 6 is at http://mysite.com/admin/build/modules/uninstall.

For Drupal 7 it's at http://mysite.com/admin/modules/uninstall.

Once you disable a module using the main modules page, visit the uninstall page and you'll be able to safely uninstall. After that it's just a matter of deleting the module folder from your server, and you won't see it in the module list any more.

Whatever you do, don't just delete the module folder without disabling/uninstalling it first, or you could easily wreck the site.

# Answer
> -1 votes
Obviously you're using a drupal version prior to 7.

In this case you can deactivate them in the module list and then just delete them via FTP.

In Drupal7 there's an uninstall tab in the module list...

---
Tags: installation
---


# Question
Title: Restrict IFRAME and OBJECT embeds certain domains
I would like to allow my users to embed certain IFRAME and OBJECT tags in nodes and comments. Is there a way to restrict them to certain domains, for example maps.google.com to allow embedding Google maps?

# Answer
> 4 votes
Allowing users to input , and doing validation on *some* subtypes of that, is certainly possible, but far from easy.

It's easy to think, "I can do that with a regular expression!". Read This SO question though, before you try, and save yourself a lot pain.

What you *can* do instead, is employ an XML parser and process the input from there, but that is far from trivial, and will require quite a bit of work.

What I recommend you *should* do instead, is create specific tags for what you want to allow. Something like \[iframe:http://some.url.here\], and then process these manually with an input filter. You would probably want to apply that filter in a text-format *after* you've run the regular "limited html" filter.

A filter is created by implementing hook\_filter\_info, and in your process callback you can do string substitution on the \[iframe\] tag, provided it references an approved domain.

---
Tags: 7, security
---


# Question
Title: Using Feeds module to import to User_Reference fields?
I'm been trying to come up with a mechanism to insert/update certain nodes in our Drupal system. When I try to do the field mapping in Feeds most of the fields are listed and selectable. But, for those fields which are defined as User\_Reference fields, they ARE NOT listed in the target field list. I can find no other reference to this.

So, how does/can one map a csv field to a user\_reference type field defined in a content type?

TIA

# Answer
Did you try patch from this thread?

The patch is http://drupal.org/files/userreference-mapper-748582\_0.patch.
> 3 votes

# Answer
My initial approach, would be to try the patch linked to by Maxime's answer, as it looks promising.

However, a more flexible approach would be to override the importing yourself. This may not be entirely appropriate for complete beginners to programming, but it will on the other hand be able to solve the most complex Feeds scenarios. I've done some fairly advanced imports this way.

First, install Feeds tamper. This module allows you to create *temporary targets* for arbitrary data. Map the source of you user-reference field onto such a target.

Second, create a module that Feeds will accept plugins from. The generics of implementing Feeds plugins is already well covered in the docs, so there's no need for me to repeat them.

Third, we need to tell the feeds processor do something useful with this data. This custom processor will do just that. Honestly though, I haven't checked exactly what a user reference array looks like, as I don't know when last I used that, and have no site to check it on.

```
class UserRefProcessor extends FeedsNodeProcessor {
  protected function map(FeedsSource $source, FeedsParserResult $result, $target_item = NULL) {
    // Perform all the regular mapping.
    $target_item = parent::map($source, $result, $target_item);

    $user_reference_target = $parser->getSourceElement($source, $result, 'id_of_temporary_target');

    $target_item->user_reference_field = array('und' => array(0 => array('uid' => $user_reference_target)));
  }
}

```

And you should be good to go :) If the `user_reference_field =` line is appropriately adapted, this could work for any type of field.
> 1 votes

---
Tags: feeds, importing-exporting
---


# Question
Title: Turning page titles to links using hook_page_alter()
I'm trying to use a hook\_page\_alter() to change make the title of certain pages a link to another page.

This is the code I would like to alter.

```
function mashavumodule_page_alter(&$page) {
  // get the user id of the patient
  $user_id = $page['content']['system_main']['nodes'][$nid]['field_user_id']['#items'][0]['value'];

  drupal_set_message(l("View Patient Profile", "user/{$user_id}" ));
}

```

Currently, I have the link outputting as a system message.

Also as a side note, if there is a more elegant way to get the value of the field\_user\_id, I'd love to know because typing

```
$page['content']['system_main']['nodes'][$nid]['field_user_id']['#items'][0]['value']

```

just doesn't seem right.

# Answer
I don't think `hook_page_alter()` is the best place to do this (though I may be wrong), it seems like since you're changing the display of the title it should be done at the theme level.

Personally I'd go for a `hook_preprocess_page()`:

```
function MYMODULE_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $field_items = field_get_items('node', $node, 'field_user_id');
    $first = array_shift($field_items);

    $user_id = $first['value']; // if 'value' is the column name for your field, it might be 'uid' if you're using a references field, 'target_id' for entity reference, etc.

    $link = l($vars['title'], 'path/for/link');

    $vars['title'] = $link;
  }
}

```
> 2 votes

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


title: Allowing users to use the same email

text:
# Question
Title: Allowing users to use the same email
I am working on a system that will be used at least partially by students some of which will likely be grade schoolers. The old system that we are replacing with a Drupal site would allow mass creation of user accounts all with the same email address. They did this so that the teacher could just use her email for all of the students and if they needed a password reset the info would just get sent to the teacher. Also, many very young students do not have their own email accounts.

I need import these accounts into my Drupal site but I am going to have trouble because Drupal 7 does not allow different accounts with the same email. After a quick Google search I did not find much that was to promising, I found a dirty hack for Drupal 5 but nothing that seemed like it might work with Drupal 7. Is there any way around this?

# Answer
You could use the Shared Email module.

> The shared email module allows multiple users to use the same email address for different accounts. The module works for both registration and account updates.

Users using that module could also be interested in the Shared Email Password Reset module.

> This module will have users reset their password based on both email and user name, there are some cases where this module can help when using the Shared Email module or when there is a requirement that passwords should be reset only if email and username matches.

Both the modules have a Drupal 8 version, and they are declared compatible with Drupal 9.
> 8 votes

---
Tags: 7, emails
---


# Question
Title: In Node References, how to show a custom field, instead of the Title?
Is it possible to show in a select list, another field instead of the Title when referencing a node?

# Answer
> 7 votes
As dobeerman says you can use a View as a source, but CCK does some playing with the View behind the scenes (I just found out as a result of this question;). If you look in `nodereference.module` at the function `_nodereference_potential_references_views()` you'll find the following code:

```
// We do need title field, so add it if not present (unlikely, but...)
$fields = $view->get_items('field', $display);
if (!isset($fields['title'])) {
  $view->add_item($display, 'field', 'node', 'title');
}

// If not set, make all fields inline and define a separator.
$options = $view->display_handler->get_option('row_options');
if (empty($options['inline'])) {
  $options['inline'] = drupal_map_assoc(array_keys($view->get_items('field', $display)));
}
if (empty($options['separator'])) {
  $options['separator'] = '-';
}
$view->display_handler->set_option('row_options', $options);

```

So this means that

* if you don't include a title field then it will be included for you;
* if you don't make all fields inline and define a separator then it will be done for you.

So if you configure the title field to be hidden, and specify an appropriate separator, you should be able to create just about any effect. If you can't achieve what you want with a view (eg. ordering nodes by their menu position) then you want to use a different approach.

You could create your own CCK widget, or (simpler) you can use a form\_alter hook. If you do the latter, you can't edit the form the normal way because CCK hasn't processed the form at this stage - you'll want to use a `#after_build` function.

I have an example of the second approach used to show nodereferences ordered by the menu if you're interested.

```
/**
 * Implements hook_form_alter().
 */
function banners_form_alter(&$form, &$form_state, $form_id) {

  // Modify nodereferences for banners so that pages are shown in primary links
  // order.
  if ($form['#id'] === 'node-form' && isset($form['#field_info']['field_pages'])) {

    if (!isset($form['#after_build'])) {
      $form['#after_build'] = array();
    }
    $form['#after_build'][] = 'banners_after_build';
  }
}

/**
 * After_build callback for modifying CCK field select options.
 */
function banners_after_build($form, &$form_state) {
  // Get the menu data
  $new_options = banners_generate_page_options();

  if (isset($form['#field_info']['field_pages'])) {
    $old_options = $form['field_pages']['nid']['nid']['#options'];
    $final_options = banners_process_options($new_options, $old_options);
    $form['field_pages']['nid']['nid']['#options'] = $final_options;
  }

  // Return new form
  return $form;
}

/**
 * Uses the old options to filter out unreferenced nids and add those that
 * weren't detected in a menu structure to the other option group.
 * @param $new_options
 *   The options list created by scanning the menus.
 * @param $old_options
 *   The options list originally passed to the form.
 *
 * @return
 *   The final options list with option groups for each menu and for orphans.
 */
function banners_process_options($new_options, $old_options) {
  // Have to assume that $old_options could get quite large, whereas
  // $new_options is based on menus, and shouldn't get too large.

  // Iterate through $new_options (the menu nids) and remove nids from
  // $old_options that exist in $new_options, and remove nids from $new_options
  // that don't exist in $old_options. After this $old_options has valid nids
  // that aren't under the menu hierarchy.
  foreach ($new_options as $menu_title => $options) {
    foreach ($options as $nid => $title) {
      if (isset($old_options[$nid])) {
        unset($old_options[$nid]);
      }
      else {
        unset($new_options[$menu_title][$nid]);
      }
    }
  }

  $final_options = array();

  // If the field is not marked required, there'll be an option for - None -
  // and it's keyed to the empty string.
  if (isset($old_options[''])) {
    $final_options[''] = $old_options[''];
    unset($old_options['']);
  }

  $final_options += $new_options;

  $final_options['Others'] = $old_options;

  return $final_options;
}

/**
 * Generates FAPI options for the allowed menus' node links.
 *
 * @return
 *   A FAPI options array with all node links on the allowed menus (NB this has
 *   not been filtered in any other way).
 */
function banners_generate_page_options() {

  $menus = array('primary-links', 'menu-top-menu');
  $options = array();

  foreach ($menus as $menu_name) {
    $tree = menu_tree_all_data($menu_name);
    $menu = menu_load($menu_name);
    $options[$menu['title']] = _banners_process_tree($tree);
  }

  return $options;
}

/**
 * Recursive function to generate the options array, keyed by nid.
 */
function _banners_process_tree($tree, $depth = 0) {

  $options = array();

  foreach ($tree as $item) {
    $matches = array();
    if (preg_match('~^node/(\d+)$~', $item['link']['link_path'], $matches)) {
      // Link points to a node
      $nid = $matches[1];
      $options[$nid] = str_repeat('--', $depth) . ' ' . $item['link']['title'];
      if ($item['below']) {
        $options += _banners_process_tree($item['below'], $depth + 1);
      }
    }
  }

  return $options;
}

```

# Answer
> 5 votes
When you create nodereference field you can select 'View' used to select the nodes in 'Advanced - Nodes that can be referenced (View)' fieldset. Also you can pass argument to this view by default.

# Answer
> 2 votes
http://drupal.org/project/nodereference\_explorer might be a bit overkill, it provides a selection dialog for node referencing and says "Plugin architecture for support of other CCK fields"

# Answer
> -1 votes
if you just include the title in views, but you set it not to show, this works fine, and keeps title out.

//edit

"Is it possible to show in a select list, another field instead of the Title when referencing a node?" when using nodereference (apart of CCK) well from my own experience you can only use the default panel in a view to populate the nodereference dropdown - if you choose to just show the node title then fine - works great - but if you list a custom field from the node instead of title you will find it still appends the node title - so if you include the node title anyway and choose to not display it in the output, this gets around that - now re-reading the question I think OP was asking how to show custom fields - i missed that but this is useful for after he is showing the custom fields using views.

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


# Question
Title: Using CCK or Taxonomy with Custom Fields in Drupal 7
I am building a site that will contain data about athletes. I'm trying to decided wether to represent the athletes as CCK or Taxonomy Terms with custom fields. Athletes will contain information such as name, DOB and image, each athlete will have a page.

News articles, sports, venues, events, and teams will be other content within the site, these could be tagged with the athlete terms if we use the taxonomy solution. The alternative would be to use node reference if athlete as a custom content type.

The Taxonomy route seems more flexible and seems like a good route to take according to this article http://www.juliakm.com/how-decide-between-using-taxonomy-terms-and-cck-field-classify-content-drupal-site I just wanted to check with people in the community if there are any drawbacks to this approach or advantages of using CCK instead?

In Drupal 7 CCK and Taxonomy Terms with Fields are in the core. The two seem incredibly similar, I was wondering what is the reasoning behind having both?

Thanks, Pete

# Answer
> 2 votes
My idea: make CCK fields of all personal data you want to collect about the athletes. (length, weight, ...) These are different for every athlete.

When you have items that are similar, you should use taxonomy. (Type: Soccer player, Golfer, ...)

Using **both** taxonomy and CCK makes a complex but great system!

\*An example:

I'm making a "travel" website about Spain. A website with many pages.

On my website about Spain I have a regio related page. This page shows content about cities, golf tracks, parks, ... It has an image on top (CCK field), a "tag" (taxonomy term to link pages - show list with simmilar content), a "regio tag" (also taxonomy list of all regio's) and two text fields: positive / negative (CCK fields to enter good and bad things about this city / track / park and so on.

The image and positive/negative fields are for all pages different. The "regio tag" can be the same for some pages (same with the tag).

This way you easily make a view with similar pages people can visit!\*

# Answer
> 1 votes
I often have this debate myself. The Julia KM article you reference has a strong bias toward taxonomy, if you look at the table you probably should just about always choose taxonomy.

However for your specific use case I would say to go the CCK route. The word taxonomy should give you a hint. The taxonomy terms are meant to classify data not be the data themselves. Yes that's a blurry area because depending on your view anything can be "data".

If your site is about athletes, as in that is the main content of your site, I would make an athlete cck type, or alternatively a cck type for each main class of athlete (Baseball, Football, Soccer, Tennis) depending on how detailed you want the fields to be (but it sounds like you just want general info so probably a single "Athlete" type would suffice).

It may be that taxonomy has pragmatic advantages, but conceptually CCK is the better choice.

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


# Question
Title: Correct way to render a modules output through a template?
I usually do exclusively functionality on a site, and as such I'm familiar with php and Drupals APIs, but I'm mostly lost in the theming layers.

I find myself with these pieces of code, that "work", but doesn't look quite right to me.

```
// ------ Actual USE of #theme -------
$block->content = array(
  '#theme' => 'MODULE_more_information',
  'dataA' => $dataA,
  'dataB' => $dataB,
  'dataC' => $dataC,
);
return $block;

// ------ hook_theme to attach the #theme to a template -------
function HOOK_theme($existing, $type, $theme, $path) {
  $base = array(
    'render element' => 'element',
    'path' => drupal_get_path('module', 'HOOK') . '/templates',
  );
  $theme = array(
    'MODULE_more_information' => array(
      'template' => 'MODULE-more-information',
    ) + $base,
  );
  return $theme;
}

// ------ Actual template -------
<?php
extract($element);
?>

<div class="content">
  <h1><?php print $dataA ?></h1>
  <h1><?php print $dataB ?></h1>
  <h1><?php print $dataC ?></h1>
</div>

```

What gives me the idea that something is amiss is that the author manually runs `extract()`, which I've never seen a template do before.

Canonical examples of how to do this "right"?

# Answer
To be honest, aside from the use of `extract()` (which is obviously bad in and of itself), I think the code is perfectly valid, and respectful of Drupal's processes/conventions.

There are two different ways to pass variables to theme functions in Drupal 7, both provided as an argument to a theme definition in `hook_theme()`. They are `variables` and `render element`.

I can't possibly explain the difference between these two better than the `hook_theme()` docs:

> Use 'render element' if you are theming a single element or element tree composed of elements, such as a form array, a page array, or a single checkbox element.
>
> Use 'variables' if your theme implementation is intended to be called directly through theme() and has multiple arguments for the data and style; in this case, the variables not supplied by the calling function will be given default values and passed to the template or theme function.

In your case you're theming a render array, rather than calling `theme()` directly, so `render element` is the one to use.

When you use a `#theme` property on a render array, the entire element (in your case `$block['content']`) is passed through to the theme function/template file. The name of the variable that you have access to in the template file is the name you have given to `render element` in the `hook_theme()` definition.

So if your `hook_theme()` defines `'render element' => 'my_lovely_var'`, you'll have access to the render array as `$my_lovely_var` in the template file.

I suspect that the author of your code was just taking a small shortcut so he/she didn't have to access the `$element` array directly with code. Without the use of `extract()` the template file would/should have looked like this:

```
<div class="content">
  <h1><?php print $element['dataA'] ?></h1>
  <h1><?php print $element['dataB'] ?></h1>
  <h1><?php print $element['dataC'] ?></h1>
</div>

```

Just for posterity, this is the same code re-written to make use of `variables` instead:

The same code using `variables` would look like this:

```
// ------ Actual USE of #theme -------
$args = array('dataA' => $dataA, 'dataB' => $dataB, 'dataC' => $dataC);
$block->content = array(
  '#markup' => theme('MODULE_more_information', $args)
);
return $block;

// ------ hook_theme to attach the #theme to a template -------
function HOOK_theme($existing, $type, $theme, $path) {
  return array(
    'MODULE_more_information' => array(
      'template' => 'MODULE-more-information',
      'variables' => array('dataA' => '', 'dataB' => '', 'dataC' => ''),
      'path' => drupal_get_path('module', 'HOOK') . '/templates'
    )
  );
}

// ------ Actual template -------
<div class="content">
  <h1><?php print $dataA ?></h1>
  <h1><?php print $dataB ?></h1>
  <h1><?php print $dataC ?></h1>
</div>

```

You could even use the following, slightly different, method to build up the block content when using `variables`:

```
$block->content = array(
  '#theme' => 'MODULE_more_information',
  '#dataA' => $dataA,
  '#dataB' => $dataB,
  '#dataC' => $dataC,
);
return $block;

```

This second method makes the block more re-usable as the theme function hasn't already been called, and other parts of the system can still alter the individual elements of the block.
> 7 votes

---
Tags: theming
---


# Question
Title: How do I query a content type with custom fields in the 'condition' statement
I need to query a content type both returning and filtering on conditions of custom fields.

```
$query = db_select('node', 'n');
$query  ->fields('n',array('field_customfield1','field_customfield2'))
        ->condition('type', 'myContentType')
    ->condition('field_customfield3',$user->uid,'=')
    ->condition('field_customfield4',$anemailaddress,'=');
$foundrecord = $query->execute();

```

This doesn't seem to work. My issue is I can't figure out how to reference the custom fields in queries.

Any help GREATLY appreciated!

# Answer
> 11 votes
You'd be better off using an `EntityFieldQuery` for this:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'myContentType')
  ->propertyCondition('status', 1) // in case you need it
  ->fieldCondition('field_customfield3', 'value', $user->uid)
  ->fieldCondition('field_customfield4', 'value', $anemailaddress);

$results = $query->execute();

if (isset($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  foreach ($nodes as $node) {
    $customerfield1 = field_get_items('node', $node, 'field_customerfield1');
    $first_value = $customerfield1[0]['value'];

    // etc...
  }
}

```

Even though it's more code, and more overhead, it has advantages over going into the database tables directly.

* You don't need to make the `JOIN`s yourself
* `EntityFieldQuery` respects node revisions, which will be harder to keep track of well using a custom query
* Your code is now portable if you decide to change the storage backend for fields to something other than MySQL (MongoDB for example).

# Answer
> 2 votes
Custom fields have their own separate tables. Join them to the node by matching their entity\_id to the nid, and then you can use them as conditions:

```
<?php
$query = db_select('node', 'n')
        ->fields('n',array('field_customfield1','field_customfield2'))
        ->condition('type', 'myContentType');
$query->leftJoin('field_data_field_customfield3','customfield3','n.nid = customfield3.entity_id');
$query->leftJoin('field_data_field_customfield4','customfield4','n.nid = customfield3.entity_id');
$query->condition('customfield3.field_customfield3_value',$user->uid,'=')
      ->condition('customfield4.field_customfield4_value',$anemailaddress,'=');
$foundrecord = $query->execute();
?>

```

---
Tags: database
---


# Question
Title: Date Module / Date Repeat: Hourly or Minutely Recurrence?
I'm setting up a Drupal 7 based calendaring system ,and the Date module has been super amazing; it does pretty much everything I need out of the box. However, correct me if I'm wrong, but it doesn't look like there's a way to set an event to reoccur, say, once every hour.

Do you have any idea for the best way to accomplish this?
I know PHP fairly well, so I'm game for writing code, but I have no idea where to start. Do I need to create a custom module that implements the Date Repeat API? What form would take, and how would it integrate with the existing Date module? Is this an unreasonably huge undertaking for a Drupal newbie?

# Answer
> -1 votes
Recurring events are handled in good old unix cron, see (http://drupal.org/cron). But there is a more, Php way .. Poor Man's Cron, see http://drupal.org/project/poormanscron (in D6, part of core in D7).

Basically, since some hosts didn't allow cron jobs Poor Man's Cron simply "hooked" a bit of code into each page using Ajax. If an amount of time had past it would run cron.php (which in turn calls drupal\_run\_cron()).

Either way ... you need to put your task into the cron queue, make sure your site is set up correctly and let the core system execute it. If your going to use a custom module see

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_cron\_queue\_info/7

---
Tags: 7, datetime
---


title: error when deleting view

text:
# Question
Title: error when deleting view
when I try to delete a view from the views module, I receive the following error: error\_1

Trying to save a new view shows this: error\_2

Any idea how to fix this?

I also cannot delete the view manually as my phpadmin tells me that there is an error and that I have to configure session.save\_path... but I cannot find any file named session.save\_path on my server.

Please let me know if you ever had this errors and if you know how to fix this. I invested 50 hrs to develop new functionality and I cannot risk the website goes down for days...

Thanks in advance!!

# Answer
> 1 votes
It sounds like you've got some pretty serious problems here.

The fact that you can't use PHPMyAdmin because of the `session.save_path` setting (which is in php.ini by the way, it's not file name) would suggest that something on your server has changed. At a guess I'd say your web server no longer has write access to the session folder, but without seeing the full error message it's hard to say.

The fact that the you can't enable the db log module is also quite worrying. That module defines the `watchdog` table upon install so the fact that it's missing might suggest Drupal is having problems creating database tables.

The best advice I can give is to get a local version of the site up and running, with permissions for files/databases set up in a way you know is correct, and see if you still have problems.

If you do, then you know that the problem is somewhere else and you should start methodically disabling and uninstalling modules until you can narrow down the culprit.

If you don't, then you know the problem is with the live server configuration.

---
Tags: views
---


# Question
Title: How do I change the ajax loading behaviour in Views?
I have a view with some exposed filters in a block; it uses AJAX and the auto-submit feature so the view is re-loaded as soon as a filter option is changed.

In the short delay between selecting an option and the view being re-loaded, the familiar blue AJAX throbber is shown somewhere at the bottom of the form (I think where the hidden submit button is currently located).

I know I can customise this image by overriding the CSS for the throbber element, but I'd prefer not to use it at all.

What I'd much rather do is temporarily fade out the exposed filter form (and ideally the main view as well), using a jQuery animation. They would then fade back in when the AJAX call is complete.

Failing that, I'd like to use the same method that the Views UI module uses when it's updating, namely placing this icon in the middle of the page:

As that is already built in I just assumed there would be a setting somewhere to change the style/location of this loading behaviour; no such luck though.

How do I implement either of these methods?

I'm using Drupal 7 with Views 7.x-3.3.

# Answer
If you don't mind using a little jquery you could always do something like:

```
$('#view-id').ajaxStart(function(){
   $('#view-filters-id').fadeTo(300, 0.5);
});
$('#view-id').ajaxSuccess(function(){
   $('#view-filters-id').fadeTo(300, 1.0);
});

```
> 44 votes

# Answer
For the sake of completeness here's the code I ended up using; it fades both the exposed filter form and the view out when the AJAX load begins, and back in again when it finishes:

```
(function($) {
  Drupal.behaviors.events = {
    attach: function(context, settings) {
      $('#views-exposed-form-events-page', context).ajaxStart(function(){
        $('#views-exposed-form-events-page,div.view-id-events', context).fadeTo(300, 0.5);
      });
      $('#views-exposed-form-events-page', context).ajaxSuccess(function(){
         $('#views-exposed-form-events-page', context).fadeTo(300, 1.0);
         $('div.view-id-events', context).css('opacity', 0.5).fadeTo(300, 1.0);
      });
    }
  };
})(jQuery);

```
> 29 votes

# Answer
Hello i have created a very simple module that dose exactly what you want to do. The module has configuration page where you can control the style of the throbber and even upload your own images without any hacking.

This is the sandbox link: http://drupal.org/sandbox/ANDiTKO/1556808

If you find it useful please reveiw it here so it can be approved as official project: http://drupal.org/node/1556114
> 10 votes

# Answer
I just have made a research.
The `throbber` is hardcoded here in the constructor of `Drupal.views.ajaxView`.
An instance of `Drupal.views.ajaxView` is not stored in `Drupal.ajax` and there is `@todo` about it.
It means that we can't go into the object and set our own params.

## How does Views it do?

The short answer is CSS.
Views admin page just hides `throbber` and adds style to it's parent `.ajax-progress-throbber`.

```
.ajax-progress-throbber {
  background-color: #232323;
  background-image: url("../images/loading-small.gif");
  background-position: center center;
  background-repeat: no-repeat;
  -moz-border-radius: 7px;
  -webkit-border-radius: 7px;
  border-radius: 7px;
  height: 24px;
  opacity: .9;
  padding: 4px;
  width: 24px;
}

```

## Can I do something with Drupal.ajax?

Yes, I found some methods you can overwrite for AJAX elements (buttons, links, etc). I have showed an example here: How to extend or “hook” Drupal Form AJAX?. But in this case it will be not so good.
Progress element is showing at `beforeSend` stage, so you can do something before it happens.
> 6 votes

---
Tags: 7, views, ajax, javascript
---


# Question
Title: Views: output item fields grouped by field instead of item?
So currently if I make up a view that outputs three articles with their title and body fields a cleaned up version of the html structure would be:

```
<div class="item-1">
   <div class="title">Item One Title</div>
   <div class="body">Blah Blah Blah......</div>
</div>
   <div class="item-2">
   <div class="title">Item Two Title</div>
<div class="body">Blah Blah Blah......</div>
</div>
<div class="item-3">
   <div class="title">Item Three Title</div>
   <div class="body">Blah Blah Blah......</div>
</div>

```

Anyone know how I can, through Views or the best alternative, make the structure like this instead:

```
<div class="titles">
   <div class="title1">Item One Title</div>
   <div class="title2">Item Two Title</div>
   <div class="title3">Item Three Title</div>
</div>
<div class="bodies">
   <div class="body1">Blah Blah Blah......</div>
   <div class="body2">Blah Blah Blah......</div>
   <div class="body3">Blah Blah Blah......</div>
</div>

```

# Answer
Look at Views Attachments. Set up your first View w/ just titles. Then Add display \> Attachment, override your Fields to get body and use Attachment settings to position it after the first. Should be a few tutorials out there if this is confusing. Hope it helps.
> 0 votes

---
Tags: views
---


# Question
Title: Send variable to the user profile in Drupal 6
I am developing a module for Drupal which provides a login form and after submission user cURL to login in with those credentials on another website.

If all goes well, the module redirects the user to their profile and should present the information cURL fetched. This is where things go wrong.

What I'm trying to do is get the `$account` variable through the username. This is all in the `module_name_form_submit` function:

```
$account = user_load(array('name' => check_plain($user)));

```

And then append the data I want to display to it:

```
$account->content['module_name'] = array(
    '#title' => t('Module Title'),
    '#values' => get_info()
    );

```

If I do a `print_r` before the redirect, sure enough, the data is there as it should. But after the redirect:

```
$form_state['redirect'] = "users/{$user}";

```

I no longer have access to that same data. So the question is, how can I set that variable in a permanent way and access it after the redirect in the user profile page? (I'm trying to avoid sessions).

# Answer
PHP is a "shared-nothing" architecture, nothing persists over multiple requests unless stored externally.

So you really only have two options:

1. Sessions. Drupal already maintains a session for you for every user (also anon users, except on the first request). So just add your data to `$_SESSION['yourmodule']['yourdata']` and you have it available on the next request where you can remove it again if you want.
2. GET. Alternatively, you can also pass the data forward through the GET request, by doing the redirect like this: `$form_state['redirect'] = array('user/' . $account->uid, array('key' => 'value'))`. As in my example, you should always use the internal URL when doing a redirect, Drupal will take care of the aliasing fory you.
> 0 votes

# Answer
I add several things to the user object in one of my sites. I use hook\_user($op = 'load') and that has always been fine. Does that not satisfy your needs? Ouch - just noticed this is almost a year old. Sorry :)
> -1 votes

---
Tags: 6, forms
---


# Question
Title: User Avatars on My Relationships: friends Block
I have read several tutorials about doing this through views but I was wondering if it is possible to modify the block created out of the box by user relationships without having to create a view.

Am using the following version for the module; -UR 7.x-1.0-alpha4

# Answer
> 1 votes
Copy /user\_relationships/user\_relationship\_blocks/templates/user\_relationships-block.tpl.php to your custom theme's directory and you can make any modifications you want from there.

Make sure **NOT** to edit that in place. You don't want to end up in a situation where your modifications are scattered all over different module folders.

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


# Question
Title: how to add #states property to a field element in drupal 7?
I wanted to add #states property to a select list field in cck input form created by content type. I ve tried the following code but the states property is not set to the field. Can anyone suggest on how to do it.

```
$form['field_ctype']['und']['#ajax']=array('callback' =>'_ajax_menu_check_boxes',
                                              'wrapper' =>'edit-field-sub-menu',
                                            'effect' => 'fade',
                                            'event' => 'change',
                                            );
$form['field_sub_menu']['und']['#states']=array(
                                  'visible' => array(
                                 ':input[name="field_ctype"]' => array('value' => '2')));

```

could anyone suggest me where I am going wrong. Is it possible to add ajax property ans states property to a same field?

```
Note : The Ajax property for the field_ctype works fine. Only the states property is not working.

```

# Answer
Fields always have have nested names like field\_something\[und\]\[value\] or something like that. I guess your query (`:input[name="field_ctype"]`) is wrong.

I find the easiest way to get it right is using the Firebug/Developer tools Console. Play around with `jQuery(':input[...]')` until it matches what you're expecting. Also check the name of the form element.
> 6 votes

# Answer
Instead of writing custom code, there is a module that provides a simple UI to the States API, Conditional Fields. Although it's currently available only as a dev release, I have used the module on a couple of my sites without trouble.
> 0 votes

# Answer
The following worked for me in order to show fields depending on the value of a select (which is a taxonomy field). On the code below, the select field is called 'template'. For convinience, the rightside array is the condition to check for and the leftside array is the action to take. This is just another way to write the standard code:

```
/* This function finds the term id from the term name on the select box */
function get_tid_by_name($name) {
  return db_select('taxonomy_term_data', 't')
    ->fields('t', array('tid'))
    ->condition('name', db_like(trim($name)), 'LIKE')
    ->addTag('term_access')
    ->execute()
  ->fetchField();
}

/* This functions hides fields on the node form of the 'basic page' content type,
 * depending on the selected template
 */
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id ==  'basic_page_node_form') {
    $lang = $form['field_slogan']['#language'];
    $template = '#edit-field-template-' . $lang;  // template field selector
    $pp1 = get_tid_by_name ('PP1');
    $pp2 = get_tid_by_name ('PP2');
    $pp7 = get_tid_by_name ('PP7');
    $pp10 = get_tid_by_name ('PP10');
    $form['field_slogan']['#states']['visible'] = array($template=>array('value' => $pp1 ));
    $form['field_image']['#states']['visible'] = array($template=>array('value' => $pp7 ));
    $form['field_links']['#states']['visible'] = array($template=>array('value' => $pp10 ));
    $form['field_pictures']['#states']['visible'] = array($template=>array('value' => $pp7 ));
    $form['field_hightlights']['#states']['visible'] = array($template=>array('value' => $pp2 ));
    $form['field_bullets']['#states']['visible'] = array($template=>array('value' => $pp2 ));
    $form['field_video']['#states']['visible'] = array($template=>array('value' => $pp2 ));
    $form['field_quick_tip']['#states']['visible'] = array($template=>array('value' => $pp1 ));
  }
}

```
> -2 votes

---
Tags: nodes, javascript
---


# Question
Title: Creating readable links for nodes in a view
I have 2 views setup - one is for a directory listing of nodes and the other displays an individual node from that directory.

The directory view is visible at `/directory` and can be filtered by letter (e.g. `/directory/b` will show all nodes whose title starts with b)

Currently, the directory listings link to `/directory/show/[nid]` but I would like them to be friendlier. For example `/directory/show/example-title`.

I can get close to this if I check 'Output this field as a link' on the Title field and set the 'Link path' to `directory/show/[title]`. However, that displays the link as `/directory/show/Example Title`.

Is it possible for this link to be displayed as `/directory/show/example-title` somehow?

# Answer
> 0 votes
**First way:** For second Views I assume argument handling is used (NID send as argument).

1. So you should modify this argument,
2. Add/change this argument validation - select PHP code
3. There you should check if this $handler-\>argument is numeric
4. if not, try find node by title ($handler-\>argument will title),
5. if found, assign to $handler-\>argument found NID.
6. Return in code TRUE if argument is numeric or node found by title.

Minus of this for nodes with the same titles, so you can use next way.

**Another way** is using Rules for that:

1. Add rule for node creation/editing
2. Add action and use next PHP code for inserting new alias:

```
     global $language;
     $path = 'node/' . $node->nid;
     $alias = 'directory/show/' . $node->title;
     path_set_alias($path, $alias, NULL, $language->language);

```

Be sure that $node accessible in your Rules PHP code action, if not, seek patterns like \[nid\], etc.
Also you should resave all your required nodes for creating new aliases for these nodes, recommend to use for it VBO module.

# Answer
> 0 votes
I solved this in the end by overriding the title field template for my directory view and generating the links in there.

So I had started with output like this:

`<a href="/directory/show/Example Page">Example Page</a>`

and my overriding title field template contained:

```
<a href="/directory/show/<?php echo str_replace(' ', '-', strtolower($variable['row']->node_title)); ?>">
    <?php echo $variables['row']->node_title; ?>
</a>

```

Which gave me the desired output:

`<a href="/directory/show/example-page">Example Page</a>`

If there's a better solution please let me know.

---
Tags: views, 6
---


# Question
Title: Webfm and views; can I create a view that has a list of links to the files?
Really new to Drupal and getting a little lost on this one. I want to create a view of files that are listed in webfm. These files will all be pdfs. Is this even possible.

My aim is to use standard drupal 6 modules to allow the users to upload reports in pdf and list them in a view. But the view needs to link directly to the file. Another option is to use nodes to display pdf files. But this has to be in a way that end users can easily upload and create a node that displays the pdf.

Any help much appreciated.

# Answer
Actually just started working on this myself this morning. The answer is yes, you can, but as far as I've read into it, the view can't be part of another view, i.e., you have to create a separate view just for WebFM files. You'll see it when you go to Views \> Add \> View Type.

Like I said, I just started working on this this morning, so I haven't gotten any further than that, but HTH. Maybe post progress here for sharing? Funny that your question came up in teh Googles.
> 1 votes

# Answer
I've got something working, hope this helps someone.

First I installed the cck toolkit. and enabled filefield and all it's requirements.

Enabled upload and installed views.

next created a custom node type pdf.

Added a new file field.

Then created a veiw showing all nodes of type pdf and listed the file field.

If you need more detail let me know
> 0 votes

---
Tags: files
---


# Question
Title: How can I render an image_field from within hook_block_view?
I want to contain my custom content type's image field (cck) within a block. I define the block within hook\_block\_view:

```
function foxyidx_block_view($delta)
{
    $t = get_t();
    if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
        $node = node_load(arg(1));
    }
    switch($delta)
    {
        case 'foxyidx_images':
            $block['subject'] = '';
            $render_out = drupal_render($node->field_image);
            $block['content'] = <<<HTML
                {$render_out}
HTML;
            break;

```

If I were to render the image\_field in a template I would use

```
print drupal_render($content['image_field']);

```

However, in the hook\_block\_view function I assume I need to use another function. Any ideas?

# Answer
I think a combination of `field_get_items()` and `field_view_value()` would do the trick:

```
$image_items = field_get_items('node', $node, 'field_image');
$image_view = field_view_value('node', $node, 'field_image', array_shift($image_items));

$block['content'] = render($image_view);

```
> 2 votes

# Answer
I modified this solution a little to handle multiple images in the image\_field.

```
$block['subject'] = '';
            $render_out = drupal_render($node->field_image);
            $image_items = field_get_items('node', $node, 'field_image');
            $image_view = '';
            foreach($image_items as $image_item)
            {
                $image_view .= render(field_view_value('node', $node, 'field_image', $image_item));
            }
$block['content'] = $image_view;

```
> 2 votes

# Answer
I found this answer on drupal.org It handles it in a different way.

http://drupal.org/node/154066
> 0 votes

---
Tags: blocks, media
---


title: Post content to Facebook Wall

text:
# Question
Title: Post content to Facebook Wall
I'm using Drupal 7.

I've an Article content type, when it gets published it needs to be posted into my Facebook Wall. How can I implement this process? I've searched the drupal.stackexchange.com but I couldn't find the right way to do. Can you put me through?

# Answer
> 1 votes
Use the Drupal for Facebook module. It's not the easiest thing to setup in the world, you'll have to read the docs carefully. One of the features is publishing site content to a Facebook Wall.

---
Tags: social-network, nodes
---


title: Field inheritance (Drupal 7)

text:
# Question
Title: Field inheritance (Drupal 7)
I would like to make a field that is very similar to the group audience field but only displays certain types of groups.

As an experiment I hacked up:

og\_field\_audience\_options

and I was able to remove the groups I didn't want but obviously this is not where this code belong.

Is there a way that I can create a new field that inherits most of the behavior of the group audience field and but has a slightly different way of picking which groups to display? Or do I need to recreate the whole field from scratch?

# Answer
Strictly speaking, fields can't "inherit", no, but you can almost do it anyway.

Drupal 7 comes with a generic "File" field, and a more specific "Image" field. Technically, one could say that Image inherits from File, but the way it's done is simply that for a lot of it's hook implementations, it just calls back to file.

Example code:

```
/**
 * Implements hook_field_load().
 */
function image_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  file_field_load($entity_type, $entities, $field, $instances, $langcode, $items, $age);
}

```

As far as I know, this is as close as you can get.
> 3 votes

---
Tags: 7, entities, organic-groups
---