# Question
Title: Invoking Drupal core tests from within a custom module .test script
I am writing a simpletest test script, where I would like to enable my module, and then invoke a Drupal core test to ensure that my module is producing core-compliant results (in particular, I render a pager alternative to core's, and would make sure that, at its minimal setup, is equal to core's one).

Is there a way to do that?

Thanks for help

mondrake

# Answer
So... I found a solution that's working, at least for my case.

It has to do with the fact that test cases are actually PHP classes that can be extended. So I tried to leverage inheritance, with a caveat...

I want to run a test on the pager, Drupal 7, after I have enabled a module that replaces the core pager.

The core pager test class is defined as

```
class PagerFunctionalWebTestCase extends DrupalWebTestCase {

```

now, my problem was that the core test would not be caring about my module to be loaded before running the tests.

I created my module test class as an *extension* of the core one, like

```
class MyPagerTest extends PagerFunctionalWebTestCase {

```

This is OK, but the point is that if I call parent::setUp() at this stage, the core setup will be run and I will still miss my module from loading before the actual test.

So the caveat is that instead of calling parent::setUp, I will call directly the 'ancestor' DrupalWebtestCase::setUp function, with *my* setup, and skip the call to parent.

Like this:

```
...

public function setUp() {
  // Enable required modules.
  $modules = array(
    'dblog',
    'mypager',
  );
  DrupalWebTestCase::setUp($modules);

  // Insert 300 log messages.
  for ($i = 0; $i < 300; $i++) {
    watchdog('pager_test', $this->randomString(), NULL, WATCHDOG_DEBUG);
  }

  $this->admin_user = $this->drupalCreateUser(array(
    'access site reports',
  ));
  $this->drupalLogin($this->admin_user);

}

....

```

That's all - class inheritance will do the magic and bring the rest of the test functions in.

Anybody sees other options?
> 2 votes

---
Tags: testing
---


# Question
Title: Import or Programmatically create nodes with Videos
I'm working on a new drupal site which I need to migrate from an existing non-drupal site. I need to be able to import the old blog posts as Article nodes (either through some standard import mechanism or I can write some php to programmatically create the nodes).

However, I'm not sure how to handle creating Image and Video data in a node, especially with the need for transcoding video after creation of the node. So, two questions:

1) How can I programmatically create nodes with binary Image and Video data?

2) When I do create a node with Video data, will the post-create transcoding job be started? I'm using Zencoder to do my transcoding.

I am not using the local filesystem for drupal, I'm storing all of my files in Rackspace Cloud Files, however, I can handle it if I need to use the local filesystem temporarily during import and then manually move things over to Cloud Files. This is only a one-time event.

# Answer
Your best bet is to use the Migrate module. It's got a kinda steep learning curve but plenty of documentation available.

The Migrate Extras module provides integration with the Media module, which could help with the video field specifically.
> 1 votes

# Answer
Take a look at Datasources.

> Datasources provides a framework to describe and manage datasource to import in Drupal.

I've written a generic module to import data into Drupal previously!
> 0 votes

---
Tags: 7, nodes, files
---


# Question
Title: how to print 'add term' taxonomy form into block
I have a taxonomy vocabulary named "jenis dokumen". I want to let anonymous users add terms within this vocabulary. I'm trying to add a block and render that form to add new term using PHP filter, but it's failing.

This is my code:

```
include_once(drupal_get_path('module','taxonomy') . '/taxonomy.admin.inc' );
return drupal_render(drupal_get_form('taxonomy_form_term', jenis_dokumen));

```

Can anyone help?

now i have success with this.

```
$vocabulary = taxonomy_vocabulary_load(2, FALSE);
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
return drupal_render(drupal_get_form('taxonomy_form_term', $vocabulary));

```

but, there is a default value in field name 'Jenis Dokumen' how can i get blank (no value) in field?

# Answer
> 5 votes
A couple things:

* The function taxonomy\_form\_term() expects the $vocabulary parameter to be an object with a "machine\_name" property
* You should wrap the vocab name in quotes
* More elegant to use module\_load\_include() instead of include\_once()

So:

```
if ($vocabulary = taxonomy_vocabulary_machine_name_load('jenis_dokumen')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $edit = array();
  $taxonomy_form = drupal_get_form('taxonomy_form_term', $edit ,$vocabulary);
  return drupal_render($taxonomy_form);
}

```

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


# Question
Title: Is there an advantage to Featurizing a view, over using Views' export?
I've created a View in Drupal 6 with Views 2. If I want to get this view from my dev site to production, is there a compelling advantage offered by using Features over using the built-in Views export?

# Answer
For *a single* View, there is no difference in functionality really. The view will be the same regardless.

I use Features anyway because it's makes it more conventient to organize multiple pieces of configuration into "features". I'm not aware that ctools offers any easy way of doing "This view with that panel and those three dependencies in one module". That is what features adds on top of Ctools.

It's worth mentioning that the Configuration module is an useful alternative that largely makes the configuration tracking easier. If you don't care about the features aspect of features, take it for a spin. (Thanks Clive for pointing this out)
> 8 votes

---
Tags: views, features, importing-exporting
---


# Question
Title: Token's available "Replacement patterns" nested table should only be displayed on-demand
The Token module provides hooks to other modules to serve their own tokens. Multiple modules that support Token integration can generate a really huge nested table tree when displaying the available tokens in the field settings:

This can lead to out-of-memory issues in Views settings or regular field settings:

Earlier I created an issue related to this problem: http://drupal.org/node/1836264. Until a possible solution comes there (e.g. a patch), I would like to solve it my own (it doesn't matter if I temporarily have to "hack" Token's core): **I would only like to load this table with the available tokens "on-demand" with AJAX or any other possible solution**.

Do you have any ideas how to solve this?

# Answer
The default token tree can contain many thousands of lines of HTML, and the corresponding Javascript listeners and functionality can totally break things memory wise (or just give you a darn laggy experience). Plus it can confuse the heck out of site administrators.

These issues refer to current developments for loading the token tree 'on demand' or via a popup:

And OP pointed out in his comments, the Token tweaks module lets you set a depth limit for the token tree, which seems to have solved his memory problem.
> 3 votes

---
Tags: 7, tokens
---


title: Ajax Form to pull two different views

text:
# Question
Title: Ajax Form to pull two different views
I have two different views that need to be toggled on a node page. I cannot put these two views together so I have created a form that will basically take the values of the form that I create, and send them as arguments to the view and display the view. I am attempting to do with this ajax. It works fine but the problem is the second time I run the form it does not refresh or update that view.

```
function photoflight_albums() {
    photoflight_gallery_themes();
  $output = render(drupal_get_form('photoflight_gallery_form'));
  $output .= "<div id='gallery-ajax-wrapper'>";
  $output .= views_embed_view('gallery', 'default');
  $output .= "</div>";

  return $output;

}

//Grabs the node titles
function photoflight_gallery_themes(){
    $type = "photo_theme";
    $theme_list = array();
    $nodes = node_load_multiple(array(), array('type' => $type));
    foreach($nodes as $themes){
        $theme_list[$themes->title] = $themes->title;
    }
    return $theme_list;
}

```

//Form calls back to the function above to the gallery-ajax-wrapper div output above function photoflight\_gallery\_form($form, &$form\_state){ $form = array();

```
  $form['themes'] = array(
    '#type' => 'select',
    '#options' => array(photoflight_gallery_themes()),
    '#ajax' => array(
            'callback' => 'photoflight_simplest_callback',
            'wrapper' => 'gallery-ajax-wrapper',
        ),
  );
  //debug($form);
  return $form;
}

//Ajax callback
function photoflight_simplest_callback($form, $form_state) {
    $view = views_get_view('gallery');
    $args = array( 'title' => $form_state['values']['themes']);
    $view->set_exposed_input($args);
    $output = $view->preview('default', $args);
    return array("#markup" => $output);

}

```

# Answer
The issue was that it was removing the HTML element so the second call had no HTML to replace. Changed to either use ajax update or on the call back wrap the return in the div again
> 0 votes

---
Tags: views, forms, ajax
---


# Question
Title: Multiple Date field with term attached to each instance
I have a need to build a "Project" content type that has a multiple date field. This date field will be used to mark particular "Milestones" within a project. I am attempting to attache a small text field or term to each instance of the multiple date field so I can plot each date on a calendar with description.

Is there a combination of modules I can achieve this with? I was reading about Field API but was hoping there was an alternative way.

Any help is much appreciated.

# Answer
I can confirm that Field Collection is the answer with a little themeing of the node edit page -thanks for your help.
> 0 votes

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


# Question
Title: how to create image upload of difference dimensions
I am creating a custom gallery. I require images that are the thumb nail and the big image size. I have custom content type. When i add the image field it allows me to enter the dimensions size. Is there a way for drupal to create 2 images. ie thumb and big image

# Answer
You can either create two image fields, one for the media image and another one for the thumb, or you could just have one and use different Image Styles ( admin/config/media/image-styles in Drupal 7 ) for both the full and thumbnail. You could even add Image Javascript Crop for more fine-grained control of the thumbnail.
> 1 votes

# Answer
ImageCache is what you are looking for. Here is a quote about it (from the module's project page):

> ... allows you to setup presets for image processing. If an ImageCache derivative doesn't exist the web server's rewrite rules will pass the request to Drupal which in turn hands it off to ImageCache to dynamically generate the file.
> -1 votes

---
Tags: 7, media
---


# Question
Title: My hook_menu_alter() and page callback don't get triggered
This question relates to How do I redirect a taxonomy menu item to another path?

I followed the recommendations of Clive and wrote a hook\_menu\_alter to provide my callback.

```
function material_menu_taxonomy_page_callback($term) {
  dsm('Entered material menu callback');
}

function material_menu_menu_alter () {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_menu_taxonomy_page_callback';
}

```

I placed a code line `dsm("Altering");` in the callback to see where in the process the callback is being called, but it never shows up.

I am fairly certain that I have the code correct.

* The hook has the name of the custom module.
* The callback name is correct.
* the callback is in the same file as the hook
* I have turned the module off and then on so that I can be sure that Drupal knows about `mymodule_menu_alter`
* And I have flushed the caches.

My assumption is that `mymodule_menu_alter()' should change the callback in the menu item array and that the callback will be called each time the menu item is selected. That suggests that my`dsm()\` message should display at the top of the page requested by the menu.

While Clive's test indicated in his answer worked, my revisions did not. Following Clive's answer recommendations I revised the code as follows.

### material.info file contained in modules subdirectory = sites/all/modules/Custom/material

```
name = Materials
description = Redefine the path for materials menu
package = CR-Hub
core = 7.x
; Includes
files[] = material.module

```

### material.module file in same subdirectory

```
function material_taxonomy_page_callback() {
  drupal_goto('taxonomy/term/1');
  // return 'Entered material menu callback';
}

function material_menu_alter(&$items) {
  // return 'Entered Material Menu Alter';
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_taxonomy_page_callback';
  return $items;
}

```

When I select any menu item neither `drupal_goto()`, or `return 'any text'` lines redirect the selected path from the menu item.

# Answer
> 4 votes
You haven't passed `$items` into the function ;)

```
function material_menu_menu_alter (&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_menu_taxonomy_page_callback';
}

```

Without that you're not actually altering anything as `$items` doesn't exist in a global scope.

You'll also need to clear the caches again once you've made the change.

**UPDATE**

Working code that I've just verified:

material.info:

```
name = Materials
description = Redefine the path for materials menu
package = CR-Hub
core = 7.x
; Includes
files[] = material.module

```

material.module

```
function material_taxonomy_page_callback($term) {
  // Calling drupal_goto() here will result in an infinite loop.
  // This is the page callback for pages with a URL like taxonomy/term/1 so
  // there's no need to redirect...you're already where you need to be.
  // This function is used to build up the new page content for the taxonomy page

  // As a test just output the name of the term related to this page.
  return $term->name;
}

function material_menu_alter (&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_taxonomy_page_callback';

  // You don't need to return anything from this function as $items is passed in by reference...anything you change in that variable will be reflected in the $items var in the calling function.
}

```

Once installed if I go to any taxonomy page the content region contains just the name of the taxonomy term for that page (using `return $term->name`). If it's not working for you the only thing I can advise is to clear Drupal's caches, or check what custom/contributed modules you've got installed that might be overriding your code.

# Answer
> 2 votes
I think what you may be missing is that the taxonomy menu item has a file set to look for the callback in the taxonomy.pages.inc

Try this:

```
$items['taxonomy/term/%taxonomy_term']['page callback'] = 'your_callback';
$items['taxonomy/term/%taxonomy_term']['file'] = '';

```

# Answer
> 1 votes
I was trying to do exactly the same thing described in Clive's answer, but the override was not working.

Finally I found out that what was preventing it from working was that I had the module Taxonomy Display enabled on the site. Disabling it was the solution to my problem.

So, you should disable any views overriding taxonomy/term/% but you should also check your enabled modules!

Hope this helps.

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


title: Interactive map

text:
# Question
Title: Interactive map
I want to make a map like the one on that site: http://www.avito.ma/
Then when I click in a region of the map I'll be redirected to a region of my site .
I'm asking if there is a module that can do this job.

# Answer
> 5 votes
A module will only be able to do so much to help you with this because everybody's maps and the precise regions that are highlighted and linked are different! So you probably would still have to create your own image map to implement the functionality.

I image what they used is the jQuery Map HiLight module with an image map to create that page. The module page itself has some information on how to build your own image map, and what the module adds to that is the highlighting functionality you see when you hover over the map areas.

Hope that helps!

---
Tags: media, google-maps
---


# Question
Title: How do you add a custom field to a menu link in Drupal 7?
I am currently using the menu module (Drupal 7 Core) to manage my menus. A menu link consists on only a title and a description. **I would like to add an image field as well as another text field**. I have considered using taxonomy rather than menu links, but I still want the capability to add a basic page to a menu.

I have looked into a module called Menu Attributes http://drupal.org/project/menu\_attributes, but it doesn't add an image field.

# Answer
Menu icons should do what you're after.

> This module allows you to upload an image in the menu-item's configuration form.
>
> After uploading the image, the icon data will be added to the menu link's options array.
> 2 votes

---
Tags: routes, media
---


# Question
Title: How can I get the labels of values of a field?
I have created a List (text) field that has key|label pairs as options. How do I get the label, when the key is what is stored in the node?

# Answer
This was my solution:

```
  if (isset($node->field_k_status[LANGUAGE_NONE][0]['value'])) {
    $info = (field_info_field('field_k_status'));
    $status =  $info['settings']['allowed_values'][$node->field_k_status[LANGUAGE_NONE][0]['value']];
  } else {
    $status = "Not Set";
  }

```

At this point, `$status` will have the label of whatever `field_k_status` is set to. field\_info\_field() gets the details about the field, and `$node->field_k_status[LANGUAGE_NONE][0]['value']` gets the value. I think that there is likely a better way, but I couldn't find it. There is a somewhat similar question asked here, but I didn't find what I was looking for anywhere else.
> 0 votes

---
Tags: entities
---


# Question
Title: Different slide intervals for Views Slideshow
I've created a slideshow using Views Slideshow and the Cycle plugin. In the Slideshow settings, there are advanced transition options that allow you to set the timer delay between slides. The project I'm working on requires that the delay between slides be different for each slide, so I need a way to do something like this:

* Slide 1: 3000 ms
* Slide 2: 5000 ms
* Slide 3: 10000 ms

I have searched and cannot find a way to accomplish this easily. Is there something I'm missing, or would this require a custom module?

# Answer
> 1 votes
You might be able to override the defaults with something like this:

```
$('.views-slideshow-cycle-main-frame').each(function(index) {
  var timer = 3000;
  if (index == 1) timer = 5000;
  if (index == 2) timer = 10000;
  $(this).cycle({
    timeout : timer
  });
});

```

This goes in an external js file or using drupal\_add\_js().

---
Tags: javascript, views
---


# Question
Title: String Overrides is not overriding the "Read more" string
I've filed a support request on drupal.org about this question, but I figured I should ask here as well because someone could know the answer.

I want to change the "Read more" link in teasers so that it says "Full story". I was pointed to the String Overrides module which supposedly makes it very simple to change the built-in strings. The UI isn't very complicated, so I'm not sure what I could possibly be doing wrong, but it's not working. I have saved the settings, flushed all caches, etc.

Do you have any idea?

# Answer
Might need some tweaking, but you can change the text in hook\_preprocess\_node(). If you set it to "Read more" you can override it with stringoverrides after, or change it to what you want at once.

In your themes template.php, add:

```
/**
 * Implements hook_preprocess_node().
 */
function MYTHEME_process_node(&$vars) {
  // Change default text of the read more link.
  if (isset($vars['links']['node']['#links']['node-readmore'])) {
    $vars['links']['node']['#links']['node-readmore']['title'] = t('Read more');
  }
}

```

Related modules:
http://drupal.org/project/readmorecontrol
http://drupal.org/project/read\_more
http://drupal.org/project/linkoutreadmore
> 4 votes

# Answer
After many hours of fighting with this, I found the source of the problem.

I believe this to be an issue in core (not really a bug, per se). In the node.module, when it is building the "Read more" link in the teaser view, it has this code in `node_build_content()`:

```
'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),

```

So when Strings Override is doing string comparison it isn't matching, because "Read more" is obviously not the same as "`Read more<span class="element-invisible"> about My Title</span>`".

I edited the node.module so isolate the "Read more" text from the rest of the HTML like so:

```
'title' => t('Read more').t('<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),

```

Then the system is rendering two strings: "Read more" and "`<span class="element-invisible"> about My Title</span>`."
> 2 votes

---
Tags: 7, string-overrides
---


# Question
Title: Switch to Drupal Mobile Theme Programatically
I found the following code on http://detectmobilebrowsers.com/ and would like to use it to programatically switch from my default theme to a mobile theme that I will also have active.

```
<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) {
    //Change Drupal theme to a custom mobile theme
} else {
    //Continue assigning the default theme
}
?>

```

Where should I place this code so it will transparently use the correct theme? I don't want to use another module or a sub domain for the mobile site. I just want to use a different theme for users accessing my site from their mobile phones. Thanks!

# Answer
The best option out there is to use module themekey that has all the tweaks to detect the user browser and serve the right theme. The performance hit is un-noticeable and it has already done all the hard work for you already.

Check a nice tutorial here: http://mustardseedmedia.com/podcast/episode52
> 9 votes

# Answer
Have you thought about responsive theming? Depending on how complex your current theme is, maybe adding some media queries and some additional css maybe enough to get you started.

Here's more to read: Drupal Responsive Webdesign
> 1 votes

---
Tags: 7
---


title: Inline image not showing

text:
# Question
Title: Inline image not showing
I have a problem after my successful migration from D6 to D7 where all inline images are not showing. Inline images are the images that are inserted in node body.

Modules being used:

1. Insert
2. Custom module

This is working fine in D6 but in D7 after saving new node the image is not showing. I have to clear the cache first or resave the node in order for the inline image to show.

Steps to replicate the problem:

1. Create a new node and save - No inline image showing.
2. Visit old nodes - No inline image showing.

My solutions so far.

1. drush cc all
2. Visit the old nodes then truncate cache\_field table
3. Resave the node

Im wondering why the inline image is not showing in newly created node and for the nodes that are not visited yet.

Any thoughts?

# Answer
> 2 votes
1) When you are adding a new node, check the *text format* option under the Body field. Ensure that it has not been set to "Filtered HTML" (if you are using the Standard profile) or some other text format that will filter out HTML tags outside a preset whitelist. However, this doesn't explain as to how the image shows up on re-save.

2) Disable your custom module and try once. Ensure that it is not affecting anything. Because, Insert, by itself, seems to be okay. Just checked out this demo.

# Answer
> 2 votes
Its because Drupal text formatter skipping `<img>` tag!

* Goto admin/config/content/formats , then configure the format.
* At bottom , there is a tab "*Limit allowed HTML tags*"
* Add `<img>` there

---
Tags: 7, entities, media, input-formats
---


# Question
Title: Menu doesnt appear on custom 'not found' page
On my site I have configured things so that the home page will appear if the URL doesnt exist. (ie in admin/settings/error-reporting I set a replacement page for the 404 page.)

The problem is that the menu doesnt appear, so if a user lands here he cant use the site properly.

My menu is the 'primary menu' and has been placed in the left sidebar. I dont have any special setting for this block - eg no page 'includes' or 'excludes'.

To help me debug can anyone tell me if this is the expected behaviour or any suggestions for what might have gone wrong?

I'm using Drupal 6.

# Answer
Drupal doesn't render the region of your theme that your primary menu is in; there's a module to change this behavior:

> On 404 Not Found error pages, Drupal will skip rendering of several pieces of your website for performance reasons. Some of these include:
>
> 1. The "Left" and "Right" regions of your theme.
> 2. The "Primary links" block and any other menu links block.\*
> 3. The Primary links and Secondary links of your theme.\*
>
> \*Unless you have configured a "Default 404 (not found) page" on admin/settings/error-reporting.

From 404 Blocks module description.
> 5 votes

# Answer
I think is important to mention this:

> Since blocks now appear on 404 pages, but navigational links are still missing, this project is being renamed…
>
> For a Drupal 7 version, see the 404 Navigation project.
> 1 votes

# Answer
There s a simple work around. I try to avoid modules for simple things. http://drupal.org/node/129762#comment-228166

> Just override theme\_page function then call phptemplate\_page right after from your template.php file.

Remember to rename "YOURTHEME\_page" with the name of your theme.

```
function YOURTHEME_page($content, $show_blocks = TRUE) {

  // Set additional conditions to change $show_blocks if you want here..
  // The following will always set $show_blocks to TRUE.
  $show_blocks = $show_blocks ? $show_blocks : TRUE;

  // phptemplate_page is what gets called usually but the
  // theme function allows us to override it with the themes' name.
  // We're calling it directly here so we don't have to copy tons of code.
  return phptemplate_page($content, $show_blocks);
}

```
> 0 votes

---
Tags: routes
---


# Question
Title: How do I implement "enable" or "disable feature" similar to Drupal Gardens?
I'm interested in implementing something similar to the way Drupal gardens let you enable and disable features in the create-site interface. (I mean the term features figuratively, not necessarily the features module.) Is this just some sort of custom form that hooks into enabling and disabling modules?

# Answer
> 0 votes
What you see on that page is a Drupal form where the form fields have been heavily themed to appear differently from how you would normally see that type of form field on a Drupal site.

Looking at the HTML source of that page, it is clear those selectors are simply checkboxes rendered with a custom theme function.

```
<div class="form-item" id="edit-features-28711-wrapper">
 <label class="option" for="edit-features-28711"><span class="feature-icon" style="background: url(/sites/default/files/connect.png) no-repeat center center;"> </span><input type="checkbox" name="features[28711]" id="edit-features-28711" value="1"   class="gardens-feature-checkbox" /><span class="label-text">Follow us</span></label><div class="feature-preview"><img class="preview-image" src="/sites/default/files/stay-connected_0.png" />Gain a following. Provide links to your (or your users') profile on Twitter, Facebook or other social networks.</div>
</div>

```

There is also custom JavaScript code that changes the appearance of the form field.

When I turn off a feature, I see a CSS class being added to a tag, and another tag value being changed. The value associated with the checkbox is not changed; it is 1 when the feature is enabled, and it is still 1 when the feature is disabled.

---
Tags: 7
---


# Question
Title: How to get multiple value with token_get_values()?
I have a field which accepts unlimited values so the values of the field get saved in an array. If I use `token_get_values()` to get the corresponding field value, I only get the first element of the array.

How can I read the whole array value or get an imploded string of values with `token_get_values()`?

# Answer
You cannot, using `token_get_values()`. The code that is returning the value of the token for a CCK field uses just the first value of the field. The function that gets the value of a token for a CCK field (content\_token\_values()) contains the following code. (See in particular the code between `// [1]`.)

```
  $content_type = content_types($node->type);
  $node->build_mode = 'token';
  $node->content = array();
  content_view($node);
  // The formatted values will only be known after the content has been rendered.
  drupal_render($node->content);
  content_alter($node);

  $field_types = _content_field_types();
  foreach ($content_type['fields'] as $field_name => $field) {
    $items = isset($node->{$field_name}) ? $node->{$field_name} : array();
    $function = $field_types[$field['type']]['module'] . '_token_values';
    if (!empty($items) && function_exists($function)) {
      // [1]
      $token_values = (array) $function('field', $items, $options);
      // [1]
      foreach ($token_values as $token => $value) {
        $tokens[$field_name .'-'. $token] = $value;
      }
    }
  }

```

The function called in `$function('field', $items, $options)` is, for a text field, text\_token\_values(), which contains the following code.

```
  if ($type == 'field') {
    $item = $object[0];

    $tokens['raw']  = $item['value'];
    $tokens['formatted'] = isset($item['view']) ? $item['view'] : '';
    return $tokens;
  }

```

Despite `content_token_values()` passing all the CCK field values, the function just uses the first value.
> 1 votes

---
Tags: 6, tokens, entities
---


# Question
Title: Changing the path of jQuery to use a CDN instead of the local file system
I am creating a custom theme and I would like to know how to update the path of jQuery to use a CDN like the following:

```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

```

I don't want to use another module. I just want a simple way to change the path of the script.

# Answer
> 1 votes
Add the following code in the template.php file of your theme. (Replace mytheme with the actual short name of your theme.)

```
function mytheme_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['type'] = 'external';
  $javascript['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
}

```

As you are replacing the copy of the jQuery library with the same version copy hosted on Google, it doesn't make much sense to do it for just a theme. It would make sense to change it independently from the theme used from Drupal.

If you plan to use a different version of the library, you should first check there aren't incompatibilities with the jQuery version, and JavaScript code used from Drupal, or third-party modules. In case of incompatibilities, some JavaScript files used by Drupal could need to be replaced (using `hook_js_alter()`). That is what the jQuery Update module does.

---
Tags: 7, hooks, javascript, cdn
---


# Question
Title: How do I get a HTML value from $form_state?
I am dynamically showing the radio box values from database on a form.

```
<input id="edit-info-prog-dates-0" class="form-radio" type="radio" value="0" name="info[prog_dates]">
<label for="edit-info-prog-dates-0" class="option"><div class="test-cost-date">Aug 13, 2012 - Sep 24, 2012</div><div class="currency-w1"><span class="currency-symbol">$</span><span class="currency-cost">350.00</span> <span class="currency-code">CAD</span></div> </label>

```

I am using the following code to generate the above HTML.

```
 $form['info']['prog_dates'] = array(
    '#type' => 'radios',
    '#title' => t('Select Dates'),
    '#required' => TRUE,
    '#options' => $dates,
    '#prefix' => '<div id="radios-programdates">',
    '#suffix' => '</div>'
);

```

I want to save the value for the cost in database. If I write the following code, I am only getting the input value '0'.

```
$form_state['info']['prog_dates']

```

How do I fetch the cost value, which is inside the `<span>` and `<label>` in HTML?

# Answer
> 1 votes
From the HTML you show, I get that the partial content of `$dates` is the following.

```
$dates = array(
  0 => '<div class="test-cost-date">Aug 13, 2012 - Sep 24, 2012</div><div class="currency-w1"><span class="currency-symbol">$</span><span class="currency-cost">350.00</span> <span class="currency-code">CAD</span></div>'
);

```

What you can do to get the 350.0 value is changing `$dates` to the following.

```
$dates = array(
  '350.0' => '<div class="test-cost-date">Aug 13, 2012 - Sep 24, 2012</div><div class="currency-w1"><span class="currency-symbol">$</span><span class="currency-cost">350.00</span> <span class="currency-code">CAD</span></div>',
  // ...
);

```

In that way, `$form_state['values']['info']['prog_dates']` would contain `'350.0'`, if the users select the radio button I shown.

From the HTML you shown, I get that in the form you set #tree to `TRUE`. Differently, the HTML name assigned to the radio form field would not be *info\[prog\_dates\]* as in your case, but *prog\_dates*. If I am wrong about that, it means you need to check the value of `$form_state['values']['prog_dates']`, instead of `$form_state['values']['info']['prog_dates']`.

# Answer
> 0 votes
If `[info]` is a fieldset then to get the value of "prog\_dates" you only need:

```
$form_state['values']['prog_dates']

```

---
Tags: forms
---


# Question
Title: Why can't I update my Drupal modules and themes?
Suddenly I found my self in a big issue: I just can't upadate my Drupal modules and themes.

When I run the update script via the GUI, the download phase passes correctley (or it seems to be). But when I perform the database update and I click to "Continue" and putting the site under maintennace mode, nothing happens. And also a major problem come: the maintenance mode persist even when I disable it.

To resolve that issue I clear all the cache from the database.

Any idea or help for that?

# Answer
1) try to run the updates via drush

2)are you sure that the new module version has a new hook\_update\_N in it? If not then there will be nothing happening during the update in GUI
> 1 votes

---
Tags: updating, maintenance-mode
---


# Question
Title: How to know if my XML Sitemap being submitted?
I've configured the XML Sitemap and Site verification modules, but I don't see the sitemap being submitted to Google. If I enter the Google Webmaster tools it says no sitemaps were submitted, but maybe it doesn't show those posted via API or something.

How could I know if it's being actually submitted? Thanks.

# Answer
> 2 votes
If you are using Drupal 7, it will show that your sitemaps have been submitted in your log messages at Admin \> Reports \> Recent Log Messages (/admin/reports/dblog)

Click on "Filter log messages" and select "xmlsitemap"

If you do this, it will show when the last sitemap was generated and when it was submitted the the search engines that you have configured it to submit to (in my case, Google and Bing).

---
Tags: xml-sitemap
---


# Question
Title: Create taxonomy 'add terms' form into block
I have two vocabularies named 'vocab\_one' and 'vocab\_two'. I create custom multiple blocks module named 'add library', in order to display the taxonomy 'add terms' form to each blocks.

Each block displayed on the same node in the content area. The position of 'Vocab Two Block' are above 'Vocab One Block'.

When I add new term on 'Vocab One Block', the new term is always stored in the 'vocab\_two'. Then I switch position of the block. This time, the new term is always stored in the 'vocab\_one'.

How to store a new term within selected vocabulary, without worrying about the block position?

here is my add\_library.module:

```
function add_library_block_info() {
  $blocks['Vocab Two Block'] = array(
    'info' => t('Vocab Two'),
  );

  $blocks['Vocab Two Block'] = array(
    'info' => t('Vocab One'),
  );

  return $blocks;
}

function add_library_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'Vocab Two Block':
      $block['subject'] = t('Add Vocab Two');
      $block['content'] = add_vocab_two();
      break;
    case 'Vocab Two Block':
      $block['subject'] = t('Add Vocab One');
      $block['content'] = add_vocab_one();
      break;
  }
  return $block;
}

function add_vocab_two() {
    module_load_include('inc', 'taxonomy', 'taxonomy.admin');
    $vocabulary = taxonomy_vocabulary_load(2);
    return drupal_get_form('taxonomy_form_term', $vocabulary);
}

function add_vocab_one() {
    module_load_include('inc', 'taxonomy', 'taxonomy.admin');
    $vocabulary = taxonomy_vocabulary_load(4);
    return drupal_get_form('taxonomy_form_term', $vocabulary);
}

```

# Answer
Every block must have unique delta, so in hook\_block\_info first $blocks change 'Vocab Two Block' to 'vocab\_block\_first', second $blocks 'Vocab Two Block' change to 'vocab\_block\_second', then in 'switch' change first 'case Vocab Two Block' to 'case vocab\_block\_first' and second 'case Vocab Two Block' to 'case vocab\_block\_second'. Then show these two blocks on the same place.
> 0 votes

---
Tags: forms, taxonomy-terms
---


title: 'Add More' Taxonomy Term Widget

text:
# Question
Title: 'Add More' Taxonomy Term Widget
I'm trying to create a field widget that is similar to the normal term reference widget with one key difference. The user needs to be able to add multiple new taxonomy terms at the same time, this may demonstrate it better:

I've got to a point where the functionality is similar to what the taxonomy/options/list modules provide (i.e. the checkboxes/radios are shown, saving etc.)

Here's important bit of the code I'm using in `hook_field_widget_form()`:

```
 $element += array(
    '#type' => $multiple ? 'checkboxes' : 'radios',
    '#default_value' => $multiple ? $default_value : reset($default_value),
    '#options' => $options,
    '#value_key' => $value_key,
    '#element_validate' => array('options_field_widget_validate'),
    '#properties' => $properties,
  );

```

What's throwing me here is that $element isn't your usual form array so I'm not sure how to add the textfield and and button - especially as their values aren't meant to be saved. What's the best way to add these fields to my widget?

As for adding the Javascript needed, am I right in thinking I should use #ajax that calls a function that rebuilds the #options for the checkboxes?

Thanks in advance!

*EDIT -* My initial question was quite vague, here's some more details on what I've tried:

```
  $element += array(
    '#type' => 'fieldset',
    '#delta' => $delta,
  );

  $element['value'] = array(
    '#type' => $multiple ? 'checkboxes' : 'radios',
    '#default_value' => $multiple ? $default_value : reset($default_value),
    '#options' => $options,
    '#value_key' => $value_key,
    '#element_validate' => array('options_field_widget_validate'),
    '#properties' => $properties,
  );

  $element['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Add another'),
    '#weight' => 5,
  );

```

This a is an amalgamation of various examples I've seen, and seems to get me closer. The problem is when I submit the entity form I get the following error:

> Notice: Undefined index: tid in taxonomy\_field\_is\_empty() (line 1402 of modules\taxonomy\taxonomy.module).

I've taken a closer look at this function and it's expecting `$item` to have the structure `$item = array('tid', 2)`. When using the above code there seems to be a delta coming from somewhere and the structure of `$item` ends up being `$item = array(0, array('tid', 2)`. I can't work out where '0' is coming from?

*ANOTHER EDIT*

I've been able to fix the above error with the following code by altering $element like so:

```
$element += array(
    '#type' => 'fieldset',
    '#process' => array('taxonomy_free_entry_ignore_parent'),
);

```

and adding the function:

```
function taxonomy_free_entry_ignore_parent(&$form, &$form_state, $complete) {
  array_pop($form['#parents']);
  return $form;
}

```

When I save the entity I'm getting a message telling me it's been saved. When I check the table for the field, it isn't being saved. What am I doing wrong?

# Answer
> 2 votes
I'm sure you could do this in `hook_field_widget_form()` (which I'm guessing is where your current code is) by just adding a child element to your existing element, e.g.

```
$element['text'] = array(
  '#type' => 'textfield',
  '#title' => 'Title',
  // etc...
);

```

If that doesn't work I know it will definitely work if you use `hook_field_widget_form_alter()`.

For example, the following is a small function which enables the `alt` field for an Image field type using the Media Selector widget (for some reason it's not enabled by default):

```
function media_image_attributes_field_widget_form_alter(&$element, &$form_state, &$context) {
  if ($context['field']['type'] == 'image') {
    $element['alt'] = array(
      '#type' => 'textfield',
      '#title' => 'Image Description',
      '#weight' => 10000,
      '#default_value' => count($element['#default_value']) ? $element['#default_value']['alt'] : ''
    );
  }
}

```

As far as the ajax functionality goes, I think you're definitely going along the right lines. I think the Field Example module in Examples has some sample code which might help.

# Answer
> 1 votes
The Module Hierarchical Select at least gets very close to what you want to achieve. Its widget looks a little different but basically does the same job and would be a good starting point for customisation. Take a look at the taxonomy demo Places I've visited.

Another option might be the Autocomplete Deluxe module.

# Answer
> 0 votes
I just found Taxonomy Other module that may suits your needs.

> This is a simple module to add an optional '- Other -' to taxonomy select lists. It allows users with the right permissions to create new terms.

For Drupal 7 port, check: Port Taxonomy Other to D7 (direct link).

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


title: how to get month and year value

text:
# Question
Title: how to get month and year value
I am using following code to build the select box for Month and year

```
$form['billing']['expiry_db'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiry Date'),
    '#default_value' => date('m Y'),
    '#date_format' => 'm Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
    '#prefix' => '<div class="field-wrapper-w1">'
);

```

I am passing following value in database

```
$form_state['values']['billing']['expiry_db']['month']

```

and

```
$form_state['values']['billing']['expiry_db']['year']

```

but it is only showing value '2' for month and value '2' for year. However I am selecting month 'December' which has value '12' in HTML. Please help

# Answer
The value for #default\_value must have the `date()` format "Y-m-d H:i:s"; the value returned in `$form_state` is a string.

In your case, the code you should use is the following one.

```
  $form['billing']['expiry_db'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiry Date'),
    '#default_value' => date('Y-m-d H:i:s'),
    '#date_format' => 'm Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
    '#prefix' => '<div class="field-wrapper-w1">',
  );

```

If the form has #tree set to `TRUE`, then `$form_state['values']['billing']['expiry_db']` a string such as `'2020-05'` for May, 2020.

As far as I can see, the value of #date\_format is only used to understand which components of a date must be returned, but the format of the returned value is always the same. Changing #date\_format to `'Y-H:s'` the returned value is `'2020 00:00'`. In you case, the code to get the month, and the year is the following one.

```
list($year, $month) = explode('-', $form_state['values']['billing']['expiry_db']);

```

### References
> 1 votes

---
Tags: forms, datetime
---


# Question
Title: views 3: select only one value from a multivalue field
I have a content type which has a multivalue image field. I need to create a view that displays a list of nodes of that type but displays only one value of that multifield, not all of them.

I need to get something like this:

* node title
* first image

---

* node title
* first image

---

etc

Any ideas? Thanks, M.

# Answer
It under the "multiple field settings" in the settings of your image field.

You should choose "Display all values in the same row", separation mark: "", display 1 item, offset 0. (translated from my own language so names might be a bit different)

**UPDATE** You will need to display fields rather then the whole node though. (I don't know how you did this before)
> 4 votes

---
Tags: 7, views
---


# Question
Title: Adjusting the month being viewed on the Calendar Block to match the month of the Day being viewed
So, I am using Drupal 7 with the Calendar Module. I am using the calendar block as the primary calendar for viewing events daily events. Everything works great, except the calendar block doesn't change its month being viewed to match the day being viewed.

For example. The calendar block is visible and starts at the month of November (because it is November). You browse to December and click on a day to view that day's events. The page loads and shows the events for that particular day in December, but the calendar block defaults back to November. I want it to show December since I am viewing a day in that month

Is there a way to have the calendar block show the month that matches the day being viewed?

# Answer
Have you tried to set "track current date in session" under admin/config/date/calendar?

This should do the trick...
> 1 votes

---
Tags: 7, blocks, datetime
---


# Question
Title: Accessing user's custom field in html.tpl.php
In my html.tpl.php , I was printing this:

```
    print $user->name;

```

which displayed `username`.

But now I need to print Custom field `"First Name"` instead of `username`.

So I tried this:

```
   print $user->field_first_name[und][0]['value'];

```

which is not printing anything although the field `"First Name"` has some value.

Where am I going wrong ? Am I missing some obvious thing ?

Thank you .

# Answer
If you are using the global variable `$user`, it doesn't always contain a full initialized object. In fact, during the bootstrap, `$user` is initialized with the data contained in the "users" table, from the following code.

```
  if ($is_https) {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
    if (!$user) {
      if (isset($_COOKIE[$insecure_session_name])) {
        $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
          ':sid' => $_COOKIE[$insecure_session_name],
        ))
        ->fetchObject();
      }
    }
  }
  else {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
  }

  // We found the client's session record and they are an authenticated,
  // active user.
  if ($user && $user->uid > 0 && $user->status == 1) {
    // This is done to unserialize the data member of $user.
    $user->data = unserialize($user->data);

    // Add roles element to $user.
    $user->roles = array();
    $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    $user->roles += db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $user->uid))->fetchAllKeyed(0, 1);
  }

```

If you want to be sure to get a fully loaded user object for the currently logged-in user, you should use the following code.

```
$account = user_uid_optional_load();

```

After that, you can get the value of any user field.

```
$fullname = field_get_items('user', $account, 'field_first_name');

```

You can also get the rendered value of the field using the following code.

```
$rendered_value = field_view_field('user', $account, 'field_first_name');

```

The other reason for which `$user->field_first_name['und'][0]['value']` could not contain any value is that the language-neutral value of the field is not be set. (`'und'` is the value of the constant LANGUAGE\_NONE, or LANGUAGE\_NOT\_SPECIFIED in Drupal 8.) If you use field\_get\_items(), or field\_view\_field(), you are sure to get the correct value.

As side note, it is preferable to keep the logic in the template.php file, in functions that are called from the template files.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Can I add a template preprocessor that's more specific than an existing hook?
I have a preprocessor function in my model that runs on the views\_view\_table hook. I want it to be called only for a specific view. If it were a hook, rather than a preprocessor, I could use, for example views\_view\_table\__myview. Can I do that with just the preprocessor, too, or do I have to register a matching hook? If so, how do I make sure it does exactly what the base hook does?

# Answer
> 0 votes
For the Views module, if you want to know its template file suggestions:

* Open edit for your view
* Click on 'Theme information'
* Use whichever template name that meets requirements
* Go back to your view and, at the bottom of 'Theme information', click 'Rescan template files'
* Your template file should be highlighted in this list

---
Tags: hooks, theming
---


title: Add a map for each node in a view

text:
# Question
Title: Add a map for each node in a view
I am building a restaurant application which would have a search functionality, and when somebody searches of restaurants for a zip code, it would return the data. The data would be the name of the restaurant, the description and the map. When a user is adding the restaurant, I am using address field and geofield to get the latitude and longitude, so getting the maps up and running isn't an issue now.

However, I trying to create the search view, but I am unable to create a view which has a path, and which would display the title, description and then the map.

```
ex: Title | Description
    MAP1(map for first restaurant)

    Title | Description
    MAP2

```

Can somebody tell me how would I build it?

The modules I am using to build this are geofield, geophp, geocoder, addressfield, openlayers, views, ctools and libraries.

# Answer
### Step 1

Install and enable the Geofield Map module. Create a view with the Geofield (latitude and longitude) fields with a contextual filter node ID. Change *Formatter* to *Geofield Map*.

>

### Step 2

Install and enable the Views Field View module. Create another view for the restaurant details. For viewing the map, you can select *Global: view* in the field. You then select which view to embed in that field and give the arguments it requires in the field settings.

>
> 2 votes

---
Tags: views, google-maps, location
---


# Question
Title: how to effectively hide a field (with title) on a form
> **Possible Duplicate:**
> specify $form elements to be excluded from display?

I would like to hide a field on a form using `hook_form_ID_alter`. The form is owned by another module. This field cannot be `unset` because it contains a value.

Using CSS `{display: none}` for the standard field class is not good because the field should be hidden only in specific conditions (which must be determined using php).

In `hook_form_ID_alter`, I could add an `#attribute` to the field with a class value e.g. `hideme` and then use CSS to hide this class. But it will leave the field title (tried).

The field has `#prefix` set to `<div class='some_class'>` (in this particular case). This prefix precedes the field as well as the title when displayed in a browser. So I could analyze the prefix with regular expression and add a `hideme` class there. But I am not 100% sure what the #prefix will contain, so the regexp could be complex.

Perhaps there is a better way to hide a field with title on a form?

# Answer
You can set the #access property for the form field to `FALSE`. The form field will not be shown to the users, but its value will be still be available in `$form_state['values']` for the submission, and validation handlers.

Using #access is always the suggested way to avoid users can change the value of a form field, and avoid any third-party module depending on that form field starts to raise warnings, or fails to work as expected.
> 1 votes

# Answer
You can use the `hide()` function instead of `unset()`, if you want to retain the value in the field. From the docs:

> Hides an element from later rendering.

In simple words, `hide()` marks the render-able array as already rendered, so that the theme's function will not render it.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: User/register Page is not found in Drupal 6 site
The user login and user register page are not found in my drupal 6 site.It was working fine until before yesterday and I changed the user login page link as www.sitename/user instead of www.sitename/user/login but the register page is still not found.

Is there any way to get back the user/register page? I didnt installed any module recently.

Thanks in advance.

# Answer
Have you checked the clean URLs? There might be a problem with clean URLs.

Try www.sitename/?q=user/login.
> 1 votes

---
Tags: users
---


# Question
Title: How to Bulk delete the document from solr without actually deleting the node?
The scenario is to delete bulk documents from apache solr, without deleting the actual node from the database. I am aware that when the node is un-published it will be deleted from solr.

But as my node are very large containing 1000's of terms I don not want to use node-save to un-publish the node.

Is there any hook or function which un-publishes the node and deletes from solr by minimal load (definitely not node save) ?

UPDATE:

* Drupal Version : 7.15
* Modules: Apachesolr

# Answer
> 1 votes
I found the answer on exploring the apache solr module,

**STEP 1**

Select the nodes from the node table alone or by joining the apachesolr index entities table,

```
// Check for unpublished content that wasn't deleted from the index.
  $table = apachesolr_get_indexer_table('node');

 // Select the nids from the node table
  $query = db_select($table, 'aien')
    ->fields('aien', array('entity_id'))
    ->condition('n.nid', 0);
  $query->leftJoin('node', 'n', 'n.nid = aien.entity_id');
  $nodes = $query->execute()->fetchAllAssoc('nid');

```

**STEP 2**

Chunk it to some limit and call the apachesolr\_index\_nodeapi\_mass\_delete function

```
      $node_lists = array_chunk($nodes, '100', TRUE);
  foreach ($node_lists as $nodes) {
    watchdog('Apache Solr', 'On cron running apachesolr_nodeapi_mass_delete() on nids @nids', array('@nids' => implode(',', array_keys($nodes))), WATCHDOG_WARNING);
    if (!apachesolr_index_nodeapi_mass_delete($nodes, $table)) {
      // Solr query failed - so stop trying.
      break;
    }
  }

```

---
Tags: 7, nodes, search
---


# Question
Title: what should I use as placeholder for a html img element?
To keep it simple I've left some out of my img field. here's my code:

```
$markup = t("<img src='%s' />", $img_src);

```

I've tried `format_string()` but that also retuns:

```
<img src="<em class="placeholder">path/to/image</em>">

```

# Answer
> 2 votes
It would probably be better to use the `theme_image()` function for that:

```
$image_html = theme('image', array(
  'path' => $img_src,
  'alt' => 'Some alt',
  // etc
));

```

If you're hell bent on using `t()` then you need to use it with the `!` prefix, so the value is passed through without any checks/sanitisation:

```
$markup = t("<img src='!src' />", array('!src' => $img_src));

```

The docs for `format_string()` explains the different kinds of placeholders you can use, and which prefix you should use for each.

---
Tags: media
---


# Question
Title: how to find whether a node has more than one revision?
How could I find whether a node has more than one revision. I use `node_load($nid)` and get a `$node` object. How can I achieve this using the object? What would be the best way to do it?

# Answer
Have you checked `node_revision_list($node)` function?

> This returns a list of all the existing revision numbers.

You can pass the current node and it will return list of all revisions.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Adding a button or text link to a content's view (Drupal 7)
I would like to add a link or a button to my content's main view (I.E. ?q=node/120) that will redirect the user to a java applet that the node already has a reference to.

Is there an easy way to add such a button or link?

# Answer
I was able to do this in hook\_node\_view.
> 0 votes

# Answer
try it in reverse mode, this mean add your `custom field` as 'exclude from display' then add the `content:link` and use REWRITE RESULTS -\> Rewrite the output of this field and put the pattern matching your custom field. ex: \[my\_custom\_title\]. HTH
> 0 votes

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


# Question
Title: How to add a new responsive Layout for large viewports to Omega Theme
I would like to add another Layout to the Omega-Theme Settings, because i need a certain media-query for an extra-large viewport. I tried adding a new setting to the .info-file but without success. Maybe this will be possible only by adding a new media-query directly to the css-file?

# Answer
You need to copy the `grids` variable from the default alpha.info file, and add your new layout in your theme's .info file like so:

```
grids[alpha_default][name] = Default (960px)
grids[alpha_default][layouts][fluid] = Fluid
grids[alpha_default][layouts][narrow] = Narrow
grids[alpha_default][layouts][normal] = Normal
grids[alpha_default][layouts][wide] = Wide
grids[alpha_default][layouts][wider] = Wider  <- Your custom layout
grids[alpha_default][columns][12] = 12 Columns
grids[alpha_default][columns][16] = 16 Columns
grids[alpha_default][columns][24] = 24 Columns

# Default settings for the new layout
settings[alpha_layouts_alpha_default_wider_responsive] = '1'
settings[alpha_layouts_alpha_default_wider_media] = 'media query here'
settings[alpha_layouts_alpha_default_wider_weight] = '4'

```

You'll also need a new CSS file (called `THEMENAME-alpha-default-wider.css`) to manage CSS for that layout, but Alpha/Omega should handle the rest for you.
> 3 votes

# Answer
You could also add include another css file in the info file and then specify the media query in the new file. This work on every template.

info file:

```
...
stylesheets[all][] = template_file.css
stylesheets[all][] = override.css
...

```

override.css

```
@media ...

```
> 0 votes

---
Tags: theming
---


# Question
Title: How do I implement two-way node references?
The node-reference module (a component of CCK) provides a great way to create a reference one node from another. What is the best way to expose a two-way relationship between the two? Example below:

For instance, in a ticket tracking system with two tickets (nodes) A & B, you could create a node reference from ticket A --\> B and mark B as a child. When viewing ticket A it would be trivial to display this information. However, I would also like to display this relationship when viewing ticket B and show ticket A as its parent.

This same requirement would also apply in non-hierarchical situations (tickets C & D) with a reference from C --\> D, the relationship should be exposed on ticket D as well as on C.

# Answer
> 25 votes
There are many modules available, your milage may vary:

BackReference (Drupal 6 only)

NodeReferrer (Drupal 7 beta release)

Node Relationships (Drupal 6 only)

Corresponding node references (Drupal 7 stable release)

Corresponding entity references (Drupal 7 dev release)

Content Dependency (Drupal 7 stable release)

# Answer
> 7 votes
Entity Reference Module now works with Corresponding Entity References. This is ideal for all nodes and non node entities.

# Answer
> 4 votes
For Drupal 6, the best option is probably the NodeReferrer module. For Drupal 7, Relation fits the bill but is not yet ready.

# Answer
> 4 votes
If you're using Drupal 7 / Views, you can build a 'reverse' relationship to get a listing of nodes that refer to a given node (or, perhaps, users that refer to a given node). Check out the patch in this issue: http://drupal.org/node/1043260

In my opinion, unless you need the explicit, pre-built reverse relationship stored in the database (this can be sometimes be helpful for performance reasons), using one of the other solutions is overkill. You can always look up a relationship in your own SQL query if you need to...

\[Edit: Since originally writing this post, the patch in the issue above has been committed to References for D7, and should be the preferred way of backreferencing (works great when simply needing lists of nodes or users referencing a certain other node or user).\]

\[Edit 2: If you're using Entity Reference, it looks like the preferred solution is to use Corresponding Entity References, and there's also the less-widely-used Entity Reference Field Synchronization.\]

# Answer
> 3 votes
In **Drupal 7** (which you indicated) it seems the solution is to use the Entity Reference Module in combination with the (Entity)Reference Field Synchronization module which adds the necessary functionality to keep the relationships synched.

The same can be achieved with References Module with cnr module \- this solution works (I'm using it on one Drupal 7 site currently), but is becoming obsolete/deprecated in favor of the first solution I gave.

All the other solution mentioned in the above answers are relevant only for **Drupal 6** (except for Relation which has the potential to become a great module, but right now, doesn't really do much and has lots of issues).

# Answer
> 2 votes
Alternatively, if you're working on a custom implementation and want a straight forward way of referencing back, you can hook into `nodeapi`, listen for the `save` operation and than programmatically update the referenced node.

---
Tags: 7, nodes
---


# Question
Title: How do I migrate a custom field from WordPress?
I'm working on migrating a fairly large blog type site from WordPress into Druapl 7. The WordPress Migrate module has imported the basic blog content very well (title, body, tags, etc), however there were custom fields set up in WP that do not import.

Looking at the xml file, there's really just one extra piece of info I need. A line for a video file (which is a code for a youtube video).

Here's how the code for this looks in the XML file:

```
    <wp:postmeta>
        <wp:meta_key>Video_File</wp:meta_key>
        <wp:meta_value><![CDATA[8ENbMuVQCYE]]></wp:meta_value>
    </wp:postmeta>

```

I have decent PHP experience, but the only customizing I've done in Drupal are relating to themes. Can I write a little addition to the WordPress Migrate module to insert this extra piece of info? Since the module migrates everything else nicely can I create a new little module that would go through the same xml file, find the matching node (by post date/time, title, some distinguishing piece of info from the xml file) and then add in the video info (assuming I would first create another row in the DB table)?

I'm at a bit of a loss, and since I need to bring in close to 1000 posts (most of which have the video code), I really need to fine a solution that doesn't involve me editing every single node by hand to add in the dang code.

~~I should also mention I currently don't have a CCK field in Drupal for the video code... that just dawned on me, so I'm off to create one and then re-migrate a portion of the blog (I downloaded it in multiple xml files for testing).~~

Update: Created that CCK field, re-imported the blog, and sadly it didn't work :) Not that I thought it would to begin with (nothing is ever that easy).

---

Update: I've been attempting to modify the WordPress Import module with little success thus far. This meta field is just some text, so I'm hoping to figure out where to add in the info I need to have it process correctly. I'm sure I need to tell it which cck field to insert the new data, just have to find it!

---

Another Update: Working on adding a WP plugin to export all the content as a CSV, then going to use the Feeds module to attempt to import everything.

My backup is going to be to use the wordpress\_migration module to import the basic stuff (title, body, tags, etc), then write a custom php page to add the video links... I'm basically thinking to find the title in the node table, grab the nid, then create the entry in the video\_field in the db table. At least that's how it's currently laid out in my head, whether or not that works in real life remains to be seen.

Course hopefully Feeds works just fine and I won't have to try the backup!

# Answer
> 3 votes
Neat. It looks like wordpress is storing a small fragment of the youtube url in the DB. I'm not sure how the the cck video field stores content -- probably in its own field, and it probably has to be set for "Youtube" before you attempt a migration.

Once you figure out where the youtube ID will be stored in a drupal field. See the documentation on how to extend worpress migrate:

> 1. Extend the appropriate class, such as the WordPressBlogEntry class with your custom behavior - add field mappings in \__construct(), manipulate the body ($row-\>content) in prepareRow(), etc.
> 2. Extend the WordPressBlog class, and override migrationClasses to point to your custom classes:

```
<?php class MyCustomBlog extends WordPressBlog {
public function migrationClasses() {
    $classes = parent::migrationClasses();
    $classes['WordPressBlogEntry'] = 'MyCustomBlogEntry';
    $classes['WordPressPage'] = 'MyCustomPage';
    return $classes;
} }

```

In your custom migration class you would then define the migration of a field using a Mapping as something like:

```
 // dest (a field in the node) <- source
 $this->addFieldMapping('youtube_url', 'source_yt_value');

```

In your custom migration class you will of course have access to the typical helper methods used in migrations to "prep" the data (retrieve the youtube url from that CDATA crud), and translate it into a valid video blurb for drupal.

---
Tags: migrations
---


# Question
Title: How can i use main-menu items as a fields in selectbox in drupal 7
Helllo, I have a content type called "Lookbook" in that i want to put one field like "Lookbook For" and this field content select box and main-menu items. I have main-menu list but I want only display submenu items of lookbook menu in select box. Is it possible that menu links display as fields?? Thanxs..

# Answer
First, create a view that references the nodes you want - e.g. that have a parent item with node id x (or whatever the criteria is for those nodes). Get that view right, and the rest is easy.

Upload and enable either the references, or the entity reference module http://drupal.org/project/entityreference or http://drupal.org/project/references

In your content type, choose a node reference item and select widget. You can base the option list on your view.
> -1 votes

---
Tags: routes, nodes
---


# Question
Title: Why are nodes not saving, and redirecting to edit instead?
When editing a node and attempting to saving it, the user is redirected to the edit form with no error message and the node is not updated. This situation is similar to the problem described in "Nodes do not save, but instead redirect to edit page again", but in Drupal 6 and in all content types. The nodes have at least one field, FileField, which is common to all nodes but I haven't had any problem with it in other sites. There're no errors, nothing in the logs. I'm clueless.

**Edit:** I've identified that the problem is with content types that have a FileField field. Sadly, I still don't have a clue of what could be causing the problem.

# Answer
It was the FileField that was causing the problem. I still don't know why but I removed it and the node could be saved again.

**Edit:** It seems the problem is caused by CCK fields. Nodes without CCK fields are not experiencing this problems.
> 0 votes

---
Tags: 6
---


title: How to remove files using File widget

text:
# Question
Title: How to remove files using File widget
After clicking on the "Remove" button, the entry disappears, but the file is still on the server.

# Answer
Managed files are deleted on cron run for D7.
> 3 votes

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


title: Where is $node->view set?

text:
# Question
Title: Where is $node->view set?
views\_preprocess\_node() contains the following code.

```
  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
    $vars['view'] = $vars['node']->view;
    $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name;
    if (!empty($vars['node']->view->current_display)) {
      $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;

      // If a node is being rendered in a view, and the view does not have a path,
      // prevent drupal from accidentally setting the $page variable:
      if ($vars['page'] && $vars['view_mode'] == 'full' && !$vars['view']->display_handler->has_path()) {
        $vars['page'] = FALSE;
      }
    }
  }

```

The part to which I am interested is the line that initializes a variable using the value of `$vars['node']->view`. I looked at the code executed from the Views module for a node, but I was able to find where `$node->view` is initialized.

Which of the node hooks (e.g. `hook_node_view()`, `hook_node_load()`, `hook_node_presave()`) would get a valid value for `$node->view`?

# Answer
> 1 votes
A quick grep of the views module points to the `views_plugin_row_node_view` class, whose `render()` function contains the following lines:

```
$node->view = $this->view;
$build = node_view($node, $this->options['view_mode']);

return drupal_render($build);

```

So when a node is rendered using the node row plugin, the view is attached to the node object immediately prior to it being passed through `node_view()`, which is why you see it in the theme preprocess functions.

To actually answer the question (which I missed before), `hook_node_view()` would get a valid view object, while the others you mentioned wouldn't (I don't think).

---
Tags: views, nodes, hooks
---


# Question
Title: Running a custom query alongside Drupal Registration Query
Good afternoon all. I would like to implement a custom query during the registration process of my registration. I've taken a look around online and can't find the information anywhere, so if anybody knows where the registration query is ran, so that I can add another query to it that would be awesome. Thanks in advance. EDIT The Query that runs alongside will go into a seperate game database, so alongside of the standard query it will also run This was my old query, so maybe it can help show what I'm trying to run.

```
  $server= "****";
    $user= "****";
    $pass= "****";
    $gamedb= "****";

$link = mysqli_connect("$server", "$user", "$pass", "$webdb") or die( "Error:" . mysqli_connect_error());
$username = mysqli_real_escape_string($link, (string) $_POST['username']);
$email = mysqli_real_escape_string($link, (string) $_POST['email']);
$password = sha1((string) $_POST['password']);
$query="INSERT INTO user (`username`, `email`, `password`, `permissions`)
VALUES ('$username', '$email', '$password', '1')";
mysqli_query($link, $query) or die ("Error:" . mysqli_errno($link));
mysqli_close($link);

```

# Answer
> 0 votes
The use of the hook\_user\_insert() it is call when the user is created. Here is an implementation example:

```
    function hook_user_insert(&$edit, $account, $category) {
      db_insert('mytable')
        ->fields(array(
        'myfield' => $edit['myfield'],
        'uid' => $account->uid,
      ))
        ->execute();
    }

```

Depending on your case you might want to check other hooks like:

hook\_user\_insert()

hook\_user\_presave()

hook\_user\_update()

---
Tags: database
---


# Question
Title: How to specify the version for drush site-install
I am running drush site-install and I want to install d6 but d7 is default, how to I specify the Drupal version?

# Answer
Usually I use `drush dl drupal` then cd into the drupal directory and then `drush si [other parameters]`.

That means, when you download drupal core you need to specify the version at that time -- not during site installation (which is just running the files).

You can do that by appending the version onto your dl argument, for example: `drush dl drupal-6` or `drush dl drupal-6.x`
> 3 votes

---
Tags: drush, installation
---


# Question
Title: Does Google Analytics module tracks superuser 1 out of the box?
Does Google Analytics module tracks superuser 1 out of the box?

UPDATE: Found this in the `.install` file of the module. What does it basically say about user 1? Can anybody explain them to me? Does it track uid 1? Thanks.

```
variable_set('googleanalytics_roles', $roles);

// Upgrade disabled tracking of "user 1" to new logic.
if (!$track_user1 = variable_get('googleanalytics_track__user1', 1)) {
  variable_set('googleanalytics_custom', 1);

  // Load user 1 object, set appropriate value and save new user settings back.
  $account = user_load(1);
  $account = user_save($account, array('data' => array('googleanalytics' => array('custom' => 0))), 'account');
  $messages[] = t('Disabled user specific page tracking for site administrator.');
}

// Delete outdated tracking settings.
db_delete('variable')
 ->condition('name', db_like('googleanalytics_track_') . '%', 'LIKE')
 ->execute();

// ...

```

# Answer
> 1 votes
> Does Google Analytics module tracks superuser 1 out of the box?

Yes, it does. In fact, the default value for the Drupal variable googleanalytics\_track\__user1 is 1, which means the control statement is executed by default.

```
if (!$track_user1 = variable_get('googleanalytics_track__user1', 1)) {
  // ...
}

```

What the code does is to save in `$user->data` the module settings, and delete the old settings.

---
Tags: google-analytics
---


title: Putting values in a template file

text:
# Question
Title: Putting values in a template file
In the past (Drupal 6), I used a function to put some values in a template file.

This function was something like `function_name('templates/my_template.tpl.php', array('key1' => 'my value', 'key2' => 'my other value'));` which returned HTML code.

Is there this function in Drupal 7?
How can I use it?

# Answer
> 2 votes
The function you are looking for is theme\_render\_template(), which gets the filename of the template file to render, and an array of variables to pass to the template file.

In Drupal 6, it is called as in the following code.

```
 $messages = drupal_set_message();
  if (isset($messages['warning'])) {
    $title = count($messages['warning']) > 1 ? 'The following update warnings should be carefully reviewed before continuing' : 'The following update warning should be carefully reviewed before continuing';
    $variables['messages'] .= '<h4>' . $title . ':</h4>';
    $variables['messages'] .= theme('status_messages', 'warning');
  }

  // This was called as a theme hook (not template), so we need to
  // fix path_to_theme() for the template, to point at the actual
  // theme rather than system module as owner of the hook.
  global $theme_path;
  $theme_path = 'themes/garland';

  return theme_render_template('themes/garland/maintenance-page.tpl.php', $variables);

```

`theme_render_template()` is still present in Drupal 7, and Drupal 8.

In Drupal 7, although, the function is only used from theme(). There isn't generally any reason to call the function directly; you can define a new theme function that uses a template file, and then call `theme()` as `theme('theme_function', $array)`. (Replace `'theme_function'` with the name of the theme function.)

---
Tags: 7, theming
---


# Question
Title: Why don't calls to drupal_set_message() show up after a drupal_goto()?
My question is similar to How to redirect the user to a page and show a message on the admin overlay (using drupal\_set\_message and drupal\_goto), but I'm not doing an overlay -- it's just a straight page. This issue has been talked around a bit on this site, but I've never seen a real resolution of it.

My situation is:

* The user submits a form, through the usual method.
* The form has a \_submit() handler, which runs: it does some stuff, sets a drupal\_set\_message(), and then redirects somewhere via drupal\_goto().
* The user properly ends up on the intended page, but the message is
nowhere to be seen.

Any clues on this? I really can't figure out why this is happening.

# Answer
> 4 votes
First of all, keep in mind that `drupal_goto()` in a form submit handler is bad. The reason is that `drupal_goto()` shuts down Drupal right after sending the location header, so the rest of your site functionality will not work.

To make a redirect, pass `$form_state` as reference in your submission handler (`FORM_ID_submit($form, &$form_state)`), and then set `$form_state['redirect']` to where you want to send the user, for example with `$form_state['redirect'] = 'node/add';`.

# Answer
> 5 votes
I tried in my test site, and the message appears, even using `drupal_goto()`. I used the following code.

```
function code_testing_date_form($form, &$form_state) {
  $form['expire'] = array(
    '#type' => 'date_select',
    '#title' => t('Expire Date'),
    '#default_value' => date('Y-m-d H:i:s'),
    '#date_format' => 'Y-H:s',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
  );

  $form['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#description' => t('Optional. In the menu, the heavier items will sink and the lighter items will be positioned nearer the top.'),
    '#default_value' => 5,
    '#delta' => 10,
    '#access' => FALSE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function code_testing_date_form_submit($form, &$form_state) {
  drupal_set_message('You have been redirected.');
  drupal_goto('user');
}

```

What could cause the issue you are seeing could be:

* There is code that clears the content of `$_SESSION['messages']`, used to contain the messages set with `drupal_set_message()`.
* There is code that invalidate the current session. In this case, the logged-in user should be logged out.
* You are rendering the form in a template file.
* The template file for the page to which the users are redirected doesn't have code to handle the `$messages` variable. The default node.tpl.php file contains the following code; if the template doesn't print `$messages`, the messages set with `drupal_set_message()` will be not seen.

```
<?php if ($breadcrumb): ?>
  <div id="breadcrumb"><?php print $breadcrumb; ?></div>
<?php endif; ?>
<?php print $messages; ?>
<div id="main-wrapper"><div id="main" class="clearfix">

```

---
Tags: 7, forms
---


# Question
Title: Adding "terms" on the fly and/or mutiple term referance submission with "unlimted values"
I have an issue which I’m hoping you guys can point me in the direction. I’m currently building a music press/media site in which I want to use “terms” for things like the artists, venues etc. Eventually writers will be able to submit their work via the normal add content route and all the various terms will be created when there filling out the submission form. At the moment I’m using a “Term Reference” field with the “Autocomplete term widget (tagging)” widget to add in the main artist. I have a separate field for the support artists with the Number of Values option set to “unlimited” however I don’t get an option to add another support artist in (like you would if the fields reference was set to text).

So I’m looking for a way to get an option within the node submission form to keep on adding support artists as term references and/or a method of adding term references on the fly so they can be selected via a drop down list whilst the submission form is being filled out (i..e not the term references are add and in place before the form is saved. Any help on this would be mostly appreciated as this has had me stuck for a while now.

Thanks.

# Answer
> 0 votes
I would recommend you try the Hierarchical Select module if you want to have a drop down select as well as have the ability to add new terms on the fly. You select this option when setting up the Hierarchical Select for the term reference field. It will add 'Add new term' to the select list.

---
Tags: taxonomy-terms
---


# Question
Title: drupal 6 to 7 site upgrade using drush_sup - how to download compatible drupal 7 modules
I used drush\_sup to upgrade my drupal 6 to 7 site. everything went smooth except the drupal 7 modules were not downloaded to the upgraded website.

During the upgrade process it did list the installed D6 modules, and the recommended D7 counterparts. I'm not sure what caused it to skip downloading it or maybe it just doesn't?

Thanks, any help appreciated.

# Answer
I would run through the site upgrade process with the `--prompt-all` flag set to see if anything strange appears.

`drush drush_sup` will upgrade core and find *good* candidates for contrib modules, I think it'll even accept dev releases, but with a warning.

You could also pass in `--auto` to the command which will just do the defaults.

Source: http://drupalcode.org/project/drush\_sup.git/blob/refs/heads/7.x-2.x:/README.txt
> 2 votes

---
Tags: drush, updating
---


title: Change CCK field data type

text:
# Question
Title: Change CCK field data type
I have a CCK field with a data type 'text', that I want to change to 'decimal'.

I have used a hook\_update\_N and db\_change\_field in order to do this.

Here is an example how I tried to do it:

```
function ptm_foo_update_6005() {
  db_change_field(
    $ret,
    'content_type_',
    'field_foo_value',
    'field_foo_value',
    array(
      'type' => 'decimal(10,2)',
      'description' => 'Foo'
    )
  );
}

```

But when I execute the update, it gives me the following error message:

> User warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

# Answer
Based on the comments on your question, I certainly hope you're doing this in a `.install` file and not a `.module` file.

The `$ret` variable is expected to be a reference, so you'll need to declare it before hand.

```
$ret = array();
db_change_field($ret ...);

```

Is your table name really `content_type_`?

And you may want to look at this and stick in a couple `dsm()` calls to see what the `db_change_field()` function is actually passing to MySQL and then you could trouble shoot the query directly.
> 1 votes

---
Tags: 6, database, updating
---


# Question
Title: Separating user edit form into small descent form
I am developing a Community website in Drupal 7,where users got profiles with many fields, but these fields are grouped for Example: Basic informations,Hobbies, Education,Experience and So on.. In normal drupal, when user wants to edit his profile, he/she will be present with a huge form with lots of fields. What i need is to separate these categories in different small forms, if possible using a custom module so the forms can be called like drupal\_get\_form('basic\_informations'); drupal\_get\_form('Hobbies'); If This will be possible then i will be able to opens this small forms in modal dialogs(ctools).

Any suggestion will be Appreciated.

# Answer
> 1 votes
No need for custom forms!

Profile2 will do all of the items you require! Here is the handbook to get you started.

This will let you have different forms (tabs) on the /user page and you can also choose which of those "subforms" you want on the user registration.

---
Tags: 7, forms, users
---


title: Add attribute to content title

text:
# Question
Title: Add attribute to content title
I'd like to add a custom attribute into the title element whenever a particular content type is displayed, whether as an individual node or through a view (specifically when displaying 'full content'). How do I do this?

I'm using Drupal 7.

# Answer
> 0 votes
You could modify the field.tpl like monymirza suggested. But you may want to use `hook_preprocess_field(&$vars)` and target the title element within the `$vars` array.

Use that function in your theme and you may view the content/structure of the `$vars` array with `dsm($vars)` from the devel module.

---
Tags: views, nodes
---


title: Drupal Time Zone Problem

text:
# Question
Title: Drupal Time Zone Problem
I've got some nodes which have different time value when I edit and display them.

13th November 2012 6 pm is the value that I input, however, when I tried to display that, it becomes 13th November 2012 7 am. My drupal time zone setting is Australia/Melbourne. When I output the whole array for displaying the time, the time zone value seems to be Australia/Melbourne as well. The array is:

Array ( \[0\] =\> Array (\[value\] =\> 2012-11-13 07:00:00 \[timezone\] =\> Australia/Melbourne \[timezone\_db\] =\> UTC \[date\_type\] =\> datetime ))

Has someone got some ideas?

# Answer
This is why when viewing data out of a Drupal database you should always use the provided wrapper functions. Because the timezone is applied at runtime and not stored in the database, which makes sense because Drupal allows for users to be "part of a timezone" and format their dates based on such.

So for you to get the field rendered just:

```
render(field_view_field('node', $node, 'field_date_name'));

```

More on this function can be found here.
> 2 votes

---
Tags: datetime
---


# Question
Title: Configuring Aegir to Set Custom File Paths
What is the best way to modify the file paths for a site deployed using Aegir?

Aegir installs sites with the file paths pointing in this format:

```
sites/<sitename>/files

```

(This path being relative to the site's platform)

What is the best way to change it to a NAS mount, mounted at, say, `/var/nasmount` ? For e.g., for a site called firstsite.com, the file paths would be:

```
/var/nasmount/firstsite.com/files
/var/nasmount/firstsite.com/files/tmp

```

and so on, along with the the corresponding entries in the site's apache conf file.

These lines appear in /var/aegir/.drush/provision/platform/provision\_drupal\_settings.tpl.php, but I am reluctant to change here as this is from 'core' Aegir (if you will):

```
  $conf['file_directory_path'] = 'sites/<?php print $this->uri ?>/files';
  $conf['file_directory_temp'] = 'sites/<?php print $this->uri ?>/files/tmp';

```

Should this be done in:

* provision\_drupal\_settings.tpl.php file above?
* Somewhere else?

Ideally, this change would be done once so all sites deployed via Aegir have this in place, and these changes survive the re-verify process of a site and/or platform.

Thanks!

# Answer
> 5 votes
The answer is to mv siltes/firstsite.com/files to /var/nasmount, then create a symbolic link to it.
(from inside your sites/firstsites.com directory, `mkdir /var/nasmount/firstsite.com`, `mv ./files /var/nasmount/firstsite.com`, `ln -s /var/nasmount/firstsite.com/files files`).

I would put this in a script so this becomes a drush command, then make it run at the end of the aegir create a site process.

I'm not an expert of where to put this script and/or how to create it.

# Answer
> 5 votes
Edit /var/aegir/config/includes/global.inc and put in it:

```
<?php
$conf['file_directory_path'] = '/var/nasmount/<?php print $this->uri ?>/files';
$conf['file_directory_temp'] = '/var/nasmount/<?php print $this->uri ?>/files/tmp';

```

This will be applied globally to all sites. If you only want to make this change for one or two sites, create a new file called 'local.settings.php' in the site dir (same level as settings.php) and put the change in there.

This is the best way of doing this without hacking templates or messing up your system with symlinks.

See also the documentation at http://community.aegirproject.org/node/71

# Answer
> 2 votes
If you edit edit /var/aegir/config/includes/global.inc, as mig5 is proposing, and the sites are running on remote servers (not on Aegir master), then you should *additionally* verify the remote servers in Aegir, in order to get the changes in /config synchronised on remote servers.

See http://community.aegirproject.org/node/71

---
Tags: files, distributions, aegir
---


title: Three level tab on user profile page

text:
# Question
Title: Three level tab on user profile page
I am trying to show a 3 level tab on the user profile page, but I cannot find a way of doing it. I've managed to get a second level working, on my custom module on drupal 7.

```
<?php
/**
 *patners page with all the tabs
 */

$items['user/%user/patners'] = array(
    'title' => t('My deals'),
    'description' => t('this is to show patners ther items'),
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access arguments' => TRUE,
    'type' =>MENU_LOCAL_TASK,
    'weight'=>-18,
);
$items['user/%user/patners/coupon'] = array(
    'title' =>'??????',
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user/patners/statistics'] = array(
    'title' => '?????????',
    'page callback' => 'partners_statistics',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
$items['user/%user/patners/coupon/all'] = array(
    'title' =>'??? ??????',
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user/patners/coupon/used'] = array(
    'title' =>'????????????',
    'page callback' => 'patners_coupon_used',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
$items['user/%user/patners/coupon/pending'] = array(
    'title' =>'??????',
    'page callback' => 'patners_pending_coupons',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
return $items;
?>

```

# Answer
Drupal doesn't provide third level local tasks by own. You have to implement it, something like this:

```
/**
 *  @see: menu_local_tabs()
 */
function my_module_menu_local_tabs() {
  return array(
    '#theme' => 'menu_local_tasks',
    '#primary' => menu_primary_local_tasks(),
    '#secondary' => menu_secondary_local_tasks(),
    '#tertiary' => my_module_tertiary_local_tasks(),
  );
}

/**
 * @see: menu_secondary_local_tasks()
 */
function my_module_tertiary_local_tasks() {
  // The index of local task starts from 0, so you need the 2 level of local tasks.
  $links = menu_local_tasks(2);
  // Do not display single tabs.
  return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
}

function my_module_preprocess_page(&$vars) {
  $variables['tabs'] = my_module_menu_local_tabs();
}

```

All of this code based on core's localtask generation function, it's normally alterable, translation-ready, access checked:

menu\_local\_tabs()

menu\_secondary\_local\_tasks()
> 2 votes

---
Tags: 7, routes
---


# Question
Title: Theming User Profile Edit Form not Rendering results.... Help?
I am not rendering any results. This is my template.php:

```
function fueldeluxe_theme($existing, $type, $theme, $path) {
    /**
    *  Account edit Forms
    */
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'template' => 'user-profile-form',
        'path' => drupal_get_path('theme', 'fueldeluxe') . '/templates'
    );
    return $items;
}

function fueldeluxe_preprocess_user_profile_form(&$variables) {
    $variables['account'] = drupal_render($variables['form']['account']);
    $variables['picture'] = drupal_render($variables['form']['picture']);
}

```

This is my user-profile-form.tpl.php:

```
<div id="account-settings">
    <div id="profile">
        <?php echo $picture; ?>
    </div>
    <div id="account">
        <?php echo $account; ?>
    </div>
</div>

```

As you can see I'm trying to load the user profile field forms. However I'm not able to render any results. The page loads okay when I add dummy text but no account field forms.

# Answer
1. Add a hook\_theme() implementation

```
function YOURTHEME_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render_element' => 'form',
      'template' => 'user-profile-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
      //add '/templates' only if you store template files in an additional folder
    ),

  );
}

```

This tells the Drupal theming system that there's a template file waiting for it in YOURTHEME/templates.
2. Next we'll define some variables to pass into that template in a hook\_preprocess\_HOOK function. We can find the structured array of the form in $variables\['form'\] and assign the form elements to the variables we'd like to throw around our tpl.php file.

```
function YOURTHEME_preprocess_user_profile_form(&$variables) {
  $variables['rendered'] = drupal_render($variables['form']['account']);
  $variables['rendered'] = drupal_render($variables['form']['picture']);
}

```

This example will put the general account info fields and the user picture upload field (if pictures are enabled) into a variable called "rendered."
3. Now that we have defined a variable, we can output it in a template file. Create a template file named user-profile-form.tpl.php in 'YOURTHEME/templates'. This is a demo example:

```
<div id="new-form">
  <?php echo $rendered; ?>
</div>

```

When you visit your user edit page, you should now see only some general account info fields and the picture fields. Create different variables in the preprocess function to separate out form elements and place them wherever you wish in the user-profile-form.tpl.php file, adding whatever markup you like.

Taken from HERE
> 2 votes

---
Tags: 7, users, theming
---


title: How to remove a box?

text:
# Question
Title: How to remove a box?
I created a custom box on the Open Atrium dashboard. The box contained PHP code, I forgot a comma and now I got a blank page. The problem is that I don't know how to remove that box now. It is not there on the database and on the Drupal admin I can't find an option to remove it. Any help would be much appreciated.

# Answer
Easy peasy, all I did was disabling the PHP Code module, editing the block and reactivating the module again.
> 0 votes

---
Tags: distributions, blocks
---


title: Extend the drupal contact form

text:
# Question
Title: Extend the drupal contact form
How do I add fields to the standard Drupal contact form? Can this be done programmatically or is it a task for a module?

# Answer
Yes, you can do that programmatically using the function `hook_form_alter` in a custom module. Follow this for creating a custom module.

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'contact_personal_form') {
    $form['new_field'] = array (
      '#title' => t('New field'),
      '#type' => 'textfield',
      'description' => t('The description of the new field goes here...'),
      '#required' => TRUE, // make the user to fill it compulsorily
    );
  }
}

```

**Update:** I forgot to mention that, the above code will just add the field to the form. The field is not added the mail you send. You should implement `hook_mail_alter` and add the field to the body, by something like:

```
function MODULE_mail_alter(&$message) {
  if($message['id'] == 'contact_user_mail') {
    $message['body'][] = $message['params']['new_field'];  //value of key 'new_field' same as in $form['new_field'] above in form alter
  }
}

```
> 2 votes

---
Tags: emails
---