# Question
Title: Converting my project's requirements to drupal's concepts
I am building a website for a client and I thought that Drupal is the best choice due to the plethora of choices that it gives me. However, this vast amount of choices made my job a lot harder. Let me describe the problem to you:

The client is selling a specific product, let's say VCRs. Every VCR is manufactured by a specific brand (e.g. Sony, LG etc). Every brand has also categories of VCRs that are similar to each other. So when we want to describe the product (the VCR) we basically have to provide the following information:

Brand (e.g. Sony) Category (e.g. FGX ; notice that this is not unique. Another company may have the same name of category) Model (e.g. 4523x)

I also want the users to be able to subscribe to specific brands and categories so that if Sony releases a new VCR they will be automatically notified (or if Sony releases a new VCR of a specific category).

When it came to converting all these to Drupal concepts I simply could not do it. The reason is that there are various different paths that I could use and I just don't know which one is the right one. For example:

* Is the category a content type or a taxonomy term?
* Is the brand a content type or a taxonomy term?
* The model is obviously a content type but how do I associate it uniquely with taxonomy terms (if the answer to the questions above was "taxonomy term")?
* What modules would I need to use in any case? I have checked the "Relation" module and it seems like it may contain some of the functionality that I need (along with the "rules" module, especially for the notification part).

PS: if you have any good suggestions for resources (blog posts, articles, books, videos etc) that explain how to break down every life requirements to drupal concepts I would really love if you could share them.

# Answer
> 7 votes
I would do it as follows: Create a vocabulary called 'VCR' Add each manufacturer as a term, then each VCR category as a child of the manufacturer. So your taxonomy structure would be like this:

* LG
    + FGX
    + Other Category
* Sony
    + FGX
    + Some Other Category

Note that while FGX is the same term in both places, it will have a different Term ID.

You would then add this to your content type on the Edit Fields page. Select 'Term Reference' under the 'Field' column and 'Select List' under the 'Widget' column. There are other widget options but I think select list is correct in this case.

You would then proceed to install Views, its a contrib module. It basically allows you to list content in very customised ways. (There is more to it than that when used with Panels, another module that you may need.) Go to /admin/structure/views and enable the view named 'Taxonomy term'. This will allow you to override Drupals' default taxonomy display.

At this point going to /taxonomy/term/\[int\] (where int is one of the taxonomy terms' id) will display all content tagged with that term. You would use Pathauto and Token to create 'pretty' URL's, I would also recommend Global Redirect whenever aliasing content.

You may need to customise the View a little, because I cant remember offhand if it will list all content, including content that is a child term of the current term by default.

Views will allow you to make blocks listing content, and you can get a little fancy and use the core Statistics module to list the most viewed product. Panels is definitely worth investigating if you have time, but in my opinion keep it used sparingly.

Views also enables you to easily provide RSS feeds that people can subscribe to. I do believe it is possible to do email updates as well but it was a while ago on Drupal 6 and my memory is shocking. I think Simple News was what we used. In as I recall it requires some configuration but you could then send an automated digest every so often. Not exactly what you requested, but it may be possible to do it with Rules as you mentioned.

If you will be doing online sales I think Drupal Commerce would be your best bet though I haven't used it in production nor played with it for about 6 months or more.

As for the PS, I couldn't find any when I started Drupal, but to me the general rule so far has been: If it isn't an object, may be useful for sorting, or categorises anything in the real world then it belongs in a vocabulary as a term.

# Answer
> 1 votes
"Content Types" are containers that accept a variety of types (integer, string, taxonomy, nodes, etc.).

In your case it appears you already have a rigid structure of strings which are related and have a predefined hierarchy which is exactly what taxonomy is efficient in handling. So I would use taxonomy.

To easily manage large taxonomies I would encourage you to install the following modules:

And Hierarchical Select to provide assistance the end user. Please try the demo at the modules site.

# Answer
> 1 votes
> Is the category a content type or a taxonomy term? Is the brand a content type or a taxonomy term?

If you want to display some content regarding the category or brand which is unique to that category or brand, then have a content type for it, so that you can add content for it. Or else make them as taxonomy terms.

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


# Question
Title: How to SimpleTest a module's use of drupal_alter() or module_invoke_all()?
I'm developing a custom module. My module calls `drupal_alter()` with a `$type` unique to my module, so other modules can alter the behavior of my module.

I'd like to write a SimpleTest for my module, which includes a test implementation of the hook my module calls. This hook implementation should *only* be used by my SimpleTest; it should not apply when the module is installed on a full Drupal installation (so therefore I can't place my test hook implementation in the `.module` file).

What's the right way to do implement a hook that only applies to an active SimpleTest?

# Answer
> 2 votes
You can create a test module and place `hidden = TRUE` in the .info file.

This will hide the module in the user interface but you can still enable it in your setUp() method.

See http://drupalcode.org/project/drupal.git/blob/refs/heads/7.x:/modules/file/tests/file\_module\_test.info for an example.

---
Tags: testing
---


# Question
Title: How do I remove required fields (or a required attribute) from customer profile in Drupal Commerce?
I only need customer to fill in name, phone and MAYBE address. Is it doable in Commerce?

# Answer
The only data required for the commerce profile is defined by the fields you attach to it. By default that is the addressfield. You make the field required or not required, which will result in some fields being required or not required.

You have two ways of solving this. You can either change the behavior of the address field by creating a plugin (code).

Or you can choose to only store the address in the address field and make it options and create a separate field for name that you can make required.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Displaying page execution time using devel
How is it possible to use devel module to show Page execution time on a site? I enebled it and it shows numbers only on admin pages. Thank you for help.

# Answer
Enabling the 'Display page timer' in the Devel settings should be enough to add it to every page. You could check:

1. That you are logged in as an administrator when viewing the pages and that you have got all the Devel permissions assigned (People \> Permission).
2. Have a look at the source of your site, Devel appends the time to the very end of the page, after the closing HTML tag. It might be hidden by your browser or theme.

Otherwise have a look at your recent log messages (under reports) or your server error logs to see if something is going wrong.
> 4 votes

---
Tags: debugging
---


# Question
Title: views exposed filter select list users with specific role
I created a content type `coty1`.

I have 2 user roles that can create that content type. `role1` and `role2`.

1.How can I create view that one of the filter field is expose that allow me to choose just users that have `role1` or `role2` (not all the users of the site).

2.How can I create view that one of the filter field is expose that I can choose just users that realy created one or more from coty1 content type?

Thanks a lot.

# Answer
You need some custom code in order to do something like this.

You can put `#access` on any form element, and along with `hook_form_alter` you are able to alter the views exposed form and require a permission that the two roles have, making it so that only users with those roles can see and use the exposed filter.

The same technique can be used for the 2nd field you want alter.

In code this could look something like this:

```
module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['exposed_filter_1']['#access'] = user_permission('special permission role 1 and 2 have');
  }
}

```

This is example code. You need to find out the form id, and maybe do other checks. Also You need to do a SQL query to figure out if the user has created a node of that type.
> 1 votes

---
Tags: views
---


# Question
Title: How to repeat events with the calendar module?
I have installed the calendar module. I create a content type call **Events** and I added a **Date** field using the **Pop-up Calendar** control type. So when I create a event node I'm able to give it a Date. So far so good.

Now I need to have something like "repeat every day", "repeat every month", "repeat every year".

Can I accomplish this with the calendar module? Do I need to install another module?

thanks

# Answer
Check that Date repeat API is checked on your module listing page
> 4 votes

---
Tags: datetime
---


# Question
Title: How can I create this sort of path structure?
Before I go ahead and implement my site's architecture, I'd like to check whether or not it's valid.

I have two taxonomy vocabularies that I want to use as part of my Pathauto settings. My site is a local accommodation guide, so I'd like to implement a URL structure like this:

mywebsite.com/cottages/Whitby/Little-Cottage mywebsite.com/holidayapartments/Scarborough/Seaside-Apartment

```
                  ^                 ^             ^
                  |                 |             |----- Accommodation name
                  |                 |------------------- Location name
                  |------------------------------------- Accommodation type

```

Which follows the syntax mywebsite.com/\[accommodation type\]/\[location\]/\[accommodation name\]

Up until now, I've found it impossible to do this using just taxonomy tokens. I always end up with paths that look wrong.

A way around this seems to be to set each accommodation type as its own content type (for example, 'cottage' content types, 'holiday apartment' content types etc), instead of just having one 'accommodation' content type as I currently have then set the path settings for each content type like so:

Cottage content types: cottages/\[termpath-raw\]/\[titlepath-raw\] Holiday apartment content types: holidayapartments/\[termpath-raw\]/\[titlepath-raw\]

Whilst this seems to produce the result I want, it feels more like a compromise than the correct solution. Before I go ahead and do this, I want to check that there isn't another way of setting up the path structure that I want using taxonomy tokens.

I'm also wondering what happens when I introduce multiple vocabularies for those content types - how will I ensure that the location vocabulary doesn't get replaced in the URL structure by another vocabulary (for example, if I use a vocabulary for holiday types - family, group, singles, couples etc - how do I ensure that this vocabulary doesn't take the place of the location vocabulary?).

# Answer
> 1 votes
Okay, I've just had a look at my old test site and I can see that I'm using the following syntax:

```
[field_locations-term-raw]/[term-raw]/[title-raw]

```

This displays like so:

```
/grange-over-sands/holiday-apartments/test-property

```

The location comes before the page type (accommodation) here, which I'm aware of, but now the path is displayed perfectly! I've previously deactivated the Domain Access module, so I can only assume that it was DA that was causing my paths not to show correctly.

This leaves me with a new question,though, which I'll start separately.

# Answer
> 1 votes
I'm not too experienced with Drupal, however I am setting up a site where each node is tagged with 2 different vocabularies. Setting up the pattern and the entire taxonomy-browsing engine was quite a challenge for a beginner. I had been grinding the soil before I eventually got what I wanted.

I would risk a conclusion that for term browsing, it'd be impossible to get the pattern you desire. You would probably need to change your approach and treat the path branches as arguments (contextual filters) for a View.

You might however get this structure to work, if you chose to use that pattern as a path for final nodes, something like:

```
[node:accommod_categ:type]/[node:location_categ:name]/[node:accommod_categ:name]

```

(This assumes that each node is tagged with 2 mandatory terms) But this would be a single node view only, rather than a category overview, which is probably what you want to supply for a web visitor.

Interesting challenge, btw, I'd be glad to see your results when you're done. Hope you find a spare minute to describe us how you did it. Good luck!

---
Tags: 6, taxonomy-terms, path-aliases, uri
---


title: Drupal hook menu and node form

text:
# Question
Title: Drupal hook menu and node form
I have a content type **leg** and this `hook_menu` :

```
$items['leg'] = array(
    'title' => t('Choose Leg'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('create leg content'),
    'page arguments' => array('mymodule_leg_select_form'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
);

$items['leg/select'] = array(
    'title' => t('Choose an existing leg'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('create leg content'),
    'page arguments' => array('mymodule_leg_select_form'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 1,
);

$items['leg/add'] = array(
    'title' => t('Create a new leg'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('create leg content'),
    'page arguments' => array('leg_node_form'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
);
return $items;

```

Here is the code snippet from `mymodule_leg_select_form()` which is called as MENU DEFAULT LOCAL TASK :

```
$form = array();
$result = db_query('SELECT nid, title FROM {node} WHERE type = :type AND status = :status ORDER BY title', array(':type'=>'leg', ':status'=>1));
$options = array();
foreach($result as $row){
    $options[$row->nid] = $row->title;
}
$form['leg'] = array(
    '#type' => 'select',
    '#title' => t('Leg'),
    '#options' => $options,
    '#required' => TRUE,
);

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

return $form;

```

The node form is not rendered correctly as you can see in the screen shot. I have two fields - `field_from` and `field_to`. They are not rendered in the form. The menu path "leg/select" which is default local task did work and correctly rendered my custom form.

The problem only is to integrate node add form in the second tab. How can I fix this error ?

# Answer
> 1 votes
The problem is not your `hook_menu` implementation, but your function `leg_node_form`. That function probably calles `node_form`, which is in file `modules/node/node.pages.inc` you have to include that file manually using `module_load_include`.

---
Tags: nodes, routes, forms
---


# Question
Title: Surround specific webform elements with a div
As the title describes, I am to style a webform and for that i need to surround specific fields in divs in order to give them their CSS properties and I have no idea how I should go about doing that. Also I'd like to do the same to the Submit button.

I've caught the form with `hook_form_alter` but no idea what to do after.

# Answer
> 1 votes
Why do you need a div?

Just use a field set and hide label and turn off the collapsible feature.

If anything this is more semantic than using a div in splitting up fields in a form. Visually will look excately the same and you can also use CSS class generated from the field set name in your styling.

---
Tags: webforms
---


# Question
Title: Move block level configuration also in Features
I am building features. Can I add blocks ans block level configuration in Features?

# Answer
Try out the Features extra module.
> 2 votes

---
Tags: 7, features
---


title: Panels is still adding sidebars

text:
# Question
Title: Panels is still adding sidebars
Here is what we are doing:

1. We are working to build a new theme for the website we are working on.
2. We are using ThemeKey and Context to utilize the areas of the new given content types / drupal paths we are using for the new theme instead of Panels.
3. Panels previously owned the pages we are building on.

**For Some Reason, sidebars/blocks (from the previous panel) is still printing to the $content tag for the new theme.**

Any Ideas? It's somewhat hard to describe the behavior over this platform, if you ask questions, I promise to answer them quickly until the problem is resolved...

# Answer
I inherited this site.

In the Panels Page Manager, rules were set up for "node/#."
Therefore, any new node was printing blocks as a sidebar because of those set rules. I reconfigured those rules, and the problem has been fixed.
> 2 votes

---
Tags: panels, nodes, 7
---


# Question
Title: Node creation PHP – menu item under proper parent
while I create node by PHP, I use this:

```
$node->menu['enabled'] = true;
$node->menu['link_title'] = $node->title;

```

but it puts link in 0 depth of the menu. It doesn't care for "Default parent" selected for content type. Neither this works:

```
$node->menu['parent'] = "menu-global-menu:961";

```

How to select parent then?

# Answer
> 3 votes
It looks like you need to set `$node->menu['plid'] = "961";` to set the parent node.

You can have a look through the menu\_link\_save doco to get an idea of what is going on, or there is a smaller code snippet on this blog that explains in a simple, fast way.

As a side note, you can use `node_object_prepare($node);` to set default values after setting your node type, which should take care of your default menu parent. I've found this guide helpful with programmatic node creation.

---
Tags: 7, routes
---


title: Drupal 7: Cannot see Module Changes

text:
# Question
Title: Drupal 7: Cannot see Module Changes
Is there any kind of cache applied to the Modules?

I am developing a module but I am not able to see the last changes I made (Adding a new Role programmatically), even after cleaning all caches.

install code (update):

```
function nutrition_install()
{

    //Create New Role
    $role = new stdClass();
    $role->name = 'nutricionist';
    $role->weight = 1;
    user_role_save($role);

  node_types_rebuild();
  $types = node_type_get_types();

 // add the body field to the node type
  node_add_body_field($types['meal']);

  // Load the instance definition for our content type's body
  $body_instance = field_info_instance('node', 'body', 'meal');

  // Configure the body field
  $body_instance['type'] = 'text_summary_or_trimmed';

  // Save our changes to the body field instance.
  field_update_instance($body_instance);

  // Create all the fields we are adding to our content type.
  foreach (_meal_installed_fields() as $field) {
    field_create_field($field);
  }
  // Create all the instances for our fields.
    foreach (_meal_installed_instances() as $instance) {
        $instance['entity_type'] = 'node';
        $instance['bundle'] = 'meal';
        field_create_instance($instance);
    }
}

```

# Answer
Unless you are using some sort of opcode cache, the code in your module itself won't be cached. Some hooks will only be run in certain cases and/or have cache. Most likely this is what is giving your problem.

A possible solution would be to uninstall and reinstall it again. (don't just disable the module, but uninstall it). Doing so removes a lot of the information about the module and could fix the problem.

If you gave more detail on the code/hooks you were using, a more detailed answer could be given.

**Update**

`hook_install` is run when the module is installed. This is a once per install only, so changing the code after the module is installed won't do anything. A new install is the only way to test the changes, after proper cleanup have been made.
> 4 votes

---
Tags: 7, caching
---


# Question
Title: Can a block span more than one region in a theme?
Can a block span more than one region in a theme? Sometimes I would like content to do this, depending on the page.

I'm aware (and heavily use) Panels which are great but I thought it would be worth considering other solutions.

# Answer
Not by default, but the MultiBlock module will solve this for you, out of the box.
> 4 votes

# Answer
Another option would be to consider Panels Everywhere: http://drupal.org/project/panels\_everywhere

From the project page:

> "Panels Everywhere is an advanced method to completely do away with Drupal's restrictive blocks system and instead use the much more freeing Panels Layout system to control how your pages look."

A further convincing point, referring to Drupal themes:

> "Panels Everywhere modifies the page as it is being rendered to 'wrap' the content in a display and can even take over your page theme to do away with the need for a page.tpl.php."
> 0 votes

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


# Question
Title: Make block render right after enabling the module
I'm working on a module which renders a small block in a footer region. My goal is to make it work out of the box with default settings. User just needs to enable it with drush, no configuration required.

In Drupal 6 version I stumbled upon a strange problem. Looks like after enabling module it's hook\_block isn't called, so block isn't rendered. It can be fixed either by doing drush cc all or going to blocks admin page. All caching is disabled on the test site.

I tried to incorporate drupal\_flush\_all\_caches and drupal\_cache\_clear into hook\_install without success.

Can someone give a hint?

# Answer
After some trials I found an easy workaround:

```
function mymodule_enable() {
  _block_rehash();
}

```

It's function which get called then one visits /admin/build/block. It rescans blocks provided by modules.
> 3 votes

# Answer
You need to implement the hook\_install hook in an .install file for your module. You'll write a record to the blocks table to add your specified block to a certain region on a certain theme whenever you enable the module. You'll use the drupal\_write\_record function to write an array like the following (or you could just use an INSERT query, although deprecated):

```
$block = array(
  'module' => 'module_name', // your module name
  'delta' => 0, // the delta of your block in hook_block
  'theme' => 'theme_name', // The name of the theme you'll add the block to
  'region' => 'footer', // The system name of the region you'll add it to
  'status' => 1,
);

```
> 2 votes

---
Tags: 6, blocks, caching
---


# Question
Title: Do something conditinally on node.tpl.php depending on if the node is tagged with certain taxonomy vocabulary
I found how to do this if the node is tagged with certain terms here. But what I would like to do is to do something conditionally in `node.tpl.php` only if the node is tagged with a certain vocabulary.

For example, I have a vocabulary called "Color" with terms "Red" "Blue" "Yellow". I would like to display the text "It has color" only if the node is tagged with at least one of those terms. Otherwise print nothing.

How can I do this in `node.tpl.php` ?

# Answer
Each taxonomy term in a node also gives you the vocabulary id that it belongs to. So you could look through the terms to see if one matches the vocabulary id of your "Color" vocabulary and then display "It has color" when found.

An easy way to do this would be to use a loop:

```
<?php foreach ($node->taxonomy as $key => $term): ?>
  // Say the vocabulary id of "Color" is 10.
  <?php if ($term->vid == 10): ?>
    <div>
      <?php print views_embed_view('my-views', 'default', $args); ?>
    </div>
    // etc
    <?php break; ?>
  <?php endif; ?>
<?php endforeach; ?>

```

For reference, to access the vocabulary id of a single term:

```
$node->taxonomy[TERM_ID]->vid;

```

Where TERM\_ID is the id of the taxonomy term.
> 3 votes

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


# Question
Title: Adding a CSS class to every form in Drupal 6 in a theme
I would like to add a class to every form tag that could appear on a page. Because it's strictly for theming purposes, I would like to do that in my custom Drupal 6 theme.

How should I do that?

# Answer
> 4 votes
Override the theme function theme\_form(). See *About overriding themable output* for an explanation of how to override theme functions.

# Answer
> 4 votes
If you want to add a css class to every form, you loose the point, since you can simple use `form` in your styles.

If you want to do this, you can overwrite the `theme_form`, the theme function for forms:

```
THEME_NAME_form($element) {
  if (!empty($element['#attributes']['class'])) {
    $element['#attributes']['class'] .= ' extra-class';
  }
  else {
    $element['#attributes']['class'] = 'extra-class';
  }
}

```

---
Tags: forms, theming
---


# Question
Title: How to implement a jscript for displaying custom ads
I am very much a beginner with scripting, drupal theming, etc and I cannot figure out how to deal with the following "problem":

I have signed up my site with a media network, which will handle all the ad revenue making. They have given me a custom .js script and shared the following generic instructions:

* upload the .js script to the website - That I can do. :)
* paste `<script type="text/javascript" src="path to script/scriptname.js"></script>` into the `<head></head>` area of all pages on the website. I guess this means editing the page.tpl.php file of the theme I am using to add this piece of code. However, I do not know how to do this, in a way that works well, without breaking the theme and how the website is displayed.
* call the script into specific ad areas/blocks using something similar to this: `<script>scriptname.display(options = {'width':635,
'ad_width':190,
'max_ads':3,
‘descFontSize':15,
'linkFontSize':12,
'linkFontColor':'999999'});</script>` Here, I am not sure if it is enough to simply copy/paste this code, while using the correct name of the script file.

The trouble is, these guys are used to working with WordPress and they won't advise me on how to set things up in Drupal. So... I appreciate any advice you can give.

PS: I am using the latest version of Drupal 7.

# Answer
> 1 votes
After you do what dkiscool said you'll need to create a block, add the required code (Name.display(...)) to it and add the block to the region where you want it to show.

Be careful when you add javascript to a block. You'll need to disable any rich text editor to avoid having the characters html encoded and also choose an input filter that does not html encode or transform newlines into page breaks or paragraphs (the php filter works but for security reasons you might want to add a new filter instead of using the php one).

# Answer
> 2 votes
Upload your .js file in your theme directory. In your theme's .info file add scripts\[\] = path/file\_name.js as follows.

This will include the .js file in each page of your site. Path of the .js file is relative to the .info file.

---
Tags: 7, javascript, advertising
---


# Question
Title: buy one get one free Ubercart discount module?
Can I use some module to make offers in ubercart I have to make an offer of 2x1 type (buy one, get one free) or buy 2 and get 1 free type of offers

# Answer
> 1 votes
It looks like Ubercart Discounts (Alternative) can do you you ask:

> ## **Features**
>
> 1. Filter both products required for the discount to apply and qualifying products that receive the discount based on multiple products, taxonomy terms, node authors, or product classes.
> 2. The above filters allow for a discount like: **buy 3 of any of X product and get a discount on any of Y product**.
> 3. Attempts to automatically add free products to the cart for codeless discounts. Discount # of products, a percentage or a fixed amount off.
> 4. ...

I don't have any personal experience with the module, but it looks promising.

---
Tags: ubercart
---


# Question
Title: How can I translate those translatable texts defined in t() in contribute/custom modules?
I wrote some custom modules, follow the Drupal standards, put all interface texts in t() function, make them translatable. Module enabled.

I enabled Locale module, added new Language under `admin/config/regional/language`:

However, under `admin/config/regional/translate/translate` I cannot see those text I defined t('xxx') in my custom modules. (cache cleared)

How can I make Drupal aware of them? Thanks.

# Answer
> 9 votes
You can use the Translation template extractor module to extract all the `t()` calls you've done.

Another option is to get the `t()`processed, by viewing the pages where they are defined and then translate them in the interface you mention. (New strings will only be added once they have appeared once).

---
Tags: i18n-l10n
---


# Question
Title: What do I need to install to run Drush make?
I want to make a site using a drush make command.I have already Drush installed on my server. When I try to run this command: `drush make --prepare-install martplug-build.make mart plug` I receive this message: `The drush command 'make martplug-build.make martplug' could not be found.`

Should I also install Drush Make? If so how to do this?

# Answer
> 2 votes
If you are using Drush-4:

```
drush dl drush_make

```

Drush will put drush\_make in the correct location (the .drush folder).

If you are using Drush-5, Drush make is included.

# Answer
> 3 votes
Did you have a look at the INSTALL.txt file. The easiest is to put it inside .drush folder

---
Tags: drush
---


# Question
Title: How do I place super-fish or nice menus in Zen theme main menu?
I have successfully downloaded the super fish module and jQuery and placed the jQuery in the libraries folder. I have also activated the module but am having problems placing the super fish blocks in the main menu of my zen theme. Under blocks, there main menu does not appear so am not sure where to place the blocks so that they appear in the main menu.

# Answer
> 3 votes
1. Once you have installed Superfish, you must define a number of superfish blocks to be available at /admin/config/user-interface/superfish
2. Then go to the block admin screen and select one of the superfish blocks /admin/structure/block/manage/superfish/1/configure
3. Define the "Menu Parent" under superfish settings to "Main Menu"
4. Define the region you wish to have the menu placed in "Region settings"

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


# Question
Title: Updating content after major upgrade from 5 to 6 (changes to production site need to be reflected in dev environment)
I have been tasked with a major upgrade from D5 to D6. The upgrade is now complete and fully themed on my development server. The current production site is very busy, with dozens of nodes being added on a daily basis. I need to somehow sync the content from the D5 site to the D6 site, and am wondering if there is any modules to assist or recommended way of doing this? I just need to retrieve the content and Ubercart orders from the last month and port them to the D6 site. Thanks for any help!!

# Answer
I have not found a better alternative to migrate module till date and I have done lots of migration including ubercart order migration. It has served me well for:

* ASP.Net (MSSQL server) -\> Drupal migration
* D6 -\> D7 Migration
* Rails (MySQL) -\> Drupal Migration

There are tons of other modules like node\_export, views bonus pack, uuid features, deploy that will let you export content out of drupal site but nothing scales better than migrate module. Having said that, its some effort as you need to write your migration classes, but it comes with excellent features like:

* Incremental Migration ( you can test your migration class, with small subset of content)
* Rollback ( In case you realize you missed something )
* Solid drush interface.

Also, once you get a hang of it you keep appreciating the fact that it always work. It knows what has been imported, it reports on warnings during migration, gives you a status update on your migration. Can't recommend it enough!! and the best part is minimum downtime, you keep syncing content till the last moment.
> 6 votes

---
Tags: 6, ubercart, upgrading
---


# Question
Title: How to set a form field sizes based upon the screen size responsively?
I'm building a mobile-first module in D7. I want to set the size attribute of a form (textfield, textarea) depending upon the screen size (i.e., using css media query). Is this possible?

# Answer
> 2 votes
Yes: you can use any CSS media query you want in your theme or module's CSS and affect form elements. You'll want to use a web inspector (like the built-in ones in Chrome and Safari, or Firebug for Firefox) to identify what selectors you want to target.

If, for example, you wanted to make the text fields on the node submission form responsive, you'd target the `.node-form` selector in your CSS file:

```
@media screen and (max-device-width: 480px) {
  .node-form .form-text {
    width: 200px;
  }
}

```

To attach your own CSS for your module's forms (or for any form), you'll want to modify the `#attached` property in your form:

```
$css_path = drupal_get_path('module', 'mymodule') . '/css/mymodule-style.css';
$form['#attached']['css'][$css_path] = array('media' => 'screen');

```

Where `mymodule` is replaced with the short name of your module. The `#attached` property is an array of CSS files: if you don't need to modify any options, you can just do:

```
$form['#attached']['css'][] = $css_path;

```

Otherwise, you'd set the key to `$css_path` and the value to an array that mimics the `$options` array for `drupal_add_css()`.

If you wanted to modify existing forms, you'd do the same thing but in a form alter function. For example, if you wanted to add your custom CSS to the node submission form, you'd do:

```
function mymodule_form_node_form_alter(&$form, $form_state) {
  $css_path = drupal_get_path('module', 'mymodule') . '/css/mymodule-style.css';
  $form['#attached']['css'][$css_path] = array('media' => 'screen');
}

```

---
Tags: theming
---


title: What is a Content Management Platform?

text:
# Question
Title: What is a Content Management Platform?
Currently Drupal defines itself as a "Content Management Platform". My assumption is that they are trying to differentiate themselves from CMS which provide a much more specific goal, such as a wiki or pure blog.

I have found some research and other systems which also use the term but not a single definition.

Can anyone provide a noteworthy definition or provide one themselves which would match the current consensus? Do other broadly scoped CMS such as Joomla and WordPress fall into this category?

Thanks!

# Answer
Jeff Eaton provides a pretty comprehensive post in Understanding 8: Where Drupal Is and Where it's Going, where he discusses these differences (at least in Drupal terms).

Drupal as a Framework

> The foundation of that stack is the essential "web framework" code for Drupal. It's the portion of Drupal that provides essential services any web application would require. Rendering data into HTML and other formats, identifying and loading plugins, handling HTTP requests and responses, caching, database and storage access, and so on all live at this layer...

Drupal as a Platform (i.e CMS)

> Moving up in the stack, we find the "building blocks" layer that Catch referred to as the "Platform" in his blog post. This is where we begin to encounter Drupal-specific approaches to CMS and web building problems. The Entity system, users, nodes, taxonomy terms and vocabularies, actions, roles and permissions, FieldAPI, text formats, and our concept of "Blocks and regions" live here, and can be used to assemble features and functionality. Reusable user interface tools and UX components are also here: things like drag-and-drop tools, Drupal 7's Overlay mechanism, and so on are all reusable tools used to craft usable interfaces.

These differences and more, are also covered in his DrupalCon London Presentation. Product, Framework, or Platform? What They Mean, And Why You Should Care

Essentially Drupal is both, a CMF and a CMS (and more) and why these discussions have come up recently in an effort for the community to define Drupal a bit more.
> 5 votes

---
Tags: 7
---


# Question
Title: Theming main menu with block--menu.tpl.php not working
My template file `block--menu.tpl.php` is not catching my main menu block. It works for custom menus. Am I missing something on this? I don't have any other specific block overrides.

I'm running Drupal v7.10

# Answer
> 3 votes
main-menu comes from system module, so it should be **block--system--main-menu.tpl.php**

Cheers

---
Tags: routes, blocks, theming
---


# Question
Title: How to programmatically add links to the links variable
I am using Drupal 6 and would like to modify the `$links` variable to include other links programmatically. I have searched high and low on Google on how to do this to no avail. Does someone know how to do this?

# Answer
### Drupal 6

In Drupal 6, you can't use hooks or alter hooks inside themes, so you'll need to create a custom module to modify the links. Once done, you'll want to implement `hook_link()` (if you're creating a new link) or `hook_link_alter()` (if you want to modify an existing link).

Adding a new link:

```
example_link($type, $object, $teaser = FALSE) {
  $links = array();
  // Add a custom link to nodes
  if ($type == 'node') {
    $links['example_mylink'] = array(
      'title' => t('Test link'),
      'href' => 'foo',
      'attributes' => array(
        'title' => 'Test link',
      ),
    );
  }
  return $links;
}

```

Modifying existing links:

```
example_link_alter(&$links, $node, $comment = NULL) {
  // Remove the read more link
  unset($links['node']['node_read_more']);

  // Change the title of the read more link
  $links['node']['node_read_more']['title'] = t('More information');

  // Move read more link to first slot
  $link_read_more = $links['node']['node_read_more'];
  unset($links['node']['node_read_more']);
  $links = $links['node'];
  $links['node'] = array(
    'node_read_more' => $link_read_more,
  ) + $links;

  // Move link to the last slot
  $link_read_more = $links['node']['node_read_more'];
  unset($links['node']['node_read_more']);
  $links['node']['node_read_more'] = $link_read_more;
}

```

### Drupal 7

In Drupal 7, this is a little more straightforward, as themes can implement alter hooks. The alter hook you're looking for is `hook_node_view_alter()`:

```
function example_node_view_alter(&$build) {
  // Remove the read more link
  unset($build['links']['node']['#links']['node-readmore']);

  // Add your own custom link
  $build['links']['node']['#links']['example-mylink'] = array(
    'title' => t('Test link'),
    'href' => 'foo',
    'html' => TRUE,
    'attributes' => array(
      'title' => 'Test link',
    ),
  );

  // Move read more link to first slot
  $link_read_more = $build['links']['node']['#links']['node_read_more'];
  unset($build['links']['node']['#links']['node_read_more']);
  $links = $build['links']['node']['#links'];
  $build['links']['node']['#links'] = array(
    'node_read_more' => $link_read_more,
  ) + $links;

  // Move link to the last slot
  $link_read_more = $build['links']['node']['#links']['node_read_more'];
  unset($build['links']['node']['#links']['node_read_more']);
  $build['links']['node']['#links']['node_read_more'] = $link_read_more;
}

```

You can place this directly in your `template.php` file.
> 22 votes

# Answer
Assuming you are talking about links that get rendered on node.tpl.php, you will need to implement hook\_link for example look at node\_link. And if you are new to drupal hooks then this need to happen in a custom module, so lets say your custom module name is "foo" you will need to write a function called `foo_link` which should have same arguments as hook\_link.
> 1 votes

---
Tags: theming, navigation
---


# Question
Title: How to have a webpage File Save As filename different from the page URL?
For example - see this BBC News Page: http://www.bbc.co.uk/news/entertainment-arts-16578905

Now Save the page as a web page - notice how the actual filename of the file saved ( BBC News - Golden Globes Ricky Gervais 'subdued', say critics.htm ) is different from the last URL fragment ( "entertainment-arts-16578905" ).

Drupal has great clean meaningful URL rewriting, I would like to use this as much as possible, so, for me, another example might be e.g. http://example.com/blog/entry-2012-01-17 and the filename could be "mysite.com - blog entry on 2012-01-17.html"

I'm sure that there might be a meta or otherwise setting in the HTML to achieve this, but how can Drupal insert this?

# Answer
Its actually chrome browser (and some others) doing this based on the page title. For example firefox will actually prefer to save as the last part of the url instead. Make sure to use http://drupal.org/project/page\_title module and that should give you what you are looking for. Not sure if there is a way to force it on firefox too.
> 1 votes

---
Tags: users, files, 7
---


title: Upload progress on nginx

text:
# Question
Title: Upload progress on nginx
I am using the latest version of Drupal 7 and my webserver is Nginx. I checked the status report and it says:

> Upload progress Not enabled
> Your server is not capable of displaying file upload progress. File upload progress requires an Apache server running PHP with mod\_php.

How can I fix that problem?

# Answer
Try with the FileField Nginx Progress module.

> This module provides support for an upload progress bar for a backend/server implementing the RFC 1867 upload using multipart/form-data. Nginx does not yet support RFC 1867 uploads in its suite of official modules. You can use the Upload 3rd party module to do that or just rely on PHP FastCGI support for RFC 1867.
> 7 votes

---
Tags: 7, files
---


# Question
Title: Calendar - Non repeating events displaying in multiple months, how to fix it?
I have normal events which are displaying correctly in the month they should but they also appear in the first line (week) of each month after.

I have tried removing the events and creating them again, creating the calendar from scratch but still they appear.

I'm not sure what extra details would help in answering this so if there is anything you need just let me know.

Thanks

# Answer
> 0 votes
It would be a guess as its hard to say without more details but its most likely to do with contextual filters not set up correctly. For month I have them set up as follows:

Provide default value: current date Granularity: month Dates to compare: Start/End date range Add multiple value identifier: Yes Content: Dates - start date (field\_event\_date) Method: OR

For week its exactly the same except using week granularity and so on for days and years. Make sure you dont have any other calendar views (even disabled ones were playing tricks on me before). Also make sure your sort is based on the same date field as the contextual filter.

---
Tags: views, datetime
---


# Question
Title: How to organize this: traders have fruits and recipes too
I'm building a site in D7 for a little community garden mall with 30 traders/shops. There is a trader which sells fruits, another one sells cakes, another one sells dairy products, and so on.

And I have a page with lots of recipes. The recipes should link to the traders. So for Spaghetti Aglio e Olio: The spaghetti you buy at the wheet farmer, the garlic at the vegetable farmer and a white wine at the liquor shop.

I have a content type trader. And a content type recipe.

How do I organize the products? We even think about selling some of the products online one day. So that a site visitor could order a box of vegetables of a trader.

Thanks, Joerg

# Answer
I would look into using the references module, you can reference one content type from another, for example on a ingredient page such as white wine, you could reference Spaghetti Aglio as a "you can make this from this ingredient".

Then on a traders content type you can refer to the ingredients etc
> 2 votes

# Answer
Another way to do this is using taxonomy and views. That way you can have an ingredients taxonomy which you can then add the terms to both the trader and the recipe. To get the recipes to show up on the traders and the traders to show up on the recipes you can then use views contextual filters and relations in conjunction with display suite or panels. I would do it this way because this would allow you to add images, descriptions and many more connections between the actual ingredients and display them easily using one of the many views display plugins.
> 0 votes

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


# Question
Title: Google+ button for sharing an article (just like TweetMeme) available?
I need a button to share the current node to Google+? Is there a module to implement it?

I already have a standalone one (TweetMeme for twitter and another one for facebook )

# Answer
For modules that implement the Google+

1. Google Plus One
2. Social media
3. Easy Social
> 2 votes

---
Tags: social-network
---


# Question
Title: How to include jquery.js before other javascript includes?
I'm using a jquery carousel on my site and getting some errors on some pages. My jquery guru said the cause of the problem is that currently jquery.js gets included after other javascript includes.

Making the jquery.js the first include will fix the problem according to him. How do I change the order of the javascript includes?

# Answer
Use hook\_js\_alter to change the order of js presentation.

For example, edit your theme's template.php:

```
function youtheme_js_alter(&$javascript) {

  $javascript['misc/jquery.js']['group'] = -500;

  $javascript['misc/jquery.js']['weight'] = -500;

}

```
> 6 votes

---
Tags: javascript
---


title: Drupal Theming and Caching Issues

text:
# Question
Title: Drupal Theming and Caching Issues
There is a content type in a view who's display is based on a theming template. In this example, the template is called views-view-fields--article-list.tpl.php . This Case Study/Articles list template works great and as expected on the local testing server. Seriously, everything is working fantastico! Changes made to this template act as expected locally.

However, when the file is uploaded to the production server, changes to the template do not seem to be responding at all. Even after the cache is cleared, the changes are not taking effect. In fact, I deleted the template all together to see if that would cause any disruption, and nothing. It still behaves the same way. Also, flushed the cache in the top left of the admin menu.

So, question is... Is there some sort of database change that needs to happen when I update the template locally and then upload to the server? Or, is there just something missing in general that is not allowing Drupal to re-scan the template files on the production server?

The server resides on bluehost, if that would be relevant, but I believe the issue is something in my Drupal files.

Ayuda, por favor?

---- I thought the below was the problem, but in looking closer, there is a weird caching problem with this file!!! It is still doing this and changes made to it are not refreshing normally. It must have something to do witgh the view's settings.

---

Here was the source of my confusion. When clearing the cache, the server wasn't responding to the changes I made in the template file. I'm still not sure what the original problem was. :( However, I had removed the template file and placed all the code from that file into the last view's 'Rewrite the output of this field option, and had re-formatted it to the correct format. But, I was seeing everything double (and broken), and assumed it was the old template file adding in its own code, thus the odd double vision!

What I forgot was to go to each field in the view UI and exclude its Display. So, yes Jimajamma, it was at the end a palm to forehead slapping! Thanks for the troubleshooting ideas.

# Answer
Have you checked that the file has the right permissions when uploaded to the server? at least make sure the webserver user has read access to it.
> 1 votes

# Answer
Probably not the case, but if you have APC's stat set to 0 you need to flush the APC cache or restart php when changing PHP file's contents.

```
<?php
// Flush the op-code cache in APC.
apc_clear_cache('opcode');
?>

```
> 0 votes

---
Tags: views, theming, caching
---


title: User Role Selection and Profile Fields

text:
# Question
Title: User Role Selection and Profile Fields
I have two user roles with profile fields.

Role 1
Name, Username, Password, Email, Address line 1, Address line 2, Website.

Role 2
Name, Username, Password, Email

I want to let anonymous user to chose user role on registration.
Upon user role selection, I want to show role-related fields interactively (with javascript).
I mean that when select Role 2, Address line 1, Address line 2 and Website fields will be disappeared, and when select Role 1, they will be appeared again.
I currently use 'user\_role\_field' module and 'autoassignrole' module.
Is there another module to achieve that purpose ?
I'm using Drupal 7.7.

Here is what I'm looking for. Click here to download and view screen draft.

Thank you for any help.
Rgds/Sithu

# Answer
> 1 votes
I grouped the fields (Address line 1, Address line 2 and Website) by using field\_group module. And hide the field group from jquery upon selecting role.

1) I created a js file ( mymodule.js )

```
Drupal.mymodule = {
    toggleProfile : function(obj){
        if($(obj).val() == 6){
            $('#user_user_form_group_profile').hide();
        }else{
            if(typeof $(obj).val() != 'undefined') $('#user_user_form_group_profile').show();
            else $('#user_user_form_group_profile').hide();
        }
    }
};
$(document).ready( function(){
    Drupal.mymodule.toggleProfile($('input[name=user_roles]').filter(':checked'));
} );

```

2) Included it from hook\_form\_alter and attached "onclick" attributes on the user role radio buttons.

```
if($form_id == 'user_register_form'){
    # User role
    $form['autoassignrole_user']['user_roles']['#attributes'] = array('onclick' => "Drupal.mymodule.toggleProfile(this)");
    if($user->uid == 1){ # if master administrator, hide it
        $elems[] = 'autoassignrole_user';
    }
}

```

One drawback is that js uses "rid" from the "users\_roles" table, i.e., $(obj).val() == 6
If there is a better solution, it would be really appreciated.

# Answer
> 1 votes
You could use Profile2 to get you started. It will allow you to assign profile fields to roles and have them available upon registration. You could then use jQuery to display the proper register form on selection.

---
Tags: users
---


# Question
Title: How to act based on a styled image is generated?
three image styles defined: thumb, medium and large. By uploading an image, its thumb/medium/large copies are not generated. . each styled copy of image is generated only when specific style is asked to be viewed.

I want to do something after styled copy is generated. For example, I want to upload medium size of image to my other server with my API copyToMyServer().

How may I do so? Couldn't find hook for this case.

# Answer
> 1 votes
I believe this is what you are looking for. http://happypixels.com/blog/triggering-creation-imagecache-derivatives-programmatically

Also see the trigger module. http://drupal.org/documentation/modules/trigger

You can add your desired action to trigged.

---
Tags: 7, media
---


# Question
Title: How can I name the template file for the edit page of a certain content type?
I would like to override only the edit page of a certain content type. Theme developer module says:

page-"content\_type".tpl.php \< page-node-edit.tpl.php \< page-node-"nid".tpl.php \< page-node.tpl.php \< page.tpl.php

If I use page-"content\_type".tpl.php, it also overrides the node view page and if I use page-node-edit.tpl.php it overrides the edit page of all content types.

**Update:**
I tried the code below, and put it in my template.php but it doesn't work.

```
function my_theme_preprocess_page(&$vars) {
 if (isset($vars['node'])) {
   $edit_or_add=basename($_GET['q']);
    if ($edit_or_add=='edit' || $edit_or_add=='add') {
      $vars['template_files'][]='page-' . str_replace('_','-',$vars['node']->type . '-' . $edit_or_add);
    }
    else {
      $vars['template_files'][]='page-' . str_replace('_','-',$vars['node']->type);
    }
  }
}

```

# Answer
```
function my_theme_name_theme($existing, $type, $theme, $path) {
  return array(
    'story_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'node-story-edit'
    )
  );
}

```

This code from here worked for me, for example for the story content type.
> 2 votes

# Answer
In D6, putting this in your theme's \_preprocess\_page() hook should do it:

```
if (isset($vars['node'])) {
  $edit_or_add = basename($_GET['q']);

  if ($edit_or_add == 'edit' || $edit_or_add == 'add') {
    $vars['template_files'][]='page-cck-' . str_replace('_','-',$vars['node']->type . '-' . $edit_or_add);
  }
  else {
    $vars['template_files'][]='page-cck-' . str_replace('_','-',$vars['node']->type);
  }
}

```

Then create a page-cck-CONTENT-TYPE.tpl.php, page-cck-CONTENT-TYPE-edit.tpl.php and/or page-cck-CONTENT-TYPE-add.tpl.php and you should be all set. (By the way, I added the cck- on my sites to be overly clear as to what was going on, it's up to you.)
> 1 votes

---
Tags: theming
---


# Question
Title: How to import Nodes and Node Location data using Feeds module?
I would like to use Feeds to import Node Location data together with Nodes themselves.

Each node of a selected content type is or is not assigned to a location.

How to do this ?

# Answer
> 1 votes
Yes, definitely go with feeds except I would go with location module instead of geofield personally as it has direct support from the location\_feeds module for mapping in all the relevant details. Its possible that you may need to do two seperate feeds (one for importing the node information and one for the location information) but you can make sure they "come together" by using the same GUID field from your feed on each one. The easiest way is to try :) Set up a dummy file first with only 10 imports.

# Answer
> 0 votes
Take a look at the Geofield module for mapping of location data when pulling in your feed. There's a page on the Drupal community documentation about mapping using Open Layers and Feeds that may help you.

---
Tags: 7, nodes, feeds, location
---


title: Add external javascripts

text:
# Question
Title: Add external javascripts
Is it possible to add external javascripts directly into the .info file of a theme?
e.g scripts\[\] = http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js

# Answer
> 24 votes
In your theme's template.php file use drupal\_add\_js() to the page preprocess method (or an equivalent preprocess).

```
function hook_preprocess_page(&$vars) {
  drupal_add_js('http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js', 'external');
}

```

# Answer
> 2 votes
The method of adding javascript depends on for what you are adding javascript for. There are different ways to add js.

* By defining in the theme.info file.
* Adding it inline.
* Adding an external js file.

You can add a js info file with this simple line of code

```
scripts[] = js/myscript.js

```

Or you can use the php function provided by `drupal drupal_add_js`

This functions lets you easily add a JavaScript file or helps in setting an inline code to any page in your theme and it takes 5 parameters (you see it in the api reference).

There is an detail post on this here.

---
Tags: 7, javascript
---


# Question
Title: How to include jQuery UI on a page without PHP?
I want to include jQuery widgets on my Drupal 7 page. So, I started the way is described here:

```
drupal_add_library('system', 'ui.dialog');
drupal_add_js('jQuery(document).ready(function(){jQuery("#dialog").dialog({ modal: true });});', 'inline');

```

However, there are two problems with this approach. First, I would prefer to keep the pages themselves HTML (with JavaScript, of course - but without PHP). And these two lines are the only PHP lines on a large HTML/Javascript page.

Second, JavaScript itself is in quotes which prevents some visual assistance from the editor (since everything is in the string) and forces me to use only double quotes or escaped single quotes inside.

So, I was wondering if there is a way to specify `drupal_add_library` outside the page, and get Drupal to read `<script>` tags and JavaScript inside those tags.

In general, I didn't find relevant documentation on Drupal side (relevant being *not* for theme or module developers but for those who want to use JavaScript / JQuery / JQuery UI as part of site building). If I missed it, I apologize!

# Answer
> 2 votes
How about creating a 'scripts.js' file in your theme folder and then simply either add it in using the `drupal_add_js` method in template.php (the same method you are using above) or if it's something that's more global, include it in your theme's .info file. You will need to tweak the JQuery call according to 7 standards. I use both of these methods all the time and it works great.

So in your 'scripts.js' file you will have something like this:

```
(function ($) {
Drupal.behaviors.myTheme = {
attach: function(context, settings) {

// your custom JQuery here

}
};
})(jQuery);

```

... and then call that however you wish as I have described above. You can also have a look at this post: Managing JavaScript in Drupal 7

# Answer
> 2 votes
* First, there is no problem of using PHP in your HTML file. Don't know if it's the reason, but you will not gain any performance of not using PHP.
* If you absolutely want to insert the javascript inline but you don't want to have to use only double quotes or escaped single quotes you can use the PHP heredoc syntax:

```
$js = <<<EOT
  jQuery(document).ready(function(){jQuery("#dialog").dialog({ modal: true });});
EOT;
drupal_add_js($js, 'inline');

```

But it's **not** really the way to go to insert javascript in your pages.

* As you commented, you can insert directly you javascript code in the header of the *html.tpl.php* template file. But it's **not** the Drupal way to do it.
* As "Danny Englander" answered you can insert it into your *.info* file. But your javascript code will be in included in all your pages. Not ideal if you don't need your widget in all your pages.
* As "Danny Englander" answered (and it's **the best** way to do it) you can use a script that you insert in only the page you need with drupal\_add\_js.

# Answer
> -1 votes
If you don't want to use php at all, then the best standard way to go about will be to add it in the .info file in theme folder. That will make drupal print you js in all pages. The down side of this approach will be that your js will loaded in all page even if you need or dont need.

```
scripts[] = js/myscript.js

```

Another way to this will be by adding js directly in the header of your theme with direct url, it not recommended and is not a standard way to go about. But that works.

```
<script type="text/javascript" src="http://your-site.com/js/jquery.min.js"></script>

<script type="text/javascript" src="https://your-site.com/js/jquery-ui.min.js"></script>

<script type="text/javascript">
jQuery(document).ready(function(){jQuery("#dialog").dialog({ modal: true });});
</script>

```

The available methods of adding javascript depends are.

* By defining in the theme.info file.
* Adding it inline.
* Adding an external js file.

You can also use the php function `drupal drupal_add_js` to do this

This functions lets you easily add a JavaScript file or helps in setting an inline code to any page in your theme and it takes 5 parameters (you see it in the api reference).

There is a detail post on this here.

---
Tags: 7, javascript
---


# Question
Title: Is there a way to display basic site statistics in a block?
I am trying to find a way to display basic site statistics in a block. I have enabled the core "Site Statistics" module but I cannot find a block that would provide me this functionality. I do not want to display anything fancy; just some pageviews and unique pageviews and perhaps, optionally, the 5 most visited pages in the website.

Am I missing something here or do I need a separate module (that I can't find) to add this functionality to my website?

Thanks in advance.

# Answer
This is a job for the views module. Using views in its most basic form you could have a block for the below in under 30 secs.

Content statistics: Most recent view

The most recent time the node has been viewed.

Content statistics: Total views

The total number of times the node has been viewed.

Content statistics: Views today

The total number of times the node has been viewed today.

Install views module, add new view, view name = stats, uncheck create a page, check create a block, continue and edit. Add fields and add the 3 above. Remove title. Add a contextual filter under advanced and use Content: nid, provide default value = content ID from url. Get rid of any filter and sort criteria and you should be good to save the view. You will now have a view block that you can place in any region to display this info.

The 5 most visited block would be similar except you would keep the content published filter and add a sort (descending) on Total views. You could use the "Use pager: Display a specified number of items | 5 items" to get a list of the top 5 most viewed nodes.
> 1 votes

# Answer
You also need Views module to make a block of 5 most visited page.

Check here: drupal 7.10: View of Most viewed posts
> 0 votes

---
Tags: 7, blocks, nodes
---


# Question
Title: How do I restrict a content type to a subset of vocabulary?
I have a hierarchical general taxonomy vocabulary called tags. Some of the terms are only relevant to particular content types; e.g., the "Apples" content type might have a sub-tree in the vocabulary with *Cox*, *Granny Smith*, and the "Oranges" content type might have *Seville* in its vocabulary sub-tree.
When editing an *Apple* node, I don't want users to be able to select *Seville* as this doesn't make sense.

I have put the terms into one vocabulary because other content types (e.g. blog articles) might want to tag against any of these.

# Answer
> 5 votes
I think http://drupal.org/project/term\_reference\_tree together with views will handle this for you. You will need to set up different views for each content type and then use term\_reference\_tree together with that view on each content type. As quoted from the module:

> If you want to filter by a view, make sure the view includes the taxonomy term ID, and that the items per page is set to unlimited, as the widget will only display the items from the first page of results.

Summarised module usage for reference:

1. Create a view to filter for the terms you want.

* Choose Taxonomy for the content, and work on the *Master* display (not *Page* or *Block*)
    * Add the *Name* field
    * Add the *Taxonomy term: Term ID* field BUT check the "exclude from display" option.
    * Turn off the pager
    * For this specific case, add relationship: *Parent term*; create *OR* group in *filter*: (vocab=tags && (parent.tid={Apples's tid} || tid={Apples's tid}). This gives the *Apples* term itself and all its child terms.
    * Possibly needed if view does not work for non-admin users: change the *Disable SQL Rewriting* option under *Query settings*, but beware that means there is zero access checks on your view.
2. Apply the view to the Term Reference field.

* Go to the content type fields page.
    * On the Term Reference field in question, click the *Edit* link at the end of the row. You can now see the "Filter by view" option. (If not, your view is wrong). Choose your view and save these options.
    * Now click the link to change the widget: choose Term Reference Tree.

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


# Question
Title: How do I change the overridden feature to default
I got "overridden" for two settings. I wanted to know why this is happening, and how to get rid of it in a proper way.

# Answer
Features takes configuration from the database, and stores it as code. When a feature is "Overridden", this means there's a difference between what is stored in the database, and what is stored in the files.

This can happen because you've made changes directly to, for example, the Views that are exported. However, it can happen for less obvious reasons.

Sometimes, when you enable a new module, this module may add additional data with a default value to the export of a module. This suddently means that when Features compares the db and files, there's more data in the db, and you have an overridden feature.

Because there are a large number of reasons you can end up with overriddes, there's no surefire way of handling them. You need to install the diff module to inspect that the difference actually is. Then you can determine if you want to "Revert" the feature (copy the Feature file data into the database), or "Re-create" it (create new Feature files, which you can then overwrite the original feature with).
> 8 votes

# Answer
This means you have made changes to the block settings and strongarm settings after you have enabled the feature. The way to get rid of it is to remove the feature and re-install it but thats kind of pointless as you obviously made changes for a reason. The best thing to do would go back to the original, make the changes and then re-export the feature. Then you wont need to make the changes.
> 4 votes

---
Tags: 7, features
---


title: Language Specific Site

text:
# Question
Title: Language Specific Site
Is it possible to create a site that has multiple languages available to the user?

Preferably as similarly as possible to asp.net using .resx files (see here http://support.microsoft.com/kb/917414)

Is there any modules you have used that can provide this sort of functionality?

Thanks

# Answer
> 3 votes
The internationalization collection as recommended by 7wonders is a good and useful set of modules, but you should first check the Core locale module, as Core provides the basis of the functionality that you request.

# Answer
> 4 votes
The internationalization collection will allow you to offer full language support for the user in the form of variables and all sorts so it is more feature full than the solution you linked.

---
Tags: i18n-l10n
---


# Question
Title: Add a vocabulary and a term-reference field or just add a select field?
I have various content types which have sub-types in my Drupal 7 site. e.g. "downloadable resources" content type, and within this there may be reports, presentations.

Is there any reason not to add this to a select field with a list of value=\>label pairs?

Should I create a separate vocabulary for these options and add a new field referencing that terms? I have a couple of other content types similarly modeled, so I would end up with a load of very small (2-3 terms) vocabularies.

Taxonomy seems to be favoured but instinctively it seems overkill?

Edit: or is it better to have very granular content types (report, presentation...), even though the fields are the same between them?

# Answer
As @reptilex mentioned, the answer to this question is going to vary depending upon your very specific situation. There are a lot of helpful documentation resources and blog posts floating about with good advice about making this decision.

drupal.org Guidelines for Taxonomy Design
blog - How to Decide Between Taxonomy and CCK to Classify Content
blog - Drupal Taxonomy vs. Content Type Field
> 3 votes

# Answer
It really depends on your content types. I would try to use taxonomies if possible, it is not as much overkill as it seems. And it will allow you to use views and other modules that reflect them.

But like I said it depends a lot on how hierarchical your content is. If you for instance have 10 content types the almost the same fields with only three possible "taxonomies" that are the same between content types, I would seriously think about using the "taxonomies" as content types and the current content types as taxonomies. It might seem evident but I have caught myself doing this wrong.
> 1 votes

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


# Question
Title: If two modules both defined the same menu path in 'hook_menu', which one Drupal will choose?
For example, "moduleone" defines the path 'admin/hello', which output `print_moduleone_stuff()`.

```
/**
 * Implements hook_menu()
 */
function moduleone_menu() {
  $items['admin/hello'] = array(
    'title' => 'Module One Hello World',
    'page callback' => print_moduleone_stuff,
  );
  return $items;
}

```

"moduletwo" defines the path 'admin/hello', which output `print_moduletwo_stuff()`.

```
/**
 * Implements hook_menu()
 */
function moduletwo_menu() {
  $items['admin/hello'] = array(
    'title' => 'Module Two Hello World',
    'page callback' => print_moduletwo_stuff,
  );
  return $items;
}

```

Both modules defined 'admin/hello' path for different result. With these two module enabled, how does Drupal select one than another? How does Drupal solve the conflict?

# Answer
The function invoking `hook_menu()` is menu\_router\_build(), called by menu\_rebuild(). It contains the following code.

```
  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }
  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);

```

If there are two modules defining the same route, the last module in the array returned by `module_implements()` will override the value defined from the other modules.

The second parameter required by `module_implements()` is defined as:

> `$sort` By default, modules are ordered by weight and filename, settings this option to `TRUE`, module list will be ordered by module name.

Since `menu_router_build()` doesn't pass the second parameter to `menu_implements()`, the function is using the default value for that parameter. This means the list of modules are ordered by their weight and filename; when two modules have the same weight, the first module that appears in the list is the one that alphabetically comes first.

Furthermore, any module implementing `hook_module_implements_alter()` can alter the order the hooks are invoked.

For this reason, you should not assume to know in which order the hooks are invoked.
If the purpose of the code is altering the route implemented by another module, for example because a route should be removed when a second module is installed and enabled, the code should use `hook_menu_alter()`. If you are trying to understand which module would "win" in the case of route conflicts, I would rather avoid such route conflict, and define a route that is not already defined from another module.

If then you are implementing `hook_menu_alter()`, and you want to be sure your module is executed last, to be the module that effectively overrides a route, you should implement `hook_module_implements_alter()` too.

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move mymodule_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

```
> 17 votes

# Answer
Whichever module has a lower `weight` value in the `system` table will be called first, so the module with the higher `weight` value will 'win' in this case.

If the weights are the same for two (or more) modules I believe there is no specific ordering done other than the ordering that comes directly from the MySQL table (I could be wrong about that though).

As the return results from the invoke of `hook_menu` are just put into a single array of menu items there will never be a 'conflict' as such, the results from later calls to `hook_menu` will simply override those from the earlier calls.
> 4 votes

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


# Question
Title: Problem importing Drupal to a CentOS 6.2 Server: The smtp authentication module does not work
I have a problem with a Drupal site running on Centos 6.2 server, Apache 2.21.15, and using PHP 5.3. The Drupal installation was made in a Windows XP computer using Wamp, it makes use of email for notifications when a new content is created, etc. In this computer (XP), it works like a charm, sending emails and doing everything right. Now that I migrated the site, copying the appropriate files from Drupal, importing the database, using phpMyAdmin, everything seems to be working right but the smtp authentication module doesn't work; there is no error, but I don't receive the test email inside this modules. Other thing funny, I've installed Drupal 7 in the server, and the smtp authentication module, and it works just fine. I guess that could be a permission problem but I can't find how to fix it.

# Answer
> 1 votes
The problem was caused from the fact I used the development snapshot instead of the stable release. Once I installed the stable release, all worked perfectly.

---
Tags: users
---


title: Rebuild Workbench cache?

text:
# Question
Title: Rebuild Workbench cache?
After adding some link to menu, on which Workbench Access has its hierarchy, I cannot immediately use this one, as a section. Tried rebuilding drupal menu (menu\_rebuild()), but it's something inside Workbench. Does anyone has dealt with this? To solve this, after adding some link to menu, I need to go to Workbench Access configuration page and just save it. Then it's refreshed, and new items (new hierarchy positions) are available to be set as sections.

# Answer
> 1 votes
If anyone will be looking for similar problem:

I wrote myselft a function. It fetches all the items from menu (which we use as a hierarchy for Workbench Access) and compare them with current Workbench Access items, those that aren't there yet, get inserted. It refreshes caches and it is possible to use all the items as sections, because it's synchronized now.

For now it seems to work. I couldn't find better solution so far.

```
function update_possible_workbench_sections($menu_name="menu-global-packages") {

$wanted = array();
$records = db_query("SELECT mlid FROM {menu_links} WHERE menu_name=:menu_name", array( "menu_name"=>$menu_name))->fetchAll();
foreach($records as $r) {
    array_push($wanted, $r->mlid);
}

$access_scheme = db_query("SELECT * FROM {workbench_access}")->fetchAll();
$existing = array();
foreach($access_scheme as $r) {
    if( intval($wpis->access_id)>0 && $r->access_type_id==$menu_name ) {
        array_push($existing, $r->access_id);
    }
}

$missing = array_diff($wanted, $existing);
$values_to_insert = array();

foreach($missing as $item) {
    array_push($values_to_insert, array( "access_id" => $item, "access_type" => "menu", "access_scheme" => "menu",
                "access_type_id" => $menu_name ));
}

$query = db_insert("workbench_access")->fields( array('access_id', 'access_type', 'access_scheme', 'access_type_id'));

foreach($values_to_insert as $value) {
    $query->values($value);
}

$query->execute();
workbench_access_reset_tree();
module_invoke_all('workbench_access_save');
return count($values_to_insert);

```

}

---
Tags: 7, routes
---


# Question
Title: How to display a js popup saying "Loading..." after user saves a node?
Been looking for solutions that would show a javascript popup or the like after a user submits or saves a node. How could I achieve this? Any modules out there?

# Answer
> 3 votes
You want it to display the instant they click the "Submit" button? The issue here is that, even if the "Loading..." popped up, the user would immediately see the page go white as the new page begins to load. It seems you're wanting to combat how page refreshes work, not Drupal.

That being said, to achieve the functionality that I think you're looking for you'd want to be opening the node create/edit form in a modal or something like that so it submits via an Ajax call and not a standard HTTP refresh. You can maybe use the Popups API module to do something like this: http://drupal.org/project/popups

---
Tags: nodes, ajax, javascript
---


# Question
Title: Is there a way to programmatically alter a field's schema?
Is there a way to modify a fields schema programmatically? I'd like the image field to have a "Premium" checkbox, but I need to store this data somewhere. Also, it needs to work for current fields and future fields as they are created.

# Answer
I believe you are looking for the API function hook\_schema\_alter.

Though you should also be aware that the Media module exists specifically to solve this particular problem in a much nicer way.
> 2 votes

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


# Question
Title: limit exposed filter to top X taxonomy terms in drupal 7
basically I have an exposed filter that lets users use the filter to search the website.

Only the terms available are sometimes 20+ items so I want to limit the available exposed terms and show only the top X terms with the most related nodes and create a 'more' button to show the rest.

Is there already a module or something for this?

# Answer
> 2 votes
I think the closest I have seen to doing what you ask is http://drupal.org/project/better\_exposed\_filters which tries to at least make the exposed filters more manageable.

EDIT:

If you are prepared to switch the filtering to faceted search you could use search\_api module in combination with its built in facets (through solr). Then you end up with being able to restrict the amount of terms you show in the facet.

# Answer
> 1 votes
I've asked a similar question a few weeks ago and got some really good answers after using a bounty. But I haven't implemented it yet.

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


# Question
Title: I need to access individual elements of a node in my module
I have the following query that fetches all the nodes of a certain type.

```
function shop_home_page() {
  $render = array();
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type AND n.status = :status';
  $result = db_query($sql,
    array(
      ':type' => 'music_albums',
      ':status' => 1,
    )
  );

  foreach ($result as $row) {
    $node = node_load($row->nid);
    $render['my_list'][] = node_view($node, 'teaser');
   }
  return $render;
}

```
1. How do I display in my page node elements such as $node-title, $node-body? I tried as `$render['my_list'][] = node->title` but it doesn't seem to work.
2. I also need to add a form with a buy button to each element. How do I attach it?

# Answer
1) You can use code like the following:

```
$render['my_list'][] = array('#markup' => '<div>'.$node->title.'</div>');
$render['my_list'][] = array('#markup' => $node->body['und'][0]['value']);

```

2) Forms can be added similarly to node\_view():

```
$render['my_list'][] = drupal_get_form('mymodule_buy_form_'.$node->nid, $node->nid);

```

I'm assuming you want the forms built with a single function, but with different id-s to work correctly (attached `$node->nid` for that). I also added an extra argument (`$node->nid`) since you may want to add it to every form in a hidden field to determine which form got submitted. Then you use hook\_forms() to get the same builder function called for all the buying forms:

```
function mymodule_forms($form_id, $args) {
  $forms = array();
  if (strpos($form_id, 'mymodule_buy_form_') === 0) {
    $forms[$form_id] = array(
      'callback' => 'mymodule_buy_form',
    );
  }
  return $forms;
}

```

The form builder function for this example:

```
function mymodule_buy_form($form, &$form_state, $nid) {
  $form = array();
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

```

And a submit handler:

```
function mymodule_buy_form_submit($form, &$form_state) {
  drupal_set_message('Form for node '.$form_state['values']['nid'].' submitted.');
}

```
> 1 votes

# Answer
This looks like it could be done with a view, using view type node list. Display type should be fields and then you select node title and teaser as fields as well as an additional field which has to be rewritten to build a buy button (depending on what action the button shall trigger).
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Theming Views, getting a list of object I have access of
I'm Currently trying to theme a view. Unfortunately I'm having a hard time to find elements I should use to access my fields.

Is there any where on the web, where I could find those variables ? or the parent one, that will allow me to find out other by searching down.

# Answer
The 3 tools that I find vital to this is:

1. Click "Theme: Information" in the view page itself. This will give you a list of template files being used for the view and suggestions of template files you can use to override them by placing them in your theme folder (or a template subfolder of your theme depending on how you have set up in your .info file).
2. Devel module \- this will allow you to inspect just about any aspect of your site and all the variables, fields etc available to you in a particular node/view.
3. Drupalforfirebug module and accompanying firefox/chrome plugin. Although I find it somewhat buggy in certain areas of drupal, it is great for inspecting all aspects of drupal (especially views).
> 3 votes

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


# Question
Title: Validation error every time on save comment form
Every time I try to leave comment on a content of a certain type I get this error:

> Validation error, please try again. If this error persists, please contact the site administrator.

Refreshing and resubmitting the comment manually does not fix the problem, I always get this issue. The content type in question is displayed via a Panels Node Template, if that matters.

# Answer
I traced the problem down to the the panels pane that displayed the comments list. If the comments list was disabled, comment submission worked fine; turned back on the validation error returned.

Looks like this is caused by a (likely) bug in CTOOLS. The patch in comment #1 fixed the issue.
> 2 votes

---
Tags: 7, forms, panels, chaos-tool-suite
---


# Question
Title: Using custom functions in Views template files = not good practice?
I have a field in my View that outputs a YouTube URL (eg. http://www.youtube.com/watch?v=rF1X12PE6PY)

I want to output just the ID part (ie. rF1X12PE6PY)

So I made a module with a function that takes the full URL and returns just the ID. Then in my views-views-fields.tpl.php template I call the function:

```
<?php print youtube_id_get($fields['url']->content); ?>

```

Now this works fine, but something tells me it's not good Drupal practice?

Will this screw up Views performance/caching? Should I create a custom Views filter instead (still learning about such things)?

# Answer
> 4 votes
This should be just fine, however, The REAL Drupal way to do this, would be for your module to provide a field formatter to views that calls this function. There are many modules which do nothing but provide functions. CTools, for example.

Having a field formatter removes your site's functionality from the "view". Which is a best practice with any kind of software. You'll be able to change the theme in the future without worrying about your youtube IDs. Creating a formatter isn't hard to do, here is a great tutorial on how to do it.

Once you have a formatter, you can simply select it from the drop down in the View's UI and you're done!

---
Tags: 7, views
---


title: Displaying custom fields in a forum

text:
# Question
Title: Displaying custom fields in a forum
I have made some custom fields at config-\>account settings (manage fields) and I have put them in my registration form but I want some of them display at image I show below under the post count and generally when they create a new topic or replay.

How do I display that field? From a search I did I found that it's inside the module VIEWS. I am searching inside there to find where to add the field.

http://img848.imageshack.us/img848/7913/costumfield.png

**Answer** At drupal 7 at Configuration - account settings - right top cornet manage fields you can create custom fields and put them where you like, then the most common to do is to add these feilds in your code with editing the source code just i didnt know how to do it.. i dont thing there is another way..! because i use the module author pane and the best way is too add them to author panel in the module code..

# Answer
You might also want to take a look at http://drupal.org/project/author\_pane. That shows author information as shown in the picture you have posted.
> 1 votes

# Answer
You might have to use Views and/or Advanced Forum modules to recreate your forum interface. http://drupal.org/project/advanced\_forum

When you install Advanced Forum module, I believe it auto-generates some views displays which are designed specifically for the forum module.
> 0 votes

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


# Question
Title: How do I query a MySQL view in Drupal 7?
I have created a database view and I would like to show the results in a Drupal Page. The view has some pretty complex SQL behind it, so trying to use the Views module isn't possible.

I just want to do `SELECT * FROM VIEW_X` and display the results on a page in PHP.

I know how to do this in Drupal 6, but how is it done in Drupal 7?

# Answer
> 7 votes
I don't think it's possible to query views using the DBTNG query builder: if you try to use `db_select()` with a view, it raises a `PDOException` complaining that the table doesn't exist.

Instead, you'll want to use `db_query()`. Let's assume you created a view named `test`:

```
CREATE VIEW test AS SELECT * FROM variable;

```

To get the value of `cron_key`, you'd do:

```
$name = 'cron_key';
$result = db_query('SELECT * FROM test t WHERE t.name = :name', array(':name' => $name));
$value = $result->fetchColumn(1);

```

The comment by drclaw on the `db_query()` API entry gives a number of examples which should help you out with figuring out how to manipulate a `SELECT` query using `db_query()`.

---
Tags: 7, database
---


# Question
Title: How do I send an email notification to a user who flagged another user using rules?
I have the Flag module set up so that the users can flag each other; there is a link shown on the user profile page. I would like to have those users who flagged another user to receive a notification by email when the flagged user post new content.

How can a user who is 'following' another user to disable email notification on new content?

I am using Drupal 7.

# Answer
> 0 votes
Notifications was still a bit wobbly on d7 when I checked last. I use http://drupal.org/project/privatemsg module which is nice because it keeps an online message as well as notifying via email (with permissions to change if you like so you can ignore users etc).

To set up the rule you add an event for the flag "A user has been flagged ....". Then any conditions you feel necessary and then Action "Send a message", recipient "flagged-user", author "flagging-user" and then whatever subject and body you like.

# Answer
> 2 votes
Solution: I created FLAG users, so that users can flag each other.

RULES is set up as follows: New event, node new content.

Elements (3 items)
1st : Fetch users who have flagged a user
Parameter: Flag: Flagname..., user: \[node:author\]
Provides variables: Users who flagged (usersflagged) Add another

2nd : Add Loop
Parameter: Lijst: \[usersflagged\]
List item: Current list item (list\_item)

3rd : Send E-mail
Parameter: To: \[list-item:mail\], Subject: Sitename | \[node:author\]..., Message: Dear \[list-item:name\], ..., From: no-reply@sitename.com

Next step to discover is how to digest the mail. And I am wondering how much impact this rule will have on a busy site.

---
Tags: rules
---


title: What is wrong with this code?

text:
# Question
Title: What is wrong with this code?
I am having a slight problem with my code; I am trying to do a if statement to make the date not print if a node is using a certain term. I have parsed `$node` to narrow down what term I would like to exclude the date from being used.

This is what is returned in the dump:

```
Array ([und] => Array ([0] => Array ([tid] => 103 )))

```

This is what I have for my code to have the date being displayed:

```
      if (arg(0) == 'node' && is_numeric(arg(1))) {
        $node = node_load(arg(1));
        $user = user_load(array('uid' => $node->uid));
        foreach ($node->field_newsections['und']['0'] as $node_time);
      }

      hide($content['comments']);
      hide($content['links']);
      $nodecontent = render($content);
      $newcontent = preg_replace("/<p[^>]*?>/", "", $nodecontent);
      $newcontent = str_replace("</p>", "<br /><br />", $newcontent);

      if ($node->type == 'post' || 'news') {
        echo '<div id="date-created">'. date('l, F j, Y g:ia', $node->created). '</div>';
      }
      else ($node_time == '108') {
        echo 'working';
      }

      print render($newcontent);

```

I am probably over looking something small.

# Answer
There are three things that needs to be corrected, in your code.

* You are using a `foreach` statement without any block; this means that that control statement is not doing anything.

```
foreach ($node->field_newsections['und']['0'] as $node_time);

```
* You are using an `else` statement followed by a condition; or you use an `else` statement without condition, or you really meant to use the `elseif` statement.

```
else ($node_time == '108') {
  //...
}

```
* You are using `render()` with `$newcontent`, which is set with a previous call to `render()`.

```
$nodecontent = render($content);
$newcontent = preg_replace("/<p[^>]*?>/", "", $nodecontent);
$newcontent = str_replace("</p>", "<br /><br />", $newcontent);

```

While `render()`, which returns a string, checks when the parameter it gets is a string, instead of an array, and it returns that parameter immediately, it is useless to call `render()` with the result of a previous call to `render()`, even if that string has been modified from any function to alter a string.

Also, as you said (in a comment for this answer) that you are using that code inside the "node.tpl.php" template file, that template file has already access to the `$node`variable that contains the node object for the node being shown. As the template file is only used for nodes, the following code is useless:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  $user = user_load(array('uid' => $node->uid));
  // …
}

```

It is also unusual for a theme replacing the HTML content; that is normally done in a module.

Supposing that you are trying to use the last item in the `$node->field_newsections['und']['0']` array (which seems a term array), I would rather use the following code:

```
$tid = array_pop($node->field_newsections['und']);
$node_time = $tid['tid'];

hide($content['comments']);
hide($content['links']);
$nodecontent = render($content);
$newcontent = preg_replace("/<p[^>]*?>/", "", $nodecontent);
$newcontent = str_replace("</p>", "<br /><br />", $newcontent);

if ($node_time != '103') {
  print '<div id="date-created">'. date('l, F j, Y g:ia', $node->created). '</div>';
}

print $newcontent;

```
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: Is it possible to add second horizontal Menu below Main Menu?
* I use "user menu" on top, for user related links.
* I use "main menu", in reaching my main contents of site.

I need one more horizontal menu below the "main menu". So second priority links will be there. Can it be possible?

(I'm not interested with drop down menus. "Main Menu" and "Second Horizontal Menu" will be independent of each other)

Thank you very much for your help.

# Answer
> 1 votes
1. Go to /admin/structure/menu/add and add a new menu
2. Go to /admin/structure/block and place the new menu block in the region of your choosing.

---
Tags: routes
---


# Question
Title: How can I import the contents of an uploaded csv file into a drupal managed table using rules custom php?
I am using drupal 7 and have the data module managing/adopting a table I have manually added to my drupal db. What I was hoping was that when a csv file is uploaded via a specific content type I could use rules to execute some custom php and import the csv into the table (as feedsdataprocessor no longer exists from what I can see). I see there is a drupal\_write\_record function but the problem is first how do I get the array out of the file and secondly my file can be different to the table in structure - for example, sometimes the csv will have columns 1,2,3,4 and sometimes 3,4,5,6,7. How can I check the headers and import into the managed table?

# Answer
> 10 votes
So conceptual steps:

1. Extract CSV file path from the node.
2. Open CSV file, read fields from header.
3. Read each row, convert the keys, save row using drupal\_write\_record().
4. Close the CSV.

I'm not sure how the rules integration will work I'm assuming you can pass the node into it some how.

So for step one assuming it's stored into $node and your field is named field\_csv\_file we can hand the URL to fopen():

```
$csv_uri = $node->field_csv_file['und'][0]['uri'];

```

So now we can open fopen() to get a file handle:

```
$handle = fopen($csv_uri, 'r');

```

If there's no value we don't want to procede.

Read the header row:

```
$row = fgetcsv($handle);
$columns = array();
foreach ($row as $i => $header) {
  $columns[$i] = trim($header);
}

```

Then load each row and convert the format:

```
while ($row = fgetcsv($handle)) {
  $record = array();
  foreach ($row as $i => $field) {
    // This is pretty brittle... if someone screws up the field
    // names the data won't be written.
    $record[$columns[$i]] = $field;
  }
  drupal_write_record('your_table', $record);
}

```

Close the file:

```
fclose($handle);

```

So issues with this:

* All this code it totally un-test.
* What happens if someone re-uploads the file? You'll probably get duplicates.
* What happens if someone messes with the headers?

---
Tags: 7, rules, importing-exporting
---


# Question
Title: Would be Drupal a good choice for my web app?
I have a 'webapp' that consists basically of making Linux command line calls; let's admit it runs the 'uptime' command and returns the output.

My app is currently built using CodeIgniter; it works fine, but i'd like to use the powerful features of Drupal that are built-in like users handling, views, imagecache etc.

My main concept is having a 'button' on which user clicks and then it runs the selected task (asynchronously, AJAX) and then shows the result (with jQuery).

I know of 'triggers' but I can't really think of having them 'do' some action once a 'button' (a link) is pressed, not a 'on node creation do ...'.

I just wonder if anyone has done something similar, and how.

# Answer
> 2 votes
Both codeigniter and drupal are php frameworks. Can you elaborate more on what exactly you are looking for? Drupal is capable of doing everything a php can do. Also Drupal 7 has built in ajax support for forms. With additional modules like ctools, you can extend ajax functionality to any DOM elements.

There is Rules module that is more powerful and extended version of triggers. Its the GUI version of if-else-then php statements.

# Answer
> 2 votes
You should take a look at the Drupal forms API. The Forms Tag contains several links to the form API list and a quick start tutorial. *(Select the tag and click on 'learn more')*.

Using forms will allow you to collect information from the user, validate the input and execute the input.

---
Tags: ajax
---


# Question
Title: Workflow and Organic Groups. How can you email the next state changer when content is posted?
I would like to notify someone with editor permissions that a user has posted content in the workflow. I found a token for the current state updating user (\[workflow-current-state-updating-user-mail\]\]), but nothing for the next user in line.

I've seen reference to using rules to send email to all users of a particular role, but I need something more like 'send email to users of a role who belong to the current group'.

Is this possible?

# Answer
Solved this by writing a module to create a custom token from a field added to the group\_node\_form. I followed this tutorial, making adaptations for organic groups: http://rbayliss.net/story/creating-tokens-drupal-6
> 0 votes

---
Tags: 6, workflows, actions, organic-groups
---