title: Node Reference input with HTML preview

text:
# Question
Title: Node Reference input with HTML preview
I am trying to show a multiple node reference input control that shows the title and an image of each node.

I have achieved it using Autocomplete Deluxe but it allows users to create new objects in the control itself which I cannot allow. I have also tried Chosen with a reference view but it strips all HTML before showing in the list.

Are there any other modules or techniques I could try to achieve this?

# Answer
In my opinion that is the case for a View. You should prepare a view with the fields you want to display from referenced nodes.

Then install Entity Reference View Widget module. With that module you will be able to use your view to select the node references.
> 0 votes

---
Tags: 7, views, nodes, ajax
---


# Question
Title: Any way to get localized term names in node paths
I have a node type "news" with an included term reference field named "newscategory". i18n-module incl. taxonomy-i18n is also installed, vocabulary is translatable and all terms are translated. But for pathauto patterns there is only the token "\[node:field\_newscategory\]" available, which will not be localized depending on the node language.

Is there any trick on achieving this?

# Answer
> 1 votes
Why don't you try Entity Token - it's part of the Entity module and provides additional tokens for use with i18n. It will make the token tree item for the term ref field expandable and you should see a token like `node:field_newscategory:i18-name`. This should get you going purely on the UI side.

Although I bet it rocks to be able to wrap one's own piece of code that just works :)

# Answer
> 1 votes
Okay, after 2 more hours of research and development I've finally managed to get the problem solved. I ended up writing a tiny custom module implementing hook\_pathauto\_alias\_alter().

The module has several dependencies:

```
dependencies[] = taxonomy
dependencies[] = field_extract
dependencies[] = pathauto
dependencies[] = i18n
dependencies[] = i18n_string
dependencies[] = i18n_taxonomy

```

Here's how I did it (tailored to my special needs, so go on and modify my code)

```
<?php

  /**
   * Implements hook_pathauto_alias_alter()
   */
  function mymodule_pathauto_alias_alter( &$alias, array &$context ) {
    if ( $context[ 'module' ] == 'node' ) {
      $node = $context[ 'data' ][ 'node' ];
      if ( $node->type == 'news' ) {
        // determine actual context variables
        $language = $context[ 'language' ];
        $pattern = $context[ 'pattern' ];
        $category = field_extract_value( 'node', $node, 'field_newscategory' );

        // translation & preparation
        $category_translated = i18n_string_object_translate( 'taxonomy_term', $category, array( 'langcode' => $language ) );
        $sanitized = pathauto_cleanstring( $category_translated->name, array( 'langcode' => $language ) );

        // re-build the alias
        $alias = explode( '/', $alias );
        $pattern = explode( '/', $pattern );
        foreach ( $pattern AS $index => $part ) {
          if ( $part == '[node:field_newscategory]' ) {
            $alias[ $index ] = $sanitized;
            break;
          }
        }
        $alias = implode( '/', $alias );
      }
    }
  }

?>

```

---
Tags: uri, tokens, i18n-l10n, path-aliases
---


title: New commerce site checkout broken

text:
# Question
Title: New commerce site checkout broken
It turned out there were two issues here: first checkout stopped working, then the server ran out of space. I now have space on the server, but the checkout still isn't working.

It's a commerce site, and checkout worked fine until launch and now the process appears to be broken. I get this message in the Drupal error log.

> Notice: Undefined index: field\_extra\_instructions in commerce\_customer\_profile\_pane\_checkout\_form() (line 165 of /home/wholebox.org/www/profiles/commerce\_kickstart/modules/contrib/commerce/modules/customer/includes/commerce\_customer.checkout\_pane.inc).

The site is wholebox.org and if anyone can help find out what's wrong, it would be very handy right now.

Could I have disabled an important module when trying to make it faster?

# Answer
Checkout problem - there are two possibilities that fixed it, as I re-enabled Extra Panes and Coupon UI at the same time.

I had set an extra field in Customer Shipping Profile. I didn't think it was dependent on Commerce Extra Panes, but when I disabled that module the process broke.

It could also be that the coupon UI module provides the text box on the checkout process, so when I disabled that it broke it.

Thanks for everyone's help in the comments above :)
> 1 votes

---
Tags: commerce
---


title: Redirecting /sites/all/files

text:
# Question
Title: Redirecting /sites/all/files
I am using Drupal 7. Is it possible to to redirect the "/sites/all/files" directory to just "/files". Also, would it be better to just create a new directory /files and copy the files over. But, I would have to change a lot of links in my content that access those files.

# Answer
> 5 votes
With Drupal 7, you do not need to do so! Drupal file paths are stored using stream wrappers so you can simply change the folder path in Admin \> Configuration \> Media File System and move the existing files to new folder and you are ready to go!

You will see `public://images/my.png` like paths in files table and many other locations. These are the stream wrappers used in Drupal 7.

However if your content has links hardcoded, they will not change. Try adding the following line right below the

```
RewriteEngine on
RewriteBase /

```

lines.

```
RewriteRule ^sites/default/files/(.*)$ http://www.example.com/files/$1 [R=301,L]

```

---
Tags: redirection
---


# Question
Title: Is it mandatory to apply every minor Core upgrade step by step?
I have a site in drupal 6.26 and I need actualize it.

I have two options:

6.26 to 6.27 to 6.28

or

6.26 to 6.28 directly

What is the best method? Thanks

# Answer
You can go from 6.26 directly to 6.28.

The most critical part, is the database update, because tables and fields can get modified, added or removed. The upgrade process in Drupal takes care of executing every single database update step.
> 3 votes

---
Tags: 6, updating
---


# Question
Title: is it possible to have two input fields per label in a Drupal form?
I've got a Drupal 6 form API question which may or may not be possible, or a good idea.

Is it possible to have two input fields per label?

I'm familiar with this format:

```
$form['example_textfield'] = array(
'#type' => 'textfield',
'#title' => t('text here'),
'#size' => 30,
'#maxlength' => 32,
'#required' => TRUE,
);

```

As the way to make one label with one field, but is it possible to have one label and two input fields? and create something like: label: {input field} {input field}

If there is a way to do it, how would I get the two values into the DB table?

Is such an approach even a good idea? or should I stick to the single label/single input field method demoed above?

# Answer
> 0 votes
I ended up using two field sets rather than try to get two input fields next to one label.

It's more work upfront, but possibly more stable/reliable.

# Answer
> 0 votes
You cannot have a label for two form fields, as the label is output with HTML code similar to the following one.

```
<label for="edit-category">Category: <span class="form-required" title="This field is required.">*</span></label>

```

The attribute `for` accepts a single form element ID; you cannot use the following HTML, for example.

```
<label for="edit-category edit-recipients">Category/Recipients: <span class="form-required" title="This field is required.">*</span></label>

```

If you don't want to use a label for the second form element, you can simply use an empty string for the #title property.

As for saving those values in the database, a label is not used when saving the value of a form element, but it is used only on the user interface. The code for saving the content of a form element doesn't use the label value, but the identifier associated to the form element.
In your case, the form submission handler would get the value entered from the user for the `$form['example_textfield']` element from `$form_state['values']['example_textfield']` where in Drupal 5 would have used `$form_values['example_textfield']`.

---
Tags: 6, forms
---


# Question
Title: How do you create a CCK field that presents a node creator with a list of the website's users?
I'm trying to add a CCK field that will present a site manager with a list of instructors which are actually a sub-group of already-authenticated users with the role name of "instructor" for a "class" content type.

The list of instructors is pretty large, and I'd rather use the actual users that are already on the site to populate that field instead of just having a plain select list.

The "class" content type will have a couple other fields, like location, day of the week, and class type. The problem is figuring out how to add the instructors, who are already authenticated users to the content type via a select list of some kind. Does anyone have any ideas on how to best accomplish this? I can't find a suitable CCK field to do what I'm trying to do, and as mentioned previously, I don't want to use just a text/select list.

# Answer
> 0 votes
You can use the modules Entity reference and Views.

Views will allow you to generate a list of authenticated users (see PS).

Entity reference will allow you to add a Reference field which can reference entities filtered by the view you choose during the field setup.

PS. In order to make the view available on the field setup page, the view my have a "References" display.

# Answer
> 0 votes
You can setup a view for those users and then install Views Field View module. With this module you can add a new field to your node which is a link to that view.

That view will be able to get arguments coming from the node where it's linked from.

---
Tags: 7, entities
---


# Question
Title: How to delete lines from a table created by a custom module?
I'm working on a custom module that has an admin form designed to contain a number of values. age 21 =\> value, age 22 =\> value, etc.

The issue I'm having is that while I can add information to the table I've created through my form, I'm only supposed to have 1 possible value per age. I dont know how to delete the old value before the new one is added.

This is what I have that adds info to my table successfully:

```
/**
* Saving Score administration settings and DB information
*/
function savingsscore_admin_form() {
  $form = array();
$form['savings_ages'] = array(
  '#type' => 'fieldset',
  '#title' => t('Saving Ages'),
  '#weight' => -1,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#description' => t('Description of fields in this fieldset here'),
);
$form['savings_ages']['saving_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => '10.85',
);
  return $form;
}

/**
* Handle submission of Admin forms
*/
function savingsscore_admin_form_submit($form, &$form_state) {
db_query("INSERT INTO {savingfactors} (saving_age21)
VALUES ('%s')",
  $form_state['values']['saving_age21']);

drupal_set_message(t('Your form has been saved.'));
}

```

I know that what happens next should start like:

```
 db_query("DELETE FROM

```

But I dont know what I should add next, I'm uncertain of the syntax. Any help or links to documentation would be much appreciated

Thanks Stephanie

# Answer
You will find an answer here.

Basically you can use Drupal's drupal\_write\_record() to let Drupal handle that.

Or you can run a SELECT query first and an UPDATE or INSERT based on SELECT's result.

**EDIT:**

Based on information gathered in comments, it seems that the "savingfactors" table has several columns and only one row. If the row is already present, with any value, then a simple UPDATE query is enough. Here's an example:

```
function savingsscore_admin_form_submit($form, &$form_state) {
  db_query("UPDATE {savingfactors} SET saving_age21 = '%s'", $form_state['values']['saving_age21']);
  drupal_set_message(t('Your form has been saved.'));
}

```

That way you overwrite only saving\_age21 field, ignoring others.

You can do the same with any other field you want to save.

There's an initial requirement: the row must exist. You can manually create it with a db client software, or you can implement Drupal's hook\_install() inside your module .install file.
> 0 votes

---
Tags: 6, forms, database
---


# Question
Title: How can I get the date_popup module to display AM/PM in the time selector?
In date\_popup's README.txt, it states that

> The time selector will add AM/PM if 'a' is in the format string.

Which leads me to believe that

```
'#default_value' => date("m/d/Y H:ia"),
'#date_format' => 'm/d/Y H:ia',

```

should result in a textfield for the time picker that looks like:

> \[2:25pm\]

but instead I just get a blank text field. I can't get any combination of default\_value / date\_format to result in what I'm looking for. Am I reading the documentation wrong, or can this be achieved?

**Update:** I couldn't get this darn thing working and decided to disable the timepicker (admin/config/date/date\_popup) and added the timepicker from http://jonthornton.github.com/jquery-timepicker/ using the following code:

```
  $form['#attached']['css'][] = 'path/to/jquery-timepicker/jquery.timepicker.css';
  $form['#attached']['js'][] = '//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js';
  $form['#attached']['js'][] = array('data' => "var jq9 = jQuery.noConflict();", 'type' => 'inline');
  $form['#attached']['js'][] = 'path/to/jquery-timepicker/jquery.timepicker.js';
  $form['#attached']['js'][] = array(
    'data' => "
      jq9(document).ready(function() {
        jq9('#edit-start-date--popup-1').timepicker();
      });",
    'type' => 'inline',
  );
  $form['start_date'] = array(
    '#title' => 'Start Date',
    '#type' => 'date_popup',
    '#required' => TRUE,
    '#date_type' => DATE_DATETIME,
    '#date_timezone' => date_default_timezone(),
    '#default_value' => date("m/d/Y h:ia"),
    '#date_format' => 'm/d/Y h:ia',
    '#date_increment' => 1,
    '#date_year_range' => '-1:+1',
  );

```

# Answer
> 1 votes
I remember having a similar issue - I fixed it using a custom module like this, the possible cause was probably that Drupal and jQuery returned different formats...

```
$GLOBALS['locale'] = $locale = 'fr';

/* [...] */

function x_form_alter(&$form, &$form_state, $form_id){
    // Fix date format in some exposed date filters (cck date)
    $date_format = 'd/m/Y'; /* Should be same as in "sites/all/js/jquery.datepicker/$locale.js" */
    foreach($form as $key => $value){
        isset($value['value']['#date_format']) && $form[$key]['value']['#date_format'] = $date_format;
        isset($value['min']['#date_format']) && $form[$key]['min']['#date_format'] = $date_format;
        isset($value['max']['#date_format']) && $form[$key]['max']['#date_format'] = $date_format;
    }
}

```

I guess you can adapt this code to your situation and even better, suggest a cleaner solution.

---
Tags: 7, datetime
---


# Question
Title: Difference between Field and Field Instance?
When we go to the path `/admin/structure/types/manage/article/fields` and use the `Add new field` option or the `Add existing field` option, does that create a field, create a field instance or attach a field instance? How to differentiate between them? So, programmatically, when to use field\_create\_field, field\_create\_instance and field\_attach API?

In the field API documentation it only mentions the admin UI and never talks about the path where to create both fields and field instances. So it's confusing. I don't even know if I even make sense.

# Answer
A field is the basic definition of a field itself. A field *instance* is an instance of that field, attached to an entity/bundle.

1. Fields are created with field\_create\_field
2. Field instances, with field\_create\_instance

To check if the field, or instance exists, use

1. field\_info\_field or
2. field\_info\_instance

When you create a field through the UI, Drupal always creates a field instance on that entity/bundle.

If you're adding an existing field, the field data is cloned and a field instance is created on the new entity/bundle.

Lastly, field settings apply globally to that field, field instance settings can vary between entity bundles.
> 24 votes

---
Tags: 7, entities
---


title: Is there a way to group Rules by type?

text:
# Question
Title: Is there a way to group Rules by type?
I would like to know if there is a way to make groups or collections of Rules so it is easier to see the types of Rules I have created. Is there a module for this? Is this something where I can/should add a taxonomy term field, assign a term to each Rule and display it in a View?

# Answer
You can "Tag" rules which is a nice feature to group / filter them.
> 2 votes

---
Tags: rules, views
---


title: Negative margins in Omega content zone

text:
# Question
Title: Negative margins in Omega content zone
I am using Omega / Delta / Context, and am trying to make the content zone a little wider than its surrounding regions using negative margins but the

```
.container-12 { margin-left: auto; margin-right: auto; width: 1200px; }

```

class overrides my attempts to change margins or width with CSS via class names (ie, using **Theme Settings** =\> **Zone and Region Configuration** =\> **Context Section** =\> **Content Zone** =\> **Configuration** =\> **Additional zone classes**)

How can I accomplish this?

# Answer
> 1 votes
OK, you really have two options.

One is to put a more specific rule in your media query sheets. So, you would need to place a rule in mytheme-alpha-default-wide.css Normally, this comes before the grid sheet, so you either need a more specific rule or `!important`.

```
.zone-content .container-12 { width: 1300px !important; }

```

Your second option is to implement implement a `hook_css_alter()`, find the wide sheet for your grid system (eg, alpha-default-wide-24.css), and then swap it out with your own version. Then, in your own version you can do something like:

```
.container-12 { margin-left: auto; margin-right: auto; width: 1200px; }
.zone-content .container-12 { width: 1300px; }

```

And, as a side note, you will likely have issues due to redefining the grid width. The grid classes inside it will not work as expected.

---
Tags: theming
---


# Question
Title: Documentation of Drupal Content Types and Views
Drupal 7, Views 3

Ok, I've got a bunch of content types and views, all working happily together, what would be really nice is a way of automatically documenting things, say a printable page of what fields are in a content type or what fields are used in a view. Searching on Google gives lots of info on creating document types but I haven't been able to find anything on actually creating documentation.

Has anyone seen anything like this?

# Answer
> 2 votes
* `admin/reports/fields` \- Field list with node type relationships.
* `admin/reports/fields/views-fields` \- Used in views.

You need Field UI module enabled.

---
Tags: views, 7
---


# Question
Title: Print the current source node of the comment
I wold like to have some clues to search. Out of the box Drupal let you see the original article or page when you write a comment and click *"preview"*. I search everywhere and I haven't a clue about how to fix the problem when I make a custom tpl for the coment-form.tpl.php I lost the part where I see the original source of the subject I'm posting. I just see the comment form. I think is not comment.tpl or comment-wrapper.tpl I also make a custom module but no luck.

# Answer
The node id for the comment is stored in:

```
$comment->nid

```

e.g, in the template, to print out the node, you could:

```
if (isset($comment->nid)) {
  print render(node_view(node_load($comment->nid)));
}

```

You could also add it as a template variable in preprocess function.

See node\_view for more options
> 1 votes

---
Tags: nodes, forms, theming, comments
---


title: remove " " after <div class="content">

text:
# Question
Title: remove " " after <div class="content">
On every content page of my drupal site, there is always a line with empty quotes " " after `<div class="content">`.
This happens only with the content page and not in any view page.
Can someone guide me how to delete this empty quotes?

# Answer
> 1 votes
Have you checked this is present in the output HTML, and not added by the browser or some JS library? A suitable way to test would be to retrieve the content page using `curl` or `wget` -

```
curl http://example.org/node/123 | grep 'div class="content'

```
* If the empty quotes are not present in the original HTML (as displayed by the above command), then you should check if the quotes are present in *all browsers*, or only *one browser*. It may relate to a JS library you're including, or to a browser plugin, or even just to your browser's means of displaying your sourcecode.
* If the empty quotes are present in the output from this command, then you can look towards some theme or module on your site. You could do this by switching themes first (to see if it's the current theme), then by disabling modules in turn (to see which specific module is causing it).

This is really just general debugging advice - you may need either to give more detail (eg the URL of your site), or investigate debugging techniques to trace the issue.

---
Tags: nodes
---


# Question
Title: How to display featured or new products on main Ubercart catalog page?
I'm having a little difficulty setting up Ubercart that may be related to the particular way I am wanting to use it. I'm sure I've just missed a setting somewhere or something.

I have the front page of my website at mysite.com, and the store located at mysite.com/store. I have added categories to the catalog taxonomy (mysite.com/store/category1). So the store is secondary to the front page.

When I go to mysite.com/store Ubercart only displays a list of the categories, and not any products (as expected, they are all within their categories). My issue though, is I would like to display some "new" or "featured" products on the mysite.com/store page instead of just the list of categories. If my store was located at mysite.com I could just use the "promoted to front page" option, but it is not.

How can I display products on mysite.com/store? Thanks

# Answer
> 2 votes
Create a view and make a block in that and then expose that on the /store page above your content or what you see fit. that should do it.

---
Tags: ubercart
---


title: Manage User Access by IP

text:
# Question
Title: Manage User Access by IP
I am building an "Extranet" (Company Intranet, available both inside and outside our network).

What I want is three levels of authorization... Authorized (via LDAP AD), guest inside network and guest outside network.

Guest inside and Guest outside is where I'm getting hung up.

For users inside the network, I want "Public" stuff accessible (along with departmental stuff, depending on user signed in). For users outside the network I want a blank screen to show up until the user logs in (with proper AD credentials).

So a "Guest" inside the network should have access to stuff without logging in... a "guest" outside the network needs to log in before anything shows up.

I've seen some stuff that will "Ban" or "Whitelist" based on IP (since all the "inside" computers will be 192.168 or 10.10), but they don't seem to grant the ability to "greylist" (ban until logged in?).

I'm thinking maybe Themekey, with a separate theme for outside-unauthorized? Or would it be better to roll something up myself?

# Answer
> 0 votes
Rules might be what your looking for. you have to find a module that plugs into rules that can check ip.

---
Tags: 7
---


# Question
Title: How I do I remove the User menu from the top right corner?
How would I go about removing the "User menu" from being displayed in the top right corner of the site when logged in? It is set to display "None" in the block, yet it seems to be up there by default.

Other than using CSS to hide it, what is the recommended way to remove these links? I've got the login/logout links in my footer instead.

# Answer
In admin/structure/menu/settings, you select which is the source for the Main links, and the Secondary links.

By default, the source for the Secondary links is the User menu; if you set it to *No Secondary links*, or another menu, the user links will disappear from the page.
> 1 votes

---
Tags: routes
---


# Question
Title: How can I edit all nodes of thier dates at once?
Is there a module that allows me to change the dates of all nodes at once instead of doing it one by one thanks.

# Answer
In this case, you could update the field in the db, much faster than node\_loading and saving all the nodes with batch update etc.. backup db first.

Fields are:

```
node.created
node.changed
node_revision.timestamp (same as node changed)

```

e.g

```
$created = strtotime('2013-01-01 00:00:00');
$changed = REQUEST_TIME; // now

$query = db_update('node');
$query->fields(array('created' => $created, 'changed' => $changed));
$updated = $query->execute();

$query = db_update('node_revision');
$query->fields(array('timestamp' => $changed));
$updated = $query->execute();

drupal_flush_all_caches(); // clear cache

```
> 1 votes

---
Tags: nodes, datetime
---


title: Zen theme not compatible with IE8?

text:
# Question
Title: Zen theme not compatible with IE8?
I am using a zen theme, the default styles and template and while the Main content displays correctly in Firefox, it is all the way to the left in IE.

In firefox, Navigation menu on top, sidebar on the left, main content on the right. In IE, Main content area on top, with navigation menu underneath and sidebar first underneat that. All left align...

What am I missing?

I just overrode all the css and everything and it is still displaying the same...

# Answer
> 1 votes
"I fixed the issue by setting the bandwidth optimization to: Aggregate and compress CSS files." said kine456. kine456 answered his own question.

This is because js files like respond.js that comes with the zen theme must get applied after you aggregate the css files for it to look correctly in ie8. I'm pretty sure its documented in the theme's readme.

# Answer
> 0 votes
You can also submit your issues directly to zen here http://drupal.org/project/issues/zen Also, Here is Project Information

```
Maintenance status: Actively maintained http://drupal.org/taxonomy/term/13028
Development status: Under active development http://drupal.org/taxonomy/term/9988
Reported installs: 103049 sites currently report using this theme. View usage statistics.
Downloads: 863,783

```

There should be a news feed to tell you when zen will be adding new features and compabaitabliy...but i cant find it. sorry.

# Answer
> -1 votes
you problems solved by just using the powerful omega theme: drupal.org/project/omega -- version 4 is out...

---
Tags: theming
---


# Question
Title: Contact form - leaving the form and resuming it later
Is it possible to have a contact form in drupal, which you can save, and resume later?

# Answer
> 2 votes
Yes, you can build a contact form with the Webform module and use its "Save Draft" feature.

---
Tags: views, 7, forms, emails
---


# Question
Title: Would like to remove welcome message from frontpage
> **Possible Duplicate:**
> Removing the “No front page content has been created yet.” message from the front page

I am using the Zen theme and don't wan't any "nodes" on my homepage. I've got menus and blocks, but not nodes as such. I don't want the "No front page content has been created yet" text to appear. What is the best way to get rid of it?

I've currently only got one template that I'm using. page.tpl.php

```
drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);

$default_message = '<p>' . t('No front page content has been created yet.') . '</p>';

```

# Answer
> 0 votes
If you add a node, publish and check "promote to front page" the "No front page content" message will disappear, even if the node isn't shown at all.

See node\_page\_default for the logic there.

Alternatively, you could look into use hook\_page\_alter to remove the `$build['default_message']`

---
Tags: nodes
---


# Question
Title: Adding form elements via ajax; input not stored in $form_state['values']
I am trying to add a date, start time, end time to a form - the user can add as many 'rows' as necessary. The form fields are being added to the form correctly, and the $form\_state\['input'\] is showing the correct values that were input on the form. However, the $form\_state\['values'\] is only showing the last one, e.g. if I add three (bringing the total to 4) it only includes the last value.

Relevant code in the form builder:

```
$num_dates = !isset($form_state['num_dates']) ? 1 : $form_state['num_dates'];
$form_state['num_dates'] = $num_dates;
$form['date']['#prefix'] = '<div id="form-date-wrapper">';
$form['date']['#suffix'] = '</div><!-- /#form-date-wrapper -->';
for ($i = 1; $i <= $num_dates; $i ++)
{
  $form['date']['calendar_date' . $num_dates] = array(
    '#title' => 'Date',
      '#type' => 'textfield',
      '#maxlength' => 15,
      '#attributes' => array('class' => array('calendar-date')),
      '#prefix' => '<div class="form-date-entry-wrapper form-row form-row-single-item">',
  );
  $form['date']['event_start_time' . $num_dates] = array(
  '#title' => 'Start Time',
      '#type' => 'select',
      '#options' => drupal_map_assoc(array(t('9:00 AM'), t('9:15 AM'))),
      '#attributes' => array('class' => array('calendar-date-times')),
  );
  $form['date']['event_end_time' . $num_dates] = array(
  '#title' => 'End Time',
      '#type' => 'select',
      '#options' => drupal_map_assoc(array(t('9:00 AM'), t('9:15 AM'))),
      '#suffix' => '</div> <!-- /form-date-entry-wrapper -->',
      '#attributes' => array('class' => array('calendar-date-times')),
  );
}
$form['add_another_date_time'] = array(
  '#type' => 'submit',
    '#title' => 'Add Another Date/Time',
    '#value' => 'Add Another Date/Time',
    '#limit_validation_errors' => array(),
    '#attributes' => array('class' => array('look-like-text-button')),
    '#submit' => array('exhibitorevents_form_add_date_time_submit'),
    '#ajax' => array(
      'callback' => 'exhibitorevents_form_add_date_time',
        'wrapper' => 'form-date-wrapper',
        'method' => 'append',
        'effect' => 'fade',
    ),
);
    $form['submit'] = array(
  '#title' => 'Submit',
  '#type' => 'submit',
  '#value' => 'submit',
  '#weight' => 100,
);

```

And the callback functions:

```
/**
 * Ajax callback for add more dates/times
 */
function exhibitorevents_form_add_date_time($form, $form_state) {
  return $form['date'];
}
/**
 * Submit handler for add more dates/times button
 *
 * Increments num_dates +1
 */
 function exhibitorevents_form_add_date_time_submit($form, &$form_state) {
   $form_state['num_dates']++;
   $form_state['rebuild'] = TRUE;
 }

```

I have added the $form\_state\['input'\] & $form\_state\['values'\] array here: http://pastebin.com/nL3DWHm8 for reference. This particular example, I added one date 'row', making 2 total.

# Answer
> 1 votes
You should add the $form\['#tree'\] so that all the values are passed.

---
Tags: 7, ajax
---


title: Can I upload Flash (swf) to drupal 7?

text:
# Question
Title: Can I upload Flash (swf) to drupal 7?
http://drupal.org/project/flashnode The module that I found only works for drupal 6. Is there a module for drupal 7?

Also, there seems to be no tag label called Flash... Maybe an advance user would want to add that?

# Answer
A Google search for *add flash to drupal 7* gives the SWF Embed module as the first result.

You could also look at the Media suite of modules, which can give you a much more user friendly interface at the expense of some additional time invested in figuring out which of the modules you need.
> 1 votes

---
Tags: files
---


# Question
Title: How do I in Drupal 7 hook into the status message update area after saving a node and it says "updated node" to be a link to that node
In Drupal 7, after saving a node it redirects you back to the page of the node with the message status saying "blog 'title of blog' has been updated".

How do I turn that status message into the link of that node? I need to do this since I have rules setup where I have it redirect to another part of my site, and it just shows the status message of that node being updated. I just need that clickable. im assuming it would be a hook somewhere hook node save?

# Answer
> 1 votes
You can use hook\_node\_update() that responds to node updates. There you can add the link in drupal\_set\_message().

However you may get two status messages, a default status message and another the custom message you just created. For removing the default message you can use Disable Messages module.

# Answer
> 0 votes
Since you're using Rules, you could add a reaction rule "*After saving content*" and use a "*Display message on site*" action to add your own message, e.g add a link using the node tokens available there. Configurable, and no code required.

---
Tags: nodes
---


title: Extra include files for hooks

text:
# Question
Title: Extra include files for hooks
I'd like to organize a .module file better by putting related hooks in other .inc files. So for example, I'd like to take a bunch of imagecache preset definitions (via `hook_imagecache_default_presets`) out of custom.module and put them in custom.imagecache.inc.

Where in custom.module should I include custom.imagecache.inc? I assume I'll be using `module_load_include()`?

If I put it in a `hook_init` wouldn't that include these hook definitions on every page request?

# Answer
> 6 votes
I'm pretty sure you have to put the hooks in the .module file. But what you can then do is call `module_load_include()` from within the hook function, and use the hook function itself as a wrapper.

So:

```
mymodule_hookfunction($arg) {
  module_load_include('inc', 'mymodule', 'includefile');
  return mymodule_function_that_is_in_the_include_file($arg);
}

```

This has the benefit of only loading the include file if the hook gets called.

NOTE: The answer really is `hook_hook_info()`, not this one.

# Answer
> 8 votes
Current answer is not 100% correct for Drupal 7. In Drupal 7 there is a hook called hook\_hook\_info. In core this is implemented with the token module via system\_hook\_info. That means that for tokens the hook can be located inside of module\_name.tokens.inc. So yes you can put hooks in related files by groups. Just remember that hook\_hook\_info must be inside of your .module file.

An example using blocks

```
<?php
/**
 * Implements hook_hook_info().
 */
function mymodule_hook_info() {
  $hooks['block_configure'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_list_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_save'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view_alter'] = array(
    'group' => 'blocks',
  );

  return $hooks;
}
?>

```

You should be able to then use a mymodule.blocks.inc file to hold all your blocks information as long at the above code/hook is inside of your .module file.

# Answer
> 3 votes
I would just take the simplier approach and add something like:

```
include_once dirname(__FILE__) . '/custom.imagecache.inc';

```

at the beginning of my custom.module file.

---
Tags: hooks
---


# Question
Title: My Superfish menu is being repeated 4 times. Why?
My superfish menu is being displayed 4 times. In the header. I originally selected 4 from the dropdown menu, but have since changed it to 1. Even after clearing the cache, the menu is being repeated 4 times. How do I fix this?

# Answer
> 0 votes
Fixed. I did all sorts of things but it looks like it was just being cached.

---
Tags: navigation
---


# Question
Title: Problem with jquery or jquery ui (animating color)
I have found a jquery code which animates colors. I made a fiddle from it (after minor change), and it's working perfectly on jsfiddle: http://jsfiddle.net/kFuzp/

Unfortunately, it's not working on my Drupal site. I have JQuery Update module and updated to 1.8, using jQuery CDN. The code (as in jsfiddle) is inserted using `drupal_add_js ($script1, 'inline')` in `mytheme_preprocess_page()`. When I debug the code in Chrome, it just runs (I can observe how the color\_index changes etc using breakpoints). But the `<p>` background color is always white.

By the way, when I change the animation property to `{ opacity: color_index/7 }` then the opacity animation is working (slowly) both in jsfiddle and in Drupal.

Why it's not working in Drupal and how to fix it?

# Answer
I was also having the same problem once, I was doing an animation in color change. It was not working for me in Drupal, however for some reason I do not know the color change animation was working when I was logged in as administrator(with admin\_menu installed), while as authenticated and anonymous user it was not working.

I used jQuery.Color() plugin and it worked for me. Its written in jQuery.animate() documentation:

> All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

Hope that helps!
> 0 votes

# Answer
It sounds like you're having a problem with your jQuery selector.

Are you using changing the properties for all paragraphs? Or just a particular one? Or a class?

Below are the selectors for each option respectively:

```
$("p")...

$("p#theIdofTheParagraph")...

$("p.theClassofTheParagraphs")...

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to retrieve form entry for use as default value?
I'm building a form in a custom module, and I'd like to have that form show as it's default value the value that had been saved to the DB during the previous edit, but I have no idea how to do it.

Here is an example of one of my fields:

```
$form['savings_ages']['savings_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => $whatgoeshere?,
);

```

My form is the basis for a calculator, so I've got over 80 fields and only ever expect to have 1 row's worth of information in my table.

I have no idea how to pull that out, so any guidance would be welcome. PLease let me know if I need to provide more detail.

EDIT: I'm still stuck on this, my normal query works when I test in the sql window of PHPmyadmin:

```
SELECT `factors_age21` FROM `savingfactors` WHERE 1 limit 1

```

but I can't seem to convert it to the correct format to work with db\_query function and echo it out as the default value of my form field. PLus I'll still have to make this query 44 times (I have 44 columns) so if there is a more efficient way, I'd appreciate it.

Second Edit: I'm starting to get a partial result, but it's still wrong.

```
$sql = "SELECT factors_age21 FROM {savingfactors} WHERE factors_age21 LIMIT 1";
$res = db_query($sql);
$item = db_fetch_object($res);

//later
$form['savings_factors']['factors_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => print $item,
);

```

It IS producing a result, but it's showing me the number "1", when my correct value is "14" any help is appreciated.

Thanks Stephanie

# Answer
```
$form['savings_ages']['savings_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => $whatgoeshere?,
);

```

I guess `$form['savings_ages']` is a fieldset. If so, then you can use the following code to get the default value that was saved in database during previous edit.

**Explanation**

When you save a form, a variable gets created with the id that you use to create form element. In your case `variable_get('savings_age21', '')` will fetch the previously saved value.

Documentation variable\_get

**Edit**

```
$form['savings_ages']['savings_age21'] = array(
    '#type' => 'textfield',
    '#title' => t('21'),
    '#size' => 10,
    '#maxlength' => 10,
    '#default_value' => variable_get('savings_age21', ''),
);

return system_settings_form($form);

```

Sorry, I forgot about system\_settings\_form($form), this way when you save the form a variable with id of form element will get created, later you can retrieve it using `variable_get()`.

If you do not wish to use `system_settings_form($form)`, then you can use variable\_set() to save a variable with any name. You have to do this `variable_set()` inside the submit handler of the form. Later while displaying the form, use the same logic `variable_get()` to retrieve the variable.
> 2 votes

# Answer
Perhaps something like:

```
// Query for default value
global $user;
$savings_age21 = db_query("SELECT savings_age21 FROM {my_table} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();

$form['savings_ages']['savings_age21'] = array(
  '#type' => 'textfield',
  '#title' => t('21'),
  '#size' => 10,
  '#maxlength' => 10,
  '#default_value' => $savings_age21,
);

```

Or else you could load the row, assuming one row per user:

```
global $user;
$record = db_query("SELECT * FROM {my_table} WHERE uid = :uid LIMIT 1", array(':uid' => $user->uid))->fetchObject();
// later on ...
$form['savings_ages']['savings_age21'] = array(
  '#type' => 'textfield',
  '#title' => t('21'),
  '#size' => 10,
  '#maxlength' => 10,
  '#default_value' => $record->savings_age21,
);

```
> 1 votes

---
Tags: 6, forms, database
---


# Question
Title: How to display "About the author" tab in article display page?
I want to basically override the normal display of article, to include two tabs in that. One tab will be "Read Article", which when clicks loads the article page. Others tab will be "About the Author", which when clicks loads the author page.

So ultimately when I go to any article page, there will be two tabs, "Read Aricle" (selected by default), and "About the author".

Please suggest how can I achieve this. I have tried overriding node display by using Panels, but I am not able to add links or display author information in another tab.

-- Thanks for your time.

# Answer
> 1 votes
There is Author Pane

> Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.

For the tabbed view you cold try Quick Tabs

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*.

---
Tags: 7, nodes
---


title: How to populate the sitemap?

text:
# Question
Title: How to populate the sitemap?
I would like to generate a sitemap using the Site Map module.

I've enabled some menus to show up. But how do I change the order of the information displayed? Also, I don't want Menu titles to be displayed in the sitemap. How would I go about populating the sitemap?

# Answer
> 1 votes
If you are using the XML Sitemap module, the most popular sitemap module on Drupal.org, you don't actually need to populate the sitemap yourself. Instead, you simply configure what you want to appear on the sitemap, and then the sitemap is automatically generated when cron runs.

Here's how to set up a sitemap on Drupal 7.

1. Install and enable XML sitemap.
2. Go to /admin/config/search/xmlsitemap and add a sitemap (you only need to add one if your site only has one language; if you have multiple languages, you can add a sitemap for each language).
3. Navigate to the items you want to add to the sitemap. If your items are all contained on menus, the easiest way to do this is to go to the "edit menu" page for each menu, scroll down to the XML sitemap options, and make sure the menu is set to be included.
4. Wait for cron to run or manually run cron yourself. You can then go back to the XML sitemap configuration page (/admin/config/search/xmlsitemap) to confirm that the content was added properly.

If you need custom links, just click the "custom links" tab. Also, the "search engines" tab allows you to automatically submit the sitemap to Google and Bing, which is a pretty useful feature.

---
Tags: 7
---


# Question
Title: If I don't see the "Full HTML" and "Filtered HTML" input formats, is it OK to add them manually?
I currently only have a "plain text" format. Is it ok for me to add additional "Text formats" on the "Configuration" screen? Eg. Full html, filtered html etc?

Or should these have been created automatically when I installed the ckeditor and IMCE modules?

# Answer
> 1 votes
By default, Drupal 7 includes `plain text`, `filtered HTML`, and `full HTML` text formats.

If you are not seeing these as choices, you are probably not logged in as an administrator and you do not have the appropriate permissions.

Non-administrators are not given access to `full HTML` by default because this can be a security risk.

Try logging in as an administrator and going to the permissions management page. Verify the permissions for `Use the Filtered HTML text format` etc. under **Filters**.

Of course, if you need an input filter with a custom configuration, you can certainly create your own. Just be careful to not give your users any input options they shouldn't have.

---
Tags: wysiwyg, files
---


title: update field value

text:
# Question
Title: update field value
how to update a field value of one content type node when a field value of another content type is changed using hook\_node\_presave?

for eg: content type | field name | field value | updated value

```
       product      | product_stock |      10     |     24
       Add stock    | stock value   |      14     |

```

# Answer
> 0 votes
* First of all you need to link the two nodes - check out this module - http://drupal.org/project/references. It provides a field (add to one content type) that stores reference (of another reference type) ie. the nid
* So 2 nodes will now be connected.
* Next, in your hook\_node\_update check when node of the first content type is updated - get the nid of the related node from its node reference field =\> node\_load(nid) =\> change whatever value you want =\> node\_save(nid).

Hope this wokrs for you. All the best!

---
Tags: entities, hooks
---


# Question
Title: How to differentiate token replacement from array index
How to escape left square bracket - \[ and Right square bracket - \] when used in views so that it is not mistaken for a token.

I have what I hope is a simple question to answer. I have tried searching online but have been unable to find an answer (perhaps using the wrong search terms - I don't know). I am using Drupal 7 with views and the fillPDF module. I have modified one of the outputs of my view to use token replacement. The issue I am having is that the string that is being used for the token replacement has an array with an index that is the same as the token. Here is the code:

```
<a href="/fillpdf?fid=33&webform[nid]=[nid]&webform[sid]=[sid]">Create a PDF</a>

```

As you can see, I need away to make sure webform\[nid\] and webform\[sid\] doesn't become webform1 and webform2 after token replacement. How do I accomplish this? There must be a way to escape the array.

Thanks.

# Answer
> 1 votes
You can escape the left square bracket - \[ using - %5B
and Right Square Bracket - \] using - %5D

So you should change your code in question to the following.

```
<a href="/fillpdf?fid=33&webform%5Bnid%5D=[nid]&webform%5Bsid%5D=[sid]">Create a PDF</a>

```

---
Tags: 7, tokens
---


# Question
Title: How to link Images of one node to other node?
I've created a content type of image.

I am using a view to display the images on the homepage. I would like each of the three images to link to existing pages/nodes (not the nodes of images themselves).

I want to link images of node `a` to node `b` is that possible ?

How would I go about doing this?

# Answer
> 3 votes
Whichever way you look at it I would say that these images should be a field on the entity that they are linking to ( you are going to have a validation nightmare having a multiple image field and an entity reference field that can't be forced to have x number of values easily ). The easiest way to then render these would be to use the views module, create a block displaying fields and selecting he image field and clicking the box to link the image to the original piece of content. You can also have a filter to select only entities where this field is filled.

In reality though a better approach would be to create a menu ( this is what you are doing after all ) and put in the images using css. example:

```
#block-system-main-menu li a {
  display:block;
  width:100px;
  height:100px;
  background-repeat:no-repeat;
}
#block-system-main-menu li:nth-child(1) a {
  background-image:url('../images/icon_1.png');
}
#block-system-main-menu li:nth-child(2) a {
  background-image:url('../images/icon_2.png');
}

```

# Answer
> 0 votes
If its in a view you can do something like this.

Or in the default content type display settings you can try

---
Tags: views
---


# Question
Title: Import latitude and longitude from XML to Location field for GMap, for Views display
From my XML data which I have imported into nodes, I have CCK fields for Latitude and Longitude. I want to import those values into Node Location so that I can have two Gmap integrations:

* Show a GMap on each node to show where it is located
* Show all matched locations on a Views page with an exposed form

Is there something I have to do with mapping the fields correctly inside of Migrate, and if so, how would I define the Location fields as destination fields? I also found this on Migrate Extras that seems to have integrated it with Location, but that was for D7.

Then, how do I integrate the GMap with my Views page and get items to filter correctly?

# Answer
> 0 votes
What I did was I just made two CCK fields for latitude and longitude. I used the function gmap\_simple\_map to create a map in my nodes, code placed in the node tempalte file.

Then, in Views, I made a block attachment that was a GMap and chose those CCK fields (which must be defined under fields) as my latitude and longitude.

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


title: Get the referenced node ID

text:
# Question
Title: Get the referenced node ID
I have a content type (a) referenced to another content type (b) by url widget, how can I get the ID of the referenced node (b)?
Thanks.

# Answer
You can get node id using :

```
$nid = $node->field_reference['und'][0]['nid'];

```

And you can check it out from this:

```
drupal_set_message($nid);

```
> 4 votes

---
Tags: nodes
---


# Question
Title: Possible explanation for error and site crashing randomly without any provocation?
I have a multilingual client that "suddenly and randomly" started suffering errors and a site crash.

The client assured us they "have not touched the site since it went live." And, more or less we can confirm that given that we have not updated the site on their behalf, as we are the the only ones with update privilages.

Has anyone had their multilingual site "just randomly crash" after months of being live with no problem?

This is the error message. Has anyone seen this before?

> WD php: PDOException: SQLSTATE\[42S22\]: Column not found:
> 1054 Unknown column 'ml.language' in 'where clause':
>
> ```
> SELECT ml.*, m.*, ml.weight AS link_weight FROM {menu_links} ml
> LEFT OUTER JOIN {menu_router} m ON m.path = ml.router_path
> WHERE  (ml.menu_name IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3,:db_condition_placeholder_4)) AND (ml.link_path IN (:db_condition_placeholder_5)) AND (ml.language IN (:db_condition_placeholder_6, :db_condition_placeholder_7));
> Array (
>   [:db_condition_placeholder_0] => 1cf698d64d1aa4b83907cf6ed55db3a7f8e92c91
>   [:db_condition_placeholder_1] => navigation
>   [:db_condition_placeholder_2] => management
>   [:db_condition_placeholder_3] => user-menu
>   [:db_condition_placeholder_4] => main-menu
>   [:db_condition_placeholder_5] => node
>   [:db_condition_placeholder_6] => und
>   [:db_condition_placeholder_7] => ja
> )
>
> ```
>
> in i18n\_menu\_init() (line 829 of sites/all/modules/i18n/i18n\_menu/i18n\_menu.module).

# Answer
Make sure the **i18n\_menu** module is enabled,

e.g:

```
drush en -y i18n_menu

```

i18n\_menu has i18n\_menu\_install to add that language field to the `menu_links` table on install, and an i18n\_menu\_uninstall to drop it on uninstall.
> 0 votes

---
Tags: 7, i18n-l10n, debugging
---


# Question
Title: Install module that has an external php script and a couple of other files
i want to develop a module that has some pdf modelling functionality. I have an external script I want to use and some javascript. i wonder what is the best solution to get a module working from the drupal install routine.

1.) Do i have to add my external script to the drupal library...and remove it when my module is deinstalled? 2.) Can you recommend some good tutorials to get started with install scripts?

Any hints are welcome...

Thanks

# Answer
You should use the Libraries module - it allows integration with external libraries and scripts.
This is the correct way of adding libraries and using third party scripts in Drupal. This way several modules can use the same library and same sources, which is better from maintenance and organization perspective.

You can define a dependency in your custom module using the `hook_libraries_info()` and then include the library when you need it with `libraries_load()`\`.

As an example, take a look at Colorbox to see how the hook is implemented there.

Check out also the Print module.

In your particular case, you will probably use TCPDF for generating PDFs, so you should define a library dependency like so:

```
/**
 * Implements hook_libraries_info().
 */
function YOUR_MODULE_libraries_info() {
  $libraries['tcpdf'] = array(
    'name' => 'TCPDF',
    'vendor' => 'http://www.tcpdf.org/',
    'download url' => 'http://sourceforge.net/projects/tcpdf/files/',
    'version callback' => 'YOUR_MODULE_tcpdf_version',
    'files' => array(
      'php' => array(
        'tcpdf.php',
      ),
    ),
  );

  return $libraries;
}

```

And when you need it, just call `libraries_load()`:

```
libraries_load('tcpdf');

```

Last thing - don't forget to add dependency for libraries in your module `.info` file.
> 3 votes

# Answer
The install routine is many used if your module has any update or addition to be done to the database. The module install would have three functions commonly

1. hook\_install function is used to execute any function when the module is being installed. This would be a good place to add content to the table you would be creating.
2. hook\_uninstall This would be used to undo any changed you make to database during your installation process and if needed delete the contents from tables that was created by your module.
3. hook\_schema This function is used to create a tables or make changes to existing tables to make your module work.

Adding Javascript files and other css files should be either done in the .info file or by using the drupal\_add\_js and drupal\_add\_css functions with in your module.

There is a great module for all new module developers to refer to understand module creation and different aspects of the drupal internals - The Example Module

If you are looking to add external code into Drupal then you should look at libraries module which enables you to add other libraries into drupal and make it play well with drupal
> 1 votes

---
Tags: installation
---


# Question
Title: how to do addition of two field values in drupal 7during node_presave?
I had made two content types content type 1 - 'product' with field name 'product\_stock' and content type 2 - 'Add stock' with field name 'stock\_value'. It also contains a node reference to product content type. I want to add the value of product stock and stock value during node\_presave.

For Example: product stock = 10 and stock value = 14, then both should be added to give 24.

# Answer
```
function my_module_node_presave($node){  // implementation of hook_node_presave
  if($node->type == 'add_stock') {
    $product = $node->field_stock_value['und'][0]['value']; //get data value of field
    drupal_set_message('product :'.$product); // print data value for checking
    $nid = $node->field_reference['und'][0]['nid']; //get nid of reference field
    drupal_set_message('nid :'.$nid); // print nid
    $p_node = node_load($nid); // implemenet node_load and get in $p_node
    $stock = $p_node->field_product_stock['und'][0]['value']; //get data value of field
    drupal_set_message('stock :'.$stock); // print value

    $stock = $product + $stock; // addition of both value
    drupal_set_message('Stock :'.$stock);
    $p_node->field_product_stock['und'][0]['value'] = $stock; // updating the product field with updated value
    node_save($p_node); // implement node_save
  }
}

```
> -1 votes

---
Tags: nodes, hooks
---


title: checkbox type in form

text:
# Question
Title: checkbox type in form
how i can knowing if the checkbox is checked or not on the form

```
function darksite_config_page() {
  $form['darksite_status'] = array(
    '#title' => t('Enable pop up screen'),
    '#description' => t('When enabled, a pop up screen will be displayed on the home page.'),
    '#type' => 'checkbox',
    '#default_value' => variable_get('darksite_status', 0)
  );

  return system_settings_form($form);
}

```

# Answer
Like so:

```
if (variable_get('darksite_status', 0)) {
  // Yes.
}
else {
  // No.
}

```
> 2 votes

---
Tags: 7, forms
---


title: Inspect $form from hook API

text:
# Question
Title: Inspect $form from hook API
How can I inspect the $form element from the hook\_node\_insert(`$node`, `$form`, `$form_value`).
I need to know how it construct.
I try with firephp `(dfb($form, 'form', FirePHP::LOG);)` with no success. Please help.

# Answer
> 3 votes
Install the devel module http://drupal.org/project/devel. In your code call `dpm($form);`

---
Tags: nodes, forms, hooks
---


# Question
Title: I can't get the SKU value for a commerce product in a rule action
I created a rule to be fired when a "New Commerce product is saved" Then I set a action to create a **Product Display** node and and another action to set the title for the **Product Display** to be the same as for the **new commerce product**. So far so good.

Now I need to create another action to set the field **product** of the **Product display** to be the same as the **Commerce product SKU**.

Here is the problem since I can not get this value. I tried to add a condition of the type "Entity has field" but it seems like the SKU vale is not a field at all.

How can I accomplish with this?

Code for the rule:

```
{ "rules_create_product_display" : {
    "LABEL" : "Create Product Display",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "commerce" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_product_insert" ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "product_display",
            "param_title" : "[commerce-product:title]",
            "param_author" : [ "commerce-product:creator" ]
          },
          "PROVIDE" : { "entity_created" : { "product_display_created" : "Created Product Display" } }
        }
      },
      { "entity_save" : { "data" : [ "product-display-created" ], "immediate" : 1 } },
      { "redirect" : { "url" : [ "product-display-created:edit-url" ] } },
      { "drupal_message" : { "message" : "Product display created. You can edit it at: [product-display-created:nid]" } }
    ]
  }
}

```

# Answer
In order to access the SKU for the product you must first use two conditions in your rule to assure that you are dealing with the right type, these are :

* Entity is of type `commerce-line-item`
* Entity has field `commerce_product`

Just as an example this Rule export applies a discount ( 5\_eur\_disc ) to a product with an SKU of *SKU-FOO-ITEM* after checking that the discount dates are current.

```
{ "commerce_discount_rule_discount_discount_per_sku" : {
    "LABEL" : "Discount per SKU",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [
      "commerce_discount_date",
      "rules",
      "commerce_discount",
      "commerce_product_reference"
    ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "commerce_discount_date_condition" : { "commerce_discount" : "5_eur_discount" } },
      { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-product:sku" ],
          "value" : "SKU-FOO-ITEM"
        }
      }
    ],
    "DO" : [
      { "commerce_discount_fixed_amount" : {
          "entity" : [ "commerce_line_item" ],
          "commerce_discount" : "5_eur_discount"
        }
      }
    ]
  }
}

```
> 1 votes

---
Tags: entities, rules, commerce
---


# Question
Title: Popup message showing content from a block
I have a block, and I want to display the content of that block into a popup message. This is my code.

```
function darksite_menu() {
  $items['admin/config/media/darksite'] = array(
    'title' => 'Pop up screen configuration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('darksite_config_page'),
    'access arguments' => array('adminster pop up dark screen'),
    'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

function darksite_config_page() {
  $form['darksite_status'] = array(
    '#title' => t('Enable pop up screen'),
    '#description' => t('When enabled, a pop up screen will be displayed on the home page.'),
    '#type' => 'checkbox',
    '#default_value' => variable_get('darksite_status', 0)
  );

  return system_settings_form($form);
}

function darksite_block_info() {
  $blocks['popup_dark_screen'] = array(
    'info' => t('Pop up Dark Screen')
  );

  return $blocks;
}

function darksite_block_view($delta = '') {
  switch ($delta) {
    case 'popup_dark_screen':
      $block['subject'] = t('Pop up Dark Screen');
      $block['content'] = get_darksite_popup();
  }

  return $block;
}

function get_darksite_popup() {
  $popup_message_parameters = array(
    'title' => t('Information'),
    'body' => t('You have completed the work'),
    'check_cookie' => TRUE,
  );
  if (variable_get('darksite_status', 0))
   {
  // if the check box is checked.
   popup_message_show_message($popup_message_parameters);
    }
}

```

The code does not work. I have installed the model of popup message, but it still doesn't work.

# Answer
You should not be printing `popup_message_show_message()`; it just includes all the necessary files and show your message. Just remove the `print` part and try that way.

```
function popup_message_show_message($popup_message_parameters) {
  drupal_add_js(array(
      'popup_message' => $popup_message_parameters
    ), 'setting');
  drupal_add_js('misc/jquery.cookie.js');
  drupal_add_js(drupal_get_path('module', 'popup_message') . '/js/popup.js');
  $default_style = drupal_get_path('module', 'popup_message') . '/styles/default/' . POPUP_MESSAGE_CSS_NAME;
  $style = variable_get('popup_message_style', $default_style);
  if (!file_exists($style)) {
    $style = $default_style;
  }
  drupal_add_css($style);
}

```

Also, never use `print_r()` directly. Either use this:

```
drupal_set_message('<pre>' . print_r($variable, TRUE) . '</pre>');

```

Or install Devel module and call the `dpm()` function this way: `dpm($variable)`. It will use Krumo to display all attributes / elements, which is times better for debugging and will not cause any errors as `print_r()`.
> 2 votes

---
Tags: blocks, javascript
---


# Question
Title: Custom field: users organized into departments
I'm building an intranet corporate site, and need to have users linked to departments. The easy way I see this to be done is to create a taxonomy vocabulary with list of departments, and then add custom field to user entity, linking it with corresponding department from departments vocabulary.

Now I want to add a "Person responsible" field to a custom content type (let's name it "Document"), which should be a list of users, organized by departments.

In future a need to use this field to control access to the document may arise.

---

So, the questions are:

1. Is my method to link users to departments good enough, or are there better ways? (as this is now in development, I can change everything painlessly).
2. What is the best way to make "Person responsible" field (a list of users, organized by departments).
3. Does all this play well with possible future access control needs?

# Answer
Add a "grouping" to the table settings if you want to group by department etc.

(You would probably want to hide the department field in this case.)

Using taxonomy for user-\>department relationship sounds fine, and use Views to make all your lists of users/departments (group by):

* Make a Vocabulary "Departments" and add some terms to it
* Make a Person content type
* Add a field to Person which is a taxonomy reference to the Department vocabulary
* Download and enable the entityreference module
* Modify the fields of the *Vocabulary* to add a field, which is an entity-reference to a Person node
* Call it Person Responsible
* Create some content to test with: Create some People, attach them to Departments, then edit the Departments (terms) to assign people responsible
* Download and enable the Views module
* Create a View of content, of type person. Add title+department fields
* Add a *relationship* to the view "Content: Department"
* Add the Person Responsible field to the view, using the relationship you just added

From discussion in IRC, I misunderstood the requirement around Document. It's simpler than described above. Just do:

* Create Department vocabulary; add some terms
* Create Person content type; add a taxonomy field referencing the Department vocabulary
* Create the Document content type; add an entity reference field referencing nodes of type Person
* Use Views to display, including "looking through" the entity reference
> 2 votes

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


# Question
Title: Reduce latency in loading a page in Drupal 6
I have activated cache in Drupal, and the Devel module.
The total time in all queries is less than one second, but the latency is 4.34 seconds.

Can anyone explain the latency? What happens during the latency time?

I am using IIS, Php 5.25, Wincache, and MyIsam.

# Answer
The database query time is just the database interaction, don't forget that PHP takes time to process its own logic.

If the majority of the page load time is outside the database you should install xhprof to actually profile your PHP functions individually to see where the damage is being done.

Basic tips for improving PHP performance - install a module like Cache Router to take caching out of the database and put it somewhere else like in memory or the file system.

Install APC or similar on your server to improve PHP performance.

Cache object load calls wherever possible, this is handled much more easily in D7 thanks to the Entity Cache module, but it is possible to do in D6. Persistent caching of node\_load() can really be your friend.

Avoid configuring your site to load a lot of tpl.php files on page loads - "fields" rendering mode in Views can do this.

Avoid "slow" core functions - some taxonomy functions can be very slow in D6, be aware that user\_load() is not even statically cached so it can be expensive if you call it a lot.

Avoid eval()'d code as it runs much slower as well as being a potential security risk - This is anything using the PHP input filter.

Disable all "UI" modules. If you're running a large number of modules it is very easy for one of them to be doing more than it "should" be, so you want to start whittling the total number down if possible. Unfortunately, modules smart enough to split their logic into "core" and "UI" often aren't the culprits for performance problems but it's worth doing anyway since it is so easy to do.

If it isn't PHP or the database that is slowing things down, your server could be under too much load and doesn't have the processing power to keep up with incoming requests. If you can process X number of requests per second and have 2\*X incoming requests then your pages will load about 1/2 as fast.

Make sure you have enough RAM to run your site comfortably, if your server starts "swapping" things can degrade very quickly.

Page Caching does *not* help at all for authenticated traffic, only anonymous traffic. Make sure that your block caching settings are correct for every custom block that you've created. It might be worth trying the auth cache module.

Unfortunately there are many, many ways to slow a site down so these tips are not really comprehensive. I used to have a bookmark to "56 tips" that you could basically review your site with and at least triple the speed but it was pulled offline at some point in the past couple of years :(

Also, you might want to try swapping to innoDB as the row-level locking can speed things up drastically over myISAM in some cases.
> 1 votes

---
Tags: 6, performance, debugging
---


# Question
Title: Is there a flag hook (flag module) which is called when a flagged node is saved?
I am using the flag module to flag content.

Say user A flags a node. When user B updates the node, I want to send a mail to the user A (who flagged the node - I know I can use the Notifications and Messaging module but I want to send a notification in another way).

Is there an hook called when a flagged node is saved? So I can tap in on that hook and then retrieve a list of all users who flagged the node?

Thanks!

Paul

# Answer
> ```
> Is there an hook called when a flagged node is saved ?
>
> ```

* No

However, you can use `hook_node_update` to trigger on a regular node save and check users who have flagged the current node ID.

You can also do most of the work without any coding using Rules, Views, Views Bulk Operations and obviously, Flag module.
> 5 votes

# Answer
I am using D6 and I use and implementation for the hook\_nodeapi and hook\_comment.

I am using a flag named follow. See the code below, maybe it can be of any help for someone.

This code returns a list of uids who have flagged the node which has changed (or has a new comment attached to it).

```
/**
 * Implementation of hook_nodeapi().
 */
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {

  switch ($op) {
    case 'update':
  // check if this node is flagged
  $flag_name = 'follow';
  $flag = flag_get_flag($flag_name);

  if($flag && $flag->is_flagged($node->nid)) {
     $list_uid = flag_get_content_flags(node, $node->nid, $flag_name, FALSE);
     $flags_by_uids = array();
     foreach($list_uid as $flags_by_uid)
     {
       $flags_by_uids[] = array($flags_by_uid->uid);
     }
  }
  break;
}
}
/**
 * Implementation of hook_comment().
 */
function MYMODULE_comment(&$a1, $op) {

  switch ($op) {
    case 'publish':
  // check if this node is flagged
  $flag_name = 'follow';
  $flag = flag_get_flag($flag_name);

  if($flag && $flag->is_flagged($a1[nid])) {
     $list_uid = flag_get_content_flags(node, $a1[nid], $flag_name, FALSE);
     $flags_by_uids = array();
     foreach($list_uid as $flags_by_uid)
     {
       $flags_by_uids[] = array($flags_by_uid->uid);
     }
  }
  break;
}
}

```
> 2 votes

---
Tags: flags
---


# Question
Title: What's the difference between global.css and default.css files in Omega theme?
I´m still testing the Omega theme, and trying to get its templates and css files to work out for me. I´ve already read at the documentation and issues´ replies at Drupal forums.

They say:

> Think of global as the 'mobile first' template and this this is where most of your css will go.

Ok, so for mobile I use only global.css and for other resolutions I use all the other templates.

> The default template is for desktop resolutions where the css is different for that of mobile. The remaining templates are really just for exceptions and other values to address scaling up to wider resolutions.

This is what confuses me, because the other css files are narrow, normal and wide. So I think narrow should be for 7" screens, normal for 10" screens and wide for all the other, bigger screens (usually the desktop). **So where fits default template?**

> Try resizing your browser window to see the changes between layouts.

I´ve tried that, setting just a line of code in every css file, determinig different body background colors for each case. global.css showed on the mobile screen. global.css showed on the 7" tablet on portrait mode. narrow.css showed on the 7" tablet in landscape mode. normal.css showed on the 10" netbook. wide.css showed on the 19" desktop screen.

The color that I´ve set at the default.css file didn´t showed. I´ve took mozilla firefox and resized the browser manually, and all the other templates showed just fine, **but default settings never appeared**.

I´ve asked this at Drupal community forums, but I would like to know what you think about this. Thanks!

# Answer
> 4 votes
Ok, this is really one of the confusing aspects of Omega. Once you grasp it, though, it does make life easier.

The full explanation is found in the Omega Theme Documentation Handbook under How CSS works in Omega - "Ogres are like Onions... They have LAYERS".

global.css applies to all layouts (hence the name). Since they apply to all layouts, this is the mobile-first sheet.

mytheme-alpha-default.css applies to all of the non-mobile layouts, which is when the grids kick in.

Then the narrow, normal, and wide sheets stack depending on which breakpoint you are on.

So if you are mobile, you just get global.css

Narrow, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css

Normal, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css

Wide, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css + mytheme-alpha-wide.css

The best way to think about this is (in order):

1. How does my site need to look on mobile? Make global.css
2. How do things change when the grid system kicks in? Make mytheme-alpha-default.css
3. How does my site look when I am on a portrait table? Make mytheme-alpha-narrow.css
4. How do things change when I am on a normal desktop? Make mytheme-alpha-normal.css
5. How do things change when I am on a widescreen monitor? Make mytheme-alpha-wide.css

In other words, don't think of this as four different layouts; think of it as a base layout that you apply changes to as you get wider.

---
Tags: theming
---


# Question
Title: How to get "configure" icons next to each block back?
My configure icons have disapeared. How do I get them back?

# Answer
> 1 votes
If you are referring to the gear icon that appears when you hover the mouse over a block, that is output from the Contextual links module that comes with Drupal core.

The same module adds contextual links to other parts of a page, such as a node.

It also handle the gear icon that you see in the page to edit a view.

---
Tags: blocks
---


# Question
Title: How to add content filter into a content page(not in a view)?
So I'm totally new with the drupal and try to wrap things around my head, which is quite overhelming at first, so my question might be a simple one for pro's.

I'm building Property Listings site where users could submit their own listings, add comments and search and view Property Listings sorted by location, type, price and etc.

So when you search the site on the Search Bar it gives you a page with all the relevant content. For example: If i search for 2bed flats at around 50k they open a page with url defined in taxonomy term"around50k". And now, i have no idea what to do to **add a filter** for "Location" on that page.

I could make the whole new page with a view for that exact type of listings and add whatever filters i want, however as there a hundreds of categories it would be a nightmare.

I know i could add more filters to a search bar, however i will have all Property Type menu on the site and i need **location* and price\* filters for each page on that menu.

Is there any functions that would create filters for content on pages or any other solution to this problem?

# Answer
You probably want to add the Panels module. There's an excellent series of screencasts on Panels/Page Manager at NodeOne.

Basically, you can use Panels and Page Manager to override paths on your site. For example, you can override all taxonomy terms. You can break this down however you like, such as "all taxonomy terms," "all taxonomy terms from a specific category," "one specific taxonomy term," "users with this role on a taxonomy term in this vocabulary," etc. Then you can create *Variants*, which are page layouts that dictate how the content should be formatted.

Using Panels, you can take the views you make and stick them wherever you like on the site. It will certainly take some time to learn how to set this up, but learning how views and panels work together will allow you to create very complicated sites with little duplication and certainly no "hundreds of pages" created manually.
> 1 votes

# Answer
Looks like you need to look into the search\_api Module

> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc. Also, with the Apache Solr integration, a high-performance search engine is available for this module. Developers, on the other hand, will be impressed by the large flexibility and numerous ways of extension the module provides. Hence, the growing number of additional contrib modules (linked below), providing additional functionality or helping users customize some aspects of the search process.
> -1 votes

---
Tags: views, nodes
---


title: show same slideshow on different sites

text:
# Question
Title: show same slideshow on different sites
how to show the same slideshow view on different sites but with different images - I have multiple sites which needs to show the same slideshow with different images. Can anyone explain how to go about this. I am relatively new to drupal and I have already setup the slidehow view / cycle module and created slideshow view and slideshow content type for one of the site and its working al good. Now I want to replicate the same on the other site (all the themes and the templates and css are the same its basically white labelling) but just use different images.

# Answer
> 2 votes
You should try the features module

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.
>
> Examples of features might be:
>
> * A blog
> * A pressroom
> * An image gallery
> * An e-commerce t-shirt store

# Answer
> 1 votes
I agree with the Features module recommendation, but if Features is too complicated or you don't have access to Drush, you can do the following.

1. Install the modules on the second site.
2. Make sure all the content types you use in the slideshow have the same names on both sites.
3. Export the view on the site with the slideshow. You can do this by going to the page that lists all your views, clicking the little triangle next to the view, and choosing "export view." Copy this code.
4. On the site that doesn't have the view yet, go to the views listing page and choose "import view." Paste the code you copied in #3.

Features will automate all of this into a single step, but if this is something you're only going to do once or need to do right away, the above approach may be faster.

---
Tags: features, views
---


# Question
Title: Views - offset when displaying all results?
In a view, either set to "display all results" or "specified number of results" and set to 0, I cannot seem to be able to use the "offset". On the other hand, if I set a number of items, say 100, I can use the offset just fine (I want to hide the first item from the result set). Any ideas on what could be causing this?

# Answer
I'm pretty sure that's the way it's designed. If you set the number of things to be displayed to `display all results` or `0` (which is the same thing), it doesn't make sense to have an offset because you already ordered it to show every single result.

If you want to use an offset, set a specified number of results. If you don't know what number to set, just pick an arbitrarily high number that you are unlikely to exceed.

**EDIT**: If you just want to hide the first item, is there some way to configure one of the filters so that the item is removed? That is another possible approach.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Clean way of building simple taxonomy browser of arbitrary depth
I have spent days trying to determine a clean way to do the following:

1. Display a list of all top-level terms in a vocabulary with links to their child terms
2. Upon clicking a link, be taken to a list of the children of *those* terms.
3. Ad infinitum until the lowest-level term, for which a list of nodes tagged with that term will be displayed.

This seems like it would be pretty commonly-needed functionality but I can't find any solution that can handle arbitrary depth, particularly if not all term trees descend to the same depth.

An ideal solution would be one that uses Views 3, Contexts, EntityFieldQueries, or anything else that's well-supported in Drupal 7.

I'm able to do *almost* exactly what I want by making a simple view with three node:term relationships (term, term's parent, and term's parent's parent) and user those for sequential contextual filters. The only problem with this is that if there's a node with a termpath of too little depth, it gets listed as "uncategorized" and generates a dead link. Instead of doing that I'd like it to link to the next child term available.

# Answer
> 23 votes
I figured out a way to do this with only the Views module. It's not perfect — it doesn't generate a nice URL and breadcrumb with the taxonomy lineage the way that my solution for a taxonomy of a single depth would do.

## Static Depth Browser

For a taxonomy of static depth (where all terms have the same depth of child terms), you would do the following:

1. Create a view of **nodes**
2. Add relationship to taxonomy term (Term)
3. Add relationship to taxonomy term parent, accessible via Term (Parent)
4. Add relationship to taxonomy term parent, accessible via Parent (Parent Parent)
5. Repeat step 4 as many times as necessary for your taxonomy's depth.
6. Add contextual filters for each one and make sure they're in the proper order. Set to display a summary when filter is not in URL.
7. You'll probably want to override the breadcrumb and title for each filter.
8. ???
9. PROFIT

## Variable Depth Browser

For a taxonomy of variable depth (where some term trees have deeper levels of nesting than others), it's a bit more complex:

1. Add a new top-level term (Foo) to your vocabulary and put all other terms under it.
2. Create a view of **terms** with a page that displays term names
3. Add contextual filter: Taxonomy term: Parent term
4. When the default value is not in the URL, provide default value
5. Set default value to your top-level term name (Foo)
6. Specify validation criteria
    * Validator: taxonomy term
    * Criteria: your vocabulary name
    * Filter value type: Term name converted to term ID
7. Click the "+Add" button at the top of the Views panel to add an Attachment to the view.
8. Add to this attachment only (override) Relationship: Taxonomy term: Content with term
9. Add to this attachment only (override) display: fields: node titles linked to nodes, and remove (from this attachment only!) display: fields: term name
10. Add to this attachment only (override) contextual filter: Taxonomy term: Name
11. When filter value is not available, provide default value: Raw value from URL: Path component: 2 (or more if your Page path has \>1 component)
12. Attachment settings: Attach to: \[name of the page display you just made\]
13. ???
14. PROFIT

Screenshots of Views' UI for reference:

# Answer
> 8 votes
1. Create a view of the type Taxonomy
2. Add a contextual filter of the type **Taxonomy term: Parent term**
3. Set **Provide default value** and keep it as fixed. give the Term ID of the top Parent term
4. Add **Taxonomy term ID** as field and Exclude it from display
5. Add a **Taxonomy Term Name** click on out put this field as a link; give the link as "path-you-set-in-view/\[tid\]"
**Note :** You should uncheck "Link this field to its taxonomy term page"

When you visit the view page you would see the children of the top parent; as per the example you would get:

* term1
* term2

When you click on term1 you would get the children. Until you reach term1.1.1. You wont get any result if you click on term1.1.1 yet. To achieve that we need to create one more view block in the above view.

1. Add a Block
2. Remove the existing contextual filter and field
**Note :** When you remove them make sure you select the **This Page (Over Ride)** from the drop down at the top next to **For** other wise the fields and contextual filters you created in the page would also be gone.
3. Add a new contextual filter **Taxonomy term: Term ID**
4. Add a relationship **Taxonomy term: Content with term**
5. Add the **Content Title** and you use the relationship from the drop down at the top.
6. Save the view and go back to the Page we create (This is important other wise you would not be able to complete the next step
7. Add a field in the **FOOTER** OR **HEADER**
8. Select "Global: View area" from the list and select the block we created from the drop down **View to insert** while you are there check **Inherit contextual filters** so that we can pass the value from this view to the block as well
9. Check **Display even if view has no result** so that when this view does not show the result the block would still be shown

Save the view, and you are done.

# Answer
> 3 votes
I think what you're wanting is Views Tree, a contrib module that uses Views to construct a tree of taxonomy terms.

(Give me a second and I'll write a quick how-to on using it view tax fields)

Apparently that module has an issue preventing it from working with taxonomy terms. Boo.

That said, I found the following code which seems to do what you're wanting (you can make it display/hide elements through some pretty rudimentary jQuery code):

```
<?php

// The ID of the taxonomy vocabulary for which you'd like to create a nested list
$vid = 10;

$depth = 0;
$num_at_depth = 0;
$tree = taxonomy_get_tree($vid);

print "<ul class=\"menu\">\n<li>";
foreach ($tree as $term) {
  $diffdepth = 0;
  if ($term->depth > $depth) {
    print "\n<ul>\n<li>";
    $depth = $term->depth;
    $num_at_depth = 0;
  }
  if ($term->depth < $depth) {
    $diffdepth = $depth - $term->depth;
    while ($diffdepth > 0) {
      print "</li>\n</ul>\n";
      $diffdepth--;
    }
    $depth = $term->depth;
  }
  if (($term->depth == $depth) && ($num_at_depth > 0)) {
    print "</li>\n<li>";
  }
  print l($term->name, 'taxonomy/term/' . $term->tid);
  $num_at_depth++;
}
print "</li>\n</ul>\n";

```

Via "Nested category lists with links to pages".

# Answer
> 0 votes
If you just want to have a set of dynamic taxonomy-browsing pages, then I would go the following way, requiring 3 Views + Taxonomy Display module which allows you to use Views to display contents of `taxonomy/term/%` pages:

1. **Top Level Terms** \- list terms whose parent is null
2. **Mid Level Terms** \- list terms whose parent is NOT null. No result: display View #3
3. **Nodes with Terms** \- list nodes tagged with terms.

As Views 1 and 2 will probably be themed in a similar way, you might consider merging them as displays into one View - it'd be manageable more easily.

I have successfully used that approach for my taxonomy. It fortunately was homogenous at each level - a given branch ended with either leaves (nodes) or branches (terms), but not both. If this would be a limitation, please test it first.

Of course this is a "pseudo-code". You'd want to set up validations and filters, and a nice, logically-looking pathauto patterns to reflect the structure.

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


title: node number evolution statistic?

text:
# Question
Title: node number evolution statistic?
Im looking for a way to store the TOTAL number of nodes published on my drupal 6 web site at a particular month of the year so I can generate some curve from it :

```
timestamp | total node nb type x
2013/01   | 96
2013/02   | 100 (I mean 96+4, cumulative)
2013/03   | 120
[...]

```

the need seems simple to me, but I cant find any statistics module that cares about this. also the need is really simple compared to the features these modules offer. I could write some piece of code about this using CRON and some requests to write such a table. maybe something with views count + cron.

but it certainly already exists somewhere as a module ?

thanks for any pointers/recipes.

jerome

# Answer
Do you really need the publishing date? or just the created date?

If you need the former, well that date isn't tracked by core - http://drupal.org/node/1838918

You could try a contrib module to start tracking that for you... http://drupal.org/project/publication\_date

If you're not worried about deleted nodes you can just do what you're after by running a query to count all the nodes that have a created date lower than month X. Or just get all nodes back, and then loop over them in php, successively incrementing counters for each month for your graph.

Otherwise, yeah you're going to have to do something with cron and get snapshots over time. I haven't heard of an existing offering for this in contrib.
> 2 votes

# Answer
You should give a try at the Count module :

> The Count Nodes Module counts total number of nodes created (published and unpublished both) in each content type. It provide a total number of blocks equals to the total number of content types created such that administrator can use one block for each content type.
>
> The Count Nodes module also provide a text box in each block to do a manual entry of total nodes. It helps administrator to show less or more count of actual nodes.
> 1 votes

# Answer
for this purpose, unfortunately, I cant find my way yet using views or this module http://drupal.org/project/views\_groupby (it doesnt work when using date published field even using field rewrite).

so here is a snippet I wrote that can be pasted in a block (you need php input).

this generates a table with 3 columns : year/month, node created / month, total (cumulative). change the nod type and drupal table preffix by yours.

```
<?php
  $header = array('month','compte','total');
  $rows = array();
  $total = 0;

  $query = "SELECT
    DATE_FORMAT((FROM_UNIXTIME(node.created) + INTERVAL 3600 SECOND), '%Y/%m') AS node_created_month,
    COUNT(node.nid) AS node_count
    FROM <db>_node node
    WHERE node.type in ('<nodetype>')
    GROUP BY node_created_month
    ORDER BY node_created_month ASC";

  $results = db_query($query);

  while ($fld = db_fetch_object($results)) {
    $total += $fld->node_count;
    $rows[] = array(
      $fld->node_created_month,
      $fld->node_count,
      $total
    );
  }

  return theme('table', $header, $rows);
?>

```

using the google chart api module http://drupal.org/project/chart one can also generate a chart using the same query.

```
    <?php
    // retrieve datas
      $query = "SELECT
        DATE_FORMAT((FROM_UNIXTIME(node.created) + INTERVAL 3600 SECOND), '%Y/%m') AS node_created_month,
        COUNT(node.nid) AS node_count
        FROM <db>_node node
        WHERE node.type in ('<nodetype>')
        GROUP BY node_created_month
        ORDER BY node_created_month ASC";

      $results = db_query($query);

      // prepare chart layout
      $chart = array(
          '#chart_id' => 'test_chart',
          '#title' => chart_title(t('blahblah'), 'cc0000', 15),
          '#type' => CHART_TYPE_LINE,
          '#size' => chart_size(545, 300),
          '#adjust_resolution' => TRUE,
          '#chart_fill' => chart_fill('c', 'eeeeee'),
          '#grid_lines' => chart_grid_lines(20, 20, 1, 5),
      );

      $chart['#legends'][] = '<nodetype>';
      $chart['#data_colors'][] = '00ff00';

      $chart['#mixed_axis_labels'][CHART_AXIS_Y_LEFT][1][] = chart_mixed_axis_label(t('nombre lieux'), 50);

      $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][2][] = chart_mixed_axis_label(t('temps'), 50);

      // inject datas into chart arrays
      $total = 0;
      while ($fld = db_fetch_object($results)) {
        $total = $total + $fld->node_count;
        $chart['#data']['<nodetype>'][] = $total;
        $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][1][] = chart_mixed_axis_label( $fld->node_created_month );
      };

      $chart['#mixed_axis_labels'][CHART_AXIS_Y_LEFT][0][] = chart_mixed_axis_range_label(0, $total);
      echo chart_render($chart);
    ?>

```

the generated graph png can be saved, and block is cachable so I wonder if its valuable to investigate about cron and add results to an existing sql table rather than to regenerate the whole thing, but well, that's a start.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: $file->original: Where does it come from?
I am attempting to write a patch for the Redirect module that automatically creates a redirect from the old file path to the new one, whenever a file is updated.

I added a hook to redirect.module:

```
function redirect_file_update($file){
      /**
     * Creates a new redirect from old file to new one when the new one has a different URI.
     */

  if (empty($file->original)) {
    $file->original = entity_load_unchanged('file', $file->fid);
  }
  if ($file->uri !== $file->original->uri) {
    $redirect = new stdClass();
    redirect_object_prepare(
        $redirect,
        array(
        'source' => file_create_url($file->original->uri),
        'source_options' => array(),
        'redirect' => file_create_url($file->uri),
        'redirect_options' => array(),
        )
    );
    module_invoke(
      'redirect',
      'object_prepare',
      $redirect,
      array(
        'source' => file_create_url($file->original->uri),
        'source_options' => array(),
        'redirect' => file_create_url($file->uri),
        'redirect_options' => array(),
      )
    );
    module_invoke('redirect', 'save', $redirect);
  }
}

```

and I verified with a `dpm()` that $file-\>original exists as expected when I'm working with files in the GUI.

But when I run tests it doesn't work. According to hook\_file\_update() docs, it should be called whenever file\_save() is called, but it appears that the code inside my redirect\_file\_update() is never being called, `entity_load_unchanged()` is returning the exact same object as plain old $file, and my $file objects don't have an 'original' property as far as the test knows, even after saving. Here's the testing code:

```
function setUp(array $modules = array()) {
  parent::setUp($modules);

  $this->admin_user = $this->drupalCreateUser(array('administer redirects', 'access site reports', 'access content', 'create article content', 'edit any article content', 'create url aliases'));
  $this->drupalLogin($this->admin_user);
}
  // Test whether replacement of a file redirects the old file URI to the new one.
  function testFileReplacementRedirects () {
  // Create a few test files and save them.
  $files = $this->drupalGetTestFiles('image');
  foreach ($files as $file) {
    file_save($file);
  }
  // Get a list of all the files we just created.
  $fileQuery = new EntityFieldQuery();
  $files_list = $fileQuery->entityCondition('entity_type', 'file')
    ->propertyOrderBy('fid')
    ->execute();
  // Pick out two files to use for our test.
  $test_file_one = file_load($files_list['file'][1]->fid);
  $test_file_two = file_load($files_list['file'][2]->fid);

  // Move file one to file two's URI
  $old_url = file_create_url($test_file_one->uri);
  $new_url = file_create_url($test_file_two->uri);
  $test_file_one = file_move($test_file_one, $dest = $test_file_two->uri, $replace = FILE_EXISTS_REPLACE);
  // Load the old module's URI and see if it redirects to the new one.
  $this->drupalGet($old_url);
  $this_page = $this->drupalGetHeaders(TRUE);
  $this->assertEqual($this_page[0]['location'], $new_url, 'Redirected from ' . $old_url . ' to ' . $new_url . '.');
  $this->assertEqual($this_page[0][':status'], 'HTTP/1.1 301 Moved Permanently', 'Status: ' . $this_page[0][':status']);
}

```

What is going wrong?

# Answer
`$file->original` is set from file\_save() to make it available to `hook_file_presave()`, `hook_entity_presave()`, `hook_file_insert()`, `hook_entity_insert()`, `hook_file_update()`, and `hook_entity_update()`. It is then removed from `file_save()` before the function returns the file object to the caller.

```
// Load the stored entity, if any.
if (!empty($file->fid) && !isset($file->original)) {
  $file->original = entity_load_unchanged('file', $file->fid);
}

```

Clearly, if the file was not previously saved, `$file->original` doesn't get set.
> 3 votes

---
Tags: files, redirection, testing
---