# Question
Title: Making contextual node paths and reference lists
First off, I am about to set up a site presenting a catalog of products. Since it's quite possible that at some point we'd open a store, I decided to use Commerce Product Display right from the start to present the products, assuming that it will be much easier to migrate to a real shop when we're ready. (Is that assumption correct?)

Now, each product will be tagged using two independent taxonomies (ie. each Display Product will have 2 taxonomy fields). That's because each product has two contexts possible: how it's built and how it can be used. The context will depend on the path user takes at the front page or the link they paste into the browser.

The issue I'm facing is that for each product I want to generate a list of related products, depending on the context.

Two questions now: 1. Is it possible to display a given Product Display page with different contextual path/breadcrumbs? 2. In a Product Display page, what module would you use to present a list of related products: Node Reference or Views Field?

Whatever you may have experience in setting up similar sites, I would be more than curious to hear from you, to learn about the precautions and caveats.

# Answer
> 0 votes
You need the Views Module. I have both of the other modules enabled, so I am not certain exactly what functionality they contain applies. The module Views Field View allows the user to contain a view in a field of another view. I do not think that is necessary for what you want to do. If you are not familiar with views I recommend watching the "Taming the Beast" video series at Nodeone.se. It will give you a good idea on how you will want to proceed.

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


title: Frontpage with images

text:
# Question
Title: Frontpage with images
I want to make a frontage with the Views module. On the frontpage, you can see 3 images, horizontal aligned. I don't understand the Views module very well, but I thought you can make for example a page with the Views module where you can add content that already exists on other pages. So I don't know what to do now, as my images don't exist anywhere.

# Answer
You're saying you want images from another site? I've got two pretty basic suggestions...

1. build them into your theme. You'll want to create a div (or three) in a template for the front page, adn then you can add them in with css pretty easily.
2. display them with a block. Create a new block, make sure you turn on HTML for your input and then add your images:

Enable the block for the region you want, and tell the block to only display on the front page. You'll want to do some simple css theming to that block, as well, to make them look how you want.

Both these options are just to display images. What do you want to do after that? Will clicking them take the user to another page?
> 1 votes

# Answer
Yes it is possible to create a frontpage with views if you only want to display what's in the view

\*create a new view \*add a page display \*add your fields and set your display setting (html list, table, etc...) \*set a path for your page display (example 'pictures') \*save your view

once you have your view saved, go to this page admin/config/system/site-information and go to the frontpage settings. replace 'node' with your views page path (in this case replace 'node' with 'pictures')

hope that helps
> 0 votes

---
Tags: media
---


# Question
Title: Order style-sheet list when adding custom one via template_preprocess_page()
I'm using `phptemplate_preprocess_page()` to add a set of style-sheets which are only needed for a certain content type.

```
function phptemplate_preprocess_page(&$variables) {
  if ($variables['node']->type == 'example') {
    drupal_add_css(path_to_theme() . '/css/example.css');
    $variables['styles'] = drupal_get_css();
  }
}

```

The problem is that my added style-sheet is added to the top of the list, which results in undesired behavior. For example, let's say that in my main theme style-sheet I define the `font-size` of `p` to be `11px`, but in my `example.css` for this specific content type I need it to be `15px`. The main style-sheet is added via the `.info` file of the theme.

It seems I can only think of icky ways to add my specific style-sheet at the bottom of the list, or at least below the theme default ones.

Is there any proper way to order them?

# Answer
> 1 votes
OK, of course, a few moments after adding the question I saw what was wrong. Since I did not specify the type it added my style-sheets it added it to the end of the modules. I now added the theme type and it was added at the end of the list.

---
Tags: 6, theming
---


# Question
Title: How do I style a block title for a single menu in a fusion theme?
I have a custom menu placed in the sidebar1 region of a fusion-based sub theme. The menu is displayed with the Menu name as the block title. When displayed, the title is styled with `<h2 class="title block-title">`. If I set colors and backgrounds in css style sheet as `h2.title.block-title {},` all block titles on the page for all regions are styled the same way, but I would like to limit the style to just one specific menu. When rendered, the menu block is embedded within a couple `<div>` levels including one for the region `<div class="sidebar-first-inner">`. Using `h2.title.block-title.sidebar-first-inner {}` does not work. How do I limit the style to just this one location of h2?

# Answer
> 2 votes
you could use

```
div.sidebar-first-inner h2.title {
   whatever css rules you need
}

```

which means set the css of an h2 with class title that is within a div with class sidebar-first-inner

# Answer
> 1 votes
The solution provided by Jimajamma will work, but it will also affect all blocks' titles in the sidebar-first region. In case you want to add additional blocks to that region in the future, it would be best to limit your CSS rule to that specific block. If you inspect the HTML, the wrapping div on the menu block should have an ID something like "block-block-menu-1". So, the ideal CSS selector would be something like:

`#block-block-menu-1 h2.block-title {
 //styles go here
}`

---
Tags: theming
---


# Question
Title: Change path /comment/reply/11#comment-form
How I can change path from ***/comment/reply/11#comment-form*** to ***/node/$node-\>nid/#comment-form*** in node $links?

# Answer
I'm guessing this is a Drupal 6 issue:

The Comment module create the links with hook\_links(). You can alter those in a custom module using hook\_links\_alter().
> 2 votes

# Answer
In Drupal 7, you can add something like this to your template.php:

```
function yourtheme_preprocess_comment(&$vars) {
  // Update 'reply' link to make it go to the comment form page anchor instead of some weird comment post page
  if (isset($vars['content']['links']['comment']['#links']['comment-reply'])) {
    $vars['content']['links']['comment']['#links']['comment-reply']['href'] = url('node/' . $vars['node']->nid, array('fragment' => 'comment-form', 'absolute' => TRUE));
  }
}

```
> 2 votes

---
Tags: comments
---


# Question
Title: How does a menu item get hidden with the Domain module?
I have a node that is restricted to site dev2. In my menu, I have a link to that node. On dev1 site, the link doesn't show up.

I have created a hook for node\_access that returns NODE\_ACCESS\_ALLOW for the view operation. Shouldn't it show up in the menu for both sites even though it is restricted to dev2 by the Domain module?

# Answer
> 1 votes
I did a project this summer that used Domain Access to split a site into desktop and mobile versions of the website. The client wanted to be able to target pieces of content for the desktop, mobile, or both.

If a piece of content is in a menu, the the domain rules will decide if that piece of content is available, which is what you are seeing. This is done with the standard node\_access methods, which grant permissions rather than take them away.

I think you have a two options here.

I think proper thing you should do it to send the node to all or multiple affiliates, which should be an option when you edit the node.

If you want to go the node\_access route, then I suspect you need to clear caches and also rebuild the node permissions. I totally forget where this option is in the UI, but you essentially need to call node\_access\_rebuild. The easiest way is probably with drush

```
drush php-eval 'node_access_rebuild();'

```

Just keep in mind that the link will appear in the menu, but the node will also be viewable. The two go hand in hand.

---
Tags: nodes, domain-access
---


# Question
Title: Rotate views results based on number of times viewed
I have 10 images that I want to rotate within a views consisting of 6 viewable slots (my Views results). I want to rotate the 10 images so that each recieves (approx.) an equal number of views. The Node Statistics option added as a Sort Criteria does not work for this because you have to actually open and view the node itself for the counter to increment. What I want is for the counter to increment each time the images are shown from within the view.

# Answer
> 1 votes
IMHO I don't think that you will be able to find a module that does this. You will need to write custom code for that. Depending on how comfortable you are hacking with Drupal and PHP you might find it trivial or very difficult.

So here are the requirements:

* The counter must persist between page renders, so you need to store it in the database. A CCK field (D6) or "just" field (D7) will do the trick. You would assign this new field to your image content type.
* This is a View. So how could you write to CCK field when rendering a View? The answer to that is preprocessors. How to write preprocessors is beyond the scope of your question. So is how to write to a CCK field. You can look for that answer in other Stack Exchange questions and the main Drupal site.
* On your View, you would then sort the images by this "counter field".

That should do it.

# Answer
> 0 votes
You can get your first part of displaying 6 of your 10 pictures an approx. equal amount of time by limiting the display to 6 and sorting them with GLOBAL RANDOM. That will just randomize the order and pick the first 6.

To your second part, that will require a lot more work, but could be done in a views theme template and a whole bunch of nodeapi()ing where each time a picture is displayed, a field is autoincremented and resaved back to the node.

---
Tags: views
---


title: Error when upgrading from 6.22 to 7.8

text:
# Question
Title: Error when upgrading from 6.22 to 7.8
I upgraded my Drupal site from 6.22 to 7.8 (before that i had upgraded from 5.9 to 6.22). After I start to run the update I had an error before it's started, apparently related to language:

Additional uncaught exception thrown while handling exception. Original

```
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'TheBIgBrother.languages' doesn't exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2513 of /mounted-storage/home106a/sub008/sc63415-EWDY/bigbrother-israel.co.il/includes/bootstrap.inc).

```

Additional

```
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'TheBIgBrother.languages' doesn't exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2513 of /mounted-storage/home106a/sub008/sc63415-EWDY/bigbrother-israel.co.il/includes/bootstrap.inc).

```

# Answer
> 2 votes
It looks like your languages table is missing. I hope you backed up your database before starting the update. If you have a backup, try restoring it and retry the update again.

---
Tags: 7, i18n-l10n, upgrading
---


title: Incorrect URL paths

text:
# Question
Title: Incorrect URL paths
I am using Drupal on this website.

On this page you will see that the URL is pointing to a page under another sub page as opposed to the programmes page.

When I changed the URL alias of one of the pages under the incorrect path it did not like it and now redirects to the page called Membership/routes which is part of the incorrect URL

`http://www.ciob.org.uk/membership/routes/epa-resources-2012`

How can I change this to actualy be this url, which would make far more sense?

`http://www.ciob.org.uk/membership/programmes/epa-resources-2012`

# Answer
> 2 votes
I think that by having a page actually aliased with `programmes` everything that you alias with `programmes/something` is resolving to plain `programmes`. That's maybe why the `programmes/epa-resources-2012` that you are trying to use "won't stick".

I would suggest that you try moving `programmes` to -\> `programmes/index` or something like that. That way nothing will be "owning" the programmes path, and you will be able to have `programmes/anything...` paths.

# Answer
> 0 votes
There is nothing I can think of that would cause Drupal out of the box to redirect "programmes/something" to "programmes," assuming both are node paths. A bad path should return a 404 error. If "programmes" is the path for a view, it would take "something" as an argument, and finding no results it would use the default value for the argument, but that does not appear to be the case here.

What are your alias and redirection settings? For example, if you have Drupal set to keep and redirect old aliases, you'll have to delete the unwanted bad paths under URL Aliases or correct them under URL Redirects, depending on what you have installed. If you have it set to keep old aliases but do not have Path\_Redirect installed, the old alias gets treated as canonical. Any newly created aliases will bring up the correct node, but the location in the browser bar will be the older one.

I would also investigate whether any global redirection is set on /membership\*.

# Answer
> 0 votes
I'm not 100% sure I understand the issue, but if I do: are you using path\_redirect? This has an option to automatically create a redirect when a node's URL alias is altered. It can be very useful, but it can trip you up in this situation (and also lead to an over-populated URL-space if your clients like to rename pages a lot:). To find out, you can go to the redirects config screen and search for programme.

---
Tags: uri
---


title: Why can I only log in with firefox?

text:
# Question
Title: Why can I only log in with firefox?
I have an install of D7.9 that I can only access the admin tools with firefox. If I use IE, Chrome or Safari, I get "You Are Not Authorized to Access this Page" when I go to www.example.com/user and login.

Funny enough, if I try IE in compatibility mode it works fine, AND, if I try a different computer it works fine.

I've tried clearing all browser data, cookies, etc and it still won't jive..

Any ideas?

# Answer
1. Login with Firefox.
2. While logged in on Firefox, open a separate window to www.example.com/user in Internet Explorer and try to log in.
3. If it fails, got back to the logged in session on Firefox and navigate to the Drupal Watchdog. See if any error appears.
4. Locate your PHP error logs, and see if they logged in any errors.
5. Edit your question and post any errors that you see.
6. ...
7. Profit!

I feel this is a somewhat ambiguous error that could be being caused by almost anything, and there will be no way that anyone here is going to be able to psychically log in to to your server and figure out what exactly is causing that, without a more descriptive question. Checking what are your current watchdog/PHP errors is probably the best thing that you can do at the moment.
> 2 votes

---
Tags: 7
---


# Question
Title: SQL Error on Calendar View with Relationships
I have a calendar set up to show a date field from nodes that I get using relationships.

The relationship goes:

Application \> Discipline \> School \> Date Field

In my view I get this error when attempting to use that date field as an argument in the Calendar:

```
user warning: Unknown column 'node_data_field_school_term_deadline.field_school_term_deadline_value' in 'where clause' query: SELECT DISTINCT node.nid AS nid, node.title AS node_title, node.created AS node_created, node_node_data_field_discipline_school_node_data_field_school_term_deadline.field_school_term_deadline_value AS node_node_data_field_discipline_school_node_data_field_school_term_deadline_field_school_term_deadline_value, node_node_data_field_discipline_school.nid AS node_node_data_field_discipline_school_nid, node_node_data_field_discipline_school.type AS node_node_data_field_discipline_school_type, node_node_data_field_discipline_school.vid AS node_node_data_field_discipline_school_vid, node.changed AS node_changed, node.type AS node_type FROM node node LEFT JOIN content_type_application node_data_field_application_discipline_id ON node.vid = node_data_field_application_discipline_id.vid INNER JOIN node node_node_data_field_application_discipline_id ON node_data_field_application_discipline_id.field_application_discipline_id_nid = node_node_data_field_application_discipline_id.nid LEFT JOIN content_type_discipline node_node_data_field_application_discipline_id_node_data_field_discipline_school ON node_node_data_field_application_discipline_id.vid = node_node_data_field_application_discipline_id_node_data_field_discipline_school.vid INNER JOIN node node_node_data_field_discipline_school ON node_node_data_field_application_discipline_id_node_data_field_discipline_school.field_discipline_school_nid = node_node_data_field_discipline_school.nid INNER JOIN users users ON node.uid = users.uid LEFT JOIN content_type_school node_node_data_field_discipline_school_node_data_field_school_term_deadline ON node_node_data_field_discipline_school.vid = node_node_data_field_discipline_school_node_data_field_school_term_deadline.vid WHERE ((node.status = 1) AND (node.type in ('application')) AND (users.uid = 1)) AND ((DATE_FORMAT(STR_TO_DATE(node_data_field_school_term_deadline.field_school_term_deadline_value, '%Y-%m-%dT%T'), '%Y-%m') <= '2011-12' AND DATE_FORMAT(STR_TO_DATE(node_data_field_school_term_deadline.field_school_term_deadline_value, '%Y-%m-%dT%T'), '%Y-%m') >= '2011-12')) ORDER BY node_changed ASC in /var/www/clients/client4/web39/web/sites/all/modules/views/includes/view.inc on line 799.

```

I'm not sure why it would be an unknown column. I don't know sql very well so I don't know where to begin when debugging this.

Any suggestions?

# Answer
Have you recently deleted a field which name was `field_school_term_deadline` ? If so your view used it and is broken now, just remove it from the list of fields.
> 1 votes

---
Tags: views, 6, datetime
---


title: drupal commerce product types

text:
# Question
Title: drupal commerce product types
I'm kind of confused with the product types. Lets say I have 2 products, a laptop and a desktop PC. Both have "brand" as a field. Would I have to create 2 product types or is there a way to have a default product type and apply the extra product typ

# Answer
> 3 votes
1. Create a product of type "computer".
2. Then create a list field in "computer" called "computer type", where you can specify "desktop" or "laptop".

You can have another list field named "brand" on the computer product.

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


# Question
Title: Ajax returned values do not update when field value changes
I have an ajax form element, *age*, that I'm passing to a query within an ajax callback. The callback generates some product information and returns it as a part of the form array.

The problem is this: if I update the age field, the callback is fired, the query is re-run, and the wrapper is refreshed, however it isn't updating the wrapper div with the new information, it's reloading the initial information.

The code lives here: http://pastebin.com/vUrCMX7c

Any help is greatly appreciated.

# Answer
> 0 votes
1. Check for any errors in Firebug's console.
2. In Firebug's net tab, what is the value coming back from the XHR callback?

If the value coming back from the XHR is the old value, then your problem is on the server side. If the value coming back from the XHR is the new one, then your problem is on the client side (like JQuery not being able to find it's target element). Hope that helps.

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


title: Webform table element and Webform

text:
# Question
Title: Webform table element and Webform
I am trying to create a form with essentially form elements stored inside a table. After digging around, have two alternatives:

1) Install Webform module along with the Webform Table Element module. Now both modules have been enabled and have cleared the caches for the heck of it. I can make the Webform alright, but I don't know how to make use of the Webform table element module and make the webform contents appear within a table. So I am not sure how to go about doing this

2) (SIDE QUESTION): The other alternative is to create a custom module that would let me build my own form with tables and all that jazz. But I am keen on learning the Drupal way although I always prefer hand-coding my challenges.

# Answer
> 1 votes
Drupal has theme() which can be used to create a table in a form. Your theme function must be registered with hook\_theme().

```
function MODULE_NAME_theme() {
  return array(
   'MODULE_NAME_header_menu' => array(
     'arguments' => array(
       'form' => NULL,
      ),
   ),
}

function theme_MODULE_NAME_header_menu($form) {
  $rows = array();
  foreach (element_children($form) as $key) {
    if (is_numeric($key)) {
      $wt = $form[$key]['weight' . $key]['#value'];
      $menu_title = drupal_render($form[$key]['title' . $key]);
      $row[] = array('data' => $menu_title);
      $href = drupal_render($form[$key]['href' . $key]);
      $row[] = array('data' => $href);
      $weight = drupal_render($form[$key]['weight' . $key]);
      $row[] = array('data' => $weight);
      $remove = drupal_render($form[$key]['remove' . $key]);
      $row[] = array('data' => $remove);
      $rows[$wt] = array('data' => $row);
      unset($row);
    }
  }
  // Individual table headers.
  $header = array();
  $header[] = array('data' => t('Title'), 'class' => 'menu-title');
  $header[] = array('data' => t('URL'), 'class' => 'menu-href');
  $header[] = array('data' => t('Weight'), 'class' => 'menu-weight');
  $header[] = array('data' => t('Remove'), 'class' => 'menu-remove');

  $output = theme('table', $header, $rows, array('id' => 'header-menu-table'));
  $output .=  drupal_render($form);

  return $output;
}

```

This creates a table with three columns (if the form has three numeric array keys: "title", "href", and "weight") plus a fourth column with a "remove" link.

---
Tags: forms, webforms, nodes
---


title: How do I remove unused links?

text:
# Question
Title: How do I remove unused links?
There Drupal links, such as **sitename.com/?q=user** or **sitename.com/?q=user/register** that a user may use for direct login or registration to my site.

What I want to do is to disable those types of direct links. I have placed my custom blocks for login and sign up in the first page, so if a user hits the URLs above, a strange view of mysite is displayed because it has 2 registration forms: One exists because of my custom block and another exists because Drupal's default registration form

Does anyone know how could I disable or remove all the links of type **sitename.com/link** and the only link that can direct to mysite to be sitename.com? I know that seems hard because it maybe is not configured in Drupal's layer, but on **HTTP protocol**. So if that is not possible, can you think of any solution to avoid the above mess?

# Answer
> 2 votes
There is two options using a custom module:

1. Disable access to this path using `hook_menu_alter()`

```
function MYMODULE_menu_alter(&$items) {
  unset($items['user/register']);
}

```

This option will send the user to an *access denied* page.
2. Redirect the user to the home page (or another one)

```
function MYMODULE_module_menu_alter(&$items) {
  $items['user/register']['page callback'] = 'MYMODULE_go_home';
}
function MYMODULE_go_home() {
  drupal_goto('/');
}

```

Inspiration: Disabling /node view and other hidden views in Drupal?

PS: I'm not sure why you want to remove `/user` ? For this special path you can also use `hook_user_view()`.

# Answer
> 0 votes
You can just use the Redirect module and redirect /user and /user/register to the frontpage. This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status.

---
Tags: navigation
---


# Question
Title: Placing a menu based on a page’s taxonomy
I created a Drupal menu and place the resultant block in the left sidebar. On the block configuration page I went to “Show block on specific pages” \> “Show if the following PHP code returns TRUE (PHP-mode, experts only).” and added the following code:

```
$tid = 0;
$desired_tid = 12;  // Change to the tid you want
$node = menu_get_object();
if ( !empty($node) && !empty($node->taxonomy) ) {
  foreach ( $node->taxonomy as $term ) {
    if ( $term->tid == $desired_tid ) {
       $tid = $term->tid;
       break;
    }
  }
}
return $tid;

```

The menu still showed up on all pages and not just the page that had the taxonomic term that had ID=12.

I then tried using the code:

```
$desired_tid = 12;  // Change to the tid you want
$node = menu_get_object();
if ( !empty($node) && !empty($node->taxonomy) ) {
  foreach ( $node->taxonomy as $term ) {
    if ( $term->tid == $desired_tid ) {
      return TRUE;
    }
  }
}

```

Same effect, the menu still was on all pages. I have disabled caching, flushed the cache, and rebooted the server, all to no affect. Any idea what I might be doing wrong?

# Answer
> 1 votes
If you will put more blocks based on taxonomies or maybe for certain content type i would recommend the context module:

http://drupal.org/project/context

With context you can set conditions with a friendly UI for display blocks in your drupal instalation.

# Answer
> 0 votes
The most likely cause is you forgot to put your code inside `<?php ?>`.

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


# Question
Title: How can you put a user profile item in a category on the user's account information page?
My attempt is:

```
function mymodule_user($op, &$edit, &$account, $category = NULL)
{
  switch($op)
  {
   (...)
      case "view":
         $account->content['my_cat']['plant_1'] = array(
                    '#type' => 'user_profile_item',
                    '#title' => 'Plant 1',
                    '#value' => '42',
                    );
  }

```

But that doesn't work as the 'Plant 1" form element appears at the top of the page without a category. The categories seem not to be derived from $op = "categories" where I defined 'my\_cat'. So how can I tell Drupal that "Plant 1" should be in the my\_cat category on the user account information pages?

# Answer
In the meantime I've figured it out. The categories are also defined in the 'view' operation by using the type 'user\_profile\_category'. For example:

```
$account->content['my_cat'] = array(
          '#type' => 'user_profile_category',
          '#title' => 'Plants Summary',
         );

```
> 1 votes

---
Tags: users
---


# Question
Title: product vs product type vs product display in drupal commerce
Is a product and instance of a product type? Like you'll have a media store where Books is a product type and 'The Definitive Guide to Drupal 7' would be a product? Product display would then be literally a way of displaying your product?

I've been trying to get some clarity by reading tutorials and watching videos and somehow it's still not clicking with me.

# Answer
> 5 votes
Product types is like node types. The main thing about is that you can tell them apart and you can put different fields on them. A product type could be books, but if your books and board games are essential the same (they need the same data) they could be the same product type, where as t-sheets would need to be a different product type, since you probably want to add data for color, size, model which doesn't make any sense for books and games.

A product is an instance of a product type, meaning it could be a green medium sized t-shirt for men, or 'The Definitive Guide to Drupal 7', along with price etc.

Product displays is the main way of displaying your products to the end user, since out of the box products can't be displayed. For this commerce has built the product reference field and the add to cart form and such features to do the trick. Meaning that you can display your products on other entities. Most often you want to use nodes for this, but in theory you can use Profile 2 with the profile entity, to allow users to sell stuff on their profile with a product reference field.

You could also use Views to display products to the end user, this is what I did with my first Commerce site, where Commerce wasn't matured yet. I wouldn't recommend this, as you loose the ability to combine products with the add to cart widget. But if you are selling antique furniture, where every product is unique, this could work out well for you, as you only would need to create products and not product displays as well.

# Answer
> 3 votes
To elaborate a bit on googletorp's comment, this model is counter-intuitive to most people, but is based on the retail model, where inventory and product display are separate.

In a store, you might have a product that you have purchased, but for whatever reason, is not on display yet, on the showroom floor. Or, you have several products in several sizes, but all have separate skus.

You create a product on the backend for each SKU, and then display several (s,m,l,xl) as a variation, in the actual product page. So, you have a single product page, that will display four individual products.

I personally don't care for the model, or at least think the process should be linked to a product display node creation out of the box. I love Commerce, but think it has some ways to go in terms of usability/natural way of product creation for stores with \<100 products.

For a visual, workflow-wise: Create---\>Products -----\> Product Node (Display) ----\> Category/Taxonomy Term Association

Hopefully, this makes sense.

---
Tags: 7, commerce, entities
---


# Question
Title: How do I insert site information data into another table?
I have developed website using Drupal. I have created an application without using Drupal, using another framework. In my application I also stored site logo,site name etc. I want to update my site information table when updating Drupal site information from admin/settings/site-information.

The fields are the following ones:

* id: int(12), primary key
* site\_title: varchar(60)
* site\_logo: varchar(200)

# Answer
> 0 votes
There are many ways to do this, but I guess one simple and 'drupalish' way to do this:

Define multiple databases in your drupal instance

Set your 2 databases to be available to drupal.

Then, it is just a matter of deciding when you want to fetch and update the data.

You could use hook\_install (or hook\_enable) and add a query in there that would load your data in drupal database when enabling the module. Or, you could create a callback that would update the data when you visit a certain url, all of this is up to you.

Hope this helps, good-luck.

# Answer
> 1 votes
You can use a hook\_form\_alter to add a submit function to the form, see http://drupal.org/node/222158 (for D6 but should be the same for D7).

In your new submit function you can do whatever you want...

You can query other database following this doc http://drupal.org/node/18429

```
  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

```

---
Tags: database
---


# Question
Title: How do I place a multigroup in another multigroup?
Is there any workaround to be able to place a multigroup inside another multigroup using CCK?

This is what CCK tells me when I try to do it:

> You cannot place any kind of group inside a multigroup.

# Answer
> 1 votes
In Drupal 7, CCK Multigroup is succeeded by Field Collection, which can be used to nest collections within collections.

In Drupal 6 however, you already have your answer. You cannot place any kind of group inside a multigroup, due to the way the information is stored in the database.

---
Tags: entities
---


# Question
Title: how to prepopulate a flexifield in form_alter?
I have a flexifield with name:

```
field_flexi_pricing[0][value][field_pricing_day_price][0][value]

```

how do i fill in a default value for this flexifield in `form_alter`?

# Answer
> 1 votes
do a form alter and add your value as a default value using the default value key,

http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html/5#textfield

```
'#default_value' => //my value;

```

you can always print $form in your form\_alter after you have altered your $form, to have a better look at your flexifield array, and chck if the default value is set like it is shown in the forms api reference link above. :)

---
Tags: entities
---


title: Mail form results (no webform)

text:
# Question
Title: Mail form results (no webform)
I've built a form within a module using form api. Simply liek this:

```
function input_menu() {
  $items['request'] = array(
    'title' => 'Request',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('input_request'),
    'access callback' => TRUE,
  );
}
function input_request($form, &$form_state) {

    $form['make'] = array(
    '#title' => t('Car make'),
    '#type' => 'textfield',
    '#required' => TRUE,
    );
}

```

I have some specific fields that didn't allow me to use webform module. Now how can I send the results of this form to my mailbox?

Thank you!

# Answer
> 1 votes
```
function input_request($form, &$form_state) {

    $form['make'] = array(
    '#title' => t('Car make'),
    '#type' => 'textfield',
    '#required' => TRUE,
    );

return $form; //you need this here
}

```

On order to send it to your mailbox, you will also need a submit button and a submit handler for your form.

Read this, it has good info on how to create, validate, submit, theme drupal forms. http://drupal.org/node/751826

FOr sending email you can use the drupal\_mail\_send() API or drupal\_mail() depending on your Drupal core

http://api.drupal.org/api/drupal/includes--mail.inc/function/drupal\_mail/7. http://api.drupal.org/api/drupal/includes--mail.inc/function/drupal\_mail\_send/6

---
Tags: emails, forms
---


# Question
Title: Allow to change site logo without giving too many privileges
I want to allow a certain role to change the site logo, but I don't want to give the 'administer site configuration' permission to that role.

At first I was hiding some form elements from the theme settings forms using `hook_form_alter()` and `$element['#access'] = FALSE`, leaving only the options related to uploading a new site logo; after that I noticed the user would need the 'administer site configuration' permission to access that form.

Do you have any idea?

# Answer
You could implement hook\_menu\_alter() to change the permission associated with that page, and use other permissions to decide which form fields should be visible to the currently logged in user. In this case, instead of using `$element['#access'] = FALSE`, you should use `$element['#access'] = user_access('your custom module permission')`.
In the case you are only interested to allow some users to change the site logo, then you can use your custom permission for the page containing that settings form, and then use the "administer site configuration" permission for the form fields only the site administrators should see (`$element['#access'] = user_access('administer site configuration')`).

```
function mymodule_menu_alter(&$items) {
  if (isset($items[$menu_path]) {
    // Use the following line if the access callback already used is not user_access().
    $items[$menu_path]['access callback'] = 'user_access';
    $items[$menu_path]['access arguments'] = array('your custom module permission');
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == $form_to_alter) {
    $form[$element_id]['#access'] = user_access('administer site configuration');
  }
}

```
> 1 votes

---
Tags: 6, users
---


# Question
Title: Import an Image Folder into one Image Field
I've searched a lot for my problem, but I haven't found an answer yet.

I want to achieve, that if somebody uploads a whole folder of images per FTP, it should be possible to select the folder during the creation of a new node and add them into one image field.

It must be somehow like the file\_attach module of drupal 6. But for Drupal 7 and for whole directories instead of single files. Does anybody has a guess or solution for me?

# Answer
It will most likely involve implementing the Drupal File API in combination with the Field API in your custom module. I can't write a full implementation for you here because honestly it would take at least an hour to do it correctly, and still my example could miss your use case. But if you have a good handle of PHP and Drupal, you should be able to do it with the two APIs I mentioned above.
> 1 votes

---
Tags: 7, media, importing-exporting
---


# Question
Title: Feeds: solution with most frequent/real time/push notification update of feeds (e.g. for twitter tweets)?
Which module (or solution) provides the quickest update of feeds after their source is updated? E.g. with Twitter if a new tweet is posted, which Drupal feed or twitter solution updates the quickest following that tweet? (I'd also be looking for general feed solutions for youtube etc).

I currently use feed aggregator which has minimum refresh interval of 15 minutes.

Do solutions require/work better if linked to a cron task?

Are there any real time genuine (i.e. not pseudo\*) *push* notification solutions out there? Please give examples for particular feeds (e.g. twitter, youtube etc.) \*by pseudo I mean a high frequency polling solution that appears to be near real time but is actually a pull on the feed from the drupal site rather than a push from the feed source.

Can feed sources like twitter be configured to *know* about subscribed external sites such that they can push updates to them?

By the way, currently evaluating the following as part of a solution for e.g. twitter (any specific advice on these welcome as is general advice on other solutions including for other feed sources such as youtube).

# Answer
> 2 votes
It looks like Twitter's "Streaming API" is your solution. However, I would look closely at their Pre-Launch Checklist before going down that route. They have 10+ things that you should comply with before becoming a stream or push consumer of their API.

Maybe a solution that would fit you is to develop a twitter stream client (that would be your server), and then to have your application users connect to your server via node.js, since node.js provides a "persistent" connection suitable for chat rooms and push-like notifications.

This is an interesting (and probably doable) suggestion, but not something that you would find pre-packaged in a Drupal module.

---
Tags: 7, notifications, feeds
---


# Question
Title: Views: combining fields of one content type with another
Let's say I have Content Type A and Content Type B. Both A and B share a taxonomy vocabulary C. C terms are C:x, C:y, C:z

I want to create a page View of Content Type A which lists every node of Content Type A. Within the physical layout of each A, I want to also show B, but only if it share's C with A.

The page generated by the View should look like something like this

```
1st CONTENT TYPE A with taxonomy C:x
=====================
Content Type A field 1
Content Type A field 2
Content Type A field 3
Content Type B with taxonomy C:x
=====================

2nd CONTENT TYPE A with Taxonomy C:y
=====================
Content Type A field 1
Content Type A field 2
Content Type A field 3
Content Type B with taxonomy C:y
=====================

```

I have everything working except for the `Conent Type B with taxonomy C:foo` working. What do I need to do to get this part working?

# Answer
> 2 votes
Check out the module Relations. It will enable you to make relationships between the two content types. You can see it in action at nodeone.se in the video series on Relations.

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


# Question
Title: How do I set permission for a custom page to be based on node access?
I have added pages using hook\_menu like so:

```
function dynamic_entries_menu() {
    $items = array();
    $items['entries/get'] = array(
            'title' => 'Dynamic Entries',
            'page callback' => 'dynamic_entries_get_entry',
            'type' => MENU_CALLBACK
    );
    return $items;
}

```

A node ID is added to the end of the URL. For example, /entries/get/10. I want to allow access to this page to anyone who has access to the requested node. How do I do that?

# Answer
Use `entries/get/%node` as path and node\_access() as access callback. Also, you might want to consider setting page arguments. It's not a good idea for the page callback to fetch the node id from the URL or using the arg() function.

```
$items['entries/get/%node'] = array(
  'title' => 'Dynamic Entries',
  'page callback' => 'dynamic_entries_get_entry',
  'page arguments' => array(2),
  'access callback' => 'node_access',
  'access arguments' => array('view', 2),
  'type' => MENU_CALLBACK,
);

```

BTW the function node\_menu() is the `hook_menu` implementation of the node module. Looking up how the Drupal core modules implement certain hooks often helps.
> 3 votes

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


# Question
Title: Drupal form does not save the user input value in the $form_state array
This question extends a prior question. I the previous one, I found several errors relating to coding, and thought I had solved the basic question, only t discover that it still is not working correctly.

I have a form to get a file name for opening (http://pastebin.com/8NfGGNSn). When I set the form field type as a textfield, the form widget saves my text entry (in the `$form_state ['values']['upload_file]` field). When I change the form widget type to 'file' the entry text from the form is not saved. My browser is Firefox and it makes available a browse button and a file selection window in the form. When I select the file from the window dialog, the form widget is completed with the full file path, however, it appears that the path text in the widget is not being placed in `$form_state[values][update_file]`. It remains empty. IN both textfield and file cases I am checking the value of the `$form_state` array during validation, so there should not be any clear or reset activity at that point. Any ideas why the content is deleted from the widget? OR does a file name get saved at another location?

# Answer
> 3 votes
File input fields work differently than other input fields. This is a restriction of HTML. The file path is not transmitted to the server, because it is considered sensitive information. Only the file data and the name of the file is transmitted to the server.

Use file\_save\_upload() to save the file. To find out what to pass as the `$source` argument, print out both `$form_state[values]` as well as the `$_FILES` array.

# Answer
> 3 votes
Oswald is right: You need to use `file_save_upload()` to save the uploaded file. The first argument of the function is the string that identifies the file form field in the form array.

If you look at the code of locale\_translate\_import\_form(), and you compare it with locale\_translate\_import\_form-submit(), you will notice that the first uses the following code:

```
  $form['import'] = array(
    '#type' => 'fieldset',
    '#title' => t('Import translation'),
  );
  $form['import']['file'] = array(
    '#type' => 'file',
    '#title' => t('Language file'),
    '#size' => 50,
    '#description' => t('A Gettext Portable Object (<em>.po</em>) file.'),
  );

```

The submission handler uses the following code:

```
  // Ensure we have the file uploaded
  if ($file = file_save_upload('file', $validators)) {
    // …
  }

```

Similar code is present in aggregator\_form\_opml(), and aggregator\_form\_opml\_submit().

```
  $form['upload'] = array(
    '#type' => 'file',
    '#title' => t('OPML File'),
    '#description' => t('Upload an OPML file containing a list of feeds to be imported.'),
  );

```

```
  if ($file = file_save_upload('upload', $validators)) {
    $data = file_get_contents($file->uri);
  }

```

---
Tags: 7, forms, files
---


# Question
Title: What is the best method to build a form to track N number of values?
I have to create a block that will be a gallery of users. The users to be featured will be curated by site editors. So I'm thinking the best way to track this is a pretty simple Drupal form / settings page where they just enter in the usernames they want.

However, the form should track N number of users. Is there a way in the Forms API to have an element that includes an "Add another value" or something similar, to allow for unlimited entries?

Or would it be better to just have a text area and ask the user to fill out one username per line?

# Answer
That, or step 1) you could use http://www.drupal.org/project/flag which would allow the editor(s) to click / unclick a toggle on a user's profile that says they are "curated" and step 2) create a view that lists which users have been flagged.
> 2 votes

---
Tags: 6, forms
---


title: Secondary navigation on pages

text:
# Question
Title: Secondary navigation on pages
I want to have navigation menu inside few pages on the left panel apart from the website's main menu on the top, and these menu items will be different for different pages. Is there a module for that?

# Answer
Take a look at http://drupal.org/project/menu\_block. It allows you to slice up your menus and might do what you need.
> 2 votes

# Answer
one way to easily create this functionality, imho, is to create multiple secondary menus

1) you can then create a block for each one configure them to show on specific pages in a sidebar

2) if you have context installed, you can incorporate a particular menu according to a path (or other definitions)

3) you can also create a secondary menu with the book module

4) multiple menu modules help you create this functionality if you read their included documentation in README.txt
> 1 votes

---
Tags: 7, navigation
---


# Question
Title: How do I determine a page's content type for non-node pages?
I’m trying to modify my theme’s `page.tpl.php` to not show certain regions when I’m displaying content from the core forum module.

```
<?php if (!$node->type == 'forum'): ?>
<div id="sidebar"><?php print $sidebar; ?></div>
<?php endif; ?>

```

This works fine when I display actual forum nodes, but not when I show pages with the forum listings (/forum, /forum/1, etc.), since those pages aren't actually nodes.

How can I determine if a *page* will be a certain content type, so I can use conditional statements in `page.tpl.php`?

**Edit:** Some quick clarification. Working with `$node->type` is easy for pages that actually use nodes. However, when working with Views, or in the case of the forum module, the content is *not* node-based (it is called with `forum-topic-list.tpl.php` and `$node` is null). Because of this, it's impossible to programmatically determine if the page is really a forum (since it's not really a node). I'm trying to figure out a way around that.

**Edit 2:** Possible (kludgy?) solution: Putting this in `theme_preprocess_page` works. Is it the best way to do it though?

```
// Determine if page is a forum
$node = $vars['node'];
$template = $vars['template_files'][0];

if ($template == 'page-forum' || $node->type == 'forum') {
    $vars['is_forum'] = TRUE;
}

```

# Answer
> 2 votes
Use template\_preprocess() for detecting node on page and pass additional variable as flag to template file, like:

```
$variables['display_region'] = TRUE;

```

Maybe Panels can help you too.

# Answer
> 0 votes
Pages do not have a content type, only nodes do. You're trying to do something programmatically here that is actually very easy to accomplish via the Drupal UI.

I would suggest that instead of hiding the sidebar region on non-forum pages in the page template, simply set the sidebar blocks' visibility to be shown only on forum pages:

```
forum
forum/*

```

Then you only need a simple check to see if there is sidebar content in your page template

`if($sidebar):`

More information on Block Visibility settings here: http://drupal.org/node/21870

---
Tags: theming
---


# Question
Title: How do I print a value from a custom user field on page.tpl?
I have a integer field connected to my users that I would like to print out in the header of my site. I would like to display the value of the field for the user that is currently logged in. When I do print dpm($user) it shows me information about the currently logged in user, but not any of the custom profile fields associated with them.

# Answer
First I want to thank @mototribe and @Kimi for helping me figure this out. I was able to get access to my field by putting

```
<?php
global $user;
$user_fields = user_load($user->uid);
$MYVARIABLE = $user_fields->field_MYFIELD;
?>

```

at the start of my page.tpl. Then I had to print it out by adding this to my page `<?php print $MYVARIABLE['und'][0]['value'];?>`
> 2 votes

# Answer
Add a THEME\_process\_page function to your template.php (replace THEME with the name of your theme):

```
global $user;
$user_fields = user_load($user->uid);
$variables['nickname'] = '';
$nickname = $user->field_nickname;
if($nickname) {
  $variables['nickname'] = $nickname['und'][0]['safe_value'];
}

```

Now you can add this to your page.tpl.php:

```
<?php print $nickname ?>

```
> 1 votes

# Answer
> I have a integer field connected to my users that I would like to print

This is somewhat confusing, have you used some module like content\_profile or you have altered the users table perhaps .. ?

Any ways, the $user object wont get your "integer field" directly as the user object prints all the data from the users table itself.

If your integer field is part of a node that user has created, try

```
global $user;
$nid = db_result(db_query( /*This is where you get the nid of the node*/ ));
$node = node_load($nid);
//then we print the field you want
print $node->integer_field;
// or if its not a node then simple print $variable; will do.

```

The above code needs to go in a block or some tpl that will print it in your header.

Please give more info if the above is not correct...
> 1 votes

---
Tags: users, 7
---


title: Site down after upgrading Views

text:
# Question
Title: Site down after upgrading Views
I have the CK profile installed and found a strange behavior in Views installed along with it (no Term ID filter criterion available), so I decided to upgrade *Views* to the latest dev build. I deleted the Views folder from the `profiles/commerce_kickstart/modules` and now my admin won't work. The error messages vary over time, but they relate to include files missing, such as:

```
Fatal error: require_once() [function.require]: Failed opening required
 '//profiles/commerce_kickstart/modules/views/plugins/export_ui/views_ui.inc'
 (include_path='.:/:/usr/local/php/pear5') in /profiles/commerce_kickstart/modules
 /ctools/includes/plugins.inc on line 468

```

How do I resolve the situation? And, most importantly, how should I proceed next time to perform a safe update of individual modules from the profile.

# Answer
I don't think there is really a "100% Safe" solution for upgrading your modules. But for the future, the best thing that you can probably do is:

1. Make sure that you are using a version control system such as CVS, SVN, Git, etc. That way when you update and see that things go south you can always revert your changes.
2. Always backup the database before running update.php. Again, if things don't work out, you always have a restore point.
3. It is a good practice to read the release notes of the version that you are upgrading to and to take a peek at the issue queue of the module in question. Most likely another Drupal developer would have tried already to perform the same update that you are trying to perform, and there is an entry in the issue queue indicating what was the problem when updating. Sometimes if there's an entry in the issue queue it will also tell you how to upgrade from one version to another. Sometimes you can upgrade without no problems, sometimes you can't, and other times you have to follow a few manual steps before upgrading.

As for the present tense, since you already attempted the upgrade, I would start by following step #3 above, and if you can't locate a relevant entry in the Views issue queue that points you in the right direction, you're more than welcome to open one.
> 1 votes

# Answer
If you deleted views from /profiles/commerce\_kickstart/modules and did not restore the new version to that same folder, then you will need to clear your site's cache in order for Drupal to find the module in the new location. Most likely, if you are experiencing WSOD from this error, you will need to use Drush (drupal.org/project/drush) to clear the cache.

Also, it should be noted that some installation profiles, such as Commerce Kickstart, may depend on specific versions of the prerequisite modules in order to function correctly. Thus, when using an installation profile, it is best practice to only upgrade as new versions of the installation profile are released.
> 0 votes

---
Tags: views, commerce, updating
---


# Question
Title: Convert theme from ASP.net-based site to Drupal
I'm supposed have to launch a Drupal 6 site within 4-6 weeks. Most of the content is already loaded into Drupal. But I'm having a dilemna about the fastest way to approach theming. Our university web developer is using Sitefinity (ASP.net) while I chose Drupal for our site. He gave me a copy of the unfinished template files a month ago (HTML, CSS, JS, images) which were designed using Blueprint CSS. I have just received access to the main university site including admin priviledges. Since it is apparent that a lot of the final design was created using a skinning feature in Sitefinity, I downloaded the complete site using WinHTTrack and am trying to cobble together my "interpretation" of the design using the main CSS file done with Blueprint, and the Sitefinity system CSS files. The Sitefinity CSS files have their own layout which is based on percentages. I'm looking at creating either a Zen or Fusion based theme. I've tried removing all the Sitefinity styling and re-building the design from scratch using Blueprint in Dreamweaver.But I'm afraid this is a waste of time. I'd appreciate some advice on how others would approach replicating an ASP.net template for use in Drupal. While not at all familiar with Sitefinity, I did download a copy of all the files from the server in case they could be used to convert the layout to Drupal, although I know PHP and ASP.net themes are nothing like each other. Any strategies would be appreciated.

# Answer
> 0 votes
You need create a new theme.

you can't just export from one to another.

The best place to start is learn how create a drupal theme, and the best place for learn that is in the handbook:

http://drupal.org/documentation/theme

# Answer
> 0 votes
I don't think there's any tool doing something automatic for you. Just take the ASP.net as as a prototype and start again with a solid base theme like zen.

# Answer
> 0 votes
Gnuget and Betaride are both right. Additionally though, if the designer worked with the Blueprint framework, it might be best to build your custom theme on the Blueprint theme.

# Answer
> 0 votes
When converting from a former CMS theme to a Drupal theme, really the only thing that will be of much use is the CSS and JS files - even those will have to be heavily edited in order to work with Drupal.

I would suggest choosing a solid base theme and then use the previous CMS's CSS and JS as a starting point for building your own styles for the new Drupal theme. You will have to completely re-write most of the CSS selectors (and any JS that uses CSS-type selectors), since the HTML structure of the previous CMS will probably not match-up with the HTML that Drupal gives you.

If you do choose to build a Fusion-based Drupal theme, you can also get great support for building your theme at http://fusiondrupalthemes.com/forum/using-fusion

---
Tags: theming
---


title: Using view arguments for taxonomy term

text:
# Question
Title: Using view arguments for taxonomy term
I have a url structured as such:

http://www.example.com/blog/unimportant-term/taxonomy-term

(is it a term or alias when the - dash has been added?)

I need to filter my result set based on the taxonomy term, and I don't know how to set that up in my view arguments.

Basically my view is getting all my blog posts, and depending on if there's a taxonomy term present, it will use that argument to filter the posts.

# Answer
> 1 votes
That should be rather easy. You have to use two arguments, a regular taxonomy argument for your important term, and the global "Null argument" to ignore the unimportant term. The null argument is added the same way as all other arguments, just have a look through the list.

I assume you know, that you have to set-up a "page" display, specify a path and insert the argument placeholders.

# Answer
> 1 votes
I suspect you have run into a problem I tried to tack involving multiple word taxonomy terms. The url needs dashes since spaces do not work well in all browsers. But the taxonomy term does not have dashes. To set up your View and read the path segment as a term do this:

1. Set up a view with a path like this example.com/something/something/%/something The path should not match the url format you are using to name your blog entries. That is because a view is not intended to intercept a URL, the path in the view is the path to the view and should be unique.
2. Set the fields and filter the view to limit the display to blog content and/or whatever else you want.
3. Create a contextual filter for a taxonomy term. In the section When the filter value IS in the URL or a default is provided check Specify validation criteria, select the vocabulary from the drop down, and from Filter Value Type select term name converted to term ID. Then check Transform dashes in URL to spaces in term name filter values

That should give you a contextual filter that reads the '%' position of the URL and displays content accordingly.

---
Tags: 6, views
---


# Question
Title: Where is the value in a form textfield stored?
I have created a simple form that displays a textfield and a submit button. The text field is defined:

```
$form['upload_file'] = array(
    '#type' => 'textfield',
    '#title' => t('File to read')
  );

```

When I enter "test" in the textfield and select the submit button, the form moves on to the Validate function which has the following code:

```
$answer = $form_state['values']['upload_file'];
  if (!$answer) {
    form_set_error('upload_file', "Please enter a file name: ");
  }

```

And I get the error message indicting that $answer is empty. Do I have the wrong array location for the stored textfield text? Or is there something else I need to do to place the values in the form ito the values array?

# Answer
> 3 votes
The easiest way to debug form related issues I have found is with the devel module

```
drush dl devel && drush en devel -y

```

This module provides a whole host of helpful functions. E.g. in your case you could use this in your validation function:

```
dsm($form_state['values']);

```

This would print a lovely formatted array of every value in the form. From there you can drill down to the required value.

I believe you should be checking for:

```
if (empty(trim($form_state['values']['field_upload_file']))) {
  form_set_error('upload_file', "Please enter a file name: ");
}

```

Or alternatively, if you are just checking to see if the textfield simply has *a* value in it, then the better approach would be to use the FAPI and declare:

```
$form['upload_file'] = array(
  '#type' => 'textfield',
  '#title' => t('File to read'),
  '#required' => TRUE,
);

```

# Answer
> 1 votes
If you compare the code of search\_form() with the code of search\_form\_validate(), you will notice the following code:

```
  $form['basic'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );

```

```
function search_form_validate($form, &$form_state) {
  form_set_value($form['basic']['processed_keys'], trim($form_state['values']['keys']), $form_state);
}

```

In your case, the validation handler access the submitted value with `$form_state['values']['upload_file']`.
If the code of your validation handler is not executed, then Drupal is not invoking it. It could be the validation handler doesn't have the right name, or another module is overwriting the validation handler with another one.

To notice the the default validation handler, `FORM_ID_validate()` (replace "FORM\_ID" with the form ID), is used when other validation handlers are not set. The code of `drupal_prepare_form()` used to set the validation handler is the following one:

```
  if (!isset($form['#validate'])) {
    // Ensure that modules can rely on #validate being set.
    $form['#validate'] = array();
    // Check for a handler specific to $form_id.
    if (function_exists($form_id . '_validate')) {
      $form['#validate'][] = $form_id . '_validate';
    }
    // …
  }

```

---
Tags: 7, forms
---


# Question
Title: Drupal 7 hook_theme() not loading template file
I'm trying to get a very simple module to load a template file using drupal's hook\_theme(). It's pretty much as simple as you can possibly imagine.

```
function sectionheader_theme ( $existing, $type, $theme, $path ) {
  return array(
    'sectionheader' => array(
      'variables' => array( 'foo' => NULL ),
      'template' => 'sectionheader',
    ),
  );
}

```

The template is named sectionheader.tpl.php. The rest of the module is working as expected. I've cleared the Drupal cache. I've inserted a `die("Debug")` statement in this function, and it is being executed, but my template is simply not being called, ever. The template merely has some debug text in it so I can see that it's working, but is not visible in any view of the module.

I've done everything in every example I can find, I've even copied and pasted code directly from other modules, and this template will still not load.

I've tried renaming the template and the 'template' array value. No luck.

# Answer
Try implementing hook\_theme\_registry\_alter() in your module

```
function sectionheader_theme_registry_alter(&$theme_registry) {

  //register a template
  $theme_registry['sectionheader'] = array(
    'template' => drupal_get_path('module', 'sectionheader').'/sectionheader',
    'type' => 'module',
  );
}
```

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook\_theme\_registry\_alter/7
> 1 votes

# Answer
I think you are missing `path` in this structure.

Have you `Cleared All Cache` as well?
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to override certain function in a module to disable the return value
Not sure how to explain this clearly but let me try.

```
/**
 * Implementation of hook_footer()  to insert Javascript at the end of the page
 */
function omniture_footer($main = 0) {

  global $user;

    $header = "<!-- SiteCatalyst code version: ";
    $header .=  check_plain(variable_get("omniture_version", 'H.13.'));
    $header .= " Copyright 1997-2009 Omniture, Inc. More info available at http://www.omniture.com -->\n";
    $header .= "<script type=\"text/javascript\" language=\"JavaScript\" src=\"";
    $header .=  check_plain(variable_get("omniture_js_file_location", 'http://www.example.com/js/s_code_remote_h.js'));
    $header .= "\"></script>\n";
    $header .= "<script type=\"text/javascript\" language=\"JavaScript\"><!--\n";

    $footer = '/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/'."\n";
    $footer .= 'var s_code=s.t();if(s_code)document.write(s_code)//--></script>'."\n";
    $footer .= '<script language="JavaScript" type="text/javascript"><!--'."\n";
    $footer .= "if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-')"."\n";
    $footer .= '//--></script><noscript><a href="http://www.omniture.com" title="Web Analytics"><img src="';
    $footer .= check_plain(variable_get("omniture_image_file_location", 'http://examplecom.112.2O7.net/b/ss/examplecom/1/H.13--NS/0')).'/'.rand(0, 10000000).'"'."\n";
    $footer .= 'height="1" width="1" border="0" alt="" /></a></noscript><!--/DO NOT REMOVE/-->'."\n";
    $footer .= '<!-- End SiteCatalyst code version: ';
    $footer .=  check_plain(variable_get("omniture_version", 'H.13.'));
    $footer .= ' -->'."\n";

$script  = $header;
$script .= $extra_variables_formatted;
$script .= $footer;

return $script;
}

```

Now my task is to disable the $script to **not show** in unpublished articles. Is there any way to do this in template.php preprocess?

**Note: The below solved my question. Its 100% working in my end. Thanks**

```
//Remove omniture tags in unpublish node
  if(arg(0) == 'node' && $vars['node']->status == 0) {
    $vars['closure'] = theme('closure');
    $omnitureTags = preg_replace( "/\<!-- SiteCatalyst code version: H\.19\.4 Copyright 1997-2009.+\<!-- End SiteCatalyst code version: H\.19\.4 --\>/si", "", $vars['closure']);
    $vars['closure'] = $omnitureTags;
  } else {
    $vars['closure'] = theme('closure');
  }

```

Put the above code in **preprocess\_page**.

# Answer
The value returned from the implementations of `hook_footer()` is used from theme('closure').

```
function theme_closure($main = 0) {
  $footer = module_invoke_all('footer', $main);
  return implode("\n", $footer) . drupal_get_js('footer');
}

```

That function is called from template\_preprocess\_page(), which uses the following code:

```
  // Closure should be filled last.
  $variables['closure']           = theme('closure');

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

```

If you want not to print the value returned by `hook_footer()`, you have the following options. As you are talking of articles, I get you mean nodes whose content type is "article"; if you used the word *articles* to mean nodes, then remove the part that checks the value of the `type` property.

* Empty `$variables['closure']` inside a preprocess function, which can be implemented in a module, or a theme (inside template.php). The following code is the code I would write for a theme.

```
function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'article' && !$variables['node']->status) {
    $variables['closure'] = '';
  }
}

```

If you are not interested in the content type of the node, then the code becomes the following one:

```
function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && !$variables['node']->status) {
    $variables['closure'] = '';
  }
}

```
* In the page.tpl.php file you normally find the following code to print the value returned from `hook_footer()`:

```
<?php print $closure; ?>

```

Replace that line with the following one:

```
<?php if (!empty($node) && $node->type != 'article' && $node->status): ?>
  <?php print $closure; ?>
<?php endif; ?>

```

If you just need not to print the value of `$closure` when a node is not published, independently from the content type of the node, then the code simply becomes:

```
<?php if (!empty($node) && $node->status): ?>
  <?php print $closure; ?>
<?php endif; ?>

```

In this way, you can remove the value added to `$closure` from all the implementations of `hook_footer()`. You can also remove the part added from a specific module, if the module always adds the same string.

If you want to change the value returned from your implementation of `hook_footer()`, you can use `menu_get_object()` to get the node object associated to the page, if there is one.

```
function mymodule_footer() {
  $node = menu_get_object();

  if (!empty($node) && $node->type == 'article' && !$node->status) {
    return '';
  }

  // Return the value you would return when the node is published.
}

```
> 2 votes

---
Tags: hooks, theming
---


# Question
Title: webform: additional options for components
Im trying to add additional options for webform component but I seem to be unable to read the data out. I successfully managed to save the data into "extra" inside the db. But I'm unable to read it out again.

what I basically did is this:

```
function webform_maxlenght_form_webform_component_edit_form_alter(&$form, &$form_state, $form_id) {
$form['extra']['message'] = array(
  '#type' => 'textarea',
      '#title' => 'Message',
      '#default_value' => isset($form['extra']['message']) ? $form['extra']['message'] : NULL,
  );
}

```

It saves it perfectly fine into the database under the field "extra" like I wanted but I'm lost as to how to use it later.

Any help is greatly appreciated, if I'm going into a completely wrong direction please say so

# Answer
> 1 votes
Please have a look to the new hook implemented in web form: hook\_webform\_select\_options\_info().

```
function mymodule_webform_select_options_info() {
  $items = array();

  $items['days'] = array(
    'title' => t('Days of the week'),
    'options callback' => 'webform_options_days',
    'file' => 'includes/webform.options.inc',
  );

  return $items;
}

```

The documentation for that hook describes it as follow:

> Define callbacks that can be used as select list options.
>
> ## Return value
>
> An array of callbacks that can be used for select list options. This array should be keyed by the "name" of the pre-defined list. The values should be an array with the following additional keys:
>
> * title: The translated title for this list.
> * options callback: The name of the function that will return the list.
> * options arguments: Any additional arguments to send to the callback.
> * file: Optional. The file containing the options callback, relative to the module root.

---
Tags: forms, webforms
---


# Question
Title: How to improve comments when using Acquia Marina theme
I'm using Acquia Marina theme but comments( sample here) and their replies look awful. It is difficult to distinguish between a comment or it's reply.

Is there any easy solution beyond a custom theming from my side.

# Answer
The only options for changing the styling of the comments in Acquia Marina are to customize the theme or to install a third-party commenting system such as Disqus http://drupal.org/project/disqus

If you decide to customize the styling of Acquia Marina, here are a few tips and resources:

Documentation on customizing a Fusion-based theme. Be sure to read the section on "Using local.css" http://fusiondrupalthemes.com/support/documentation/customizing-your-theme

If you are not very familiar with CSS, a good, general tutorial on what CSS is and how to use it - http://www.w3schools.com/css/default.asp

The Firebug plugin for Firefox is very helpful for troubleshooting CSS and discovering what CSS rules need to be written to make changes to your theme's styling. Here is a tutorial on using that plugin: http://www.kristarella.com/2009/02/how-to-use-firebug-for-css/
> 0 votes

---
Tags: 6, comments
---


title: theme taxonomy term object

text:
# Question
Title: theme taxonomy term object
I created a module that looks up some taxonomy terms using taxonomy\_get\_tree() does some stuff with it and then passes it to a template file. In that template file i want to display them sorted according to some parameters.

The sorting stuff and all works fine but in the end i would just like to display the term using its standard template. But i can't get this to work, i have the entire term object and what i thought i had to do was something like:

```
theme('node', array('elements' => array('#view_mode' => 'teaser', '#node' => $term)));

```

but the array needs a lot more items then i can provide, so isn't there an easier way?

# Answer
You are passing 'node' as the `$hook` value, although your data is for a taxonomy term rather than a node. Trying using the hook 'taxonomy\_term' instead of 'node'. I'm not sure what the proper structure for the `$variables` array is, but if you have the full term object, I would try just passing `$term` as the second parameter.

documentation for theme()
http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7

documentation for theme\_taxonomy\_term()
http://api.drupal.org/api/drupal/developer--theme.php/function/theme\_taxonomy\_term/7
> 0 votes

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


# Question
Title: How do i implement symmetric relationship with node reference module in drupal 7?
i have a content type with one node reference field to same content type and so i related that content type as like A-\>B,B-\>C,C-\>D,D-\>E and so on.But i want to relate E to C,B and A along with D automatically and so i can list out all A,B,C & D in E node page as referenced nodes.Can you tell me how can i implement this type of references in Drupal 7?

# Answer
> 2 votes
I suggest you to look at the relation module. It allows creations of symmetric associations which involve more than to entities. Haven't tried it myself, though.

---
Tags: nodes
---


title: Activate two menu items

text:
# Question
Title: Activate two menu items
I am using Drupal 6. How would I programmatically activate two or more menu items when I am on a certain node page?

# Answer
Use menu\_set\_active\_item
> 1 votes

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


# Question
Title: Help me to understand what element_child() does
Can anybody help me understand what **element\_child** is doing?

It is called as `element_children($form)` where form contains keys like "cancel", "submit" and "#redirect".

This snippet from common.inc

```
/**
 * Check if the key is a child.
 */
function element_child($key) {
  return !isset($key[0]) || $key[0] != '#';
}

/**
 * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
 */
function element_children($element) {
  return array_filter(array_keys((array) $element), 'element_child');
}

```

# Answer
Suppose you have an array as the following (it's an array as accepted from the form API):

```
  $form['example_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Testing text'),
    '#default_value' => '',
    '#size' => 45,
    '#maxlength' => 45,
    '#required' => TRUE,
    '#description' => t('This is an example form demonstrating forms usage in the installer profiles tasks. Enter any text to see what happens.'),
  );

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

  $form['errors'] = array();
  $form['#action'] = $url;
  $form['#redirect'] = FALSE;

```

If you execute `element_children($form)` will return an array containing the following indexes:

* example\_text
* continue
* errors

When `$key` is a string `$key[0]` is the first character of that string. The value of `!isset($key[0]) || $key[0] != '#'` is `TRUE` when the string `$key` is empty, or when the first character of that string is not *#*; `array_filter()` returns an array containing the keys and values for which the function referred as second argument returns `TRUE`.

The reason to do this is that, in the array used by the form API, keys starting with *#* are considered properties of that form field (or of the form), while keys that don't start with *#* are considered child of that form field; in the example code I used, '#redirect' is a property of the form, while 'example\_text' is a form field that is child of the form.
> 5 votes

---
Tags: 6, forms
---


# Question
Title: How to disable the "clear log messages" functionality for administrators?
For a production site, for auditing purposes, I would like to disable the "clear log messages" functionality for all administrators. This function is shown within admin/reports/dblog (within the "Recent log messages" report).

How to do this?

# Answer
You would have to use hook\_form\_alter, and either remove that form or put access control on it. This needs to happen in a custom module.
> 2 votes

# Answer
A quick css display:none on the form will do it, assuming you trust your administrators enough to not go into "inspect element" and turn it back on again.
> 0 votes

---
Tags: 7, log-messages
---


# Question
Title: Testing Modules with an External Database
I'm writing an application that is using Drupal APIs to connect to an external database and doing a bunch of stuff with this data (reading/writing/deleting). I was wondering if there are any best practices for writing simpletests in Drupal 7 with this kind of application. I know simpletest basically installs a new instance of Drupal, then uses this sandbox environment to do testing. However none of the schema for this external database is defined in drupal.

Any tips on how I can test against this database, and not have a bunch of left over data when tests complete?

# Answer
User the setUp and tearDown methods to setup and tear down your external db.

A typical thing would be to write code that first empties the db and then populates it with the test data.
> 2 votes

---
Tags: 7, testing, database
---


# Question
Title: Website owners to claim their websites by uploading control file ?
For my website directory I would like users to be able to claim their own websites.

This is needed to allow only validated and authorized users to edit website-related content.

I would like the system to ask users automatically to upload a control file with a filename generated in Drupal 7.

Drupal will check automatically if the filename can be downloaded from the claimed website and if so it will assign authorization to the claimant to edit related content.

How to do this in D7, preferably with existing modules ?

# Answer
It shouldn't be too difficult to code it:

If you have the website URL and the control file name stored in a node you can use drupal\_http\_request to perform a GET against the URL and filename.

If you get a status 200 returned the file exists and you can update another field on the node to indicate that the URL has been successfully validated.
> 2 votes

---
Tags: 7
---


# Question
Title: Drupal 7.8, Webform 3.x w/ AJAX - #process callbacks cannot be found for select components
We've written some custom module code to AJAXify Webforms using Drupal 7's new #ajax actions.

There's one small snag with the forms though. We're returning the form element for processing when it does not validate, and the form is rendered and returned to the client. This works well for everything except for components that require additional processing (using `#process` callbacks, e.g. `webform_expand_select_ids`, `webform_expand_checkboxes`). When the form is submitted via AJAX, Drupal isn't loading Webform's component includes so it cannot find the callback functions.

To get around this, I've added code to the core form.inc to load the component's include file so `form_builder()` has access to it, which obviously isn't the best way to achieve this. This allows checkboxes/selects to be rendered properly at least.

```
function form_builder($form_id, &$element, &$form_state) {
    if (module_exists('webform')) {
        module_load_include('inc', 'webform', 'components/select');
    }

...

```

Is there a way to force Drupal to load a required module when using the AJAX system?

I've used the steps outlined at http://envisioninteractive.com/drupal/add-ajax-to-a-webform-in-drupal-7/ which works well, except for these few issues.

# Answer
There is the form\_load\_include() function that is invoked during the initial form build and before `form_builder()`. You can include this in a `hook_form_alter()`.
> 0 votes

---
Tags: ajax
---


# Question
Title: Drupal 7 views grouping and aggregation with recipe ingredients
I'm using drupal 7 in conjunction with the recipe module, Every recipe has a number of ingredients that are stored as fields in the database. I'm trying to create an xml view (using views datasource) that lists all of the recipes, but also lists their ingredients. Here is my problem, rather than this;

```
<node>
<title>The Title<title>
<ingredient name> Ingred 1<ingredient name>
<ingredient name> Ingred 2<ingredient name>
<ingredient name> Ingred 3<ingredient name>
<node>

```

the output I'm getting is this;

```
  <node>
    <title>The Title<title>
    <ingredient name> Ingred 1<ingredient name>
  <node>

  <node>
    <title>The Title<title>
    <ingredient name> Ingred 2<ingredient name>
  <node>

  <node>
    <title>The Title<title>
    <ingredient name> Ingred 3<ingredient name>
  <node>

```

It lists it as three seperate nodes, even though there is only one node. I've tried using the "aggregation" settings but still no luck, any ideas?

# Answer
I use the group by option in the Format settings. If you group by the Title, then Exclude that field from display...you should end up with a list as you describe above.
> 0 votes

---
Tags: 7, views, css-js-aggregation
---


# Question
Title: How to access $variables in a module function where $variables is not passed to it. (D7)
I have a custom module that retrieves a view.

I would like to set a page variable that sums up a bunch of fields as im iterating through them.

So how to i access the `$variables` variable if it isnt an argument of my function?

# Answer
> 1 votes
Call your function from inside your module's preprocess\_page() hook. Eg, in your custom module, let's say your function that calls your view is mymodule\_call\_view(). Let's further assume it returns the value you want to set your page variable to. You could do it this way:

```
mymodule_preprocess_page(&$variables) {

  // any other preprocessing you are doing goes here

  $variables['variable_you_want_to_set']=mymodule_call_view();

}

```

Then, when drupal is building the page, it would call your preprocess function, which would call your function that iterates through the view, etc...

---
Tags: 7
---


# Question
Title: How to show single pop-up for whole guest session
In my site I want to place a javascript ad code( from Zedo) which is popping up one window for each page visit by the user which is quite nagging.

Ideally what I want is to pop up the ad after user leaves the site or closes the window.

At least I want is to show single pop up in the whole guest session.

I place the ad code before \</body\> in page.tpl.php but it gets executed for every page.

I'm thinking to make it better by using this logic:

```
if(time() % 3 == 0)
{
//javascript ad code here
}

```

At least this will reduce pop up by 3 times.

Are there any better ideas?

# Answer
You can use one cookie, if is the first time to the user enter into your page then create a cookie, when the user change of page you will check if the cookie exists and if exists don't show up the ad.
> 3 votes

# Answer
You could set a cookie like this when the user first enters the site:

```
// php
if(!isset($_COOKIE['ad_zero'])) {
   // display your ad and set the cookie
   setcookie('ad_zero',1);
}

```

You could also use jQuery Cookie Plugin like this:

```
if($.cookie('ad_zero') != 1) {
  // display your ad and set the cookie
  $.cookie('ad_zero',1, { expires: 1 });
}

```
> 3 votes

---
Tags: theming, javascript, 7
---


# Question
Title: How to find out what modules are adding links to a menu?
I was wondering if there's any way to find out what modules are adding links to what menus using hook\_menu()? I don't care if it's a module or custom code added to Drupal core, I just need to know. There's a link showing up in my main menu and I have no idea what's putting it there. I'd really rather not go through every single module and check their menu hooks.

# Answer
> 3 votes
To find a particular menu entry, search the `menu_router` table for the path or something that matches the path if arguments are used, and then use a hook\_menu\_alter to print the menu item to debug:

```
function mymodule_menu_alter (&$items)
{
  print_r($items["foo/bar/baz"]);
}

```

Then look at the `page callback` index. If will contain a string with the function name that gets called for that menu item (see hook\_menu for more details). In general, the callback function will closely match the module name. For example, if the callback is "foo\_bar\_generate\_a\_page" then the "foo" or "foo\_bar" module owns that menu entry.

# Answer
> 3 votes
You're after module\_implements(). It will allow you to specify the hook (in this case 'menu') and then get an array of module names back.
Of course, you'll still need to manually open the files to check, but you should be able to narrow it down from the menu path and title.

It might be worth flushing the caches too.

# Answer
> 1 votes
Most text editors (notepad++, sublime text, textmate, etc) have "Find in files" functionality that you can use to search your entire Drupal codebase. Just put in the path you're curious about (e.g., `user/login` or `admin/appearance`) and point it to your `sites/all/modules` folder and it should point out exactly what module's `hook_menu` is responsible.

If it doesn't find anything, make sure you're not searching for a menu that has arguments. If I wanted to know what module is responsible for `node/add/page` I would need to make sure to leave off `/page` since that won't be hardcoded in any `hook_menu`.

---
Tags: 7, routes, hooks
---


# Question
Title: Get currently active 'simpletest' user during test
How do you retrieve the current 'simpletest' user during a simpletest.

During a simpletest is the $user GLOBAL from the test environment or the live environment?

# Answer
Inside the test method?

No idea what in $GLOBALS\['user'\] is, but you certainly can't rely on it. You are never "logged in" in that context, you are only logged in when doing requests with drupalGet()/drupalPost().

If you used drupalLogin(), you can look for $this-\>loggedInUser. If not, then it's not possible, other than maybe doing a GET to /user and then trying to get the username from title.

Inside a page callback, $GLOBALS\['user'\] is the current user, just like you'd expect.
> 3 votes

---
Tags: 7, testing
---


# Question
Title: How to access same name table fields in table join using db_fetch_object
I've SNO in both A and B tables.

I do

```
db_query('SELECT * from A JOIN B on A.SNO=B.SNO')

```

Now how do I access both SNO fields of A and B using db\_fetch\_object?

# Answer
You should name your fields in the SELECT, then you can use AS to rename them to something clearer:

```
SELECT fielda, fieldb, A.SNO AS thisone, B.SNO AS thatone, FROM... etc

```
> 2 votes

---
Tags: 6, database
---


# Question
Title: How should I prevent second page of site's front page from being indexed?
My website's second page has the URL http://example.com/node?page=1

I've got the marinelli theme installed.

For SEO purposes, what should be done for the second page node?page=1 of blog listings? Should I disallow it from robots.txt or do something else?

# Answer
> 1 votes
Since `view?page=1` will almost always be the same as `view`, you should add these lines to your robots.txt

```
Disallow: /*sort=
Disallow: /*order=
Disallow: /*page=1

```

More at: http://larsolesen.dk/content/struggling-duplicate-content-drupal-7

---
Tags: nodes
---


title: Printing regions in html.tpl.php

text:
# Question
Title: Printing regions in html.tpl.php
I need to output some regions in the html.tpl.php template since these don't change between page.tpl.php and page-front.tpl.php (just to name two). Basically I want to avoid code duplication.

However there seems to be nothing associated with regions in html.tpl.php, nor I could retrieve anything using drupal\_get\_region\_content (both with and without parameters it just returns an empty array).

Ideas?

# Answer
I solved like this:

```
function mytheme_preprocess_html(&$variables) {
    $variables['region_name'] = block_get_blocks_by_region('region_name');
}

```

and then I could do

```
<?php print render($region_name) ?>

```
> 18 votes

# Answer
`drupal_get_region_content()` returns the content that has been set with previous calls to `drupal_add_region_content()`, but it doesn't include the content of the blocks, which are rendered in the page through block\_page\_build().

If you search for "drupal\_add\_region\_content" in Drupal source code, you will notice that the function is called by:

* `drupal_get_region_content()`
* `install_display_output()`
* `template_preprocess_maintenance_page()`
* `update_task_list()`

What you set for the blocks in the administrative page is in which regions the blocks will be rendered, but their content is not added with `drupal_add_region_content()`; in fact, none of the functions listed above (which are the only functions calling `drupal_add_region_content()`, except the code for testing a Drupal installation) is for rendering/adding the block content.

If you need to render the blocks in your own code, you should check the code used in `block_page_build()`. In particular, this is the code that is probably more useful for you:

```
  // Fetch a list of regions for the current theme.
  $all_regions = system_region_list($theme);

  $item = menu_get_item();
  if ($item['path'] != 'admin/structure/block/demo/' . $theme) {
    // Load all region content assigned via blocks.
    foreach (array_keys($all_regions) as $region) {
      // Assign blocks to region.
      if ($blocks = block_get_blocks_by_region($region)) {
        $page[$region] = $blocks;
      }
    }
    // …
  }

```

The first two lines verify the page being shown is not the demo page used to show where the theme regions are placed.

If you need to render the blocks in a different way, it is more probable you are interested in overriding theme\_block() in your theme, or (even more probably) creating a custom block.tpl.php template file. Another way to alter the way the blocks are rendered is to use a preprocess function for the blocks (hook\_preprocess\_block()).
> 2 votes

---
Tags: 7, theming
---


title: Using custom JavaScript

text:
# Question
Title: Using custom JavaScript
Is there a location where I can drop in a custom JavaScript file in Drupal 7.x?

It just includes simple event actions for menus, and I don't want to edit the theme/module files.

Or do I have to just add the "include" hook to the theme/module?

# Answer
There's three places where you can put your Javascript resources:

1. Your theme folder. If you have a theme in your site named Mechaflash, you could put it inside Mechaflash/js or just in `Mechaflash`. In order to make the theme folder "more organized", generally people create a dedicated `js` folder. I would place Javascript in the theme when your Javascript delivers functionality specific to the theme / presentation layer, or that it affects all of the site (global).
2. In one of your custom modules. The same principle of creating a dedicated `js` folder can also apply here. I generally put JS on the modules when the Javascript is delivering a very specialized functionality relevant to a specific module. It also allows you to "package" your Javascript with your modules and to pass this modules to other sites (i.e. a modular approach).
3. In the site's library folder. I've never done this personally. Not because it's bad, but because I think it's reserved for more complex functionality that other modules (and themes) can use. A good example, the JQuery UI library.

You can do all of this using the drupal\_add\_js() function. Here are some examples of how to add a JS file from a module:

```
// Add a "javascript library" from your module. JS_LIBRARY is an integer constant with a value of -100, which means that `mecha_library.js` will be added before `mecha_ninja.js`.
$module_path = drupal_get_path('module', 'my_module');
drupal_add_js($module_path. 'js/mecha_library.js', array('group' => JS_LIBRARY));

// Add a javascript file from your module. The default 'group' here is JS_DEFAULT, so mecha_ninja.js will be added after mecha_library.js.
$path = drupal_get_path('module', 'my_module');
drupal_add_js($path. 'js/mecha_ninja.js', 'file');

```
> 6 votes

# Answer
Drupal 7 allows `scripts[]` and `stylesheets[]` in both theme.info and module.info files.
> 3 votes

# Answer
The easiest way is in your theme .info file.

You just need to add scripts\[\] = myscript.js in to the .info file of the theme you are using.

More info
> 2 votes

---
Tags: theming, javascript
---


title: Pass term id from menu to views block

text:
# Question
Title: Pass term id from menu to views block
first post, here goes, I want to get the tid from the taxonomy/term/% taxonomy menu to look up a query on a cck table to pass an array of nids to filter a views block view. I can get the tid of the term being viewed and I can get the view to accept an array of nids, just can't figure out the bit in between. D6 BTW, got panels if that makes it any easier! Some of the stuff I have read says its easier done with panels. But I'm stumped!

# Answer
> 1 votes
If what you want to do is create a list of nodes (or fields of nodes rather) that have a certain $tid, you would create a view, probably filter it on node type and if it's published, put $tid in as an argument to further filter things based on it, select whatever fields in the nodes that pass all of these you want displayed, and then over on the top left of the form, add a block display, name it whatever you want, save it all, then go into your Blocks admin page and put that block in whatever region of your theme you want. (Or at this point use panels, but I don't, so don't know how lol) And take a couple breaths in between all of these steps :)

ADD: Check out the http://mustardseedmedia.com/podcast/episode31 video as Bob there answers in great depth how to adjust your views to do what I think you are attempting here, and can answer all the details you need a lot easier than me going into that detail here.

---
Tags: views, 6
---


title: Adding CSS Class To Unread Comments

text:
# Question
Title: Adding CSS Class To Unread Comments
Hello im sure that this would be possible from my experience of drupal. I have threaded comments. People who reply to comments up the thread have their comment up next to the comment they replied to. My members seem to miss these comments when viewing the thread. Is it possible to add a css class or something so as unread comments are a differant colour?

Thanks

# Answer
It should wrap new comments in a comment-new class already, but if your theme does it differently, you could edit its comment.tpl.php or copy comment.tpl.php from the comment module to your theme and act upon the $comment-\>new value to wrap it differently yourself.
> 1 votes

---
Tags: theming
---


title: Field API isn't saving data

text:
# Question
Title: Field API isn't saving data
I have looked through multiple tutorials and I don't know what I'm missing.

I have created a new field type using the Field API and it's displaying everything perfectly, but when I try to put information in the textfield and hit save, nothing shows up on the form after the submit and nothing gets put in the database.

Can anyone tell me what I'm missing? Here is an example of the code I've written:

in the module.install file i have:

```
function cptc_test_field_schema($field) {
 $columns = array(
 'field_test' => array(
   'type' => 'int',
   'unsigned' => TRUE,
   'not null' => FALSE,
 ),
);
return array('columns' => $columns);
}

```

and in the module.module file i put

```
function cptc_test_field_info(){
return array(
'field_test'=> array(
  'label' => 'test',
  'description' => 'test crap',
  'default_widget' => 'widget_test',
  'default_formatter' => 'formatter_test',
 ),
);
}

function cptc_test_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$value = isset($items[$delta]['value']) ? $items[$delta]['value'] : '';
switch($instance['widget']['type']){
case 'widget_test':
  $element['widget_test'] = $element + array(
    '#title' => 'Additional Email Addresses',
    '#type' => 'textfield',
    '#default_value' => '',
    '#size' => 60,
  );
  break;
default:
break;
}
$element['#element_validate'][] = 'cptc_test_field_widget_validate';
return $element;
}

```

There's a lot more to it (obviously), but figured that I shouldn't post everything - for expediency's sake. The other hooks I have implemented are:

```
hook_field_is_empty
hook_field_validate
hook_field_widget_error
hook_test_field_widget_info
hook_test_field_widget_validate
hook_test_field_formatter_info
hook_test_field_formatter_view

```

Thanks in advance!

# Answer
> 3 votes
In your function `cptc_test_field_widget_form()`, change `$element['widget_test']` to `$element['field_test']`. and make sure your `hook_field_is_empty()` has the following line of code:

```
return empty($item['field_test']);

```

# Answer
> 0 votes
My first thought looking at that is that your widget is defining a textfield, size 60, but your database is only made to hold an integer.

---
Tags: hooks, entities
---