# Question
Title: How to list all taxonomy terms in a vocabulary followed by associated node titles in Views
I am trying to list all of the taxonomy terms from a vocabulary in views and have the node title of all of the nodes that have that term associated with them listed under each term. For example, I have a vocabulary of State names. The various nodes have a term reference field to link the node with a state. I then want to create a view that will show the state name followed by the nodes with that state name, then the next state name etc. I can create a taxonomy view that lists all of the state names, but can't find a way to add the node titles under each state name. I am converting an existing non-Drupal site to Drupal 7.

Here is a link to the current page that I want to make happen in Drupal. It shows the states following by what would be the node titles for each state.

http://www.cbfisk.com/do/DisplayInstrumentList/filter/geographic

Thank you for any help.

# Answer
> 1 votes
Create a view in following way,

```
1. create a new view to show taxonomy terms of type state
2. Then click relationship under advanced, and choose 'Taxonomy term: Content with term'
3. Then under 'fields' add ' Content: Title' as new field, by keeping relationship 'node'
4. Under 'format' choose HTML list (or table), and set  Taxonomy term: Name  as grouping   field
5. You can choose 'exclude from display' option for field  Taxonomy term: Name

```

Then you will get the output in desired format as below,

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


title: Switching nodes no refresh AJAX

text:
# Question
Title: Switching nodes no refresh AJAX
What I have is a view that shows couple of nodes of type "product", they are related by an SKU ID.

What I'm trying to achieve is a way to switch between those related product produced by the view without refreshing the page.

Checking "Use Ajax" in my view did not achieve what I want.

Thanks,

# Answer
i have developed module ajax\_links\_api which help you to load any drupal page to a specified div with help of JQuery Ajax.

in your tpl =\>

```
    <?php  l_ajax($title, $path, $target)  ?>

```

*$title: Title.*

*$path : Drupal path.*

*$target (optional):* ID or CLASS of DIV to be replaced. Default value is .region-content, you can change default value in admin page 'admin/settings/ajax\_links\_api'

**Example :**

```
<?php l_ajax("Load node 1", "node/1", ".region-content") ?>

```

Hope you can use this for this case
> 2 votes

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


# Question
Title: Alter Color module fieldset within theme settings form
I've set up Color module for my theme - it works pretty well, but takes too much vertical space (I have a bunch of colors). What i'm trying to do is to alter `system-theme-settings` form to make Color scheme fieldset collapsible. So here's my code:

```
function test_form_system_theme_settings_alter(&$form, &$form_state) {
  drupal_set_message('DEBUG: ' . print_r($form['logo'], 1));
  // Above line prints array of logo settings - so function works well

  drupal_set_message('DEBUG: ' . print_r($form['color'], 1));
  /* This line prints nothing and I get:
   * 'Notice: Undefined index: color in test_form_system_theme_settings_alter()
   * (line 16 of /var/www/sites/all/themes/test/theme-settings.php).'
   */
}

```

As you can see, i can't alter $form\['color'\] because it doesn't exist. Here's the color\_form\_system\_theme\_settings\_alter function.

Am i missing something?

# Answer
> 3 votes
Definitly `system-theme-settings` is a core form where color module adding its fields using `hook_form_alter` in the same manner you are doing.

The point at which your `hook_form_alter` is invoked seems to be earlier then the color module's.

Check out hook\_module\_implements\_alter to alter the registry of modules implementing a hook.

# Answer
> 2 votes
If you want theme to alter the color fieldset, you will need to use the `#process` variable.

For instance:

```
function YOURTHEME_form_system_theme_settings_alter(&$form, &$form_state) {
  $form['#process'][] = 'YOURTHEME_make_collapsible'
}

function YOURTHEME_make_collapsible($form) {
  $form['color']['#collapsible'] = TRUE;
  $form['color']['#collapsed'] = TRUE;

  return $form;
}

```

Functions defined in the #process variable will run after modules have done their altering. Therefore, you can access `$form['color']` and alter it from theme's theme-settings.php.

---
Tags: 7, forms
---


title: Drupal on custom page?

text:
# Question
Title: Drupal on custom page?
I created a .php page outside of Drupal. On that page I want to check if a user is logged into my Drupal site.

Is that possible?

# Answer
If the PHP file is in the same directory where cron.php, and index.php files from Drupal installation are, then you can use the following code.

```
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  //...
}

```

If the PHP file is in another directory, then you should use the following code.

```
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', 'the directory containing the includes directory from Drupal');
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  //...
}

```
> 6 votes

# Answer
Then you need to include these lines at top of your file

```
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Then use the following code to check if the user is logged in or not,

```
global $user;
if ($user->uid) {
// User is logged in
}

```

For anonymous user uid will be 0.
> 1 votes

---
Tags: users
---


title: Odds Link Hover Behavouir

text:
# Question
Title: Odds Link Hover Behavouir
Hello i dont seem to be able to change the colour of my links hover on my main content table. Ive tried everything but it seems to want to stay white. Can anyone identify the CSS i should be changing?

thanks

main left table here- enter link description here

# Answer
> 0 votes
This does the job:

```
#main-content table tbody .views-field a:hover {
  color: orange;
}

```

It's a CSS specificity issue (also the reason that I never use ID's to style elements). Check this page out from Stuff and Nonsense for a REALLY good explanation on CSS specificity (in relation to Star Wars).

---
Tags: theming
---


title: How to highlight current node in views

text:
# Question
Title: How to highlight current node in views
I made a panel for showcasing individual nodes. That panel has a left column that contains a view with a list of all nodes (think teasers), and a right column with the node content.

In the view which generates the list of nodes in the left column, how can I highlight the current node?

# Answer
If you list complete node teasers, it means, the nodes are rendered by node.tpl.php. So just add a class to the node template in \_preprocess\_node something like this:

```
$node = $vars['node'];
$menu_object = menu_get_object();

if ($menu_object && $menu_object->nid == $node->nid) {
  $your_custom_class = 'this-is-the-actual-node';
}

```
> 1 votes

---
Tags: views, 6
---


# Question
Title: Add html widget programmatically to the list “Add fields” in views in Drupal 7
I'm trying to create a html widget that will be available in all views. I would like to have the widget available in the list "Add fields" in views.

The module Easy social have this functionality, but I can't figure out how they did that.

So how can I from my module programmatically add fields to the list "Add fields" for views?

Any help appreciated.

# Answer
This documentation will help you, just add a field handler then you are done! Click here
> 0 votes

---
Tags: views, hooks
---


# Question
Title: Referenced entity with multiple values making duplicate rows in views
I checked *'distinct'* in my view configuration in *Query settings* under the *'advanced'* fieldset.

So say when I have have three entities connected to one node, there would be three rows in my view of the same node of course one for each entity.

**Fields settings**

* Content: Hour ('event')
* Content: Title ('event')
* Content: Body ('event')
* (Content entity referenced from field\_event\_performer) Content: Title
* (Content entity referenced from field\_event\_performer) Content: Body
* (Content entity referenced from field\_event\_performer) Content: Foto
* Content: Title ('event')
* (Content entity referenced from field\_event\_performer) Content: Performer

Some fields I've given a class in order to hide them using jQuery and show them in a modal frame when clicked on. That's why fields are shown double. First I thought the problem was be because of the weird field settings. But the nodes that show only one time have the same field settings, only do they have more performers referenced.

**I have 4 filter criteria in total:**

* Content: Published (Yes)
* Content: Type (= Event)
* Content: Evenement type (= Presentatie) | Settings (taxonomy)
* Content: Locatie (= Kraakhuis) | (taxonomy)

Having done searches I noticed that everyone who had this problem, only needed 1 field from the referenced entity and could use the aggregation funtion as found under *advanced*. This works quite fine here as well if I only needed 1 field.

But in my case, when output into a modal frame, **one entire row** should look like this:

* Node123 title
* Node123 body
* referenced entity 1 title
* referenced entity 1 body
* referenced entity 1 picture
* referenced entity 2 title
* referenced entity 2 body
* referenced entity 2 picture
* referenced entity 3 title
* referenced entity 3 body
* referenced entity 3 picture

# Answer
> 0 votes
What helped is going custom code. Instead of relying on the fields that would have come out of the Views query, I grabbed the nid of my referenced field of my 'event' content type and loaded the rest of the fields via `node_load();`. All of this happening in a tpl file views-`view-fields--viewnale--block.tpl.php`

I used the row object and made a loop that went over the multiple valued referenced entity.

```
    <?php foreach($row->field_field_evenement_performer_1 as $key => $whatever): ?>
    <?php $performer = node_load($row->field_field_evenement_performer_1[$key]['raw']['target_id']);

    $title = $performer->title;
    $picture = $performer->field_performer_foto['und'][0]['uri'];
    $bio = $performer->body['und'][0]['value'];

    print '<div class=\'forModal\'><h3>' . $title . '</h3></div>';
    print '<div class=\'forModal\'><img src="' . $picture . '"/></div>';
    print '<div class=\'forModal\'>' . $bio . '</div>'; ?>

<?php endforeach ?>

```

---
Tags: 7, views
---


# Question
Title: Is there a module that provides a field for referencing values of another field
Initially I thought I could use the same field on both entities, but I want the user to be able to select unlimited values from the reference field limited to the options that could exist in the original field.

In the field settings, I need to have the ability to select a field to reference. When looking at the field instance I'd like to be able to tell which field the value should be compared against. The user should be able to select from all of the possible values of field A and store that selection in field B.

**Changed this, as it made it sound like I wanted something similar to node reference**

> Entity 1: Field A
>
> Entity 2: Field B (Values from Entity 1: Field A stored in Field B)

The goal is to be able to use Field B to find entities having Field A that are the same value

Is there any way to achieve this kind of relationship between fields?

# Answer
> 1 votes
Field reference module may help you !

> Defines a field type for referencing one field from another.
>
> This module is modelled on Node reference and usage is similar.
>
> Depending on configuration, authors can pick fields from the same node/entity, from other nodes/entities, from specific revisions, from specific languages, or even a specific delta value within the field. Fields can be displayed using either the 'full' or 'teaser' mode from their original node/entity.

---
Tags: 7, entities
---


# Question
Title: Display extra information adjacent to system_settings_form() output
I have a properly constructed set of data coming out of a call to `system_settings_form()`. How can I add to that data to display additional items on the form page?

I'm currently trying (and failing with):

```
// ...inside drupal_get_form callback
// $form has some form elements in it
$return =  system_settings_form($form);
if (!hay_problemas()){
    $return['warning'] = array(
        '#type' => 'div',
        '#class' => 'warning',
        '#markup' => 'WARNING:  Filesystem permission are broken'
    );
}
return $return;

```

# Answer
> 1 votes
I think this must be

```
// ...inside drupal_get_form callback
// $form has some form elements in it

if (!hay_problemas()){
  $form['warning'] = array(
    '#attributes' => array('class' => array('warning')),
    '#markup' => t('WARNING:  Filesystem permission are broken'),
    '#weight' => -10, //set position relative to other $form['key']
  );
}

return system_settings_form($form);

```

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


# Question
Title: Greater control of search results using $snippet
In \*node--content\_type.tpl.php\* I can do the following:

```
hide($content['body']);
print render($content);

```

Can I draw and hide field elements from a node's content in a similar way from `$snippet;` on *search-result.tpl.php*?

If not how do I gain greater control of the placement of images and body text in search results?

# Answer
> 1 votes
For me, the best way to have control over the display of each result was to comment out all of the default information that is rendered in *search-result.tpl.php* and instead load and render each result in its teaser form. I achieved this in the following way:

```
$view = node_view($result['node'], 'teaser');
print render($view);

```

# Answer
> 3 votes
> Can I draw and hide field elements from a node's content in a similar way from $snippet; on search-result.tpl.php?

You cannot, as `$snippet` is a string, not an render array. In fact, the default template used by Drupal contains the following code.

```
<?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?></p>
<?php endif; ?>

```

What you can do is implementing `hook_preprocess_search_result()` to change the content of `$variables['snippet']` with the content you want to show. See template\_preprocess\_search\_result() for a list of the variables passed to the preprocess function.

As you seem interested to alter what shown as result for a node search, you could also implement `theme_search_result__node()` as `template_preprocess_search_result()` use the following code to set the theme hook suggestions array.

```
$variables['theme_hook_suggestions'][] = 'search_result__' . $variables['module'];

```

The documentation for theme() says:

> There are two special variables that these preprocess and process functions can set: 'theme\_hook\_suggestion' and 'theme\_hook\_suggestions'. These will be merged together to form a list of 'suggested' alternate theme hooks to use, in reverse order of priority. theme\_hook\_suggestion will always be a higher priority than items in theme\_hook\_suggestions. `theme()` will use the highest priority implementation that exists. If none exists, `theme()` will use the implementation for the theme hook it was called with. These suggestions are similar to and are used for similar reasons as calling `theme()` with an array as the $hook parameter (see below). The difference is whether the suggestions are determined by the code that calls theme() or by a preprocess or process function.

---
Tags: 7, search
---


# Question
Title: Rules Link - Insert into System Node Content Template Variant
I'm trying to incorporate a Rules Link into an edited Panels Node Template Variant (Structure -\> Pages -\> Variant). The Rules Link is a simple "Apply Now" but I'm a little confused as to what I should be inserting as a Content. Previously it was working fine (the Rules Link added to the Content Node Field set and when any said content type was viewed it was there).

This item when I look at the content types available (Activity through to Widgets), I select Form (and available content) or Node or Node Token Type), all I get on the saved Node Template when viewing is basic text 'Entity info.' in the said Block and no actual Rules Link (ie general 'blue' URL link). My efforts to get it to show in the Node Variant is not a success and I've tried the Content types available for insert. I roughly understand what is happening and how things 'should' work and presumed what I did before would merely work in the edited Node, it seems quite self explanitory but not having much joy at this stage or maybe I'm merely missing a small point.

Could someone share with us the general process of getting a Rules Link to show in a Node Content Template Variant in order for the Rules Link to process to the next stage. Thanks.

# Answer
> 0 votes
I appear to have found the answer to my original question above and solved it, though I'm not too sure if it would be the ideal (correct) approach, but it's ideal for now. After reading this post Use content panes as blocks I approached my issue by using a Mini Panel to include the said Rules Link, it worked fine. Put simply, I just created a Mini Panel, included the Rules Link as Content (see how in the above post), saved, then went back to my original Node Template Panel Variant, edited and included as a new Content in the Panel Editor, then saved that Panel. Voila!

You may have to fiddle with the Override Panel headings etc to get rid of any unwanted shown text: i.e Panel Name (I justed wanted the Link URL to trigger workflow and not the actual Mini Panel Title, so use the 'Override' Title option). It couldn't be that easy? well it is.

Sometimes I think we may over complicate Drupal, now in my opinon we shouldn't, we just need to see the wood from the trees. Clearly I'm learning Drupal, so will you.

---
Tags: rules, navigation
---


# Question
Title: Search results: order & group by custom field
I customized the display of my search results so I can show custom fields in the search results (other question).

I have a custom field ('Department'). I want to show the search results grouped and ordered by that field.

# Answer
Found an answer... hook\_preprocess\_search\_results is exactly what I need.

```
function mymodule_preprocess_search_results(&$variables) {
    $variables['search_results'] = '';
    $output_results = '';
    $output = '';

    // loop through results, group by department
    $departments = array();
    foreach ($variables['results'] as $result) {
            $departments[$result['node']->field_department[$result['node']->language][0]['value']][] = $result;
    }
    ksort($departments);

    foreach ($departments as $department => $departmentResults) {
        $value = "";
        foreach ($departmentResults as $key => $result) {
            $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
        }

        $output_results .=  '<div id="tabs"><h3>' . $department . '</h3>';
        $output_results .=  $value;
        $output_results .=  '</div>';
    }

    $output .= '</ul>';
    $output .= $output_results;
    $output .= '</div>';

    $variables['search_results'] = $output;
}

```
> 1 votes

---
Tags: 7, entities, search
---


# Question
Title: Choosing sub-term after choose term when user post article
This is my taxonomy, really large. My client want to choose in 2 dropdown menu, first one is parent term, after that, the second menu fetch sub-term which belong to parent term in first menu. How can I do? Is there any module for this case?

> Car
>
> * BMW
>     + BMW1
>     + BMW2
>     + BMW3
> * Audi
>     + Audi1
>     + Audi2
>     + Audi3
> * Toyota
>     + Toyota1
>     + toyota2
>     + toyota3

# Answer
Hierarchical Select is exactly for that purpose.

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
>
> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Let the site administrator edit content at page
I'm using views (outputing fields) to display the content of a page and that's working fine for the end user (the visitors). I have 2 questions about the administration for this page.

1. Is it possible to let the administrators edit the content type(s) within the view from the page that´s being displayed? Like the way you do when you edit articles (click edit in the right corner)? Views can do that when you list content but not fields? See my screenshot where i try to explain it.

2.Is it possible to organize the content (and the different content types) in a structured an hierachial order that's meaningful for the site administrators? For example I would love to first list the page on level 1 and then display the different content types below the page on level 2. See my second screenshot where I try to explain this.

# Answer
1. It is not clear what you want to edit - *content types* (page, article, blog etc.) or *nodes*? If you want to edit particular nodes in a view which outputs fields, core Contextual filters module have views implementation so you can choose `Global: Contextual links` as a field. You can even configure which links to display as contextual links.
2. Check out Views Bulk Operations and Administration Views as they allow you to alter the admin interface using views.
> 0 votes

---
Tags: views, users, nodes
---


# Question
Title: how to display related node titles to taxonomy terms
I want to display list of taxonomy terms and besides each taxonomy term need to display represented node title as well. For suppose To X taxonomy term a,b,c are taxonomy child terms. I have created a page and selected b term. Now I want to display in the below o/p.

```
>  X
>        a
>        b -> <node title>
>        c

```

# Answer
The solution will be to use a taxonomy view using the views module and in the view add a relationship the content type where the terms are use. To finish you can display the results as an HTML list grouping by the parent term.
> 1 votes

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


title: File upload broken on node form

text:
# Question
Title: File upload broken on node form
I have the same problem described in I get image field upload errors with a custom node\_add() form.

How do I add these lines to the menu item array?

```
'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

```

I get the following errors:

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'node\_form' not found or invalid function name in drupal\_retrieve\_form() (line 800 of C:\xampp\htdocs\semt1\includes\form.inc).
> Notice: Undefined index: #node in comment\_form\_node\_form\_alter() (line 1194 of C:\xampp\htdocs\semt1\modules\comment\comment.module).
> Notice: Trying to get property of non-object in comment\_form\_node\_form\_alter() (line 1211 of C:\xampp\htdocs\semt1\modules\comment\comment.module).
> Notice: Undefined index: #node in location\_node\_form\_node\_form\_alter() (line 14 of C:\xampp\htdocs\semt1\sites\all\modules\location\location\_node.module).
> Notice: Trying to get property of non-object in location\_node\_form\_node\_form\_alter() (line 15 of C:\xampp\htdocs\semt1\sites\all\modules\location\location\_node.module).
> Notice: Undefined index: #node in menu\_form\_node\_form\_alter() (line 629 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
> Notice: Trying to get property of non-object in menu\_form\_node\_form\_alter() (line 629 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
> Notice: Undefined index: #node in menu\_form\_node\_form\_alter() (line 630 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
> Notice: Trying to get property of non-object in menu\_form\_node\_form\_alter() (line 630 of C:\xampp\htdocs\semt1\modules\menu\menu.module).
> Notice: Undefined index: #node in translation\_form\_node\_form\_alter() (line 135 of C:\xampp\htdocs\semt1\modules\translation\translation.module).
> Notice: Trying to get property of non-object in translation\_form\_node\_form\_alter() (line 135 of C:\xampp\htdocs\semt1\modules\translation\translation.module).
> Notice: Undefined index: field\_im in file\_ajax\_upload() (line 271 of C:\xampp\htdocs\semt1\modules\file\file.module).
> Notice: Undefined index: #suffix in file\_ajax\_upload() (line 280 of C:\xampp\htdocs\semt1\modules\file\file.module).

I am using this module.

# Answer
> 1 votes
Try this:

```
function yourmodule_menu_alter(&$items) {
  $items['system/ajax']['file path'] = drupal_get_path('module', 'node');
  $items['system/ajax']['file'] = 'node.pages.inc';
}

```

---
Tags: files
---


title: How to force node.status=0

text:
# Question
Title: How to force node.status=0
I need to force the status value of a node=0 when the user has a certain role.

I've made

```
 function mymodule_node_save($node){
    if($node->type=="mytype") {
        global $user;
        if(in_array("simple",$user->roles)) {
            $node->status=0;
        }

    }
}

```

But the status is always saved as 1. What am i doing wrong?

# Answer
There is not hook\_node\_save() in Drupal 7, but there is a hook\_node\_presave() that is fire when saving or updating content. So your code should look like:

```
function mymodule_node_presave($node){
    if($node->type=="mytype") {
        global $user;
        if(in_array("simple",$user->roles)) {
            $node->status=0;
        }

    }
}

```
> 3 votes

# Answer
@redhatlab is correct about Drupal 7 not invoking `hook_node_save()`. If you need to be sure the status is effectively set to 0, without other modules to alter it, I would use code similar to the following one.

```
function mymodule_node_insert($node) {
  mymodule_update_status($node);
}

function mymodule_node_update($node) {
  mymodule_update_status($node);
}

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_insert' || $hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_update_status($node){
  if ($node->type == 'mytype' && in_array('simple', $GLOBALS['user']->roles)) {
    $node->status = 0;
  }
}

```

The code checks the roles assigned to the currently logged-in user. If you want to check the roles assigned to the node author, you should use `$node->uid` to load the user object of the node author. It is then generally preferable to check the user has a specific permission, rather then checking which roles are assigned to the user.

`node_save()` first invokes `hook_node_presave()`, and then `hook_node_insert()`, or `hook_node_update()`. The code I wrote would allow your module to be the last one changing the node status.

### References
> 5 votes

---
Tags: 7, nodes, hooks
---


# Question
Title: How do I attach a CAPTCHA when adding the contact form to a node?
I am embedding the Drupal contact page in a node. I added the following code in template.php.

```
function sakura_preprocess_node(&$variables) {
  $node  = $variables['node'];
  if (!empty($node)) {
    $variables['template_files'][] = "node-" . $node->nid;
  }
}

```

Then, I created the node-24.tpl.php template file (for the node where I add the contact form).

```
require_once drupal_get_path('module', 'contact') .'/contact.pages.inc';

//no need to maintain two version of node.tpl.php
include "node-page.tpl.php";

function local_contact_page() {
  $form = contact_mail_page();
  // override default values here if you want
  // next one will select a different category
  //$form['cid']['#default_value'] = 0;
  $form['submit']['#value'] = 'Отправить';
  unset($form['copy'], $form['subject']);
  dpm($form);
  return($form);
}

function local_contact_page_submit($form_id, $form_values) {
  return(contact_mail_page_submit($form_id, $form_values));
}

function local_contact_page_validate($form, $form_state) {
  return(contact_mail_page_validate($form, $form_state));
}

print drupal_get_form('local_contact_page');

drupal_set_message($form_id);

```

I also enabled the CAPTCHA module with the math method. On /contact it shows the CAPTCHA, but it doesn't show it on the contact form I embebbed in the node.

How can I make the CAPTCHA appear on the node page with the contact form?

# Answer
> 1 votes
Webform module is best for creating forms and still having options that come with regular nodes. It also integrates with captcha.

What is the reason you are embedding the form in the node like that?

---
Tags: emails
---


title: node/add url redirect

text:
# Question
Title: node/add url redirect
I have two group content types (I use OG groups) which are still under development. I created dummy content types so that these links will appear in the group content creation links.

But they are not ready yet. Instead i would like to redirect the user when he clicks on the link to an article which basically describes what the functionality is and is under development.

I googled and searched drupal answers for this but could not find anything that fits my problem. Please let me know if someone knows how to redirect node creation links in a group context to a static article page. Thanks.

# Answer
You can use `hook_menu_link_alter()` to hide those links. For example:

```
/**
 * Implements hook_menu_link_alter().
 */
function MYMODULE_menu_link_alter(&$link) {
  if ($link['link_path'] == 'node/add/dummy-type')) {
    $link['hidden'] = 1;
  }
}

```

Or can use `hook_menu_alter()` to redirect to other URL. For example:

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/dummy-type']['page callback'] = 'drupal_goto';
  $items['node/add/dummy-type']['page arguments'] = array('node/1');
}

```

You can also use `hook_menu_alter()` to hide the links:

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/dummy-type']['access callback'] = FALSE;
}

```
> 1 votes

---
Tags: 7, navigation, redirection
---


# Question
Title: "jquery_file_upload.id is part of the primary key but is not specified to be 'not null'"
I have installed the jQuery File Upload module, and I get the following error:

> jquery\_file\_upload.id is part of the primary key but is not specified to be 'not null'

What does that error message mean, and how can I resolve it?

# Answer
> 1 votes
The error message is about the schema currently used by the module, which defines the primary key using the following code.

```
function jquery_file_upload_schema() {
  $schema['jquery_file_upload'] = array(
      'description' => t('Stores files sizes for each user.'),
      'fields' => array(
          'id' => array(
              'description' => t('auto increment'),
              'type' => 'serial',
              'size' => 'normal',
          ),
          'uid' => array(
              'description' => t('registered user'),
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
              'default' => 0,
          ),
          'file_name' => array(
              'description' => t('File Name.'),
              'type' => 'varchar',
              'length' => '255',
              'not null' => TRUE,
          ),
          'file_size' => array(
              'description' => t('File Size.'),
              'type' => 'float',
              'size' => 'big',
              'default' => 0,
          ),
      ),
      'primary key' => array('id'),
  );
  return $schema;
}

```

The correct definition would be the following one, as the fields that are part of the primary key should be declarated as "NOT NULL."

```
function jquery_file_upload_schema() {
  $schema['jquery_file_upload'] = array(
      'description' => t('Stores files sizes for each user.'),
      'fields' => array(
          'id' => array(
              'description' => t('auto increment'),
              'type' => 'serial',
              'size' => 'normal',
              'not null' => TRUE,
          ),
          'uid' => array(
              'description' => t('registered user'),
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
              'default' => 0,
          ),
          'file_name' => array(
              'description' => t('File Name.'),
              'type' => 'varchar',
              'length' => '255',
              'not null' => TRUE,
          ),
          'file_size' => array(
              'description' => t('File Size.'),
              'type' => 'float',
              'size' => 'big',
              'default' => 0,
          ),
      ),
      'primary key' => array('id'),
  );
  return $schema;
}

```

There is nothing you can do, if not opening an issue report for the module, in its issue queue. Be sure there isn't already a report about that.

---
Tags: database
---


# Question
Title: Using chinese character in drupal_mail_send() generates unreadable character
I am using code similar to the following one.

```
$message = array(
  'id' => 'named_fund',
  'to' => $email,
  'subject' => '恭喜您！',
  'body' => '恭喜！',
  'headers' => array('From' => 'Company Name <example@example.com>', 'Content-Type' => 'text/html; charset="utf-8";'),
);

drupal_mail_send($message);

```

When I use Chinese characters for the "From" header, I get strange characters. Why?

# Answer
> 1 votes
Try this:

```
drupal_mail_send(utf8_encode($message));

```

As Oswald implied, this is a character encoding issue.

If any data is coming from, or going to be stored in, the database, also make sure your database character encoding is utf8\_general\_ci.

# Answer
> 0 votes
If you have configured drupal to use an SMTP library (by setting the `smtp_library` drupal variable), you are responsible for properly encoding the headers (unless the library does that for you).

If you did not configure drupal to use an SMTP library, make sure that the source code of the module is encoded in UTF 8.

---
Tags: 6
---


# Question
Title: Limit number of nodes able to have custom field selected
I have a content type named "Story" with a boolean field "Featured".

When users create/edit a story they can check the featured checkbox. Stories that are featured appear in a block throughout the site. The block only shows two stories.

Ideally, if there are two stories featured and a user creates a new story and selects the featured field, it would deselect the featured field for one of the two original stories. Only two stories can be featured at once. Is this possible?

The traditional route is to have the views block show the two most recently created stories that have the featured field selected. From an administrative perspective I want to make it easy for site editors to keep track of what's featured (these users are new to web publishing) so it'd be great if there was a limit on the number of nodes that can be "featured".

Any thoughts are appreciated! Thanks!

# Answer
A view can be used with a limit on the number of items to two with a filter that requires that story to be featured, then sorted by publish date (descending to show the latest). Otherwise, if you want an administrator to have total control over exactly which two stories are featured, use Nodequeue or use the node sticky bit and make sure only admins have access to set the sticky bit.

You can reuse the same view to create a page view that shows all stories that have the featured flag set.
> 1 votes

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


# Question
Title: Change JSO(N) parameters that have been set by another module
I am trying to override parameters that have been set by another module. The other module uses `drupal_add_js()` to set the parameters.

```
 $settings = array('color'=>'red','type' =>'round');
 drupal_add_js(array('MyData'=>$settings),'setting'));

```

This adds a JavaScript object to the `drupal.settings` data object. I want to override that in another module, and I don't know how. It seems to always "ADD" to the array and NOT override it.

The following code doesn't work.

```
$js = drupal_add_js(null,'setting'); //<-- get the JS
unset($js['setting'][1]['MyData']['color']);
drupal_add_js($js,'setting');

```

```
 $settings = array('color'=>'PINK'); // <- Change red to pink
 drupal_add_js(array('MyData'=>$settings),'setting'));

```

How can I do what I am trying?

# Answer
> 0 votes
You should try this

```
// Get all the current javascript information
$current_js = drupal_add_js(NULL, NULL, 'header');

// Filter the information down to just the settings.
$current_js_settings = $current_js['setting'];

```

# Answer
> 0 votes
What you could do is using code similar to the following one in your module.

```
function mymodule_preprocess_page(&$variables) {
  $javascript = drupal_add_js(NULL, NULL, 'setting');

  foreach ($javascript as $index => $array) {
    if (isset($array['MyData'])) {
      $array['MyData'] = /* Change the array values. */;
    }
  }

  $variables['scripts'] = drupal_get_js('header', array('setting' => $javascript));
}

```

In Drupal 7, altering the JavaScript code added from another module is done implementing hook\_js\_alter().

# Answer
> 0 votes
Here is an another way,

Lets consider original data is available in Drupal.settings.myData.

Now set your custom data in different place say Drupal.settings.custom.myData, then use the following JavaScript code to merge those values,

```
jQuery.extend(Drupal.settings.mydata, Drupal.settings.custom.myData, true);
Drupal.attachBehaviors();

```

Include these lines in your custom JavaScript function, attachBehaviours take care of applying these new settings :)

I'm using this when I have to deal with lot of ajax requests in the page.

# Answer
> 0 votes
If using Drupal 6 you can use the AdvAgg module to do what you need. It provides hooks that allow you to alter js before it is pushed out into HTML. Here is an example of how to overwrite JS using advagg in Drupal 6: http://drupal.org/node/231451#comment-6574710. Note that is is changing inline code not the settings, but changing the settings should be fairly straight forward.

---
Tags: 6, javascript
---


# Question
Title: Get info from entity reference using PHP
I'm trying to use PHP to get user IDs from an Entity Reference of users in a content type.

I have got as far as doing (where I actually get the NID from elsewhere):

```
$node = node_load(123);

$info = field_get_items('node', $node, 'field_my_users');

```

But how do I get the IDs from `$info`?

# Answer
> 5 votes
You just need to get the `target_id` from each of the field values, which you can do by looping through `$info`:

```
$uids = array();
foreach ($info as $field_item) {
  // Entity reference fields store their data in the 'target_id' column
  $uids[] = $field_item['target_id'];
}

```

---
Tags: entities
---


# Question
Title: How do I use a different template for the anonymous users?
If the user is the anonymous user or an authenticated user, I want to use the page1.tpl.php; with other roles, I want to use page.tpl.php.
How do I write the code?

# Answer
You should not need an additional page1.tpl.php. In the page.tpl.php you can use:

```
<?php
  global $user;

  if ($user->uid > 0) {
    print /* Insert content only for authenticated users. */;
  }
?>

```

If you want to show some content when the user has the "administrator" role, then you can use:

```
<?php
  global $user;

  if (in_array('administrator', array_values($user->roles)))) {
    print /* Insert content only for users with "administrator" role. */;
  }
?>

```
> 4 votes

# Answer
If you want to handle different templates for different scenarios the context module is a great tool. This case is quite simple, so you could handle it with code like suggested. But using the context module, makes it a bit more manageable, and allows you not only to decide what template to use, to also what blocks to insert. It's a great module and is one of those I use for almost all of the sites I make.
> 5 votes

# Answer
I think you can use a preprocess function. Something like that:

```
function yourtheme_preprocess_page($vars) {
   global $user;
   if (!$user->uid || in_array('user authenticated', array_values($user->roles))) {
      $vars['template_files'][] = 'page1';
   }
}

```
> 4 votes

# Answer
Every user on a Drupal site is an anonymous user, or an authenticated user. Requiring to use the page1.tpl.php template for anonymous, or authenticated users would mean that the page1.tpl.php template is always used.

if by authenticated users you mean users that don't have any other specific role, then you could use the following code in your page.tpl.php file.

```
if (empty(array_diff(array_keys($GLOBALS['user']->roles), array(0, 1))) {
  // The user is anonymous, or the user doesn't have other roles
  // apart the one of authenticated user.
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Link a field in content types to the user profile
I want to link the output of a field (e.g. "Written by:Name" or "Photographed by:name") in the content type (e.g. Article) to the user profile.

Can anyone help me with it?

# Answer
First, you should make sure that the default author relationship isn't sufficient to satisfy your needs. Every content type has a creating user; this relationship can usually be used to create any necessary links between the content and the user in Views, Panels, or other modules.

However, sometimes you need to have multiple users associated with content. Your "photographed by:" example sounds like a good example of this use case. In that instance, I would use the User Relationships module to add a User Relationship field to the content type.
> 0 votes

---
Tags: nodes, navigation
---


title: How to add field in field

text:
# Question
Title: How to add field in field
I have a content type with text field (unlimited). Text field is limited to 250 chars and will be used to put names inside User can choose as many fields as they want depending on how many names they have for this node.

What i would like to do is to let users upload image next to text field.. if they chose 15 text fields, then they can also upload 15 images, but each image connected to its text field.

# Answer
Recently I've been using Field Collections for this use case. It allows you to make groupings of fields (which, for those in the know, are actually entities themselves) which you then attach to a content type.

The only downside I've noticed with this module is that it does require some knowledge of how entities work if you're going to work with Field Collections on a programmatic level, but from a site builder perspective, I think it might fit your use case nicely.
> 0 votes

# Answer
I think you're looking for the Double field module.

> Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can divide your fields into two seporate parts. For the moment it includes the following sub-widget types:
>
> * Textfield
> * Select list
> * Single checkbox
> * Textarea Consequently, in all there are 4 x 4 = 16 widget types.

Currently it is not supporting file upload. However, you can make this as support request in that module's issue queue.
> 2 votes

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


# Question
Title: How can I assign a block to a panel or mini-panel?
I was reading the project description for Panels, and I noticed it was a way—using mini-panels—for me to rearrange the contents of my site.

So I just created a mini-panel with a two column layout. I want to add one block to the left and one block to the right. How can I do this?

# Answer
Mini panels are blocks and you can add Mini Panels to Panels. You can't add blocks themselves to Panels, but usually most of the **content** that you can display in a block, you can actually display in Panels, content such as Activities, Menus, Mini panels themselves, Miscellaneous, Pages elements, Views, Widgets, Nodes, Custom content and more.

See Drupal - Blocks vs Context vs Panels.
> 3 votes

# Answer
You can add custom blocks to mini-panels. So create a custom block on the block admin page - admin/structure/block - and then add to your mini-panel or panel.
> 2 votes

---
Tags: panels
---


# Question
Title: Get the total value of the users vote in Rate module
I have added rate module to enable voting on comments and content. But I want to get the total no. of vote got by a users comment and give badges based on that. I have no clue how to do it.

# Answer
> 1 votes
You need to do custom coding to achieve above functionality. Assigning User Badges on Cron run will be a good option. Below steps will help you to solve the problem.

* Create a custom module
* Implement hook\_cron
* Get list of users who doesn't have comment votes badge.
* Get above list of users comment score using custom query
* Loop through results and check for your condition to assign badge
* Assign badge using user-badges API. Look into user badges module where it assigns badge to user to figure out logic to assign badge!

Hope it helps :-)

---
Tags: rating, users
---


# Question
Title: Cannot use object of type stdClass as array
I'm very new to Drupal and I'm receiving the error:

`Cannot use object of type stdClass as array`

in the following code:

```
$toolbar = $page['toolbar'];
foreach( $toolbar['menu_menu-smart-resources'] as $id => $object ) {
  $toolbar['menu_menu-smart-resources'][$id]['#localized_options']['attributes']['data-role'] = 'foo';
}
print render($page['toolbar']);

```

Can someone help.

# Answer
> 0 votes
You are able to change menu attributes using Menu Attributes module . If any customization is needed on top of that then you can follow the below process.

You can able to override theme links using `theme_menu_link` in `template.php`. Follow below step to override.

* Go to your active theme folder might be in *sites/all/theme* or if you are using default theme then themes folder
* Go to the active theme folder
* Look for `template.php`
* Override `theme_menu_link` by copy pasting entire function and replacing theme with your theme name.
* Do your changes inside function wherever necessary!

---
Tags: 7, routes, toolbar
---


# Question
Title: source code shows proper img tag from $row output, but no actual image in browser
In my tpl file that has custom code for a block view, I have an object $perfomer which I use to display it's picture with custom code. So I've written code as follows:

```
    <?php $picture = file_load($performer->field_performer_foto['und'][0]['fid']);  ?>
    <?php $realpicture = file_create_url($picture->uri); ?>
 <?php  print '<img scr="' . $realpicture . '" alt="'.$title.'" width="120" height=120/>'; ?>

```

So like the title of my question says, in my source code I get a proper img tag that looks like this:

```
<img scr="http://www.breinwijzer.be/festidev12345/sites/default/files/Santens_Patrick.jpg" alt="Patrick Santens" width="120" height=120/>

```

To test this, I pasted this html into a Page, and the picture showed just fine on that page. However, in the block view for which the mentioned `tpl` file is coded, there is no picture shown in the browser, only a square box of `120px` by `120px` with the `alt` value inside of it.

# Answer
> 1 votes
Ok creds to clive. See syntax error in comments.

For those who need the actual code in the answer: `<img scr` should be `<img src` :)

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


# Question
Title: print theme_get_setting in php-as-css file
I'm trying to print out settings from my theme's theme-settings.php into a file called custom.php. Below is the code I'm using in custom.php:

```
<?php
    header("Content-type: text/css; charset: UTF-8");
define('DRUPAL_ROOT', '/path/to/my/drupal/installation');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

body {
    background: url(<?php print (theme_get_setting('theme_custom_background_path')) ?>);
?>;

```

This is what the result is when the page is rendered in the browser:

```
body {
    background: url();
}

```

I'm obviously missing something here -- theme\_get\_setting isn't working. I'm not sure what kind of code I need to link this file to my theme.

Does anyone know if there is a way to get custom.php to recognize the settings I've defined in my theme's theme-settings.php file with theme\_get\_setting? I feel like I'm so close but just missing a few lines of code.

At the end of the day if I absolutely need to, I can just print the settings out inline within the head section of html.tpl.php - but I'd much rather include them in a separate stylesheet with the .php extension.

Any suggestions?

# Answer
Below code worked for me ! Make sure there is a value for setting "**theme\_custom\_background\_path**" in your theme settings. For example i can able to get logo path of theme using below code

* Created a file called get\_setting.php inside my Drupal Root
* Copy pasted below code
* Executed in browser.

Code

```
define('DRUPAL_ROOT', getcwd());
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$theme_settings = theme_get_setting('logo');
print "body { background: url(" . $theme_settings . ");}";

```
> 1 votes

---
Tags: 7
---


# Question
Title: Create custom block module with sorting of block content
I am using Drupal 7. I want to create a module which shows All the latest posts in Group with sorting options for the posts(a dropdown for sorting posts in block with various options). I am using organic group module for group management.

I have created a block module which can fetch the content for the particular group, but I am not able to manage sorting drop down form.

Does any one have idea, how to display form in block output and then sort that form.

I am also using file attachment with posts in group. So my sorting parameters includes no of files in post, postdate(i can get using views), Most viewed, Most comment,

Note: I want to build custom module because first I tried with Views module, but I am not able to get various sorting parameters which i need for sorting

# Answer
> 0 votes
You can do it with views + some minimal coding in your module: Make the view as you need, use a custom block to put 4 link with 4 different query arg: mysite.com/node/1?no\_files=1, mysite.com/node/1?post\_date=1 etc. For the dropdown you can use ctools jump menu feature, it's a simple drupal\_get\_form with this parameters.

If the dropdown is ok, let's modify the view's result based on query\_arg: See hook\_views\_query\_alter.

To get how do you need to change the query, I'm used to create the same view with all different filter what I need, and put `file_put_contents('/tmp/log', var_export($query));` into your \_view\_query\_alter implementation. If all different query of views are in log, it's easy to figure out, what do you need to modify in $query.

To order your views by file attachment exists, just add a filter named Field: Your File Attachment to the view, and use the operator Is Not Empty (NOT NULL). (As I understand, in this one case, you want to filter the query, not to sort.)

Most comment sorting need the sort criteria: Content: Comment count, Most viewed is not so exact, it depends, what do you use to tracking content viewing.

---
Tags: blocks
---


# Question
Title: How To Open The Comment Form In Modal Form
I want To Provide The Link "Add Reviews" For Content Type Example "Doctor". Then How I can Use the Comment Functionality For That. So that When the user Click on the Add reviews Link A modal Form Appears Having Text Field with "Rating Star". so that user can submit Reviews For that Content Type.

# Answer
You can use Colorbox Node.

So you should have this link in your node.tpl.php:

```
print l(t('Review'), 'comment/reply/' . $nid . '?width=600&height=600', array(
          'attributes' => array(
            'class' => array('colorbox-node')
                )));

```
> 1 votes

---
Tags: 7, comments, chaos-tool-suite, rating, javascript
---


# Question
Title: Horizontal scrolling in Safari on one content type only when logged out?
So I have spent numerous hours trying to solve the following issue and without success I bring it to Drupal Answers. For some reason, on my site for content type 'level\_1' when browsing in Safari it creates long horizontal scrolling. The strange thing is that when you are logged in, the issue is not there. Furthermore the issue doesn't exist when I coded the HTML/CSS pre-Drupal installation.

It's not an issue of caching as I've made changes and checked they followed through when not logged in.

Anyone have any ideas?

If someone has the opportunity to try and debug this issue it would be greatly appreciated.

The error occurs here in the Safari browser: http://beta.innovista.org/about-us

Thanks for your time.

# Answer
> 1 votes
Looking though the markup, the problem is on the H2 for your search form.

`<h2 class="element-invisible">Search form</h2>`

Can't say exactly what's up, but if you take off the `width` from `.level1 h2, .related h2, .tabTog h2` then it seems to be fine.

# Answer
> 0 votes
Thanks for providing a link. The problem also occurs in Chrome, but not Firefox. I'm pretty sure your problem is in the iframe that sits outside the "widewrap" container. It is the only thing that stretches across the screen on inspection.

I'm guessing it is part of some facebook (body class:fbBody, table id:fbChrome) integration tool - there is a table inside the iframe that is pulling the width across the screen.

---
Tags: 7
---


# Question
Title: Show current page on Drupal 7 breadcrumb
Is there anyway to add the current page title on drupal 7 breadcrumb?

# Answer
> 6 votes
Some themes - like Zen - provide this option, so check under Appearance -\> Settings. If your theme doesn't offer the option, you can edit your theme's page.tpl.php - simply add `$title` after the `$breadcrumb` variable. Alternatively you could override `theme_breadcrumb()`.

# Answer
> 4 votes
You could also use the Menu breadcrumb module to do this (it has D6 and D7 versions too).
It allows you to

> *"Append the page title to the breadcrumb (either as a clickable url or not)"*

See this tutorial:
Tutorial - How to Work and Style Breadcrumbs in Drupal 7

# Answer
> 1 votes
As a side note, if you are coding your breadcrumb trail in the template.php file, the page title will be added in the breadcrumbs to any \[custompage\].tpl.php file automatically.

I am not saying it's a *better* way of doing it. Personally, it was a more convenient solution for me, as i have multiple \[page\].tpl.php files.

(I also changed the default output to `<li>` list items, in order to get the CSS markup right.)

```
function templatename_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  $crumbs = '';
  if (!empty($breadcrumb)) {
    $crumbs = '<div id="breadcrumbs"><span>You are here: </span><ul>';
    foreach($breadcrumb as $value) {
      $crumbs .= '<li>' . $value . '</li>';
    }
    $crumbs .= '<li>' . drupal_get_title() . '</li></ul></div>';
  }
  return $crumbs;
}

```

Maybe this is of some help to anyone.

# Answer
> 1 votes
You could use the Custom Breadcrumbs module it has an option where you can include the current page title (or any other token field)

# Answer
> 0 votes
If you want to have breadcrumb in a block, you can create a block with the following content:

```
<?php
$bcarr = drupal_get_breadcrumb();
$bcarr [] = drupal_get_title();
print  theme('breadcrumb', array('breadcrumb'=>$bcarr));
?>

```

This is for Drupal 7 and the content type should be PHP code.

---
Tags: 7, breadcrumbs
---


title: Cannot pass variable to js file

text:
# Question
Title: Cannot pass variable to js file
I cannot pass variable to js file, from my `common.module`

```
  $max_length = 10; //variable_get('title_max_length');
      drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');
      drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));

```

Javascript works fine, but i need to get `**$max_length**` variable from module. At the moment its not working. here is js file:

```
(function($, Drupal) {
/*Character limit for news node*/

    Drupal.behaviors.common = {
        attach: function(context, settings) {
            var length = $('#edit-title').val().length;
           /* ####################################### */
           /* Does not work */
            var char_limit = Drupal.settings.common.max;
           /* ####################################### */
            if (length >= char_limit) {
                $('div.form-item-title label span.form-required').text("characters left limit exceeded for displaying on home page");
            } else {
                $('div.form-item-title label span.form-required').text(char_limit-length-1 + " characters left");
            }

            $('#edit-title:not(.edit-title-processed)', context).keyup(function () {

                $(this).addClass('edit-title-processed');
                var new_length = $('#edit-title').val().length;

                if (new_length >= char_limit) {
                    var chars = char_limit-new_length;
                    $('#edit-title').css('color','red');
                    //$('div.form-item-title label span.form-required').text("characters left limit exceeded for displaying on home page");
                    $('div.form-item-title label span.form-required').text("" + chars-1 + " characters");

                } else {
                    var chars = char_limit-new_length;
                    $('div.form-item-title label span.form-required').text(chars-1 + " characters left");
                    $('#edit-title').css('color', 'black');

                }
            });
        }
    };
})(jQuery, Drupal);

```

# Answer
> 1 votes
Interchange below lines that should work !!

```
$max_length = 10; //variable_get('title_max_length');
drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');
drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));

```

to

```
$max_length = 10; //variable_get('title_max_length');
drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');

```

---
Tags: javascript
---


# Question
Title: Adding attribute to menu - page specific
Hi I know I can alter menu links classes/attributes using theme\_menu\_link() function. But from what I can see, there is no way to determine what current page is being rendered from within the function.

i.e. I have a wep app that loads in 4 pages (ajax) and you can swipe to change page. I need to add an attribute on each menu link and they differ depending on the page.

Question being, how can I determine page from within theme\_menu\_link();

Regards

# Answer
> 0 votes
found it,

```
$page = arg(0);

```

cheers anyways

---
Tags: routes
---


# Question
Title: How to build Druapl 7 bilingual website?
How I can build a bilingual version of my newly build website using Druapl 7. I am using module Locale and entity\_translation.When I clicking the arabic(my intention to support English,Arabic),that is not intending to RTL. I have updated content type field "Language" to "Language Neutral",how I can add the feature of bilingual in a manned which could change the language and indentation of each content?

Thanks in advance.

# Answer
The Internationalization (i18n) module is good, Here is an excellent tutorial.

It's fairly robust, so I imagine it supports LTR script.
> 4 votes

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


# Question
Title: From where the execution starts in Drupal
Generally in any HTML file execution starts from index.html and PHP file starts from index.php.

But in Drupal from which file the execution is started, i know that it is started from bootstrap file but what calls the bootstrap file ?

What is the execution sequence when i write http://example.com which will load/install drupal ?

# Answer
**index.php** inside Drupal root folder is the starting point of execution. It calls the bootstrap functions. Please see the code inside drupal 7 index.php file below.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

```
> 2 votes

---
Tags: installation, bootstrapping
---


# Question
Title: How can I display/hide a div based on taxonomy term value on node.tpl.php file?
I am not a dev, but am trying to show and hide a div for on a particular node type node.tpl.php file based on taxonomy term value.

can someone please let me know how to do this.

****I AM ADDING THE ANSWER HERE AS I AM NOT ELIGIBLE FOR ANSWERING ****

I have a div which prints the taxonomy value of a node (where 30 is the vacabulary ID):

```
    <div class="node-r-status-tid-0 <?php print $term_css;?>">
        <?php print THEME_NAME_taxonomy_list($node, 30); ?>
    </div>

```

Below is the PHP code to make the dive show and hide:

```
    <?php
    if ($node->taxonomy[868])
      $tid = 868;  // This should be the taxonomy term id that you want to theme on
        foreach ( (array)$node->taxonomy as $term ) {
          if ( $term->tid == $tid ) {
            $term_css = " node-r-status-tid-" . $term->tid;
            break;
          }
        }

    if($node->taxonomy[869])
      $tid = 869;  // This should be the taxonomy term id that you want to theme on
        foreach ( (array)$node->taxonomy as $term ) {
          if ( $term->tid == $tid ) {
            $term_css = " node-r-status-tid-" . $term->tid;
            break;
          }
        }
    ?>

```

Using css classes I make the dive display:block or none.

Please let me know if the above code can be fine tuned further

Thanks, Anand

# Answer
In Drupal 6 add somthing like this to your template.

```
foreach ($node->taxonomy as $term ) {
  if ($term->tid == YOUR_TID) {
     print "<div>...</div>";
  }
}

```
> 0 votes

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


title: CDN and Boost - not working properly

text:
# Question
Title: CDN and Boost - not working properly
I have a drupal 6 site. Recently I've set up a CDN (not using the module. manually, and more specifically Google PageSpeed Service) to serve my content which is cached by boost. What I've noticed that when cron is run, the boost cache files are not deleted. This happens probably because my real domain name - www.example.com points to the cdn, which internally uses a different cname to reach my server (origin.example.com). Unlike other CDNs, PageSpeed doesn't request pages from my server using the internal cname, but rather uses www.example.com.

So anyway, to make a long story short: when cron runs, it clears origin.example.com cache files and not www.example.com (and these are the files my visitors get). I should say also that this CDN doesn't support https, so I access the admin using origin.example.com.

So, any ideas....

# Answer
> 1 votes
I have a similar setup using Pressflow, changing

```
$base_url='http://www.yourdomain.com';
$cookie_domain = 'yourdomain.com';

```

in **sites/default/settings.php** seems to get boost cache cleared.

---
Tags: 6, caching
---


# Question
Title: Creating a sortable table in the backend?
I want to create a custom view where informations are shown in table format. In the backend i want to create a view like this:

Do you know a module to achive this? Or how would you create a module for that? Any hints are greatly welcome!

Thanks a lot!

# Answer
If by *view* you mean that you want to create a custom module page for administrators, check out Examples modules, especially tabledrag\_example and tablesort\_example.

However, if you want to use Views, check out DraggableViews module.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Do I need to create a database table or are there already tools on offer?
Pretty new to drupal, I'm afraid!

I have a excel table of survey results which I need to display certain cells from on a drupal page. I was thinking of creating a new table in my drupal database and then using PHP to link to it. I can't seem to create this table and what I've read suggests that this isn't a good way to go about it.

Does anyone know a better tool within drupal for this? Views or creating a custom module?

Thanks

Ed

# Answer
Unless you need some additional styling or processing of data, the easiest way is to Embed a spreadsheet using Google Docs. You don't need any module for that.

If you need to have that data in Drupal as well, then check out Feeds Excel or this thread on drupal.org. The latter relies on the PHP Excel reader class which you should use in your custom module.
> 1 votes

---
Tags: views, database, theming
---


# Question
Title: Add javascript to multiple specific urls
I'm trying to add some javascript to my template.php file on a Drupal 7 site. I'd like the javascript to load on a specific set of pages, based on the url. For example, I'd like the script to load on:

mysite.com/blog/page1

mysite.com/blog/page2

but not on:

mysite.com

or mysite.com/blog

or mysite.com/about

I'm using

```
function mytheme_preprocess_html(&$variables) {
  $theme_path = path_to_theme();
  $path = drupal_get_path_alias();
  if($path == 'blog/page1') {
      drupal_add_js($theme_path . '/js/example.js');
    }
}

```

to load the script on that specific page, but is there any way to use a url argument or wildcard or something so that all internal blog pages (i.e. blog/page1, blog/page2, blog/page3) will load the script?

Thanks!

# Answer
> 7 votes
The `drupal_match_path()` function should do the trick:

```
$path = drupal_get_path_alias();
$pattern = 'blog/*';

if (drupal_match_path($path, $pattern)) {
  drupal_add_js($theme_path . '/js/example.js');
}

```

---
Tags: theming, javascript
---


# Question
Title: Converting a project using Drush in localhost
I have a D6 project in my localhost

i.e `C:\wamp\www\ProjectName_6`

I need to migrate the above mentioned project to D7 in the same directory using drush.

Should be like this `C:\wamp\www\ProjectName_7`

I am using Drush Version 5.7 which is located in the following path

`C:\Documents and Settings\All Users\Application Data\Drush\`

Could anyone kindly provide a **step-by-step guide to complete this process** or any **good links which is suitable for new bie**...

I googled a lot. But can't find any good article... (My search keywords may be wrong... )

# Answer
> 2 votes
Drush Site Upgrade 7.x-2.x is for upgrading FROM Drupal 6 sites TO Drupal 7 sites. I know that the version numbering is a bit confusing, but it is based on the fact that the Current version of Drush is 7.x-5.x. This version of Drush supports both Drupal 6 and Drupal 7, but is versioned 7.x to match the most recent stable version of Drupal supported. Similarly, Drush Site Upgrade is versioned 7.x to match the version of Drush that it works with. I added a sentence to the Drush Site Upgrade homepage to clarify that it is for D6 -\> D7 upgrades; the README.txt already explains this.

As for a step-by-step guide to using Drush Site Upgrade, please understand that the Drush Site Upgrade command itself **is** a step-by-step guide to upgrading your Drupal site. This command will print out an explanation of what it is about to do at every step, and then prompt you before taking action. Run with the --always-prompt flag when you're first getting started to insure that absolutely everything will be prompted. If there is a step that is not applicable, or does not work right for your environment, you can tell Drush sup to skip the step, you can do the operation(s) you need to by hand, and Drush sup can continue the upgrade process on the next step. If something goes horribly wrong, you can always start over from the beginning and try again.

As you inferred, Drush Site Upgrade will not actually upgrade the code of your custom modules to D7. For help with that, please see http://upgrade.boombatower.com/.

---
Tags: 7, drush, upgrading
---


# Question
Title: Add "webforms like" values to profile.module select list
Is there a module that can allow me to add custom values to select list items in the Profiles module in Drupal 6, like webforms does it. For example:

```
my_value_1 | my_text_1
my_value_2 | my_text_2

```

which will create a select list

```
<select>
<option value="my_value_1">my_text_1</option>
<option value="my_value_2">my_text_2</option>
</select>

```

# Answer
> 0 votes
Try Content Profile module. Using this module you can create user profile where you can add cck fields to the user profile content type.

> This module builds user profiles as content (aka nodes), which opens the opportunity to use all the powerful modules for content for user profiles too, e.g. the Content Construction Kit (CCK). It's intended to be simple and useful, but extensible by further modules.

---
Tags: webforms, users
---


# Question
Title: How to print a date from Date module using user timezone
I would like to send an email out to a user when a new 'event' content type is posted. In this email, I want to display the title of the event, the body, and the date itself. For the date, I would like to print the date in the timezone of the user receiving the email.

So, when I send the email, I first get the user's account and the event node:

```
<?php
  $account = user_load($uid);
  $event = node_load($nid);
?>

```

I want to first check if the user has a timezone set in the user's profile, and if not, default back to the timezone used (and stored) with the event itself. So, something like:

```
<?php
  $timezone = $account->timezone ? $account->timezone : $event->field_event_date[$event->language][0]['timezone'];
?>

```

But, at this point, I'm not sure exactly how to print the date in the node in the correct timezone. I'm thinking I might have to first create a new DateTime object, then convert it using date.module's date\_format\_date, or maybe convert the date to a timezone, calculate the offset, and use PHP's date() function or format\_date() to display the end result, but this all seems overkill.

Is there a simpler way to print out a date from a date field attached to a node in a user's timezone?

\[Edit:\]

I'm trying to format the date using format\_date() or date\_format\_date(), but format\_date() requires a time stamp, which is difficult to create from the date field's output, and date\_format\_date() also requires proper timezone information when I create a date object, and I've found it difficult to account for the timezone supplied by the date field, and then translate that into the timezone for output.

\[Edit 2:\]

Here's the code I ultimately used:

```
<?php
  $event = node_load([nid]);
  // Build event date + timezone.
  $timezone = $account->timezone ? $account->timezone : $event->field_event_date[$event->language][0]['timezone'];
  date_default_timezone_set($event->field_event_date[$event->language][0]['timezone_db']);
  $date = strtotime($event->field_event_date[$event->language][0]['value']);
  $date_formatted = format_date($date, 'custom', 'M j, Y g:i a', $timezone);
?>

```

# Answer
> 1 votes
You just need to use format\_date() and pass a string for the timezone in the `$timezone` parameter, which by default will use the value returned by date\_default\_timezone\_get().

# Answer
> 1 votes
The problem is the configuration of the date field itself. In its settings (field management-\>edit), you will find an option **"Time zone handling"**. This option controls the way this field is parsed and its display. I will venture a guess that yours is set to "Site's time zone". This means, that the default timezone will be used to convert this datetime into UTC, and the same will be used to display it. If changed to "User's time zone" option, then user's timezone will be used instead, and the default one will be the fallback if none such is set. The latter is taken into account from the format\_date() function, without your having to set the $timezone parameter explicitly.

In your case, since each event has a timezone of its own, I would also consider the second option "Date's time zone". In this case, custom date timezone is not taken into account by format\_date(), thus needs to be explicitly set.

Read the complete documentation here

---
Tags: entities, datetime
---


# Question
Title: How do I set my views to return a 404 using Global: Null under contextual filters?
Standard Drupal behavior is to pass all arguments through, whether or not they requested. Sometimes this behavior is desired. However, I need to return a 404 for anything but a query string.

Example of the problem http://drupal.org/project/modules http://drupal.org/project/modules/google.com \<- This should return a 404; 200 given. Duplicate content penalty!

The views 404 module assumes that by default you do not want arguments passed through. However there is no D7 version of the module.

But the project page says that 404s for views can also be accomplished by setting the Global: Null under Arguments.

Obviously in D7 "arguments" are now "contextual filters", but I am unsure as to what settings to add to the Global:null contextual filter to get my desired result.

Any help would be appreciated.

# Answer
In *Contextual filters* select *Add*; in the dialog box that appears, select *Global: Null*.

Click on *Add and configure contextual filters*.

In the dialog box that appear next, in the fieldset *When the filter value is available or a default is provided*, check *Specify validation criteria*, select *\- Basic validation -* for *Validator*, and select *Show "Page not found"* for *Action to take if the filter value does not validate*. In the fieldset *More*, check *Fail basic validation if any argument is given*.

I tested it with an "Articles" view I created, and it works.

The "Global: Null" argument must be the last one. If you need a user ID, for example, first you add it as argument, and then add the "Global: Null" argument.

I altered the "Article" view to accept a user ID as argument, which is used to filter the list of article nodes. The view still works, as it doesn't accept an extra argument.
> 22 votes

# Answer
You can do this using views out of the box functionality. In every contextual filter setting you can see a check-box "Specify validation criteria" check that to see more settings.

Then, you can select "validator" based on your view conditions. If you would like to custom validate then select php code. Return True or False in php code based on your validation conditions.

Finally select "Action to take" as Display Access denied ! See below screenshot for nid contextual filter.
> 1 votes

---
Tags: views, 7
---


# Question
Title: #states doesn't work with exposed filters
I have two exposed filters Contry (name=field\_country\_tag\_tid) and City (name=field\_country\_tag\_tid\_option\_limit). Reference limit option Module limet avaliale options in city but not when page with filters loaded at first time. That why I wanted to desable City Filter by using #states

```
function mymodue_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'map') {
   $form['field_country_tag_tid_option_limit']['#states'] = array(
  'visible' => array('select[name="field_country_tag_tid"]' => array('value' => '1')),
       );

    }
}

```

I used the following example http://api.drupal.org/api/examples/form\_example!form\_example\_states.inc/function/form\_example\_states\_form/7

But there are no any changes in my exposed filter, where is my mistake? Thanks

# Answer
I tried to use `id` instead of `name` and now it works!
> 0 votes

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


title: views export to xls

text:
# Question
Title: views export to xls
I need to export views into xls file. If I use any of possible modules like views bonus or views xls export, I get a simple file with xls extension but inside is clean html code of the table instead of a compiled code as excell would produce. I can load it into excell and save it as proper xls file but is there a straight solution? Thank you.

# Answer
> 3 votes
Did you try the Views data export module? Here is a quote about it (from the module's project page):

> ... designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV.
> * Microsoft XLS.
> * Microsoft DOC.
> * Basic TXT.
> * XML.
>
> This module also exposes a drush command that can execute the view and save its results to a file.

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


# Question
Title: How do I create a block that has links to site registration and forgot password programmatically?
Can anyone help me writing code for a block containing the "Register" and "Forgot your password?" links that are shown to the anonymous users?

# Answer
If you want to learn, I suggest, look at the relevant part of drupal core: `user_block_info()` \- this is the block info definition.

`user_block_view()` \- This builds the renderable array of block.

You see here `$block['content'] = drupal_get_form('user_login_block');` This makes the complete user login form. If you want to show only the two link, just change this to something like this:

```
$block['content'] = array(
  '#markup' => 'the pure html of your links',
);

```

To check, how to generate the core these links, see the `user_login_block()` in core. The line 1323 is the html markup in you block's content, what do you need
> 1 votes

# Answer
I take you are creating a module to show a block containing those two links. I would use the following code, in that case.

```
function mymodule_block_info() {
  $blocks['login']['info'] = t('User login');
  $blocks['login']['cache'] = DRUPAL_NO_CACHE;

  return $blocks;
}

function mymodule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'login':
      if (!user_is_logged_in()) {
        $links = array();
        $links['register'] = array(
          'title' => t('Register'),
          'href' => url('the link to your registration page'),
        );
        $links['forgot-password'] = array(
          'title' => t('Forgot your password?'),
          'href' => url('the link to your page to get a new password'),
        );

        $block['subject'] = t('User login');
        $block['content'] = array(
          '#theme' => 'links',
          '#links' => $links,
        );
      }

      return $block;
  }
}

```

If you need the code that you use in admin/structure/block/add to create a new block, then you should use the following code in "Block body."

```
<?php
  $links = array();
  $links['register'] = array(
    'title' => t('Register'),
    'href' => url('the link to your registration page'),
  );
  $links['forgot-password'] = array(
    'title' => t('Forgot your password?'),
    'href' => url('the link to your page to get a new password'),
  );

  print theme('links', array('links' => $links));

```

In "Show block on specific pages," select "Pages on which this PHP code returns `TRUE` (experts only)," and enter `<?php return !user_is_logged_in(); ?>` in the text area shown behind.

The text format must be "PHP code," which means the PHP filter module must be enabled.

You need also to assign a region to the block, or it will never appear.
> 0 votes

---
Tags: blocks
---


title: Get date of last update for a view

text:
# Question
Title: Get date of last update for a view
Is there an easy way to check when I last made changes to a particular view or views display?

# Answer
No, unfortunately there isn't. If you look at the views\_view and views\_display tables in the Drupal database, that information simply isn't stored.

I even checked whether you can get to info like that if you're using the Features module with views, but even that only lets you know if a view has been updated since your last created feature, but gives no information about the date of any changes...
> 2 votes

---
Tags: 7, views
---


title: Weekly Calendar Block

text:
# Question
Title: Weekly Calendar Block
I'm looking to display a weekly events calendar. I've set up content type `event` and added a starting day field. What I'm essentially looking for is this:

So the interface is a tabbed one, so as long as I can get the current week and its events grouped by date I should be fine, but I need to be able to pull future weeks via ajax in a manner the Calendar View does. So the question is this: can this be done with some Calendar View template? How can this be put together with views? I tried to modify the Calendar block provided as Views Template, but all I ended up was a monthly block.

Thank you in advance.

# Answer
You can do something quite close to that with views. When you set up your view (or just use the one that comes with the Calendar module and clone it and start editing your new copy).

Just make sure you go to the **Calendar settings** and choose 'Week' as your Calendar type:

Of course, you have to choose which fields to display for your event type and here's what you'll roughly end up with:

I've added css to my theme to change the look of this calendar page, and that's probably a separate topic. Most of the functionality you want is available through the calendar module... just set your type!!

Hope this helps.

================= EDIT =========================

So, after reading your comment, here's how I'd modify the solution above. Same calendar, but choose 'Day' as the calendar format. Then under the 'Header' section, add a Header and choose "**Global: text area**". Here, using php, we can output links to how many ever days you need before and after today's date... since this doesn't happen automatically. You'd need to enable the php filter module to make this possible.

So, using the 'php filter' format for the global text, you can add the following code (I would check it to display even for empty views...):

```
<?php
print( "<a href=" . date('Y-n-j') . ">" . date('l') . "</a> | ");
print( date("l",strtotime("+1 days")) . " | ");
print( date("l",strtotime("+2 days")) . " | ");
?>

```

The above just prints out today's week day, then tomorrow and the day after. You can change to suite your needs. I've also only printed the first one as a link. You see, the day calendar format can be navigated by just going to /2012/11/23 to get to Nov. 23rd of this year, etc. Very easy to figure out the links, so you can build your own menu using php in the header.

This is the output you'd get, and of course, you can always beautify with css:
> 3 votes

# Answer
You must use views module with Calender module, see this video to learn how to do it, but after you fishing creating your calender view you must make some CSS changes.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Views Taxonomy Term argument to represent "no term"
With Views 2.x, Drupal 6, I've created a taxonomy and have enabled it for a Content Type. I then create some content:

node\_1 is associated with term\_1 (tid=1)
node\_2 is associated with term\_2 (tid=2)
node\_3 has no term association

I've created a Node View that has an Argument for "Taxonomy: Term ID". In the argument configuration, I enable "Allow multiple terms per argument".

Using the Live Preview for the View, I can pass in arguments. So I pass in "1" and the view shows me node\_1. I pass in "2" and the view shows me node\_2. I pass in "1+2" and the view shows me node\_1 and node\_2. This is good.

What I can't figure out is how to pass an argument that will return me just node\_3. Is there something I can pass to Arguments that essentially means "no argument"?

# Answer
> 1 votes
Just in case anyone else stumbles upon this answer, we solved this problem with the following approach:

```
function MODULENAME_views_query_alter(&$view, &$query) {

  if($view->name == 'your_view_name')){

    //Flip the term table join to a LEFT join
    $view->query->table_queue['term_node_value_0']['join']->type = 'LEFT';

    //CLear the extra condition (removes a where clause on the join limiting only matching term ids)
    $view->query->table_queue['term_node_value_0']['join']->extra = null;

    //Look through the where clauses and add a null condition clause
    if($index = array_search('term_node_value_0.tid = %d', $query->where[0]['clauses'])){
      $query->where[0]['clauses'][$index] .= ' OR term_node_value_0.tid IS NULL';
    }
  }
}

```

It changes the JOIN type to a LEFT join, removes the limiting clause from that join and adds a condition to match against null values. It's obvious limitation is that it should be using aliases instead of hard coding the field name.

The function should go in your modules views.inc file where Views expects to find this hook.

---
Tags: views
---


# Question
Title: How does Drupal handle non Drupal sub directories?
I have a question about how Drupal handles requests made to subdirectories of the Drupal root that aren't under Drupal control.

What I mean is lets say I have a Site directory as such:

My main site -- an HTML flat site -- includes -- sites -- ... Other drupal necessary files

My concern is: does Drupal load bootstrap on every server request made to its directory? For example, I go straight to mysite/anhtmlflatsite - does Drupal do any type of loading? Or does it just let the web server serve up the sub directory no Drupal love added?

I ask because right now when accessing these flat sites I'm noticing that some files in my includes directory are getting hit (we have them push messages to the error log so that's how I know they're getting loaded when I access these flat sites). Also whenever the Drupal install breaks so do the paths to these flat HTML nothing to do with Drupal sites as well.

Curiouser and curiouser... Anyone have any insight to what's down the rabbit hole?

Oh and I'm using Drupal 7

# Answer
> 3 votes
The default .htaccess file has these lines in it:

```
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

So Drupal will only attempt to take control of a path if the file or directory doesn't already exist. All requests to your flat HTML site should be served without Drupal getting involved.

Maybe you've got some 404s in your flat HTML site? If they point to a folder underneath the web root that might explain why Drupal is getting hit.

---
Tags: .htaccess, files
---


# Question
Title: file_create_url printing different addresses on live and local installations
I'm using the following code to print out the path of an image uploaded through theme-settings.php:

```
<img src="<?php print file_create_url(file_build_uri(theme_get_setting('my_setting')); ?>" />

```

Locally, everything works fine -- the path renders as I expected:

```
http://localhost/drupal/sites/default/files/image.jpg

```

When the site is online, however, the same code renders the following address:

```
http://www.mydomain.com/sites/default/files/public%3A//image.jpg

```

Does anyone know why public:// would be printed out on a live server but not on a local installation? My guess is that the problem is related to the use of file\_build\_uri.

I'd like to find some code that prints out the URL correctly on both live and local installs. Perhaps I'm not using the best approach with the API to achieve this end?

# Answer
> 1 votes
The following code worked on both the local and live install:

```
<?php print file_create_url(theme_get_setting('my_setting')); ?>

```

---
Tags: files, uri
---


# Question
Title: How can I display the last modified date on my site?
I am using Drupal 7, and I would like to include a PHP snippet on my home page that displays the date the site was last updated (i.e., had content added or modified).

How can I go about doing this?

# Answer
Assuming you just want to check nodes (and not other content, like users), you'll want to check the `node` table and find the row with the latest `changed` timestamp. This function should do the trick:

```
/**
 * Get the last updated date for nodes.
 *
 * @return
 *   A formatted date for the last updated time if there are published nodes,
 *   FALSE otherwise.
 */
function _mymodule_last_updated() {
  // Pull from cache if available
  if($cache = cache_get('mymodule_last_updated')) {
    $last_updated = $cache->data;
  }
  else {
    // Otherwise, find the timestamp for the latest node record
    $last_updated = db_select('node', 'n')
      ->fields('n', array('changed'))
      ->condition('status', 0, '>') // only published nodes count
      ->orderBy('changed', 'DESC')
      ->range(0, 1)
      ->execute()
      ->fetchField();

    // If nothing found, return FALSE.
    if (!$last_updated) {
      return FALSE;
    }

    // Otherwise, save the data to cache for one hour.
    cache_set('mymodule_last_updated', $last_updated, 'cache', time() + 3600);
  }

  return format_date($last_updated);
}

```

Now, wherever you wanted to put the information, just call `_mymodule_last_updated()`:

```
if ($last_update = _mymodule_last_updated()) {
  $last_update_text = t('Last updated: @name', array('@date' => $last_update));
}
else {
  $last_update_text = t('There have been no updates lately.');
}

```

However, I'd suggest creating custom module and defining a block. This would allow you to avoid having to mess with the PHP code any time you wanted to move the information around, and expose it to others who don't have access to the source code.

Once you've created your custom module, you want to implement the `hook_block_info()` and `hook_block_view()` hooks:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks['mymodule_last_updated'] = array(
    'info' => t('Last updated block'),
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();

  // Only act if it's our block
  if ($delta == 'mymodule_last_updated') {
    $block['subject'] = t('Last updated');

    if ($last_update = _mymodule_last_updated()) {
      $block['content'] = t('The site was last updated on @date.', array('@date' => $last_update));
    }
    else {
      $block['content'] = t('There have been no updates.');
    }
  }

  return $block;
}

```

Once defined, your new block would show up in *Structure**Blocks*.

***Note:** in all of these snippets, you'll want to replace `mymodule` with your custom module's name.*
> 4 votes

# Answer
Use trigger module in the core to keep track all the modify events of your system. And save the time of that event to a global variable by variable\_set(). Thus you don't need to query the whole nodes table each time a page viewed. And you can keep track of other entity\_type's modification.
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Pressflow + CDN, node access counter not updating
I am using Pressflow (Boost+Varnish) with "boost ajax stat block" enabled for stats, things were working ok and node counter was getting updated. Few days ago I started using full-site acceleration via CDN and the node access counter (page reads) is no longer updating ?

In theory boost ajax stat should work with caching, why is it not in this case ?

Website : http://www.megaleecher.net/

# Answer
Finally found a working solution.

Module - http://drupal.org/project/jstats gets the job done, make sure to copy the **jstats.php** file into root.

Thanks
> 1 votes

---
Tags: 6, caching, cdn
---


title: Schedule Delivery Time and Date

text:
# Question
Title: Schedule Delivery Time and Date
Is there a module from Drupal Commerce to schedule Delivery date and time ?

Customer is required to specify the date and time. This then will be displayed in the admin side.

thanks appreciate your help

# Answer
> 2 votes
Check it out Commerce Field Group Panes module. Using this you can able to add field Delivery Date & Time field to check out process.

> This enables an easy way to collect information in the checkout process. For example customer comments, feedback about where the customer founds the shop or any other fieldable information.

---
Tags: commerce
---


# Question
Title: Create jump menu with more options using programmatically
I am using Drupal 7 and CTools. I want to create a jump menu using Ctools. I have checked the example code provided in the Ctools module. And it is working fine for one link only.

How do I add more links in Jump menu:

In the code shown below, look at here: **$url = url('mypostings/groupsort');** I want to add more links in the jump menu,like url('mypostings/test1'), url('mypostings/test2') etc..

```
/**
 * Implementation of hook_menu();
 * @return
 */
function post_display_menu() {
    $items['mypostings'] = array(
            'title' => 'My Posts in Group',
            'page callback' => 'get_my_postings',
            'access callback' => TRUE,
            'expanded' => TRUE,
    );
    $items['mypostings/groupsort'] = array(
            'title' => 'My Postings Filter',
            'page callback' => 'get_my_posting_filter',
            'access arguments' => array('access simple page'),
    );
    return $items;
}

function get_my_postings() {
    global $user;
    // Include the CTools tools that we need.
    ctools_include('ajax');
    ctools_include('modal');
    // Add CTools' javascript to the page.
    ctools_modal_add_js();
    $header = array(
            array('data' => t('Title'), 'field' => 'n.title'),
            array('data' => t('Created'), 'field' => 'n.created'),
            array('data' => t('Author'), 'field' => 'u.name'),
    );
    $query = db_select('node', 'n');
    $query->leftjoin('users', 'u', 'u.uid = n.uid');
    $query->fields('n',array('title', 'created'))
    ->fields('u',array('name'))
    ->groupBy('n.nid');
    $result = $query->execute();
    $rows = array();
    foreach ($result as $row) {
        $rows[] = array('data' => (array) $row);
    }
    $build['tablesort_table'] = array(
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
    );

    drupal_add_js($sample_style, 'setting');

    ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
    ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');

    $output .= $build;

    // Create a jump menu
    ctools_include('jump-menu');
    $form = drupal_get_form('post_filter_jump_menu_form');
    $output .= '<h3>'. t('Jump Menu') .'</h3>';
    $output .= drupal_render($form);

    return array('markup' => array('#markup' => $output));
    return $build;
}

/**
 * Helper function to provide a sample jump menu form
 */
function ctools_ajax_sample_jump_menu_form() {
    $url = url('mypostings/groupsort'); // I want to add 3 links in jump menu How can i add it
    $form_state = array();
    $form = ctools_jump_menu(array(), $form_state, array($url => t('Sort')), array());
    return $form;
}

```

# Answer
See below code !

```
$form = ctools_jump_menu(array(), $form_state, array($url => t('Jump!') , 'http://www.google.com' => 'Go to google'), array());

```

OR

```
$options = array();
$options[$url1] = $label1;
$options[$url2] = $label2;
$form = ctools_jump_menu(array(), $form_state, $options, array());

```

Third argument of ctools\_jump\_menu is $select which is

> An array suitable for use as the #options. The keys will be the direct URLs that will be jumped to, so you absolutely must encode these using url() in order for them to work reliably.
> 2 votes

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


# Question
Title: how do I add a favicon to RSS feed in Bitnami Drupal?
I have the Bitnami Drupal AMI that is on the AWS marketplace. I have set up a blog and it is being syndicated at another site.

Everything is working great (the Bitnami Drupal AMI rocks), but (you knew there was a "but") I see other blogs that are being syndicated and they have favicons.

How can I get a favicon into my Drupal blog's RSS feed so a favicon shows up when that feed is syndicated at another site?

# Answer
You can try to modify the line 1611 of the file *installdir/apps/drupal/htdocs/includes/theme.inc*. Change feed.png for the name of your image previously placed in the folder *installdir/apps/drupal/htdocs/misc/*

The original line is:

```
  if ($image = theme('image', 'misc/feed.png', t('Syndicate content'), $title)) {

```
> 0 votes

---
Tags: feeds
---


title: Drupal 7 Tokens in Field Help text

text:
# Question
Title: Drupal 7 Tokens in Field Help text
In Drupal 7, I've created a content type, with a textfield. In the field settings, I'm invited to add some "Help text", and the description for this specifically says "This field supports tokens".

However, I'm finding that the tokens are never replaced with actual values. The token just displays literally under the form field.

I've also been unsuccessful when testing with "simpler" tokens than "current-date". What am I missing?

# Answer
Tokens in the "Help text" field work, at least for the taxonomy term reference field.

I tried adding "\[current-date:long\] \[current-user:ip-address\]" to the help text of a taxonomy reference field, and I obtained the following.

Tokens didn't work for the image field, though.

I have also tried with \[current-date:custom:e\], and it worked.

What confused me is that I didn't notice the summary of available tokens I normally expect from the Token module. It doesn't appear for the taxonomy reference field, but it appears for the image field, for which the tokens are not replaced.
> 1 votes

---
Tags: 7, entities, tokens
---


# Question
Title: Create a block with sorting in drop down
Using Organic group module, In the block I want to create sort dropdown as shown in image. Which will allow to sort the data according to various parameters like date, tag, group etc.

How can I achieve it programmatically.

# Answer
You can use table display to manage the listing of all the posts. Now to filter/sort the data you can user ctools jump menu. Using Ctools jump menu you can create various menu items for different sorting type.

To see the example of Ctools jump menu see the **ctools\_ajax\_sample** module which comes with Ctools module package.
> 0 votes

---
Tags: blocks
---