# Question
Title: How to create a View displaying the list of files attached to a page?
I have added a file-field to my Page content type and activated the description field. Multiple files are allowed.

I want to create a block (with Views) that displays the list of files (descriptions with links) attached to a given page.

I have tried 2 approaches:

1. In views I have added a relationship with files, but the description is not accessible from the list of fields provided (filename, size, extension, but no description)
2. Create a new display (in addition to default and Teaser ) with the Content:Files field, it displays the list nicely **BUT** it shows the title and I can't see any option to disable it.

If someone has an idea that would be great! Thanks a lot.

# Answer
If this is for Drupal 7, a solution I found was using Rewrite Results. Create a view showing Content of type Page which displays an unformatted list of fields. Within the View, under fields add your File Field. In the settings for the field set the Formatter to URL to file, remove the label and then under Rewrite Results tick "Rewrite the output of this field". Within this section you have access to the files description field so you can enter something like

```
<a href="[field_files]">[field_files-description]</a>

```

Which will output the description as a link to your file.
> 2 votes

---
Tags: views, files
---


title: Trying to make view template

text:
# Question
Title: Trying to make view template
I have a content-type that has an imagefile and a url; I want the url to wrap around the image. So I'm trying to make a viewtemplate based on the information in `Theming information`

based on this description

```
/**
  * This template is used to print a single field in a view. It is not
  * actually used in default Views, as this is registered as a theme
  * function which has better performance. For single overrides, the
  * template is perfectly okay.
  *
  * Variables available:
  * - $view: The view object
  * - $field: The field handler object that can process the input
  * - $row: The raw SQL result that can be used
  * - $output: The processed output that will normally be used.
  *
  * When fetching output from the $row, this construct should be used:
  * $data = $row->{$field->field_alias}
  *
  * The above will guarantee that you'll always get the correct data,
  * regardless of any changes in the aliasing that might happen if
  * the view is modified.
  */

```

I made `views-view-field--my-view--block--field-image.tpl.php` to look like this:

```
$url = $row->{$field->URL}
?>
<a href="<?php echo $url; ?>" target="_blank">
  <?php print $output; ?>
</a>

```

But I'm getting `Cannot access empty property` on the `$row->{$field->URL}` line. Can I only access the image field from within the template for the image field? I was looking at `views-view-fields--my-view--block.tpl.php` but not sure how to access things from in there

# Answer
I would do the following: `<pre>` `<?php print_r ($row); ?>` `</pre>` This will give you the full tree of the $row
> 1 votes

# Answer
Instead of doing this in a template file you could do this by using Rewrite Results within the field settings of a view, either by creating your own Global custom text field or editing the settings of the link field or image field. In the rewrite results section you can create a link around the Image as long as the image and the link are both fields within the view.
> 0 votes

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


# Question
Title: Does Apachr Solr use Taxonomy or CCK fields for faceted search?
I'm trying to put together a simple faceted search block using Solr. Search with Solr works, but I'm unsure of what's required for creating a block of search properties for faceted search.

For example, my content is for accommodation, so I want to be able to search by price range, capacity and location. Price range and capacity data are already populated as CCK fields, but location is set up as a hierarchical taxonomy.

I'm wondering what Solr requires for me to implement a simple, faceted search block. Does it use CCK fields for search properties or Taxonomy? Or have I misunderstood how faceted search blocks for Solr are built?

# Answer
> 1 votes
Out of the box, apachesolr.module 6.x and its friends can facet on taxonomy and cck text fields (with certain limitations). You just need to enable the desired facets in the settings, having made sure that the vocabulary is actually connected to your content type in the vocabulary settings.

For price range / any numeric range faceting I have not found a working contrib module. There is a module though, http://drupal.org/project/apachesolr\_facetbuilder which allows you to build at least categorized facets for your numeric values.

---
Tags: search
---


# Question
Title: file upload using CCK not showing nid reference
I have uploaded the image using CCk the file path is stored in file table but where i can find the nid and fid for the uploaded file?

# Answer
> 0 votes
So lets say you have a content type X. You add a field Y to X to upload a file (using filefield or image etc) then you will find the nid and fid in the field table created by cck. This table will be something like content\_field\_Y which should have the nid and fid that you desire.

Update: To clarify the column name will not be simply fid, but will be the machine name of the field suffixed with \_value, \_nid etc.

---
Tags: files
---


# Question
Title: How to restrict permissions for administering Taxonomy?
I would like a user role to be able to add/edit terms for a specific vocabulary, but not all vocabularies.

In the permission settings for taxonomy, it seems that I need to give the role permission to 'Administer vocabularies and terms'. But then they can edit *all* vocabularies; the edit/delete permissions for each vocabulary don't have any effect?

I've seen various taxonomy access modules, but they seem to restrict the use of terms on nodes etc. My situation is more simple; a specific role just needs to be able to add additional terms to a vocabulary.

What am I missing here?

# Answer
For D7 there is a taxonomy access fix module. It makes it possible to manage access permissions to individual vocabularies.
> 9 votes

# Answer
Try to use some specific taxonomy access modules that may help you like Taxonomy Access or TAC lite.
> 1 votes

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


title: Move footer structure to html.tpl.php

text:
# Question
Title: Move footer structure to html.tpl.php
I've attempted to move the footer structure of a theme from page.tpl to html.tpl so the footer elements can occur outside of internal width specific layout.

In doing so I receive an error:

> Fatal error: Only variables can be passed by reference in....

One of the many lines in question is:

```
<?php print render($page['footer_first']); ?>

```

Can someone explain what exactly the issue is here and how I can best solve it ? Muchly appreciated!

# Answer
I am not too sure what this error would be caused by but I would recommend instead of putting the footer into the html.tpl.php put a wrapper div around the other elements within the page.tpl.php excluding the footer and styling that wrapper with a specific width.

eg.

```
    <div class="wrapper" width="960">
      //all content in here
    </div>
    <div class="footer">
      //footer here
    </div>

```
> 2 votes

# Answer
the regions (for example $page\['footer\_first'\]) are not available in html.tpl.php. Why wouldnt you want to render it in the page.tpl.php? You can however create a hook like this:

(From drupal api page)

```
<?php
function hook_preprocess_html(&$vars) {
  $vars['page']['page_bottom'][] = array('foo' => array('#markup' => 'foo'));
  // Or other render array stuff
}
?>

```
> 0 votes

---
Tags: theming
---


# Question
Title: Will the Search API increase performance of searches in the Views Exposed filter?
How to increase the performance, if one of the main activities on a website would be searching in Views exposed filters? Will the Search API module (with Database Search/not Solr) significantly increase the performance of such searches?

# Answer
It probably will, depending on the Search API backend you are using. Something generally true is if you are using any other backend than database, the querying for the search will be dispatched to this additional backend instead of the database, which is Drupal primary storage, and will avoid your database a lot of suffering.

It will also makes things easier to scale, since a lot of search engines can be replicated more easily than database. Even without this statement, you can at least put the SQL server and the search engine on different servers, which means they will eventually be faster since they won't have to share one box resources.

It doesn't mean it will be faster in all cases, it depends on your environment and configuration.

Regarding the queries themselves, if you are doing a lot of fulltext searches, using a backend such as Apache SolR (or any other search engine, Xapian, etc...) it will surely be a lot faster since they have been made for this. If you are doing facet oriented search, it will also help a lot.

But, in the end, if your views filter only are on exact strings, integers and such, it may not be faster in the end, it will just be more scalable.

You have to remember that creating an index for your data will also imply that you install a whole lot of modules in your Drupal site, you'll have to benchmark a bit. But if the primary business matter of your site is searching, I'd say give it a try.

I don't know if my answer sounds good.
> 3 votes

---
Tags: 7, performance, search
---


# Question
Title: Drupal Commerce: Alter 'Checkout' link in user menu
How do you hook into the 'checkout' link in the user menu?

If there is an item in the basket, want to be able to add a class to the 'checkout' link.

Ideally from the theme template and not hacking the core.

# Answer
Use this function in your custom module to return a bool for determining if there items in the basket/cart.

```
function items_on_cart(){
global $user;
$cart = commerce_cart_order_load($user->uid);
$line_items = count($cart->commerce_line_items) ? true : false;
return $line_items;
}

```

Then in your theme template do the following...

```
function YOURTHEME_menu_link(array $variables) {

    $element = $variables['element'];
    $sub_menu = '';
    $name_id = strtolower(strip_tags($element['#title']));

    // add class to checkout link if basket active
    if ($name_id == 'checkout') {
        if (YOURMODULE_items_on_cart()) {
          $element['#localized_options']['attributes']['class'][] = 'active';
        }
    }

```
> 1 votes

---
Tags: commerce
---


title: Showing Details with Drupal Views 3

text:
# Question
Title: Showing Details with Drupal Views 3
I have a table structure for fee details as

```
fid
name
description
currency
fee
instalments
created

```

This fee schedule has N no of instalments and storing in a cross ref table as

```
iid
fid
instalment_no
amount
payable_by

```

This fee schedule has associated students and are storing in a cross ref table as

```
fid
uid

```

I need to show the details of a fee schedule to end user with all installments and students. Is this possible to get this fee detail page using views 3.

Please help me to write the SQL to fetch fee details with students and fee instalments.

Thanks in advance for your help.

**EDIT**

One of my friend suggested me to create three displays in views each showing result from each table i.e. first display to show the fee details, second fee instalments and third to show the fee students. Then in page display all three views by using the functions views\_get\_view. Thanks Inian :)

While doing the way Inian suggested, I found attachment as a display type and that solved my problem and I don't have to write any custom code now.

Umar

# Answer
One of my friend suggested me to create three displays in views each showing result from each table i.e. first display to show the fee details, second fee instalments and third to show the fee students. Then in page display all three views by using the functions views\_get\_view. Thanks Inian :)

While doing the way Inian suggested, I found attachment as a display type and that solved my problem and I don't have to write any custom code now.
> 0 votes

---
Tags: views
---


# Question
Title: Should I disable all UI modules once the site is in production?
Just wondering if I should I disable all UI modules once the site is in production? e.g.: Context UI

Most of them are not required for any other module.

# Answer
> 5 votes
This is probably considered best practice in terms of performance because on every call each module is loaded into memory and executed.

However you may find it annoying to have to constantly re-enable the modules, particularly with views or rules.

---
Tags: 7
---


# Question
Title: theme_key does not switch theme when URL user/<uid>/edit is called
Hello fellows and Gurus,

I am having a problem with a mobile theme of our standard website (running Drupal 7)

We therefore have two URLs:

* mywebsite.com
* m.mywebsite.com

We use the ThemeKey module to redirect to the correct theme/templates. We also tried Mobile Tools, but it does not work any better, so it is currently disabled.

For most pages, the url detection works and successfully redirects to the mobile theme when `m.mywebsite.com/<somepage>` is called.

However, when user wants to edit his own profile (`m.mywebsite.com/user/<uid>/edit`), the standard page is shown instead.

Same happens with the "cancel account page" (`m.mywebsite.com/user/<uid>/cancel`).

However the registration page (`m.mywebsite.com/user/register`), and the forgot your password page (`m.mywebsite.com/user/password`) works OK. Even when the user is connected for the latter.

Any ideas of what could be wrong in our configuration/code ?

# Answer
Here is the answer : http://drupal.org/node/1130158

To quote:

> `user/%/edit is` an admin path. See function user\_admin\_paths for details.
>
> So if you enabled an "Administration theme" at "`/admin/appearance`", this theme will be applied instead of any theme configured using ThemeKey.

Also: Don't forget to specify "system" in your settings for theme\_key.
> -1 votes

---
Tags: theming, users
---


# Question
Title: Which is the theme template file that contains the logo image of the site?
I need to change the output of the logo (to make it adapative) of a site. Which is the theme template file that contains the logo image of the site?

# Answer
The `$logo` variable is printed from `page.tpl.php` *around* line 77.

```
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" /></a>
<?php endif; ?>

```

Depending on what you want to do though you could also use `template_preprocess_page()`.
> 1 votes

---
Tags: theming
---


# Question
Title: How to perform action after a file is deleted?
Is there an API hook I could use to run some custom PHP code after a file is deleted? I need access to the name of the file which has just been deleted.

I attempted using hook\_nodeapi, and testing for when the operation is delete, but it seems by this stage the file row has been removed from the database, and I'm left with just information about the node itself.

I'm using Drupal 6. (I see that Drupal 7 *does* have a hook: hook\_file\_delete)

# Answer
> 2 votes
I believe you can use FileField; this module is now part of Drupal 7 core, and provides additions to the API, such as hook\_file\_delete().

---
Tags: hooks, files
---


# Question
Title: How to add HTML to page following user/register to track Google AdWords conversions?
I want to track conversions for Google AdWords. Basically I want to track when people sign up via the user register page (i.e. when they click join).

Google provides code (which is basically a little image) which it says I have to add to the page I want to track. I figure I need to add this to the page which comes after the visitor clicks the join button at the bottom of the `user/register` page.

(1) Is there a module to do this (Drupal 7)? OR
(2) How can I add HTML to the page following the `user/register` page (perhaps using `hook_page_alter`)?

# Answer
> 1 votes
In case of GA or some of the social plugins, you can just add the code in a custom block with FULL HTML format, so you can try creating custom block (maybe in footer) with your code and set the pages where it will appear to `user/register`

---
Tags: 7, hooks, advertising
---


title: Showing total of amount in view

text:
# Question
Title: Showing total of amount in view
I am listing the fee of students in a view developed using views 3. How can I show the total of fee for all records displayed at bottom as Total Fee:

Thanks for your help.

# Answer
> 2 votes
Sounds like a job for Views Calc.

> This module adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

---
Tags: views
---


title: Paging & panels

text:
# Question
Title: Paging & panels
I have a site with a front page that is built up with different blocks; some of these have paging activated. They work great because they are Ajax controlled.

When you scroll all the way down to the bottom, use the pagination, and change page, the blocks change page too, and end up to the same page.
I would love to have my panel to react in such a way that when you change the page using the pager at the bottom, the blocks don't change page too.

How can I achieve it?

# Answer
You will need to ensure that each pager has a different pager id. Normally, you only have page=X in the url, but if several blocks "listen" to that, you get this behaviour. If your blocks comes from Views, then there is a pager setting for setting an alternate pager id, which exists specifically to work around this.

If your pagers come from a different module, you will have to open an issue with that module about how to change the pager id.
> 2 votes

# Answer
Just use the Ajax pagination too in the bottom panel; it won't conflict again.
> 0 votes

---
Tags: paging
---


# Question
Title: Robust handling of the pager in an Ajax controlled View, when URI is shared with another user?
I have a gallery content type, it references a number of images. When viewing gallery content, a View renders a gallery image, and a pager set to display a single item at a time allows the user to go back and forth with a link that will *change the url*.

As a user, I can now copy the URL and send it to someone else, who will see exactly the same image.

Problems show up however, when we decide to load *only* the new image, instead of the whole page, with JS. Since we no longer change the url, the JS-using user will remain at `page=0` all the time, and can no longer share this URL as intended.

I have two suggestions of my own, but I haven't implemented either yet, and would love to hear either comments on those, different answers, or just votes on whichever answer you think is the best.

# Answer
> 0 votes
With Javascript, I could manipulate the `#` value of the URL without triggering a page reload. Using this, a custom Javascript pager could be implemented, that will override the `?page` value with any `#page` value instead. Unfortunately that would mean loading two images. This way, paging with JS will update the `#page` value, and this url can then shared and get the intended behavior.

# Answer
> 0 votes
When using Javascript, the next/previous button could manipulate the `#` part of the URL with a `page=X` variable, and then if this is sent somewhere using a service like facebook or twitter, we just parse the `#page=X` into `?page=Y` instead. If the url is copied directly, then we manipulate the copied text with JS to remove the `#` and move it's value into `?`.

I believe I've seen such JS url-mangling practices before, but I also though that browsers protected the clipboard from manipulation with JS.

---
Tags: views, javascript
---


title: Different logo on different pages

text:
# Question
Title: Different logo on different pages
I want to switch my site logo for different pages. Actually there are two site logo's that need to appear on different set of pages on my drupal 6 website.

What is the easiest way of doing this? Is there any module available for doing this or some other easy steps??

# Answer
> 1 votes
This module appears to have helped many: Logo Tool

From the Logo Tool page:

> A simple tool to display either a random logo on every page refresh, else display a specific logo on specified pages and a default set logo on all unspecified ones.

---
Tags: 6
---


# Question
Title: How to programmatically modify fields of taxonomy terms?
In D7, how do I programmatically add/modify fields to taxonomy terms? They are clearly fieldable and in UI I can add and edit fields in them just like I do in nodes but it proved to be no easy task in the code. Say I have a vocabulary named Fruit with terms like Apples and Bananas. I've added a field to it named `main_article_id`, so all terms have Name, Description and Main Article Id. When I create a node named Apples that has a reference to the Fruit vocabulary (`field_fruit`) and Apples term is selected, the code should update Apples term and set its `main_article_id` field to `$node->nid`. Here is my code:

```
//hook_node_insert fires after new node has been inserted into db
function MYMODULE_node_insert($node)
{
    $taxonomy_term_id = $node->field_FRUIT[LANGUAGE_NONE][0]['value'];
    $taxonomy_term = taxonomy_term_load($value['tid']);
    if($taxonomy_term != FALSE)
    {
        //doesn't work
        $taxonomy_term->field_main_article_id[LANGUAGE_NONE][0]['value'] = $node->nid;
        taxonomy_term_save($taxonomy_term);
    }
}

```

# Answer
The column name for a field isn't always `value`; in the case of taxonomy term references it's `tid`, and in the case of node/entity references it depends on what module you're using.

For a field created using the References module the name is `nid`, and for one created using the Entity Reference module, it's `target_id`.

The following code should work a bit better:

```
//hook_node_insert fires after new node has been inserted into db
function MYMODULE_node_insert($node)
{
    $taxonomy_term_id = $node->field_FRUIT[LANGUAGE_NONE][0]['tid'];

    // $value['tid'] isn't defined anywhere in this function scope so I
    // assume you meant to use $taxonomy_term_id here
    $taxonomy_term = taxonomy_term_load($taxonomy_term_id);
    if($taxonomy_term != FALSE)
    {
        $column_name = 'nid'; // Or 'target_id' if you're using entity reference

        $taxonomy_term->field_main_article_id[LANGUAGE_NONE][0][$column_name] = $node->nid;
        taxonomy_term_save($taxonomy_term);
    }
}

```
> 9 votes

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


# Question
Title: Use body field for views nivo slider instead of title field
I'm implementing a Views Nivo Slider on a Drupal site. It's currently taking the title field for the caption and using the whole text as a link. How can I configure it to use the body field for the caption so I can just have specific words for links instead of the entire field?

# Answer
When you set up the view, you can click on the Row Style options (the little gear thingy :) and then it will give you three options, Image Field, Title Field, and Link Field. The Title Field is the Caption and you can put any field that you've selected in your view (in Fields) you want for it. So, if you've selected Node Body as a field, you should be able to select it there. But, just as using the Node Title, it will put in the whole body (or at least what part will fit I'd imagine) in the caption. If you want something else, you may want to consider yet another field in your content type, or some sort of views rewriting of the field.
> 0 votes

---
Tags: 7, views
---


title: Correct server permissions

text:
# Question
Title: Correct server permissions
> **Possible Duplicate:**
> What are the recommended directory permissions?

I have recently installed a site on a debian LAMP server. I've finally got to work by changing the permissions to -

/sites - 755

/sites/all - 755

/sites /default - 755

/sites /files -777

/sites /default/settings.php -755

/private -777

/public -777

/sites /files/tmp -777

However, i am unsure if these are the correct permissions to use and they don't create any vulnerabilities.

Thanks in advance.

# Answer
This is all subjective to your situation, but...

If you're the sole developer on the site then you just need to make sure that your Apache user's group has write access to your files directories (or any other directories where files are uploaded or generated. That way both you and apache can access those files using 775 mode.

If you uploaded all of the directories as a user with a primary group that apache is not in, you are better off changing the group to one that apache is in and keeping 775 rather than granting 777 permission.-

If you're on a shared hosting, in some cases group write permission on files is dangerous, so don't do the above in that situation.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Why are field widgets not form elements?
Form elements are often separate from field widgets, yet they implement very similar functionality.

Sometimes, their functionality also creep across the two apis, such as in this question: Is displaying a working Field Widget Form on its own possible?

It seems logical to me that a field widget could *be* a form element, that *also* happens to map directly to some underlying storage, especially since form api was already in place when field api came about.

I'm wondering why this is not the case.

**Edit:** As pointed out by kiamlaluno below, according to the official docs, widgets *are* Form API elements, which means I need to edit my question a little.

I came about wondering about this, because I wanted to use the Core tagging widget as a form element. To the best of my knowledge however, there is no easy way of doing that. Despite the docs *claiming* widgets are elements, that does not seem to necessarily be true.

If a widget was declared as

```
function hook_widget_info() {
  return array('my_widget' => array(
    'base element' => 'some_form_element_machine_name',
  ))
}

```

then the element definition would be separate from the widget, so that it could be used on both ways, but currently this is not the case.

**Edit 2:** Feature request opened.

# Answer
> It seems logical to me that a field widget could be a form element, that also happens to map directly to some underlying storage

Widgets are form elements; they just have additional capabilities a form element doesn't have. The documentation about the field widget API describe the widgets using the following words:

> Widgets are Form API elements with additional processing capabilities. Widget hooks are typically called by the Field Attach API during the creation of the field form structure with field\_attach\_form().

Every widget is implemented using at least one form element, but a module implementing a widgets needs to implement some hooks that are not required from a form element:

While the first can be considered the equivalent of hook\_element\_info(), the other two are additional hooks necessary for the widgets to work. It's thanks to the information passed to `hook_field_widget_form()` that a widget is rendered.

Drupal could have implemented widgets expanding the properties returned from `hook_element_info()`, but the truth is that a widget and a form element are two different things that are used in different cases; consider a widget a more specialized type of form element.
If `hook_element_info()` were used also to return information about widgets, the code looking for widgets would need to filter out the form elements to keep the widget information; vice versa, the code looking for form elements should filter out the widget information. Considering how ofter that information is required, that is the reason why two different hooks are necessary.

Drupal could have used a "base element" property returned from `hook_field_widget_info()`. If such property has not been implemented, it means nobody proposed it, or it has been proposed, but it has been though to be useful on few limited cases.

As for Drupal 8, things changed a little, and form elements are objects of classes implementing `FormElementInterface`, while field widgets are objects of classes implementing `WidgetInterface`. The interface that is common between those interfaces is `PluginInspectionInterface`, which doesn't define any method for rendering a form element, which are instead defined from `RenderElement`, an abstract class.
Since now widgets are implemented with classes, the base widget is essentially the base class from which a widget class is derived; there isn't the need of a property to define the base widget of a widget.
> 11 votes

---
Tags: entities
---


title: Views: redirect to default value URL

text:
# Question
Title: Views: redirect to default value URL
When you have a contextual filter in Views and the value is not in the URL, how do you make Drupal actually redirect browser to the default value that you provide, so that the value is reflected in the address bar?

Say you have a view of a company affiliates and the path is: `company/affiliates/`. If I provide a fixed value such as `oregon`, I would like the user (= the address bar) to be redirected to `company/affiliates/oregon` upon visiting `company/affiliates/`. Is there a way to do that?

# Answer
> 0 votes
Answering my own question: the only solution that worked for me was to use the Redirect module and redirect company/affiliates to company/affiliates/oregon with 307 (temporary moved). I'm not sure 307 is safe for robots, but out of all 3xx errors seemed the safest.

# Answer
> 0 votes
In the view, set the path to company/affiliates and the contextual filter to taxonomy ID (or whatever) and set the default value to type fixed value of Oregon. So company/affiliates goes to the Oregon page but company/affiliates/New-York goes to the New York page and company/affiliates/Massachusetts goes to the Massachusetts page while after all that the plain company/affiliates and company/affiliates/Oregon goes back to the Oregon page.

---
Tags: 7, views, redirection
---


# Question
Title: How to download file by clicking on icon in file module?
I have a File field in drupal 7 (with file module) which I forced with views to display as an icon and name of the file which uploaded. The Name displays as a link (to download file). Now I want to link the icon to the file too. So when users click on the icon they would be available to download file (and I prefer to exclude the name from display).
What should I do now to make the icon as a download link?
Thanks.

# Answer
I guess the problem is that 'html' in $options is set to FALSE by default, thus stripping the icon html code generated by theme().

I tried modifying a bit the code above and it worked perfectly:

```
/**
 * Implements theme_file_link().
 */
function yourtheme_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' =>     $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Updating 'html' to TRUE so that the html code to display the icon is     printed
  $options += array(
    'html' => TRUE,
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '<span class="file">' . l($icon, $url, $options) . ' ' .     l($link_text, $url, $options) . '</span>';
}

```

Note that I added 3 lines (plus a commented line, 4) to update the value of HTML.
> 2 votes

# Answer
```
/**
 * Implements theme_file_link().
 */
function yourtheme_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '<span class="file">' . l($icon, $url, $options) . ' ' . l($link_text, $url, $options) . '</span>';
}

```
> 1 votes

---
Tags: 7, files
---


# Question
Title: What happens when a site goes in maintenance mode while a user is editing an node content?
Let's imagine a user is editing a node content. In the mean time, a Drupal administrator puts the site in maintenance mode.

1. Does the user have a chance to save his work (assuming it does not have the "Use the site in maintenance mode" priviledge)?
2. Is there a way to send them a warning, like 'maintenance in 5 mins'?

Thanks.

# Answer
Unless you notify the editors about that, they will lose their work on that node. You can do that either by using some contrib modules or by creating your own custom module. Either way, I think you definitely need some kind of ajax solution so they can be notified even when they are on the node edit page.

You can check Privatemsg and Private Message Growl modules. I'm not quite sure how they work but they look promising.
> 2 votes

---
Tags: 7, maintenance-mode
---


# Question
Title: removing menu block title causing problems
I know how to remove the menu title from the block by going into the block setting and putting

```
<none>

```

in the title space.

But when i do this a smaller version of my menu appears in place of where the title was.

any clues on how to fix?

# Answer
> 1 votes
Issue has now been solved. Problem was the omega framework setting can be forced to render a menu, as well as being able to publish a menu via blocks. If both are enabled you will see two menus, so you have choose which part of drupal you want to render the menu, blocks or the omega framework I chose blocks :)

# Answer
> 1 votes
Please try to put in the block title

```
<none>

```

instead of space

---
Tags: routes, blocks
---


title: Javascript/CSS from module not loading

text:
# Question
Title: Javascript/CSS from module not loading
I am using a custom module (copied from a site where it *is* working)

The module's .info file is as follows:

```
name = jCarousel Rotator
description = An image rotator implementing the jCarousel jQuery plugin
package = mymodules
core = 7.x

stylesheets[all][] = css/jcarousel_rotator.css
scripts[] = js/jquery.jcarousel.min.js
scripts[] = js/jcarousel_rotator.js

```

But none of these files are loading. The theme I'm in is made from scratch.. is there something that needs to be added to the template.php for those include hooks to work?

I searched all the code of the old site and the files are not being explicitly loaded elsewhere.

I have been able to load the files by adding the code manually to the footer, but this is not a great way to have a module integrated.

As requested, my html.tpl.php is as follows:

```
<?php include 'header.php'; ?>
<?php echo $page; ?>
<?php include 'footer.php'; ?>

```

# Answer
> 2 votes
Based on your edit including html.tpl.php, I agree with Chapa that's it very, umm, "Un-Drupaly". This is the default system rendering of html.tpl.php:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

You see where it says:

```
<?php print $styles; ?>
<?php print $scripts; ?>

```

That's where Drupal dumps your JavaScript and CSS files. If you're not making those calls chances are you're not going to get any included files. I guess to verify this you'd also have to edit in your header.php and footer.php files so we can see what they contain. This is where you want to start looking.

I recommend backing up your existing html.tpl.php file to somewhere, and then overwriting it with the system version of it, which can be found at `modules/system/html.tpl.php` relative to the root directory of your site on your system.

# Answer
> -2 votes
It will be better if you post the modulename.info file here. As it seems the code in the info file is correct.

About a proper way, If you use hooks then this is what you can do.

drupal\_add\_css() & drupal\_add\_js().

```

drupal_add_css(drupal_get_path('module', 'module_name') . '/style.css', array(
    'group' => CSS_DEFAULT,
    'every_page' => TRUE,
));

```

Then you can call it in hook\_init(). Hope that helps you.

# Answer
> -2 votes
How about adding using `drupal_add_css()` and `drupal_add_js()`. In you .module you can add JS and CSS via `hook_init()`.

Something like this:

```
/**
 * Implementation of hook init
 *
 */
function module_name_init(){
  drupal_add_js(drupal_get_path('module', 'module_name') . '/js/module_name.js');
  drupal_add_css(drupal_get_path('module', 'module_name').'/css/module_name.css');
}

```

---
Tags: 7, theming
---


# Question
Title: Is there a clear separation between user data and Drupal data in the database?
> **Possible Duplicate:**
> Deploying content updates from staging server to live server

I am trying to find a solution to the following scenario:

1. Let's assume a Drupal site is in production. Users create a lot of content everyday.
2. In development, additional features (content types and others...) and modules are being added to the site.
3. Comes the day to move the upgraded site to production.
4. The upgraded site is out of synch with user data in production.

How does one solves this issue? Is there a clean way to perform this? Should one export 'some' databases tables from current production and import them into the upgraded system? If yes which tables?

# Answer
> 1 votes
You might want to look at the Deploy and UUID modules together.

# Answer
> 0 votes
From what I can read, it does not seem to be the case. Moreover, Drupal 7 does not know about UUIDs, meaning that a given content may have different numbers/identifiers on different systems. UUIDs are planned for Drupal 8.

In the mean time, one can explore the node export module.

---
Tags: 7, updating
---


# Question
Title: Theme a view of one content type with node references to another
I'm attempting to theme a view containing of content type 'Activity' which includes Node References to a second content type 'Category'.

When using the views-view-list template it appears I cannot access or the fields which are included through Node References.

Any help would be appreciated.

# Answer
> 0 votes
What you need to do is add a view relationship (in Views 2 and Views 3) that uses your node\_reference field to create the relationship. This will make these fields available to your view.

Thats the quick answer, this video explains it better:

http://gotdrupal.com/videos/drupal-views-relationships

---
Tags: views, theming, nodes
---


title: Assigning a student to a teacher

text:
# Question
Title: Assigning a student to a teacher
I've looked around for a couple hours but am not sure the best way to do what I need.

I need to set up a student teacher relationship so that when a student logs in on some pages viewed by the student the teachers picture and information will show up.

For example: the student logs in and is taken to the members area. Then the student clicks on lessons then on week 1 lesson 2. When the page for lesson 2 comes up it would have in the corner a picture of the teacher they are assigned to along with the teachers name, contact information...

What would be a good way to do this?

# Answer
You can also use the Relation module to implement this. It depends on how teachers are assigned. Are teachers assigned to students ? or lessons ? based on this you can create a relation using the UI and assign teachers. For displaying information relation module integrates well with views, rules, cck and is very easy to create one.

I also used the module in my project where communities can have objectives and goals. I use the relation module to create relations and use the views to display the connections from the community.

I would also recommend you to watch relation tutorial if you want to learn more about it.
> 3 votes

# Answer
You can probably accomplish that by using simple blocks.

You can edit your templates to show whatever blocks you want to, according to the node associated to the logged user, that being the professor to the student.

Not too hard I guess, and I hope that my answer can put you in the right track.
> 0 votes

---
Tags: entities
---


title: How to let Drupal use two databases

text:
# Question
Title: How to let Drupal use two databases
I want to use an admin specific page to insert or remove new users, instead of using the Drupal administration panel.

How can I prescind from the Drupal default database and insert the users' information in my personal database? Is it possible?

# Answer
In drupal 7 you can easily connect to 2 or more different databases. From your question I guess you have a module to handle the users rather than the normal Drupal Way. So you can follow the following,

```

$databases = array (
  'default' =>  // main drupal db starts from here
  array (
    'default' =>
    array (
      'database' => 'drupaldb', // main drupal db name
      'username' => 'root', // main drupal db username
      'password' => 'password', // main drupal db password
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),'yourcustomdb' =>  // additional database starts here
  array (
    'default' =>
    array (
      'database' => 'database', // additional database name
      'username' => 'root', // additional database username
      'password' => 'password', // additional database password
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    )
  ),
);

```

Then in time of calling it,

```

db_set_active('yourcustomdb');
$query = db_query('....');
db_set_active('default'); // We need to call the main (drupal) db back

```

I hope this one helps you.
> 7 votes

# Answer
Use the Web Services module, it will allow you to make remote calls using a REST server you setup and administer it remotely.

EG: yourdomain.com/rest/user/create
> 0 votes

---
Tags: 7, users
---


# Question
Title: Using the Feed Import module, I can not map for “address field”
I use the Feed Import" to import nodes. The other fields were OK, but I cannot map the address field provided by the Address Field module.

I edited the feed, used "Enter field name," and set to "FIELD\_CONTACT\_ADDRESS: LOCALITY," but it doesn't work.

I also tried "FIELD\_CONTACT\_ADDRESS:LOCALITY," "FIELD\_CONTACT\_ADDRESS\_LOCALITY," "FIELD\_CONTACT\_ADDRESS-LOCALITY," but they don't work.

# Answer
> 4 votes
You may need to set your country. I've seen feeds import the data into the tables, but nothing displays because there is no country set.

---
Tags: feeds, importing-exporting, entities
---


# Question
Title: Available updates report does not list all available module updates
I just noticed that the page `admin/reports/updates` highlights subsequent modules as I proceed with the upgrades. For example, initially the Webform and Token modules got the yellowish highlight, and then when I applied the updates to those two, refreshing the page highlighted subsequent modules, say: Date and Rules.

So, is there a particular logic in which the suggestions are made? And, can one get a COMPLETE list of update candidates at one shot?

# Answer
In Drupal 7, two methods are used to fetch update information. One uses a setting `update_max_fetch_time` which is set to 5 seconds by default. On each cron run - whether from the server's cron or triggered by a visitor (poormanscron) - or page refresh of `admin/reports/updates`, this value is used. Not every module's status can be fetched within those 5 seconds, which is what you're seeing.

If you use the 'Check manually' link from the 'Available updates' page (`admin/reports/updates/check`), a batch operation is used instead, which should process all modules. There are however also reports that this doesn't always work correctly (`Failed to get available update data for [number] projects` message, you would then see the status of some modules in a grey box). You may also have to clear Drupal's cache first for this to work correctly.

The best thing to do is probably to set up a cron job to run each hour (for example). This will progressively keep the status of all modules updated.

Another workaround would be to override the update\_max\_fetch\_time value and set it to e.g. 30 seconds (you can set `$conf['update_max_fetch_time'] = 30;` in settings.php, or with Drush do `drush vset update_max_fetch_time 30`). But if a cron run is then triggered by poormanscron, this could lead to a long page loading time.

This is from issue 952394 (still open).
> 10 votes

---
Tags: 7, updating
---


title: Up-to-date lineup of WYSIWYG editors?

text:
# Question
Title: Up-to-date lineup of WYSIWYG editors?
I've been browsing through modules at drupal.org, in search for a Drupal7-savvy WYSIWYG editor. I looked into this (horribly outdated) lineup. It looks like the only actively maintained editor at this moment is CKEditor. Has anyone come across any other solution? Even if not wrapped into module, perhaps it would be easy to integrate into admin-side. I'm obviously looking for the least expensive option. Ability to define custom templates and integration with Media module - would be a plus.

# Answer
The reason you see so many abandoned projects is that instead of maintaining multiple separate modules for individual packages, work has gone into making those packages compatible with the WYSIWYG API module. By abstracting the editor library from the editing interface, you gain the ability to use different editors for different input formats, and it becomes quite simple to swap one out for another.

According to the project page, WYSIWYG API has direct integration with

* CKEditor
* FCKeditor
* jWysiwyg
* markItUp
* NicEdit
* openWYSIWYG
* TinyMCE
* Whizzywig
* WYMeditor
* YUI editor

as well as a whole host of useful plugins.
> 4 votes

---
Tags: 7
---


# Question
Title: How to authenticate a user which exists in an external site?
I would like to authenticate a user which exists in an external site.

Here is a use case:

1. In Drupal, user enters his username and password and hits submit.
2. Drupal tries to find that user in it's system and does not find him. At this point an error message is still premature.
3. Drupal then runs a custom function which does a REST call to an external site. The REST call validates the username and password.
4. If the username and password pair is valid, the REST call returns a success code.
5. I then log him in.

Is this possible? If so, how? What hooks do I need to implement? What method should I call to log a person in?

I can programmatically log a user in via

```
$form_state['uid'] = <user_id>;
user_login_submit(array(), $form_state);

```

but user\_id needs to exists in Drupal for this piece of code to work.

I am using Drupal 7.

Thanks.

# Answer
> 2 votes
Based off of your comments, it sounds like you have the basic procedure down: hook\_form\_alter the user\_login form, and use your own validation.

If you take a look at user\_login\_default\_validators, I think your problem is that you need to swap out user\_login\_authenticate\_validate with your own, but still get the form back into the same state.

I think your best bet is to do your RESTful authentication in a validator, and then set `$form_state['uid']` to a valid user in the system.

My suggestion is to create a single user that you map all of your REST logins to, and use this as `$form_state['uid']`. This way, you still can use the permission system across your site. To get them logged in, you can just do a user\_load with the `$uid` of your special user.

I am not positive, though, if having all of these users will cause any problems with sessions. I have only done something similar with Drupal 6 and each remote user got their own account in Drupal.

# Answer
> 1 votes
Yes. Your workflow is *totally* feasible, I have worked on a site that had a very similar set-up, except for the major difference that a user account **was** created, though account creation required only with a valid email.

The account that was creaated was still seen as 'anonymous' in the session layer of the application, I had to implement it so anonymous users could have cached pages as *all users were seen as 'anonymous'* instead of being logged in and drupal by default does not cache anonymous page views. This was a D5 setup, I am assuming D7 is most probably still the same.

But, adding a user account is very low overhead, maybe you just delete the user accounts daily or weekly if you really don't want them piling up.

Happy coding

---
Tags: 7, users
---


title: Authcache vulnerabilities?

text:
# Question
Title: Authcache vulnerabilities?
In my experience Authcache gives a great enhancement to performance, however I am wondering what are the potential vulnerabilities using authcache and boost together? My worry is that when the administrator does not exclude user specific paths in boost configs, a saavy user can somehow access to other users' cookies and do nasty things.

I guess it is not just a hypothesis, as I've seen that at least in one occasion in a boost+authcache+varnish arrangement a user reported that others have sent message on her part without her knowledge. If this indicate a real security hole, how should one counter int? Which paths should be absolutely excluded from being cached by boost?

What other potential security holes can be in this setting and how to avoid them?

# Answer
> 1 votes
Long term I would take a look at ESI over authcache. Not sure when manarth will get a stable release of 7.x out. ESI has fairly strong security with rotating keys and things like that.

---
Tags: caching
---


title: How can I remove Javascript files?

text:
# Question
Title: How can I remove Javascript files?
I wanted to remove some JavaScript files, since they conflict with my custom JavaScript on my mobile theme.

I tried with the following code, but it is not working in `hook_preprocess_page()`, which I think it really works in the first place; it's just that the original initialization of `$scripts` in page.tpl.php loads after `hook_preprocess_page()` alteration.

```
// Load all js scripts
    $scripts = drupal_add_js();

  // Unset all unnecessary scripts
    unset($scripts['module']['sites/all/modules/ajax/ajax.js']);
    unset($scripts['module']['sites/all/modules/contribs/mollom/mollom.js']);
    unset($scripts['module']['sites/all/modules/contribs/views_slideshow/js/jquery.cycle.all.min.js']);
    unset($scripts['module']['sites/all/modules/contribs/views_slideshow/contrib/views_slideshow_singleframe/views_slideshow.js']);
    unset($scripts['module']['sites/all/modules/contribs/views_slideshow/contrib/views_slideshow_thumbnailhover/views_slideshow.js']);
    unset($scripts['module']['sites/all/modules/quicktabs/js/quicktabs.js']);
    unset($scripts['module']['sites/all/modules/panels/js/panels.js']);
    unset($scripts['module']['sites/all/modules/tipsy/javascripts/jquery.tipsy.js']);
    unset($scripts['module']['sites/all/modules/tipsy/javascripts/tipsy.js']);
    unset($scripts['module']['sites/all/modules/boxes/boxes.js']);

    // Recreate the template variables

    $vars['scripts'] = drupal_get_js('header', $scripts);

```

How can I remove JavaScript files from the list of JavaScript files load when my theme is used?

# Answer
This how solved my problem.

Found out that jquery\_update uses `hook_theme_registry_alter()` to unset jquery in Drupal core and replace a new version of Jquery. So this `preprocess function` is being load after everything all. What I did is I created a `hook_theme_registry_alter()` and update the `weight` of the module higher than `jquery_update` module so I can override the `jquery_update_theme_registry_alter()`.

This `jquery_update_theme_registry_alter()` prevents any alteration in javascript which a big headache if you're working on some adjustments like in my case.

Code:

```
function my_module_theme_registry_alter(&$theme_registry) {
    global $theme;

    // Only apply this code in mobile theme
    if($theme == 'myTheme') {
    //Attach the my_module_preprocess_page in the theme registry preprocess functions
      $theme_registry['page']['preprocess functions'][] = 'my_module_preprocess_page';
    }
}

function my_module_preprocess_page(&$variables) {

    // Perform the logic if either jQuery Update's jquery.js is newer than core's.
    if (variable_get('jquery_update_replace', TRUE)) {
        // Get an array of all the JavaScript files loaded by Drupal on this page.
        $scripts = drupal_add_js();

        // Replace jquery.js first.
        $new_jquery = array(jquery_update_jquery_path() => $scripts['core']['misc/jquery.js']);
        $scripts['core'] = array_merge($new_jquery, $scripts['core']);
        unset($scripts['core']['misc/jquery.js']);

        // Loop through each of the required replacements.
        foreach (jquery_update_get_replacements() as $type => $replacements) {
            foreach ($replacements as $find => $replace) {
                // If the file to replace is loaded on this page...
                if (isset($scripts[$type][$find])) {
                    // Create a new entry for the replacement file, and unset the original one.
                    $replace = JQUERY_UPDATE_REPLACE_PATH .'/'. $replace;
                    $scripts[$type][$replace] = $scripts[$type][$find];
                    unset($scripts[$type][$find]);
                }
            }
        }
        // Unset javascripts that is/are not needed in mobile theme
        unset($scripts['module']['sites/all/modules/boxes/boxes.js']);

            .....

        // Recreate the scripts variable
        $variables['scripts'] = drupal_get_js('header', $scripts);
    }
}

```

Hope this will help others. Please let me know if this approach is a violation. Thanks
> 1 votes

# Answer
Checkout AdvAgg. Has hooks for you to use and plays nicely with jquery update.
> 1 votes

---
Tags: 6, javascript, theming
---


title: Caching the Drupal bootstrap

text:
# Question
Title: Caching the Drupal bootstrap
I'm curious if anyone has made attempts to "cache" the bootstrap process in Drupal.

Normally, Drupal will run the 7 bootstrap phases on each request, but perhaps on a deployed production system, one could "do away" with some or all of these?

Possible suggestions I have in mind could be

1. Serializing the bootstrapped state and sticking it into memcache
2. A script could generate a patch for bootstrap.inc that will hardcode certain information into the file.
3. I believe David Strauss has tried to keep a bootstrapped Drupal running on libevent.
4. Other craziness?

What attempts are there, and which are known to be (somewhat) reliable?

# Answer
> 12 votes
PHP is a shared nothing architecture. That has its advantages and disadvantages.

One disadvantage is that it's not easy to do something like this. There isn't much of a state that can be stored somewhere.

I did some quick tests and when logged in, then the boostrap seems to take about ~17% of the total time and more than 50% of that is actually loading all the .module and .inc files. That's not something that you can store in memcache. Also, it doesn't seem to matter much if I use memcache or the database cache.

I tried to get some results when having the page cache enabled, but Xhprof doesn't seem to return reliable results then; the whole thing simply seems to be too fast. But even then, the biggest part involves executing init/exit hooks and loading files it seems. I found an interesting issue there: It looks like the User module is seriously slowing down the cached page response because it triggers the registry due to the entity controller in the .module file.

That said, David Strauss showed some experimental work in Copenhagen where he created a memory snapshot after bootstrapping and then returning to that once the page was served. He did use Drupal 6 for that. After looking at the numbers above, I imagine that the performance gains of doing this in Drupal 7 would be quite a bit smaller. One reason for this is that the database connection is lazy loaded (And you can get quite far in the bootstrap when using e.g. Memcache before you need to execute the first query) and there's a lot that is cached.

What's *really* bad in Drupal 7 is the render layer with these huge arrays and endless recursions and loops. That one pretty much undoes all the performance work that went into Drupal 7. Let's see how it looks in Drupal 8, if Twig makes it into core.

Lastly, about the mentioned advantages. One large advantage is that memory leeks are rather irrelevant because everything is freed after each request. I've seen many Java applications where memory usage constantly increases and need regular restarts.

# Answer
> 5 votes
Nope, it was David Strauss who was experimenting with kargo-event (now called Kellner) at https://code.launchpad.net/~fourkitchens/pressflow/6-evented but I doubt anything serious came out of it.

Drupal 7 *does* have a lot of bootstrap already cached, there's a `cache_bootstrap` bin for that. You can stick it into memcached.

You can go overboard and decrease code loading with moving some / lots of Drupal code into C. Damien and dhthwy created PHP extension at http://drupal.org/project/drupal\_php\_ext not much is done with it. Or do hiphop. I do not know the current state of hiphop & Drupal 7.

At the end of the day, however, you need to take a good hard look at the engineering costs of, say, getting hiphop work with Drupal 7 (and all the contrib!) and compare it with renting a few more servers. If you can save, say 5% of your servers and you have 100 000 servers, go for it, but are you Facebook? Be careful and economical with optimizations.

# Answer
> 1 votes
Saw an interesting presentation about doh (Dynamic Object Handler) at the High Performance Drupal meetup. In short he talks about bootstrapping drupal fast by using it. Gets interesting around the 15:30 mark. Autoload on steroids in short with runkit functionally as well. QA at the 33:00 mark.

---
Tags: performance, bootstrapping
---


# Question
Title: Location and Gmap relationship - what is alternative to show Location items on a google map?
Recently the Gmap module has described itself on the module page as now being a 'legacy' module. If you have used this recipe in the past, you may be familiar with the long and unresolved issue of the project trying hard to migrate to Google Maps API v3.

Unfortunately, because of this issue, the Location and Gmap combination is no longer a viable solution to show Location based items on a google map.

What would be the current Drupal 7 equivalent recipe? I would prefer to keep the Location module in use as I need it for proximity searches, but I am open to suggestions. Thanks for your ideas!

# Answer
> 0 votes
According to the book *Mapping with Drupal*, the alternate to Location/Gmap is Geofield/Geocoder/Addressfield. However, proximity searches don't currently work with this solution.

I have been experimenting with a lot of modules in this space and unfortunately Drupal 7 is behind the times in this regard.

---
Tags: 7, location, google-maps
---


# Question
Title: How to make the title field of a node/add form hidden or locked
I'm prepopulating the title of the node/add/content\_type using the URL. I would like this form to be hidden or locked so that the user can't accidentally edit it. I've been looking though the Drupal documentation and haven't found a way to hide fields at all. Any help would be appreciated.

# Answer
I'd probably just hide it with CSS to be honest.

Either that, or I'd use Automatic Nodetitles to populate the title with tokens (path token in your case) as it has the option to hide the title field AND auto-generate it with minimal effort.

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.
>
> When the token module is installed it's possible to use various node data for the auto generated title - e.g. use the text of a CCK field (since 5.x).

Another option would be to use `hook_form_alter()` and set `#disabled` to `TRUE` to disable user input.
> 4 votes

# Answer
You could use css to simply hide the title element in your node edit form. I also think you should be able to achive this by using the `hook_node_presave()`, something like this would work:

```
function YOURMODULE_node_presave($node) {
  // you may also wan't to check the 'status' of the node
  if($node->nid && $node->type == 'your-custom-content-type') {
     // check if title has changed
     if($node->title != 'your-prepopulated-value') {
        // notify user that the update couldn't be performed
        drupal_set_message('You may not change the title of this kind of nodes!','warning');
        // set node to null to force making no changes
        $node = null;
     }
  }
  return $node;
}

```
> 0 votes

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


# Question
Title: How to hide homepage link from menu once logged in?
I have a "home" link on my primary navigation menu. Once the user is logged in, the home link is irrelevant and I don't wish to show it.

I've set the access control permissions for the "home" page to only show for "anonymous user", but it's still visible in the menu once logged in. I'm guessing that authenticated users can see everything anonymous ones can, even if they don't have the box ticked. Is there some way around this?

I'm aware of "menu per role", but I read that it's better to set the permission of your content directly and let Drupal hide/show where appropriate, so I'd like to avoid using menu per role if possible.

# Answer
> 0 votes
You could hook into the menu link in the theme template and hide with some styling.

```
function THEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $name_id = strtolower(strip_tags($element['#title']));

  if ($name_id == 'home') {
     $element['#localized_options']['attributes']['class'][] = 'hide';
  }
}

```

# Answer
> 1 votes
Try with this code

```
function THEME_menu_item_link($link) {
  global $user;
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ( ($link['href'] == '<front>') && ($user->uid == 0) ){
       return '';
  } else {
      return l($link['title'], $link['href'], $link['localized_options']);
  }
}

```

---
Tags: routes
---


# Question
Title: Workflow for an entity based menu system?
I've been considering stopping to use the menu system all together, in favor of taxonomy terms, or other entities. Entities are superior to regular menu-entries in many ways because they integrate well with most other Core systems as well as contrib.

Since vocabularies already have the ability to create a hierachical structure, taxonomy terms seems to be the ideal candidate here.

The question is, how have you attempted to implement this, and how did it work out? Are there any pitfalls that one should be aware of before trying this, or any limitations that limit the usability of this approach?

# Answer
> 2 votes
I have pretty much abandoned the menu system for most of my sites, or at least the main menu, in favor of Taxonomy Menu. Here is a link to my most recent site that takes advantage of Taxonomy Menu

buyagainbaby.com

The main menu there as well as all the blocks you see on the front page are done with taxonomy menu.

The types of sites I design usually categorize some type of product or other information, and it's easy to use views to do some pretty amazing things with taxonomy as arguments, which you cannot do with just the default menu terms or IDs alone. Take a look at some of my other questions having to do with taxonomy menu, or ask any questions about implementation if you have any.

---
Tags: routes, entities
---


title: Disable Rich Text in comment field

text:
# Question
Title: Disable Rich Text in comment field
I have installed CkEditor for drupal. But it is showing it for comment form also. I don't want it to be shown. I dont want the user to have an option to select either. I just want them to have plain text. How can I do that?

# Answer
> 12 votes
Go to URL as in fig (for page comments on page content type). Change the type of text to Plain text as shown.
You can change the comment settings for *article* or *book* in similar way by just replacing page from the URL with the respective content types.

# Answer
> 2 votes
The best and the most easy way is to go to the content type For example if the content type is "Articles" then go to Home » Administration » Structure » Content types » Article » Comment fields

And there in the comment field make sure it is set to plain text. And then there will be no problem and the user won't be asked to select a text format from the Drop down. As simple as that.

---
Tags: 7, comments, input-formats
---


# Question
Title: Multiple site with multiple databases and single login
I have two instances of Drupal on same server *instance 1* and *instance 2* with different databases. I want the following feature: unique login for both instances.

When I login to *instance 1* and if I open the URL of *instance 2* on same browser then it should not ask me to log in again. While any add/update operation is performed on *instance 1* or *instance 2*, the user table should be updated in both databases.

# Answer
> 2 votes
This is not something that it easy to accomplish, your main problem will be to keep track on the users on the two instances, since users doesn't have a Global Unique ID (GUID) but instead uses the user id or uid which is a simple serial id.

You also have to figure out how to handle people editing the same profile at the same time on the two different sites, which easily can lead to some major headaches when site 1 wants to update site 2 and vice versa.

You can take a look at the bakery module which can be used for a single signup system. I'm not sure this will be useful out of the box for you, but you probably could find some inspiration to how you can handle signing in users on multiple sites.

In any regard - you will probably need some custom coding or a clever module I haven't heard off yet.

# Answer
> 2 votes
The modules for SSO I can find are the following:

* The CAS module implements SSO using the phpCAS library. It can be used for sites that aren't on second-level domains.
* The simpleSAMLphp Authentication module allows users to authenticate against a SAML Identity Provider, which could be a Drupal site running the drupalauth for simpleSAMLphp module.
* The Account Sync module allows to synchronize accounts through different sites, and it has a simple support for single sign-on.
* The Bakery Single Sign-On System allows users to be logged in on different sub-domains, such as drupal.org, api.drupal.org, and groups.drupal.org. It doesn't require the sub-domains share the database tables containing user information, but it works only on sub-domains, as it uses some cookies. It updates some fields used in the user profile, and a user that is blocked in the master site is also blocked in the client sites. Updating user fields is a feature that is going to be removed from future versions of the module, as the module is going to be a pure SSO module.

If the instances you are referring are sub-domains, then Bakery is a start, even though you would need to write custom code to update the fields you need to keep update between the different sub-domains. The task would be simplified from the cookies the module uses, and from the fact that the init field present in the "users" table is set, in the slave sites, to the profile link in the master site.

Between the modules I listed, only the CAS module has a release for Drupal 8.

---
Tags: 7, multi-sites
---


title: I can't get date values using $_GET

text:
# Question
Title: I can't get date values using $_GET
In my view, I have two filters: title (text box), and date (combobox); date has two values: year and month.

When I select the filters parameters in the view, and I click *search*, the filter values appears in the URL such as in `mysite/views-path?title_filter=aaa&date_filter[year][value]=2012&date_filter[month][value]=3`.

I used `$_GET` to get the value of the title filter, and it worked, but I can't get the date values using `print $_GET['date_filter[year][value]'];`.

Can anyone tell me how to get values like date using `$_GET`?

# Answer
> 2 votes
Arrays in query strings get converted into actual PHP arrays when you use `$_GET`.

To get the value in your case you'd use something like:

```
print $_GET['date_filter']['year']['value'];

```

---
Tags: 7, views
---


# Question
Title: Am I allowed to include a JQuery Plugin in my Drupal Module?
I'm writing a Drupal module and I want to make use of a JQuery plugin, but I'm unsure if I'm a) breaking any rules and b) if there are any licensing considerations.

My question is can I use plugins and what is the best way to include them (i.e. in the libraries folder or as part of my module or via something third party).

# Answer
> 3 votes
Do you intend to publish your module as a contributed module on drupal.org? In that case: Probably not. The page 3rd party libraries on Drupal.org states:

> This is the policy for 3rd party code libraries in Drupal's contribution repositories.
>
> 1. In general 3rd party libraries are forbidden, so do not commit any. Document for your users how to find and install it.

After that, it mentions some exceptions.

I understand that it's tempting to include the plugin in your module, but there are some good reasons not to. For instance:

* If other modules use the same plugin, having it in the libraries folder will prevent collisions.
* Users will always be able to get the latest version of the plugin.
* You, as module maintainer, probably do not want to be bugged about releasing a new version every time the plugin is updated.

# Answer
> 1 votes
http://jquery.org/license/

> You don’t have to do anything special to choose one license or the other and you don’t have to notify anyone which license you are using. You are free to use a jQuery project in commercial projects as long as the copyright header is left intact.

http://en.wikipedia.org/wiki/MIT\_License

> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

To sum it up - you can use it and it is up to you to choose how - the libraries folder is what you want

# Answer
> 0 votes
Some modules provide a drush script for downloading the libraries. See CKEditor.

---
Tags: javascript
---


# Question
Title: Where is the 'display post information on' settings?
I've seen the discussion of this setting, which I gather used to be under theming.

They discuss it being moved to content type, which makes a lot of sense; going through content types in my install, I don't see any option similar to this. Where is it in Drupal 7?

# Answer
> 1 votes
It's under "Structure \> Content Types \> *your content type* \> edit \> Display \> Settings."

# Answer
> 0 votes
It's under the the tab 'Display settings' of the edit page of your content type; for Article this is on `admin/structure/types/manage/article/edit`: Display author and date information.

---
Tags: 7, nodes
---


title: Programmatically create an entity

text:
# Question
Title: Programmatically create an entity
I created an entity via Entity Construction Kit, Initially I wanted to use rules to create the new entity but the entity is fielded and the fields don't get exposed in rules (as of now, someone is trying to work on a patch for that), but in the interm I wanted to write a simple function that creates a entity, which I assumed would be somewhat like creating a node programmatically, but I've been at this for like 4 hours and I haven't gained an inch, I have entity\_create and entity\_save but they don't do much and I can't find any documentation on it.

What I'd like to see is how to create an example entity from a bundle made with eck, or through code, that is fielded.

Thanks so much

Edit: The last thing I need to figure out is how to specify the name of the fields that are attached to the entity so I can enter values for those as well.

```
$values = array('uid' => 1, 'field_receipt_prod_ref' => 1, 'type' => 'receipt');
$new_ent = entity_create('receipt', $values)->save();

```

# Answer
> 15 votes
Most of what you have doesn't look too bad. The key thing with fields that you are missing is that they have a language, that they can be multi-valued, and that the value is generally stored in a 'value' subkey. I'm assuming that the ref field is a nodereference, which means it's actually stored with `nid` instead of `value`.

The easiest thing you can do to see how this is structured is to install the `Devel` module, and use the `Devel` tab that to look at the structure. Not sure if that shows up with ECK entities, but it does for Nodes.

Try this:

```
$new_ent = entity_create('receipt', array(
  'uid' => 1,
  'type' => 'receipt', //bundle
  'field_receipt_prof_ref' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'nid' => 1,
      ),
    ),
  ),
))->save();

```

# Answer
> 27 votes
The simpler approach is with the help of `entity_metadata_wrapper()`.

```
$e = entity_create($entityType, array('type' => $bundleName));
$ew = entity_metadata_wrapper($entityType, $e);
$ew->field_name->set('value');
$ew->save();

```

---
Tags: 7, entities
---


# Question
Title: How to rebuild everything that can be rebuild during module development?
During module development, Drupal does not use all relevant information provided by a module on every HTTP request. Examples:

This list might not be exhaustive.

Is there a way to update all these information in the database in one go. Preferably via a Drush command?

# Answer
> 4 votes
```
drush cc all

```

Catches most of it. Registry/files\[\] changes can be tricky, but should work as well in most cases.

Node access records are not rebuilt by that, that wouldn't make sense to me. Unless working on a node access module, you don't want to have that rebuilt, as there could possibly be many nodes which means that this process could take a very long time.

# Answer
> 0 votes
Disable the Drupal cache

D6: place this in settings.php `$conf['cache_inc'] = 'includes/cache-install.inc';`
D7: http://drupal.org/node/797346#comment-3681298

---
Tags: caching
---


title: Modules custom templates

text:
# Question
Title: Modules custom templates
I'm currently building a module that has a popup page in it. The popup page is very simple and no real header/footer so I don't want to use the standard html.tpl.php page.tpl.php

How can I override the master templates with my own much simpler ones?

# Answer
> 1 votes
If memory serves me well I think the easiest way is to simply print the output in your page callback function, and not return anything:

```
function MYMODULE_popup_page_callback() {
  // Your theme variables
  $vars = array('foo' => 'bar');
  $output = theme('MYMODULE_popup_page', $vars);

  print $output;

  // If there's nothing more to be had from this page request you might as well end it (gracefully).
  drupal_exit();
}

```

The other, more involved way, would be to override the default `delivery callback` for your menu item. The default is `drupal_deliver_html_page()`; if you want to go down this route I'd recommend reading and understanding that function to see what you'll need to do in your own function.

---
Tags: theming
---


# Question
Title: How do I add a block of JavaScript to the home page only?
I have a block of JavaScript I need to add to my homepage (and only my homepage) to enable the logging of clicks via a heat mapping service I signed up for.

They specified the code needed to be placed just before the `</body>` tag, but I imagine it's safe to put it anywhere within the `<body>` tag.

I'd like the snippet not to appear on any other pages. How can I accomplish this?

I am running Drupal 6.

# Answer
If by home page you mean the front page, then you can implement `hook_preprocess_page()` in a custom module.

```
function mymodule_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
    $variables['scripts'] = drupal_get_js();
  }
}

```

The same code works on Drupal 7, as `$variables['is_front']` is set in \_template\_preprocess\_default\_variables() (called from template\_preprocess()), using the following code.

```
  // drupal_is_front_page() might throw an exception.
  try {
    $variables['is_front'] = drupal_is_front_page();
  }
  catch (Exception $e) {
    // If the database is not yet available, set default values for these
    // variables.
    $variables['is_front'] = FALSE;
    $variables['db_is_active'] = FALSE;
  }

```

The reason of calling `drupal_add_js()` first, and then `drupal_get_js()` is that, in the case another module that is executed after would run the following code, the JavaScript file would still be added.

```
function quite_a_different_module_preprocess_page(&$vars) {
  drupal_add_js(drupal_get_path('module', 'quite_a_different_mymodule') . '/quite_a_different_module.js');
  $vars['scripts'] = drupal_get_js();
}

```

Using `drupal_add_js()`, the file will be added to the output returned from drupal\_get\_js().
> 15 votes

# Answer
If the code can go in the head section, then add the following function in your template.php.

```
function MYTHEME_preprocess_page (&$vars) {
  if ($vars['is_front']) {
    $vars['scripts'] .= "// my JS for the home page";
  }
}

```

You can also add the following code, in the appropriate place of your page.tpl.php.

```
<?php if ($is_front): ?>
  // JS goes here
<?php endif; ?>

```

There are other ways to accomplish this, but this is probably the easiest.
> 6 votes

# Answer
In Drupal 7 if you want to include the js in the tag with the

last solution, the file you have to modify, after you copied it inside your theme from the system folder, is **html.tpl.php**.

Not strictly the Drupal way but works
> -3 votes

---
Tags: javascript, nodes
---


# Question
Title: disable administrator role in add user form
Some role in my site has permission to create users but not a administrator one.
How to disable create a new user of administrator role?
Is there a module for that?
thanks.

# Answer
> 1 votes
You can create a module that uses a hook, something like

```
function remove_admin_role_choice_from_add_user_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['roles'][3]['#access'] = FALSE;
}

```

---
Tags: 7
---


title: How to add a node to a taxonomy term?

text:
# Question
Title: How to add a node to a taxonomy term?
I have searched long and hard for this, but I cannot figure out how to add a node to a taxonomy term.

I have taxonomy (Region) with term (North America) and I am trying to add the node (USA) to North America.

Could someone please teach me how this can be done? I just cannot find it anywhere on Drupal 7 Admin controls.

# Answer
You need to add a 'Term reference' field on the relevant content type:

1. Go to http://mysite.com/admin/structure/types/manage/page/fields (where 'page' is the name of your content type).
2. Add a new field, using 'Term reference' as the field type.
3. On the next page, choose the vocabulary you want the content type to reference.
4. On the page after that, choose specific settings for the field.

Next time you go to add/edit a node of that content type, you'll be able to choose terms from your selected vocabulary.
> 3 votes

# Answer
Basically, you don't add nodes to taxonomy. You instead tag node with a term reference from a vocabulary. So you need to add a field to your node content type, a field of type "Term reference", and on the edit form for USA you will be able to select North America.
> 0 votes

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


title: List field with 'Select All' option?

text:
# Question
Title: List field with 'Select All' option?
I have a Product content type with a list field of Groups (another content type). I would like to be able to have a 'Select All' item in the Groups list that allows the user to relate the product to all groups.

Note: This isn't the same as using javascript or ctrl+a to select all items in the list, because that approach would mean that when a new group is added it would not automatically be selected.

# Answer
> 0 votes
There are two workarounds that hit my mind, depending on the logic your UI could have. 1. If having no Group assigned could mean "assigned to all" - go for it. 2. Else: consider adding additional checkbox (boolean) field labeled "Fits all" (or whatever you like).

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


# Question
Title: What's the correct way to make it so that node_load both loads and caches additional, custom data?
For example, I'd like node\_load to load the path alias of the node, and cache it for future node\_load calls (just like node\_load caches all of the data, i think). I assume this is done in a module, but I haven't been able to find examples of this.

# Answer
> 0 votes
The hook you're after is called `hook_node_load()`. I think the example from that page is probably the easiest to understand:

```
function hook_node_load($nodes, $types) {
  $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
  foreach ($result as $record) {
    $nodes[$record->nid]->foo = $record->foo;
  }
}

```

The example loads some custom data from a table, based on the ids of the nodes passed into the function. It then loops through the query results, and adds the custom data to the relevant node objects.

When you call `node_load()` or `node_load_multiple()` for nodes that haven't been cached yet, your `hook_node_load()` function will be called and the custom data added.

Next time you call those functions for the same nodes your hook won't be called, but the node objects returned from the static cache will already have your custom data attached to them.

---
Tags: 7, caching, nodes
---


title: Can I Remove comment_body on my Node

text:
# Question
Title: Can I Remove comment_body on my Node
Is it safe to remove this when I create a custom node? It is not relevant to what I am doing. Thanks.

# Answer
Yes, It's safe to remove comment body from the type of node you have created. One may turn off the comments settings from content-type settings.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to fetch data from already saved nodes to the edit-form for node creation?
I have this scenario: a content-type A (event) has an entity-reference to another content-type B (location). Now, if an editor adds a new event and enters the (already existing) location by "autocomplete" or dropdown-list, i want to display all other events referenced to that location in the edit form to prevent dups (and redundant work).

I imagine this like a "check colliding events for this location"-button, that is triggering a view perhaps, but it has to be "before" saving the new node.

I already tried a bit with Rules-module, but there's probably no way to trigger this, though the rules-event "before saving new content" is just one step to late, because all the work is already done and all fields are filled...

Is there an approach on module-level for this or do i have to dive into modifying hook\_form\_alter?

Can someone point me in the right direction? Thanks a lot in advance.

(Drupal 7.14, Views 7.x-3.3+122-dev, Calendar 7.x-3.3+0-dev, Date 7.x-2.5+8-dev, BEF, Address Field 7.x-1.0-beta2)

---

Update: So far i achieved an approach with a combination of Views and Panels. I override the standard "Node add/edit form" with a panel for my content-type A. To show the nodes of Content-Type B i added a view to that panel. They are shown in a two-column layout.

This works until i bring the "check" into the game. I added an exposed filter to the view, but when i use it, the node form is submitted instead of showing the filtered view.

I opened another question on this issue: Exposed filter of a view embedded in a panel overriding a node form triggers node submission. How to prevent this?

**Question:** Am I totally wrong with this approach (Panel with View and Form)?

Is it possible to have a custom form with the exposed filter "before" the node form to use the results of the filter to show the view?

I'm lost a bit...

Any help highly appreciated...

# Answer
SOLVED:

Via http://drupal.org/node/1028952#comment-3968840 i found this little module

http://github.com/Itangalo/Node-creation-block--Drupal-7-

that resolved my issue.

Another possibilty (although in dev-status) is the use of this module: http://drupal.org/project/formblock
> 0 votes

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


# Question
Title: Exposed view in field widget submits node form when filtering
I have defined my own field widget for node\_reference fields. This contains a simple view that lets you select a node to reference. However, if i try to use exposed filters as a part of this widget it will try to submit the whole node form every time i press "Apply". Thus i can't use the exposed filters in views. How can i get around this?

I have ajax activated for the view and have tried different types of displays.

EDIT: Just want to add that i am using Drupal 7 and the latest version of views!

# Answer
I don't understand exactly whether you're using a form here, but if so, you could give this little module a try, that resolved a similar issue of mine.

http://github.com/Itangalo/Node-creation-block--Drupal-7-

creates blocks for node-forms. If you seperate view from the block (e.g. with Panles) this approach could possibly help you too...
> 0 votes

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


title: Meta tag page descriptions

text:
# Question
Title: Meta tag page descriptions
> **Possible Duplicate:**
> Meta tags aren't saved with all content types

I'm using Meta Tags to control the meta data on my Drupal 7 site. This module seems to give your nodes control over what your page descriptions display via the vertical menu at the bottom of the page you're editing. This description doesn't show though.

The only thing I can think of is the global options which you can find by "configuring" the module itself. If I set a global page description, it will show on all pages, and if I disable it, or leave it blank, there will be no description shown.

Why is the data set on individual nodes not overwriting this global quality? There doesn't seem to be another module to help me with descriptions either.

# Answer
I've used this module successfully today actually - with no configuration alterations.

One reason for things not working for you could be your theme which after all does control the markup for your site.
> 1 votes

---
Tags: 7, meta-tags
---


# Question
Title: TinyMCE Filtered Html is stripping in line styles
Is there anyway to allow inline styles. When setting a table width, using the Table icon width field, the width gets set as an inline style for the table tag, and that gets stripped out. How frustrating!

Anybody have any solutions?

# Answer
> 1 votes
if you use filtered html it is by default remove any inline styles or class attribute also javascript tags you have to make it full html that allowed style If you want to use filterd html you can use wysiwyg\_filter module

It give you control which attibute you can use so you can add inline style

---
Tags: wysiwyg
---


# Question
Title: Custom permission always denying access?
In my module:

```
function mymodule_menu() {
    $items['reports'] = array(
    'page callback' => 'reports',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content', 'hr functionality')
    );
    return $items;
}

function mymodule_permission() {
  return array(
    'hr functionality' => array(
      'title' => t('HR functionality'),
      'description' => t('Do things only HR are allowed to do.'),
    )
  );
}

```

I set HR to have "HR functionality" permissions. I logged in as a user with HR role, and I get access denied to my reports page. I tried clearing cache, etc. If I remove the "hr functionality" access argument it lets me in.

Even if I log in as admin, I get access denied.

What am I doing wrong here?

EDIT: The method I ended up writing per accepted answer:

```
function multiple_permission_callback() {
    global $user;
    $permissions = func_get_args();

    if (empty($permissions))
        return false;

    foreach ($permissions as $permission) {
      if (!user_access($permission, $user)) {
        return false;
      }
    }
    return true;
}

```

# Answer
The default function for the `access callback` is `user_access()`, which has the following signature:

```
function user_access($string, $account = NULL)

```

This is the function that will receive your `access arguments`.

It only takes one permission string at a time, so the second string you're passing in is being used as the `$account` object. This will cause problems in the `user_access()` function and is probably why it's returning `FALSE` all the time.

If you want to test two permissions you could provide your own `access callback`:

```
function mymodule_menu() {
  $items['reports'] = array(
    'title' => 'Reports',
    'page callback' => 'reports',
    'type' => MENU_CALLBACK,
    'access callback' => 'mymodule_reports_access'
  );
  return $items;
}

// Potentially accept an account object to make the function more re-usable
function mymodule_reports_access($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }

  return user_access('access content', $account) && user_access('hr functionality', $account);
}

```
> 4 votes

---
Tags: 7, users
---


# Question
Title: Select previous/next nodes of same content type programmaticaly in Drupal 7
there are modules out there for my problem, but they are not stable and also i need to be able to manipulate the result so here we go:

i need to provide a block on a certain node type which offers a previous and next link to cycle through the nodes of the same content type.

how can i select the previous and next node programmatically using db\_query() and then output the links to them?

thanks in advance for your help

# Answer
> 0 votes
You haven't provided any indication of the sort order you want so I'll guess at created date:

```
$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created LIMIT 1", array(':created' => $current_node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created LIMIT 1", array(':created' => $current_node->created))->fetchField();

if ($prev_nid > 0) {
  $prev_link = l('Previous', "node/$prev_nid");
}

if ($next_nid > 0) {
  $next_link = l('Previous', "node/$next_nid");
}

```

You'll need a reference to `$current_node` (i.e. the node relating to the current page). There are dozens of places you could put this code so I'll let you decide on that, but if you want an easy way to grab the node object associated with the node page you're on use this:

```
$current_node = menu_get_object();
if (isset($current_node->nid) && $current_nid > 0) {
  // We're on a node page and $current_node is a valid, loaded node object
}

```

Hope that helps

# Answer
> 1 votes
**Clive** is right. But **$prev\_nid** is looking for the first node in the table. So you could add an **ORDER BY**, like this:

```
$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created ORDER BY created DESC LIMIT 1", array(':created' => $node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created ORDER BY created LIMIT 1", array(':created' => $node->created))->fetchField();

```

---
Tags: database
---


# Question
Title: How do you order meta tags added by drupal_add_html_head()?
I'm adding Open Graph support to a Drupal site and I have a bunch of drupal\_add\_html\_head() calls, like:

```
  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => $node->title,
    ),
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/' . $node->nid, array('absolute' => TRUE)),
    ),
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

```

In total, I have 10 of these. They don't seem to output in the same order they are called (all in a single function).

Is there some kind of weighting I can use to set the order?

# Answer
> 15 votes
Use the #weight property. As drupal\_get\_html\_head() uses drupal\_render() to render the meta tags, #weight is used when rendering them.

I uses the following code to make a test on my local site; it is the same code you are using, except it doesn't have any reference to the node object.

```
  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => "This is the title",
    ),
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/1', array('absolute' => TRUE)),
    ),
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

  dsm(drupal_get_html_head());

```

The output I got is the following one.

```
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta property="og:url" content="http://tero.local/dr72/node/1" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<meta property="og:title" content="This is the title" />

```

As you see, the last added tag is the first to appear.

I then run the following code.

```
  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => "This is the title",
    ),
    '#weight' => 10,
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/1', array('absolute' => TRUE)),
    ),
    '#weight' => 200,
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

  dsm(drupal_get_html_head());

```

The output I got is the following one.

```
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<meta property="og:title" content="This is the title" />
<meta property="og:url" content="http://tero.local/dr72/node/1" />

```

As you see, the order of the meta tags has been changed; the meta tags added from the code appear after the default meta tags added from Drupal.

\_drupal\_default\_html\_head() (the function that returns the default meta tags) uses #weight for the "Content-Type" meta tag.

```
  $elements['system_meta_content_type'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'Content-Type',
      'content' => 'text/html; charset=utf-8',
    ),
    // Security: This always has to be output first.
    '#weight' => -1000,
  );

```

---
Tags: theming, 7
---


# Question
Title: Save node when content with reference to it is created
I have two content types - Review, and Business. Reviews have an entity reference field linking the review to the Business being reviewed. On the business page, I have fields that display the averages of the submitted reviews for different aspects of the Business. However, the average only updates itself when the node is saved. So, I need a way to automatically save the business page when a review referencing it is created. I'm assuming that the best way to go about doing this would be using Rules, but I am not sure what actions to assign to the Rules to make it tick. Any suggestions?

# Answer
So I thought I had submitted an answer already, but apparently it didn't submit. So, here's the quick and dirty. Under `content is of type` select the type of content being saved. Next, under `fetch entity by id`, click on `switch to data selctor` under identifier. Next, enter `node:your-reference-field:nid`. Create another action, select `save entity`, and then select `entity fetched`, which was made available in the previous step.
> 0 votes

# Answer
in rules (sorry the terminology is not exact) :

* action : node save
* condition : type = review
* select the bussiness from the review
* resave that business (you will have to force it probably)

or the same in a hook (node\_api, operation save, nodetype review)

the best would probably be creating an agregated view end embedding that into your node (or attaching with a block, many possibilities)
> 1 votes

---
Tags: rules
---