title: Two select field cck field

text:
# Question
Title: Two select field cck field
I need to implement two select field in a content type.Currently cck modules allows only one select field. So how can I implement two select fields using cck.

Eg:- select field value for months and year.

Tks in adv Vil

# Answer
Try Date module. This provides the cck widget to select the date.

The Select List date widget presents users with a drop-down list or textfield for each part of the date (year, month, day, hour, etc.). The whole selector is collapsed onto a single line using css (except for the timezone selector, if date-specific timezones are collected). The selector is highly configurable and you can set it up to use 5, 10, or 15 minute increments for minutes and seconds, or make some parts of the selector use textfields instead of drop-downs, useful to allow any year without creating a huge drop-down selector.

For more Documentation See here
> 0 votes

---
Tags: entities
---


title: drupal form api call function

text:
# Question
Title: drupal form api call function
I have a select box in my drupal form and i want to call a spesific php function whenever the select option is changed. How can i achieve this?

this is my code so far:

```
function langSelect_form($form, &$form_state) {
    $form['langSelect'] = array(
       '#type' => 'select',
       '#options' => drupal_map_assoc(array(t('English'), t('Norsk'),t('Samisk'))),
    );
    return $form;
}

```

thanks!

# Answer
You can go through AJAX Forms in Drupal 7. It describes how you can use ajax in your form with examples
> 1 votes

---
Tags: forms
---


title: Custom theme region for page

text:
# Question
Title: Custom theme region for page
I would like to be able to custom theme a region for specific pages, is this possible? If so how?

For example I have a ragion called `rightbar` and I know the region can be themed using `region--rightbar.tpl.php` but is there a way of theming this using something like `page--node--1--region--rightbar.tpl.php`?

Or am I going to have to condition the `region--rightbar.tpl.php` script?

# Answer
> 0 votes
I used the following code to achieve a solution to my answer.

```
/**
* Implements hook_preprocess_region().
*/
function care_preprocess_region(&$vars) {
    // Make sure we are on a single node page
    // This code will allow you to add the following templates for regions:
    // region--RNAME--node-NID.tpl.php
    // You can update the conditions to anything you want and rename the template
    // suggestions.
    if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
        $vars['theme_hook_suggestions'][] = 'region__' . $vars['region'] . '__node_' . arg(1);
    }
}

```

# Answer
> 1 votes
Use the following code:

```
/**
 * Implements hook_preprocess_region().
 */
function YOURTHEME_preprocess_region(&$vars) {
  // Make sure we are on a single node page
  // This code will allow you to add the following templates for regions:
  // region--node-NID.tpl.php
  // You can update the conditions to anything you want and rename the template
  // suggestions.
  if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
    $vars['theme_hook_suggestions'][] = 'region__node_' . arg(1);
  }
}

```

---
Tags: 7, theming
---


# Question
Title: How to apply CSS to "views-exposed-form--view-name.tpl.php"
I am theming a views exposed form which is a block. The views filters are displayed in a block and I am theming this using "views-exposed-form--view-name.tpl.php". I want to apply CSS to this template file.

How to do this.

# Answer
You could add the CSS in `<style>` tags on top of your template. Most browsers will probably understand what you want, it does result in ugly HTML though.

You could also add the CSS in your main CSS file and use .view-id-viewname .div (etc.) to target elements specificaaly in that view
> 1 votes

---
Tags: 7, views
---


# Question
Title: What determines who can view an unpublished node?
The Node Access documentation explains that there are three things that affect node permissions, used in this order of preference until an answer is received: an overriding `bypass node access` permission; `hook_node_access` (used on single nodes and not in listings); `hook_node_grants` (which compares against the `node_access` table).

What I can't see is how (un)published content is handled. The only default implementation of `hook_node_access` is `node_node_access` which you can see completely ignores the 'view' mode, answering only for create/delete/edit modes.

The `hook_node_grants` docs say explicitly that (un)published content is "not handled by the system".

But there are the checkboxes in the user permissions table for `view published content` and `view own unpublished content` etc. Where are these implemented?

# Answer
> 5 votes
It is handled by `node_access`:

* it checks for the "view published content" - without this permission every operation is denied, published or not.
* it checks the `view own unpublished content` permission.
* it checks if `hook_node_access` gives either deny/allow. If not...
* If **no** module implements `hook_node_grants` then there's a default allow for published nodes (and therefore a deny if not).
* If modules **do** implement `hook_node_grants` then the `node_access` table is consulted. I found that published content receives a "default grant" in the node\_access table thanks to node\_access\_acquire\_grants, meaning anyone can view it. Unpublished content has no default grant so is therefore denied.

# Answer
> 0 votes
basically the unpublished content is visible only to those roles that have "Administer content" permission.

you can use this module but I had some problems with it and decided to build my own, lighter module.

---
Tags: 7, users
---


# Question
Title: Create pagination in theme('table') when not using SQL query
I would like to create a pager in the table when there is fix amount of rows.

The method suggested on internet creates table, and it fetches data by using sql query, but i want to create a table from the data from the array.

```
visitedgroups = array('1','2','3','4');//It is an array of node id which are group entity
$header = array(
                array('data' => t('Group Name')),
                array('data' => t('Group Since')),
                array('data' => t('Join')),
            );
            $rows = array();
            foreach ($visitedgroups as $groupid) {
                $groupnode = node_load($groupid);
                $createdtime = format_interval((time() - $groupnode->created) , 2) . t(' ago');
                $joinlink = l('Join Group', 'group/node/'. $groupnode->nid.'/subscribe');
                $rows[] = array( l($groupnode->title, 'node/'. $groupnode->nid),
                                                t($createdtime),
                                                $joinlink,
                                    );
            }
            $output .= t('Recently visited groups by you, in which you are not member.');
            $output .= theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('group-visited-table')))).theme('pager');

```

The above code generates the table and working fine. But i want to add pager in the table. From the references on internet i found that people adds,

> $query = $query-\>extend('TableSort')-\>extend('PagerDefault')-\>limit(10);

ahead of $query-\>execute(), but i don't have query.

So how can i apply pager in this scenario..

# Answer
> 7 votes
Try the following function:

```
/**
 * An generic array pager for Drupal.
 * For Drupal 5 and 6, the default limit is 10. For Drupal 7 it is 9.
 */
function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

$output = pager_array_splice($yourarray, 5);  // 5 is per page values

```

See Paging non-SQL data for more details.

---
Tags: theming
---


title: $user -> uid always return 1

text:
# Question
Title: $user -> uid always return 1
I found on google that `hook_menu()` is cached, and I have to use a callback function, but I couldn't fix it. `$user->uid` is always 1. I don't know how to solve this problem. I'm a beginner. Tnx.

```
function test_menu() {
  $items = array();
  global $user;

  $nodde = db_query("SELECT title, nid, vid FROM {node} WHERE uid '$user->uid'")->fetchObject();

  $items['test'] = array(
    'title'            => t($nodde->title),
    'page callback'    => 'test_output',
    'access arguments' => array('access content'),
  );

  return $items;
}

```

# Answer
As you suspect the results from `hook_menu()` invocations are cached. As you're only clearing the caches while logged in as user 1, that's why the logged in user is always user 1 for your router item.

To get around it you'll need to use a title callback, which is evaluated separately to the cached data:

```
function MYMODULE_menu() {
  $items['test'] = array(
    'title callback' => 'MYMODULE_title_callback',
    'page callback' => 'test_output',
    'access arguments' => array('access content')
  );

  return $items;
}

function MYMODULE_title_callback() {
  global $user;

  $args = array(':uid' => $user->uid);
  $node = db_query("SELECT title, nid, vid FROM {node} WHERE uid = :uid", $args)->fetchObject();

  return t($node->title);
}

```

Also make sure you're not putting variables directly into the query string as this will leave you open to SQL injection attacks. You should use parameter replacement instead (as in the above example).
> 6 votes

---
Tags: routes
---


# Question
Title: Mysterious "Page not found" on every page load for authenticated users
I recently migrated my site to a new server, and restructured the urls, etc... so naturally there are quite a few 404's out there from other sites linking to old content. So far, so normal.

But among the page not founds, I'm getting something really bizarre: as far as I can tell, every single page load of the site **by authenticated users** is generating one particular "page not found" error for a file at location sites/default/files/stripes54-navywhite.jpg.

*Every page load for every authenticated user*.

Now this file does not exist. Nor are there any links on the site to it (the file name is familiar: we may have had a file at that location at some point in the past, on the old site).

I have searched page source, I have searched through the contents of all my site files, I have searched my complete db using phpmyadmin. There is no reference to this file anywhere, as far as I can tell.

So what could possibly be causing this? Where is this file mysteriously being referenced? Watchdog is giving me no help here.

My only clue at the moment is that this page not found seems to ONLY be triggered by authenticated users: not seeing any anonymous users triggering it.

Does anyone have any earthly idea what might be going on here? A big thanks to anyone who can help!

I'm even getting this error generated by admin pages, which use a separate admin theme. For example, when browsing my database log.

There is one entry in the file\_managed table where origname is stripes54-navywhite.jpg. Unfortunately, this doesn't really shed much light on the problem.

# Answer
> 0 votes
After further investigation, this appears to be an issue with CloudFlare. Disabled it, and the problem went away... re-enabled it, and the problem returned, but with a different image url!

Yet further investigation shows Cloudflare's Website preloader to be the culprit. So nothing to do with Drupal.

---
Tags: 7, media
---


title: drupal entity property show in views

text:
# Question
Title: drupal entity property show in views
I am using **ECK** module to create entity type. Now i want to show property of that entity to be show with views. Is there any way to do it?

# Answer
If ECK doesn't define the entity and property types for views, you will have to do that yourself using either `hook_views_data` or `hook_views_data_alter`.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to pass Get parameter to url when url has "?" mark
In my site clean urls is not working. As a result ?q is getting appended to the url.

My site url is http://abc.com/?q=user

I wrote a form in a page, and redirect to another view which is http://abc.com/?q=listings.

When I click on submit button in form page GET parameter are not getting appended correctly: They are getting appended as http://abc.com/?field\_list=3 which has to be like this http://abc.com/?q=listings&field\_list=3. I must use GET method in the form.

How should I redirect to URLs that contains "?q="?

How to do this.

# Answer
If you are redirecting from the form submission handler, you need to use code similar to the following one.

```
$form_state['redirect'] = array(
  'listings',
   array(
     'query' => array(
     'field_list' => '3',
   ),
);

```

That code is equivalent to calling `drupal_goto('listings, array('query' => array('field_list' => '3'))` which should never be used inside a form submission handler. In both the cases, the function that is called to build the URL is url(), which works when clean URLs are enabled, or not.

```
  // With Clean URLs.
  if (!empty($GLOBALS['conf']['clean_url'])) {
    $path = drupal_encode_path($prefix . $path);
    if ($options['query']) {
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
    }
    else {
      return $base . $path . $options['fragment'];
    }
  }
  // Without Clean URLs.
  else {
    $path = $prefix . $path;
    $query = array();
    if (!empty($path)) {
      $query['q'] = $path;
    }
    if ($options['query']) {
      // We do not use array_merge() here to prevent overriding $path via query
      // parameters.
      $query += $options['query'];
    }
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
    $script = isset($options['script']) ? $options['script'] : '';
    return $base . $script . $query . $options['fragment'];
  }

```
> 1 votes

---
Tags: 7
---


title: Editing a footer menu in a theme

text:
# Question
Title: Editing a footer menu in a theme
How can I edit a footer menu in theme like Bartik, currently its displaying the menu in vertical format and I want it in horizontal format. Any idea how I can go about editing this. e.g.
current: Menu 1 Menu 2 Menu 3

Desired: Menu 1| Menu 2| Menu 3

# Answer
You can do this using CSS

Firstly you will want to create your own theme using bartik as a base.

1. Copy /themes/bartik to /sites/all/themes/YOUR\_THEME
2. Rename bartik.info to YOUR\_THEME.info
3. Edit YOUR\_THEME.info, Make Changes, name = YOUR\_THEME, description = YOUR\_DESCRIPTION
4. Edit template.php replace all instances of 'bartik' with 'YOUR\_THEME'
5. Goto /admin/appearance
6. Find YOUR\_THEME Enable and set default.

Why do we do this? Never hack the core or contributed modules and themes, If you do, updates will be a nightmare.

Now you will need to find the "id" of the menu element. In Chrome right click on the menu and 'Inspect Element' you may need to click up and down in the code window to find the relavant container. Example: id='block-system-user-menu' for the user menu block.

Modify /sites/all/themes/YOUR\_THEME/css/style.css I will use 'block-system-user-menu' as an example.

Add this code (depending on your id).

```
#block-system-user-menu li,
#block-system-user-menu ul.menu li a {
  border:none;
}
#block-system-user-menu ul.menu li a {
  float:left;
  border-right:1px #fff solid;
}
#block-system-user-menu ul.menu li.last a {
  border-right:none;
}

```

That's it done!

You could also use the superfish module at http://drupal.org/project/superfish This will allow you to have a horizontal menu from any of your menus with some default styling or the ability to style it yourself in the same way as outlined above if you prefer. It is also an easy and clean way to get drop-down menus on your site.
> 0 votes

---
Tags: routes
---


# Question
Title: How to edit personal contact form e-mail content - Drupal 7
I looked everywhere in my admin for this. Can it be achieved via the admin panel or do I have to make a custom module?

I can't seem to find an adequate code snippet on Drupal Answers. Help would be greatly appreciated.

# Answer
I don't believe that this can be done through the admin panel though it is quite easy through a module using hook\_mail\_alter()

if it is the drupal core contact form then use this in YOUR\_MODULE.module

```
function YOUR_MODULE_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    //MODIFY THE MESSAGE HERE
  }
}

```

(always remember to clear caches after adding a hook)

It is a good idea to get the devel module and add

```
dpm($message);

```

see what the variables are that you want to modify and enjoy.
> 1 votes

---
Tags: 7, nodes, emails
---


# Question
Title: Is there any way to make a menu link *not* a link?
I have a hierarchy of links in my menu, but one of the higher level entries needs to simply be a category, and not link to anything. It is "Related Sites" and has a bunch of related links under it, but should not itself link to anything.

Drupal doesn't let me save it without a URL, and vomits a bunch of errors if I try using '#'.

How can I achieve this with a minimum of hassle?

# Answer
> 4 votes
You can try the Special menu items module.

One of its features is:

> User can create a new menu item and place either `<nolink>` or `<separator>` to the Path field

---
Tags: routes
---


# Question
Title: Views Slideshow fixed 1st slide even though its random order
I'm using D7.15, Views Slideshow 7.x-3.0, jQuery Cycle 2.9999.8.

The problem is that when Slideshow initially starts, even though it is set to show random order of slides (~100 nodes linking via Views), the first slide is always the same and it is shown in a bit glitched way - it does not works as a link, it is shown for shorter amount of seconds and in general does look like it is shown while all the rest of slideshow is loading. Starting from the second slide the order is random and it works perfectly. It can also be recreated in case of page refresh - if you refresh the page in any browser you may get the same result no matter of what browser you use. You can check it here http://www.scanorama.lt (the main slider part).

I have searched for this issue registered at Drupal issue queue, but it looks like that there is none.

Any ideas, what could be the reason for such glitch?

# Answer
It appears as if your slides are always appearing in the same order in the source code.

Are you sure that the order in your view is set to random?

i.e SORT CRITERIA, Global: Random (asc)

nothing else.

Also I would really recommend not having that many nodes in your slideshow as It creates an insane amount of html markup which is not great for a number of reasons and performance will really take a hit. 5 or less slides would be ideal I would say about 10 should be an absolute maximum.
> 1 votes

---
Tags: views
---


# Question
Title: How to render variable number of Long Text fields as JavaScript tabs with custom tab names
The usual way to produce JavaScript tabs is by listing the tabs titles in an HTML list, then list the corresponding contents in divs, then use jQuery to display the content of the current active tab. See this tutorial for more info.

What is the best recipe to generate this html and allow this type functionality? The number of tabs and tab names can vary from node to another.

The best I can think of is creating a field of type "List (Text)" for the tabs titles, and another unlimited "Long Text" field for the tabs contents. Then edit the node template for that content type to output the contents within that HTML structure mentioned about.

Is there a better way to do that?

# Answer
> 0 votes
I found the answer, without writing a single line of code. Here you are: http://previousnext.com.au/blog/introducing-field-collection-tabs-formatter

Used Field Collection Tab formatter module.

> Field collection tabs provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.You can optionally choose a field from the field collection item to be used as the tab title.

---
Tags: 7, theming, entities
---


# Question
Title: Archiving forums on time basis in drupal 7
I am using advance forum on drupal 7. I want to add following functionality to it:

**Archiving:**

I could define forum posts older than 6 months or so should be automatically be archived and visible only to admin.

Any module or pointers to achieve same highly appreciated.

# Answer
You could use the Rules module.

Create a rule to set the node status to "unpublished" when the node is older than 6 months and make it execute every time the cron runs.

Also, make sure you allow only the admin to see the unpublished content
> 1 votes

---
Tags: nodes
---


title: Display an empty password field

text:
# Question
Title: Display an empty password field
I have a password field which currently displays the current password. How can I force the input to be displayed as blank? From the documentation here, it seems that `#default_value` or `#value` don't work (so I can give them an empty string as a value). How can I do this?

# Answer
> 2 votes
We have a client who runs a security scan that flags login forms that have autocomplete enabled, and have been using this solution for a few years now:

```
/**
 * Implements hook_form_alter().
 *
 * Remove autocomplete from all user forms.
 * Based on http://www.midwesternmac.com/blogs/jeff-geerling/disabling-autocomplete-forms
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'user_') === 0) {
    $form['#attributes']['autocomplete'] = 'off';
  }
}

```

---
Tags: forms
---


title: Mobile Redirect

text:
# Question
Title: Mobile Redirect
So I need to set up mobile redirect for a Drupal 7 site I've been working on, but there are some conditions and I can't quite decide what the best route would be. Basically, if the user is browsing the site on mobile, we need to redirect to m.example.com - However, we also want this to NOT happen if the user is browsing within the "Events" section of our site "example.com/events," but there is also a link ON the mobile site to view the full page and redirects to "example.com/?nomobile=true" and if the user follows this link we want to break the redirect

Given these conditions, does anyone know the best course of action? Whether it's a module that can be configured (Simple Mobile Redirect doesn't seem to be flexible enough to handle all of this), or some kind of PHP code - I tried doing this with JavaScript but the redirect just doesn't seem to fire (even though the console.logs within the function are returned, so I don't think that will work.)

Much appreciated

# Answer
The Context module will allow you to create contexts and set reactions for each context.

A context can be anything:

* User has this role
* The page is a taxonomy term page
* The visitor is using a mobile

You will need these modules:

---

Another option is to use the **Omega Theme** which is a fully featured responsive base theme, it looks a little bit complicated at first but the documentation is excellent.

**PS:** You will still use the Context module, you can find how on the documentation.
> 1 votes

---
Tags: 7, redirection, theming
---


# Question
Title: How to send email to "anonymous" user when a new node is created
I've been looking at a couple of modules and none of them seem to work the way I want to.

I'd like to display a textfield for an anonymous user to enter his email. Everytime a node of a certain type (blog post) is created, an email would be sent to every person who gave their email.

How could I achieve that in Drupal 7 ?

Thanks

# Answer
> 1 votes
Simplenews looks like it would work perfectly for this.

> Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.

# Answer
> 0 votes
You can write your own custom module. If you are showing form as a block, you can use hook\_block\_info() or hook\_block\_configure() hooks

Then use YOURMOUDLE\_form api to create form and implement the submit handler for the form i.e YOURMODULE\_form\_submit() where you write insert queries

Now to send the email you can use hook\_node\_insert() hook to do your things after the node is inserted in the tables

# Answer
> 0 votes
Use rules module with the following information. Create a field for that content type called email.

**Events** After saving new content

**Conditions** Content is of type "select your content type"

**Actions** Send mail - and in the to section use your field token like \[node:field-email\] with an appropriate subject and message.

---
Tags: 7, emails, notifications
---


# Question
Title: How to troubleshoot subdomain issue on Aegir
I set up Aegir on a rackspace server. Everything works correctly. I then create a new site and set the url to testname.mydomain.com. After Aegir is don provisioning the site I go to the front page at testname.mydomain.com and see my new site. The front page works fine, but every other page, gets a page not found error, so when I attempt to login I'm unable. How do I go about troubleshooting this issue.

So it turns out this is somehow related to platform, I added another platform based on makefile (for open atrium) and it seems to work correctly, I'm not really sure why this would happen, but I figured I would update incase anyone else is having the seam issues.

# Answer
> 1 votes
Your platform is most likely missing the .htaccess file in its top-level directory, or (less likely, or else the Aegir interface itself would likely show the same problem) mod\_rewrite is not enabled on your site.

See if you can get to http://testname.mydomain.com/?q=user

If that works, but http://testname.mydomain.com/user doesn't, then your .htaccess file is missing or being ignored by Apache.

---
Tags: aegir
---


# Question
Title: Admin pages including content edit are exremely slow
I am using latest 7/16 version of core and complicated field collections with all kind of stuff. The problem is it takes up to 1 minute to load all kind of pages in admin section. All dev modules and update manager are disibled.

How could i know what exactly cause such a low performance? What can i do to improve it?

# Answer
> 2 votes
best answer: You need to profile the PHP code in order to see what is causing the slowdown. Also check firebug to see if anything is taking a long time to download. Go through all the slides from my DIY Drupal 7 Performance presentation.

quick answer: You can try the first 4 patches listed in the Performance wiki as these are things that I identified on our setup as being slow.

---
Tags: 7, performance, users
---


# Question
Title: Theming with Views generates error undefined variable
I have a basic installation of Drupal 7, with the Views module. I am using the Garland Template.

When I try to create a new template for my views the following error is thrown:

> Notice: Undefined variable: build in include() (line 2 of /XXX/public\_html/themes/garland/views-view—block.tpl.php).

There is only one line in that template:

```
<?php dpm($fields); ?>

```

Most likely this is something simple to resolve, but I cannot find the answer.

# Answer
Not sure what the variable $fields are but try and do a dpm($rows) this should return an array of the fields from the views.
> 0 votes

# Answer
It is because no `$fields` variable is being passed to the template. First check before you do dpm to see if $fields exist and it is not empty.

```
<?php if (!empty($fields)): ?>
    <?php dpm($fields); ?>
<?php endif; ?>

```
> 0 votes

---
Tags: views
---


title: Drush alias doesn't work

text:
# Question
Title: Drush alias doesn't work
None of my site aliases defined in /home/peter/.drush/aliases.drushrc.php seems to work. When I ran:

```
drush sa @mysite.dk.local

```

I got

```
$aliases['mysite.dk.local'] = array (
 'uri' => 'mysite.dk',
 'root' => '/usr/share/nginx/www/drupal-7.16/sites/',
 'path-aliases' =>
 array (
   '%dump-dir' => '/usr/share/nginx/www/drupal-7.16/sites/drush.dbdumps',
   '%files' => '/usr/share/nginx/www/drupal-7.16/sites/files',
  ),
);

```

which looks ok, but when I do

```
drush @mysite.dk.local status

```

I get

```
PHP configuration     :  /etc/php5/cli/php.ini
Drush version         :  4.5
Drush configuration   :
Drush alias files     :  /home/peter/.drush/aliases.drushrc.php

```

So it seems that drush couldn't find specified path, cause when I run second command in sites directory everything is showing up as expected. Can anybody point out what I'm missing?

# Answer
If your settings.php file is at /usr/share/nginx/www/drupal-7.16/sites/default/settings.php, then you should change your 'root' line as follows:

```
'root' => '/usr/share/nginx/www/drupal-7.16',

```

The way you have it, Drush is expecting that your Drupal root is at /usr/share/nginx/www/drupal-7.16/sites, which is to say that it is also expecting to find your settings.php file at /usr/share/nginx/www/drupal-7.16/sites/sites/default/settings.php. Take out the extra 'sites' as shown above, and it should work fine.
> 2 votes

---
Tags: drush
---


# Question
Title: I want to make a news slideshow of nodes
I see the module Views jQFX Nivo Slider and it's mentionned that the current slideshow is a demo of it.
I installed the module and really don't know how to make something like that with it..
Can you help me please ?

# Answer
> 3 votes
This module is a Views jQFX addon that integrates the Nivo Slider plugin with views. The Views jQFX module is a dependency.
@Anoop Joseph -- Go through modules README.txt, it explains step by step configuration

---
Tags: javascript, views
---


# Question
Title: How can a field be rendered as a <meta> element?
## The problem:

I would like to be able to manage custom `<meta>` elements, on a per-item basis in a custom theme. An example would be for adding open graph and schema tags, but I'm really looking for a generic solution.

I'm aware of custom modules, such as Meta Tags, but I'd rather avoid relying on other modules at this point.

## What I've Tried:

After looking at `them_field` it looked as though I should create a custom theme function for my custom field (`field_test` being used for this example). The theme function could add a `<meta>` tag and not return any content to be rendered.

In `template.php`:
```
<?php
//I *did* actually use my theme name instead of THEMENAME
function THEMENAME_field__field_test($vars) {
    drupal_add_html_head(array(
        '#tag' => 'meta',
        '#attributes' => array(
            'content' => drupal_render($vars['items'][0]),
            'name' => 'test'
        )
    ), 'test');

    //I figured this would prevent the field from being rendered inline
    return '';
}

```

Using that code the custom `<meta>` element *was* correctly added to the `<head>`. Nevertheless, the field was still rendered on the page.

If I changed the output to:

```
return ' ';

```

The content was no longer rendered to the page, but an unnecessary space character would be output where the field was to be rendered.

Is there a better way to render a field as a `<meta>` element?
-or-
How can I prevent this themed field from rendering inline?

# Answer
> -1 votes
try to return drupal\_add\_html\_head array directly

```
<?php

function THEMENAME_field__field_test($vars) {
    return drupal_add_html_head(array(
        '#tag' => 'meta',
        '#attributes' => array(
            'content' => drupal_render($vars['items'][0]),
            'name' => 'test'
        )
    ), 'test');
 }

```

---
Tags: 7, theming, entities
---


# Question
Title: How can add Thumbnail image in Drupal 7 site?
I have set an image style as a thumbnail, but it doesn't render as my thumbnail style. Instead, it is showing the original size of image. How can I solve this problem.

# Answer
> 1 votes
You can edit the content type and configure in the manage display fields. Go to `admin/structure/types/manage/article/display` considering article is a content type.Replace 'article' with what every node type you have and change the image fields display options as shown in the screen shot.

# Answer
> 1 votes
change image format from 'mange display'.

* Navigate to the Content types page (Administer \> Structure \> Content types).
* In the table, locate the row that contains your content type and click the manage display link.
* Specify the "thumbnail" format.
* Click Save.

---
Tags: 7, media
---


title: Domain Access permissions issue

text:
# Question
Title: Domain Access permissions issue
I am having an issue with Domain Access in Drupal 7.

The admin user (and seemingly any user I add to the system) is unable to edit content attached to any child domains on the site. The main domain is fine, but all others on the same site is effected.

When I attempt to edit content on the Admin (or other user) I get:

> You are not authorized to access this page.

I can view all content with no problem.

How do I fix these permissions issues?

The following is the screenshot of the permissions implemented by the module.

The "Bypass content access control" permission is disabled for all roles including the "Administrator" one; no other access module is enabled. Two Domains have been set up, the primary one and a sub-domain, which shares some content and has its own. Two languages are enabled for each domain (English and French) using the i18n module.
The "Edit any content on assigned domains," and "Delete any content on assigned domains" permissions are set, but the users still cannot edit the content.

# Answer
> 0 votes
If you are logged in at your maindomain and want to edit content on the other domains, you have to enable the`$cookie_domain = '.yourmaindomain.com';` in your settings.php. It is also described in this video domain acess video

# Answer
> 1 votes
Hi try to configure this setting http://yoursite.tld/admin/structure/domain/roles

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


title: Devel user & decrease number queries

text:
# Question
Title: Devel user & decrease number queries
I'm trying to decrease the number of my queries with the devel module but I have two questions.

1) Why do I have 281 dblog\_watchdog queries? How can I get rid of them? Why should I keep them, I already have the apache logs?

```
INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9)

```

2) How to show the number of queries for anonymous users? Right know it doesn't show anything.

# Answer
1) By default, *dblog* module is enabled. It is real performance bottleneck for big sites. But you can use syslog module (from core) or contrib analogs to write logs in /var/log/drupal.log and etc.
Rsyslog config can be something like this:

```
    local0.warning /var/log/drupal_site_err.log
    local0.info;local0.!warning /var/log/drupal_site.log

```

You should **analize** your logs and **fix** errors, warnings and even PHP notices. I think 281 messages per page — this is a lot.

2) On your dev site you can allow anonymous users to see devel information with permission “Access developer information”. Don't forget to disallow Devel on production.
> 2 votes

---
Tags: 7, performance, debugging
---


title: Get nodes with the same term a node

text:
# Question
Title: Get nodes with the same term a node
I'm trying to make a block, with views, that shows me a list of nodes that has the same term of the node that I'm viewing:

* I open node/1 that has a term reference field to the term "10"
* I want to display other nodes that have a reference to the same term

I use a contextual filter, but how should I pass the term? Have I to use a php value as default argument?

# Answer
> 6 votes
Oh, it is really easy with powerful Views module.
There is cool option for contextual filters “Content: Has taxonomy term ID” and “Content: Has taxonomy term ID (with depth)” — *Load default filter from node page, that's good for related taxonomy blocks*.

**Tip:** don't forget to exclude node, which is current!

---
Tags: 7, views
---


# Question
Title: can't get $form_state['values'] when ajax Dynamic select list in the form (dependent dropdown)
I write a form like ajax\_example way to bulit a dependent dropdown select.

when select one and called the ajax\_call\_back function ,the values I get in $form\_state\['values'\] (use dpm($form\_state))has no element ,but has $form\_state\['input'\] contains what I want... and even I commit the form,the $form\_state\['values'\] still wrong outputs. here is picture. how make the $form\_state\['values'\] works???

**when I add another form blow the form,the ajax didn't work at all,even if add the same as itself...** and the error message is :

> **The form has become outdated. Copy any unsaved work in the form below and then reload this page.**

the call back of form like this

```
>  $build['og_user_filter_form'] =drupal_get_form('og_user_filter_form');
>
> $build['user_admin_account']= drupal_get_form('og_user_admin_account');
>
>return $build['og_user_filter_form'];

```

if I return $build\['og\_user\_filter\_form'\],it works,but even though i use blew code,it doesn't work ,either.

```
>  $build['og_user_filter_form'] = drupal_get_form('og_user_filter_form');
>
> //$build['user_admin_account']= drupal_get_form('og_user_admin_account');
>
>return $build;

```

here is my code:

```
/**
 * Form builder; Return form for user administration filters.
 *
 * @ingroup forms
 * @see user_filter_form_submit()
 */
function og_user_filter_form($form, &$form_state) {
  $form['group_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'school_group'   => t('School group management'),
      'public_group' => t('Public group management'),
    ),
  );
  $form['school_group'] = array(
    '#type' => 'fieldset',
    '#title' => t('School group'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "group_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="group_type"]' => array('value' => 'school_group'),
      ),
    ),
  );

  //XXX choose grade.
  //get all grade nodes(content type == 'grade').
  $group_grade_nodes = druedu_og_get_nodes_by_group('grade');

  if(empty($group_grade_nodes)){
    $grade_groups[] = '-No Result-';
  }else{
    $grade_groups[] = '-Select-'; //default value
    foreach ($group_grade_nodes as $grade_nodes) {
       $grade_groups[$grade_nodes->nid] = $grade_nodes->title;
    }
  }
  // School group information.
  $form['school_group']['grade_group'] = array(
    '#type' => 'select',
    '#options' => $grade_groups,
    '#title' => t('Which grade?'),
    '#default_value' => '-Select-',
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="group_type"]' => array('value' => 'school_group'),
      ),
    ),
    '#ajax' => array(
      'callback' => '_ajax_grade_group_callback',
      'wrapper' => 'subject-container',
      'effect' => 'slide',
      //'progress' => array('type' => 'none'),
    ),
  );
  //XXX subject container init.
   $form['school_group']['container']['subject_group']= array(
    '#type' => 'fieldset',
     '#title' => t('Subjects'),
    '#prefix' => '<div id="subject-container">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
    '#attributes' => array('class' => array('hidden')),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="grade_group"]' => array('!value' => '0'),
      ),
    ),
    //TODO in css add .hidden {display:none;}
  );

  dpm($form_state);
  if (!empty($form_state['input']['grade_group']) && ($grade = $form_state['input']['grade_group'])) {
    $subject_groups_nodes = druedu_og_get_nodes_by_group($grade);
    if(empty($subject_groups_nodes)){
      $subject_groups[] = '-No Result-';
    }else{
      $subject_groups[] = '-Select-'; //default value
      foreach ($subject_groups_nodes as $subject_nodes) {
        $subject_groups[$subject_nodes->nid] = $subject_nodes->title;
      }
    }
    $form['school_group']['container']['subject_group']['subject_group'] = array(
      '#type' => 'select',
      '#options' =>  $subject_groups,
      '#title' => t('which subject?'),
      '#default_value' => '-Select-',
      '#prefix' => '<div id="subject-container">',
      '#suffix' => '</div>',
      '#ajax' => array(
        'callback' => '_ajax_subject_group_callback',
        'wrapper' => 'class-container',
        'effect' => 'slide',
        //'progress' => array('type' => 'none'),
      ),
      '#states' => array(
        'visible' => array(
          ':input[name="grade_group"]' => array('!value' => '0'),
        ),
      ),
    );

    // class container init.
    $form['school_group']['container']['class_group'] = array(
      '#type' => 'fieldset',
      '#title' => t('CLass'),
      '#prefix' => '<div id="class-container">',
      '#suffix' => '</div>',
      '#attributes' => array('class' => array('hidden')),
      '#states' => array(
        'visible' => array(
          ':input[name="subject_group"]' => array('!value' => '0'),
        ),
      ),
    );

  }

  //XXX choose class

  if (!empty($form_state['input']['subject_group']) && ($subject = $form_state['input']['subject_group'])) {

    $group_class_nodes = druedu_og_get_nodes_by_group($grade,$subject);
    if(empty($group_class_nodes)){
      $class_groups[] = '-No Result-';
    }else{
      $class_groups[] = '-Select-';
      foreach ($group_class_nodes as $class_node) {
        $class_groups[$class_node->nid] = $class_node->title;
      }
    }
    $form['school_group']['container']['class_group']['class_group']  = array(
      '#type' => 'select',
      '#options' => $class_groups,
      '#title' => t('which class?'),
      '#default_value' => '-Select-',
      '#prefix' => '<div id="class-container">',
      '#suffix' => '</div>',
      '#states' => array(
        'visible' => array(
          ':input[name="subject_group"]' => array('!value' => '0'),
        ),
      ),
    );
  }
  return $form;
}

/**
 * Callback element needs only select the portion of the form to be updated.
 * Since #ajax['callback'] return can be HTML or a renderable array (or an
 * array of commands), we can just return a piece of the form.
 * See @link ajax_example_advanced.inc AJAX Advanced Commands for more details
 * on AJAX framework commands.
 *
 * @return renderable array (the checkboxes fieldset)
 */
function _ajax_grade_group_callback(&$form, &$form_state) {
  //$form_state['rebuild'] = TRUE;
  //$form_state['input']['subject_group']=0;
  //$form_state['input']['class_group']= '0';
  return $form['school_group']['container'];
}
function _ajax_subject_group_callback($form, &$form_state) {

  return $form['school_group']['container']['class_group'];
}

```

# Answer
> 0 votes
Resloved, can't use this hook\_menu()

```
$items['admin/og'] = array(
    'title' => 'Group adminstrator',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('og_admin'),

```

and

```
 og_admin(){
  $build['og_user_filter_form'] =drupal_get_form('og_user_filter_form');

  $build['user_admin_account']= drupal_get_form('og_user_admin_account');

  return $build['og_user_filter_form'];
}

```

should user directly user hook\_menu()

```
 'page callback' => 'drupal_get_form',
 'page arguments' => array('og_user_filter_form'),

```

and the og\_user\_filter\_form is the dependent dropdown form.

---
Tags: forms, ajax
---


# Question
Title: How to tell if node has been updated via UI form as oppose to programmatically?
I am importing/updating nodes from a web service using node\_save. One feature that I want to achieve is when the imported node is changed locally, it should not receive any further updates from the web service.

So, what I want to achieve is:

* Detect when a node has been updated
* If the update was carried out by a user submitting a form (as oppose to programmatically)
* Then flag that this node should receive no further updates form the web service (I don't need any assistance with this part)

I wanted to use hook\_node\_update but I'm not sure how to tell whether the update was carried out by a user submitting a form.

Any suggestions?

# Answer
> 1 votes
Create an additional field in the content type - for example `update_source` \- and set the value programmatically.

If the user is editing the node on `node/[nid]/edit` page, set the value to `UI` and otherwise set it to `programmatic`.

You can do this with simple `hook_form_alter()` and URL checks to make sure the user is on `node/[nid]/edit` page. Something like this would work:

```
if (arg(0) == 'node' && arg(1) && arg(2) == 'edit') {
  // Your code
}

```

---
Tags: 7, nodes
---


title: Get all Taxonomy Terms

text:
# Question
Title: Get all Taxonomy Terms
I have added a vocabulary as Sites with machine name as sites. I have added two custom fields in this vocabulary as :

1) URL 2) Status 0 or 1

I need to make a dropdown of all terms with status 1 something like.

> get term.name from term join vocabulary on vid where vocabulary.machine\_name = sites and term.status = 1

```
$v =  taxonomy_vocabulary_machine_name_load('sites');

$t = taxonomy_get_tree($v->vid);

```

How do I get an array of enabled terms in the 'sites' vocabulary?

# Answer
> 3 votes
Yes, `entity_load` can be used, but you have to retrieve entity ids yourself:

```
$terms = array();

$v = taxonomy_vocabulary_machine_name_load('sites');
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $v->vid)
  ->fieldCondition('field_status', 'value', 1) // If your field name is 'field_status'
  ->execute();

if (!empty($result['taxonomy_term'])) {
  $terms = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
}

// dpm($terms);

```

---
Tags: taxonomy-terms
---


# Question
Title: caching views based on arguments as taxonomy term id
Hi need to enable caching based on taxonomy term id from the url which the views takes as an argument

1)simple cache returns empty results

2)views\_arg\_cache module also empty

3)views\_content\_cache module aslo empty

please help if any body has tried such scenario and found the solution

# Answer
http://drupal.org/project/cache\_actions might help you out.

Cache actions provides rules actions for clearing drupal caches.

It currently provides actions for:

> Clearing Drupal cache bins
> Clearing CSS/JS cache
> Clearing The cache of specific views
> Clearing The cache of specific panel pages
> Clearing The cache of specific mini panels
> 0 votes

# Answer
I found the solution by choose Granularity -\> Arguments
> 0 votes

---
Tags: caching
---


# Question
Title: Drupal 7 | Associate dynamic user to a content type
I have a content type "Article", with a field "author".

Is it possible to assign users with "writers" role dynamically with this field ?

The goal is to display in the article node, a link which redirects to the writer(user) profile.

For example :

-Article Title

-MM/DD/YYYY

-Written by : randomWritter (dynamic link)

# Answer
References module will enable you to do that.

It allows you to create fields and associate them with existing content/users on the site. It also features integration with Views so you can have more complex logic to filter out the available options.
The field can also be displayed as an autocomplete.
> 1 votes

---
Tags: nodes, users
---


title: Menu items shown in Navigation menu?

text:
# Question
Title: Menu items shown in Navigation menu?
I made a module for displaying nodes(links) from database. And I have simple question, why are the links displayed in the navigation menu? I want to be displayed in a separate menu (like navigation menu with my custom title etc etc...), but whatever I do they show up in the navigation menu.

```
function test_menu(){

$items = array();

  $items['test1'] = array(
    'title callback'   => 'test_callback1',
    'page callback'    => 'test_output1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

      $items['test2'] = array(
    'title callback'   => 'test_callback2',
    'page callback'    => 'test_output2',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,

  );
       ..... etc etc
      return $items;
}

```

This is page-test.tpl.php

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

```

# Answer
It's because you're using the `MENU_NORMAL_ITEM` type, which will add the item to a menu, and haven't set a `menu_name`. From the docs:

> "menu\_name": Optional. Set this to a custom menu if you don't want your item to be placed in Navigation.

If you want to add the link to a different menu try something like this:

```
$items['test1'] = array(
  'title callback'   => 'test_callback1',
  'page callback'    => 'test_output1',
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'main-menu'
);

```

If you don't want the link to be added to a menu automatically at all, change `MENU_NORMAL_ITEM` to `MENU_CALLBACK`.

Remember to clear the caches when you make any change to `hook_menu()`, otherwise the changes won't be picked up.
> 1 votes

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


# Question
Title: How to check progress of sql-sync that hangs up?
I run:

```
drush sql-sync @mysite.es.remote @mysite.es.local

```

then I hit `Yes` to continue then command completely hangs up for ever. Meanwhile I checked phpMyAdmin and it seems that it's synced my local database with remote but it's still missing some tables.

Is there any way how to check progress of sql-sync?

# Answer
> 7 votes
Run with `--verbose` or `--debug` to see more and lots of output, respectively, or run with `--simulate` to see only the commands that Drush *would* run.

Another helpful thing to do with sql-sync is to run `drush @mysite.es.remote sql-conf` and `drush @mysite.es.local sql-conf` \- this will print out the database records `sql-sync` will use for the two sites. In your case, since you are getting to the `y/n` prompt, this part is probably working.

---
Tags: drush
---


# Question
Title: How to trick feeds into re-importing nodes?
I have a content type in a feature. I am using feeds to import actual nodes from one site to another. I added new fields to the content type, and re-exported it into the features module. However, the feed ran before I updated the feature on the downstream site, and now it's not pulling the new field data. I know this will work, because it's worked before when I added new fields. However this time it's grabbed the data before it knew about the new fields.

How can I trick feeds into thinking it needs to update all the nodes? I tried setting the `changed` value on the nodes in the database to the current timestamp, but that didn't work. What criteria is feeds using to decide if the node data has changed?

# Answer
> 1 votes
In the feeds config area, under "Processor Settings", there is an option checkbox for "Skip Hash Check", which will cause the feed to update the items regardless.

---
Tags: feeds
---


# Question
Title: How do you get template preprocess functions to fire on hook theme suggestions?
If you have a theme function like theme\_field() for instance. I know you can do something like this:

```
function THEMENAME_preprocess_field(&$varialbes) {
  dpm($variables);
}

```

and that will print out the all the variables (if you have Devel enabled). Then I see theme\_hook\_suggestions like this "field\__field\_date\__featured\_event". However, when I try to do this:

```
function THEMENAME_preprocess_field__field_date__featured_event(&$varialbes) {
  dpm($variables);
}

```

The above does not work at all. Why is this? Is it possible to use a preprocess function on a theme suggestion? or are theme suggestions just for theme overrides and not for preprocessing?

thanks!

# Answer
> 2 votes
You need to do this before you can do that...

```
/*
 * Implements hook_preprocess_field().
 */
function YOURTHEME_preprocess_field(&$vars) {
    if ($vars['SOME_FIELD']) {
        $function = 'YOURTHEME_preprocess_field__'.$vars['SOME_FIELD'];
        if (function_exists($function)) {
            $function($vars);
        }
    }
}

```

---
Tags: 7, hooks, theming
---


# Question
Title: How to make a form that captures a value from $_REQUEST[]
Update: This question now has a clone: https://stackoverflow.com/questions/13184335/drupal-how-to-make-a-form-that-captures-a-value-from-request

I have been trying to make a form that captures a value passed in from `$_REQUEST`.

1. A field is displayed only if a $\_REQUEST variable exists (done)
2. The user can modify the field
3. The field is validated in whatever way
4. The (modified) value gets used

In this specific case, I am using a `hook_user` function, but I hope that the solution is applicable to any Drupal form.

Here's a simplified version of my code where the user would have an extra field to specify that they have a favorite fruit if they were to register using the following URL:

http://example.com/user/register?fruit=pineapple

```
function fruity_user($op, &$edit, &$user, $category = NULL){
    switch($op) {
        // Add extra fields if $_REQUEST contains values for them
        case 'register':
            if($_REQUEST['fruit'] == 'pineapple'){
                $fields['user_reg_info']['profile_fruit'] = array(
                     '#type' => 'textfield'
                    ,'#description' => 'Your favorite fruit (if applicable)'
                    ,'#locked' => 0
                    ,'#value' => $_REQUEST['fruit']
                );
            }
            return $fields;
            break;

        // check registration for mistakes
        case 'validate':
            if ($edit['form_id'] == 'user_register') {
                if ($edit['profile_fruit']){
                    verify_fruit($edit['profile_fruit']);
                }
            }
            break;

        // runs after the new user is inserted
        case 'insert':
            if($_REQUEST['fruit']){
                db_query('INSERT INTO user_fruits SET `uid`=%d `fruit`="%s"',array($user->uid, $edit['profile_fruit']));
            }

            // record information
            watchdog('user', t('user %user picked out a fruit',array('%user' => $user->name)));
            break;
    }
}

```

With the above code, the field does make itself visible only when `$_REQUEST['fruit']` is present but if you change your fruit to "watermelon" on the form, `insert` still uses "pineapple".

# Answer
> 0 votes
The answer was to use `#default_value` instead of `#value`.

http://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/6#default\_value

---
Tags: hooks, forms
---


title: customized login block

text:
# Question
Title: customized login block
I made a template for the login block on the main page. It works.

Here is user-login.tpl.php code:

```
<?php
    $elements = drupal_get_form('user_login_block');
?>
<div class="login">
    <div class="login_header">Login</div>
<?php
print drupal_render($elements["form_id"]);
print drupal_render($elements['name']);
print drupal_render($elements['pass']);
?>
      <div class="forgot_password">
             <a href="/" class="forgot_password">Forgot password</a>
      </div>
       <input type="submit" name="" value="Log in" />
       <a href="/" id="sign_up">Sign up</a>
</div>

```

`<form>` and `<div>` tags were added around my template code, breaking the layout. Now the block doesn't float: left.

Here is the rendedered HTML:

```
<form action="/node?destination=node" method="post" id="user-login-form" accept-charset="UTF-8"><div><div class="login">
    <div class="login_header">Login</div>
<input type="hidden" name="form_id" value="user_login_block" />
<div class="form-item form-type-textfield form-item-name">
  <label for="edit-name--2">Login <span class="form-required" title="This field is required.">*</span></label>
 <input type="text" id="edit-name--2" name="name" value="" size="15" maxlength="60" class="form-text required" />
</div>
<div class="form-item form-type-password form-item-pass">
  <label for="edit-pass--2">Password <span class="form-required" title="This field is required.">*</span></label>
 <input type="password" id="edit-pass--2" name="pass" size="15" maxlength="60" class="form-text required" />
</div>
      <div class="forgot_password">
             <a href="/" class="forgot_password">Forgot password</a>
      </div>
       <input type="submit" name="" value="Log in" />
       <a href="/" id="sign_up">Sign up</a>
</div>
</div></form>

```

How to remove extra `<div>` and put the form inside `<div class="login">`? I tried that manually, but then I get 2 forms.

# Answer
You could alter the form on the theme layer to wrap the form in a div...

```
/**
 * Implements hook_form_alter().
*/
function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {

    //dsm($form_id);

    if ($form_id == 'YOURFORMID') {
        // add prefix and suffix to form
        $form['#prefix'] = '<div class="form-class">';
        $form['#suffix'] = '</div>';
    }
}

```
> 2 votes

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


# Question
Title: Proper use of hook_menu_breadcrumb_alter()
I have a situation where I need to mess with a breadcrumb on a page and insert some items in the middle. In my instance `drupal_set_breadcrumb()` can't be used, so I need to implement a `hook_menu_breadcrumb_alter()`. I am a little confused about proper usage with this, though, and am not terribly familiar with the guts of how the menu module works.

Is there a proper method for building elements that go into the `$active_trail` array, eg

```
$foo = array(
  'title' => $node->title,
  'href' => 'node/' . $node->nid,
  'link_path' => '',
  'localized_options' => array(),
  'type' => 0,
);

```

`title` and `href` are easy enough, but I don't quite get how the other play into this particular context. It is easy enough to figure this out from what is there, but I would like to do "the right thing".

Is there a proper method (or best practice) for testing whether `$item` is a node and to load it? Again, I can `dpm($item)`, poke around, and get what I need.

I have what I need working, but it is messy and would like to fix it for the long term.

# Answer
> 1 votes
The properties for each trail item that are documented are the following:

* title: Title of the item
* href: Drupal path of the item
* localized\_options: Options for passing into the `l()` function
* type: A menu type constant, such as `MENU_DEFAULT_LOCAL_TASK`, or 0 to indicate it's not really in the menu (used for the home page item)

The code that builds the breadcrumbs is the following.

```
foreach ($active_trail as $parent) {
  $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
}

```

The other values (type and link\_path) are not used to create the breadcrumbs, but they could be used from other modules that alter the breadcrumbs. Using the default values used from `menu_set_active_trail()` for those properties probably causes less compatibility problems with other modules.

```
$trail[] = array(
  'title' => t('Home'),
  'href' => '<front>',
  'link_path' => '',
  'localized_options' => array(),
  'type' => 0,
);

```

> Is there a proper method (or best practice) for testing whether `$item` is a node and to load it?

The `$item` argument `hook_menu_breadcrumb_alter()` gets is the value returned from menu\_get\_item(). If you want to check it is for a node, you can use the following code.

```
if (isset($item['load_functions'][2]) && !empty($item['map'][3]) && $item['load_functions'][4] == 'node_load') {
  $node = $router_item['map'][5];
}
else {
  // The menu item is not for a node.
}

```

That is the code executed from menu\_get\_object() when it is called with its default arguments.

### References

---
Tags: routes, breadcrumbs
---


# Question
Title: The same rules, only one being triggered
I am working on a website and one (maybe more) rule is not being triggered.

The rule that is not working is as follows

```
Event:
After updating existing content
Condition:
Content is of type...
Actions:
Show a massage on the site...
...
More actions

```

I tried to reproduce the problem with a following rule

```
Event:
After updating existing content
Condition:
Content is of type...
Actions:
Show a massage on the site...

```

But it works.

The rule used to work. The portal is under development. There are many added modules. The rule weight is the same.

The only difference between the two rules is the name (I tried changing the name) and actions performed.

Any idea what can be wrong?

UPDATE I tried cloning the faulty rule and the clone does not work. Below I attach the code of the faulty and working rules.

Works

```
{ "rules_test_update_rule" : {
    "LABEL" : "test Update Rule",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "test_case" : "test_case" } }
        }
      },
      { "data_is" : { "data" : [ "node:field-workflow-status:tid" ], "value" : "28" } },
      { "NOT data_is_empty" : { "data" : [ "node:field-workflow-reviewers" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Test case got updated", "type" : "warning" } }
    ]
  }
}

```

Does not work

```
{ "rules_tc_admin_review_v1" : {
    "LABEL" : "TC: admin review",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "privatemsg_rules", "windbench_workflow", "og" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "test_case" : "test_case" } }
        }
      },
      { "data_is" : { "data" : [ "node:field-workflow-status:tid" ], "value" : "28" } },
      { "NOT data_is_empty" : { "data" : [ "node:field-workflow-reviewers" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "User has been notified.", "type" : "warning" } },

```

........ more in the "DO" section, should be irrelevant.....

# Answer
> 1 votes
That is a weird one.

I don't know what caused the problem but the fix was to export and import the rule.

The interesting part is that cloning the rule did not work, even when I simplified/changed the cloned rule to

```
{ "rules_tc_admin_review_cloned_" : {
    "LABEL" : "TC: admin review (cloned)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "DO" : []
  }
}

```

The rule was never checked. There seems to be a bug. Possibly in the rule cloning function.

---
Tags: rules
---


# Question
Title: why i can't write anything to a custom cache table?
First in mymodule.install I declared mymodule\_schema(hook\_schema) mymodule\_install() and mymodule\_unistall()

Where mymodule\_schema() is like this:

```
function mymodule_schema() {
    $schema = array();
    $schema['cache_mymodule'] = drupal_get_schema_unprocessed('system', 'cache');
    return $schema;
}

```

this worked perfectly and table `cache_mymodule` with the same structue as table cache was created.
But in my code, using this:

```
$cid=some_calcuated_cid();
$cache=cache_get($cid,'cache_mymodule');
if (!$cache){
    $data = some_calcuated_data();
    cache_set($cid,$data,'cache_mymodule');
    dpm('CACHE SET');
else {
    dpm('used cache');
}

```

I always get 'CACHE SET', Now if i change 'cache\_mymodule' to just cache, Or remove it, It works perfectly (saying used cache), Am I missing some hook in mymodule?

# Answer
> 4 votes
It looks like the problem is just a misnamed variable.

Surely

```
$data = some_calcuated_data();
cache_set($cid,$cache,'cache_mymodule');

```

should be

```
$data = some_calcuated_data();
cache_set($cid, $data, 'cache_mymodule');

```

At the moment you're setting the cache as `NULL`, any time it's already `NULL`...probably not what you were going for :)

# Answer
> 4 votes
You don't need to create your own table to use the internal cache. Just use cache\_set() and cache\_get() as documented. This will store the $my\_data in the default 'cache' table:

```
// Store $my_data in cache.
cache_set($data_id, $my_data);

// Get $my_data from cache.
$data = cache_get($data_id);

```

Your code snippet should look something like this:

```
$cid = some_calcuated_cid();
$cache = cache_get($cid);

if (!$cache){
  $data = some_calcuated_data();
  cache_set($cid, $data);
}

```

Documentation:

cache\_set()

cache\_get()

# Answer
> 0 votes
In order to debug this, enable the mysql log which displays all queries executed (you will need a mysql restart)

```
mysqld.exe --log=path\to\log\file\your-log-file-name.log

```

This will give you a clue if the respective sql insert command is actually triggered and executed. And you should also check (via sql) if 'cache\_mymodule' is empty or not after the code snippet execution.

---
Tags: 7, caching
---


# Question
Title: How to give anonymous user access in a menu hook?
I have a module with a menu hook that I want to give access to everyone. At first I had simply

```
function hook_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_callback',
  );
  return $items;
}

```

But when I navigated to `/search`, I got a warning that I didn't have permission. I thought I had remembered somewhere along the line that I could do `'access callback' => TRUE,` in the menu hook to allow anonymous access, but that doesn't seem to work either.

Do I really have to add another function that just returns true to use as the access callback to give anonymous users access to this path?

# Answer
You can definitely set `'access callback' => TRUE` on the menu item and that will bypass any access checks, you don't need to implement a function that just returns `TRUE` (it would be redundant). Don't forget you need to clear the caches before changes in hook\_menu will get picked up though.

Rather than just blindly returning `TRUE` though it's probably a better idea to assign a permission to the anonymous user role, or piggyback off of one that's already there (`access content` is the usual suspect for this if it fits in with your workflow). You can do that by using `'access arguments' => array('access content')` **instead of** `'access callback'` (don't use both).

Also you've missed out the `title` in your example, according to the docs that property is required. I doubt that's actually causing the problem though.

Just on another note, you mention that you're visiting '/search' to test this page - the path you've defined will be at '/site\_search' instead.
> 11 votes

---
Tags: routes
---


title: hook_field_schema() does not work

text:
# Question
Title: hook_field_schema() does not work
I'm creating a module to introduce a new field type. I downloaded the example module by drupal and i start programming. But when I install the module the .install don't add colums to the dbtable related to new field.

```
 function field_instagram_field_schema($field) {

   watchdog('start field_instagram_field_schema()', 'We are in!');

   switch ($field['type']) {
    case 'instagram_gallery':
      $columns = array(
        'stream_type' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        ),
        'input_tag' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        ),
         'thumb_dimetion' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        ),
        'thumb_number' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        )
      );
      break;
  }

  return array('columns' => $columns);
}

```

**UPDATED**
When i install the module and create a field of this new type this function is not runned..

# Answer
Your code is correct, but nothing will happen when you install the module itself. It will only be invoked when you create a new field of type `instagram_gallery`.

But that is not all. The only module that will get's it `hook_field_schema` invoked, is the module that actually defined the field. This is done with `hook_field_info`, so you need to have the following code in your `field_instagram.module` file:

```
/**
 * Implements hook_field_info().
 */
function field_instagram_field_info() {
  return array(
    'instagram_gallery' => array(
      ...
    ),
  );
}

```

Since you are defining your own field, you also need to use

* `hook_field_is_empty`
* `hook_field_formatter_info`
* `hook_field_formatter_view`
* `hook_field_widget_info` (unless you can use an existing widget)

**Update**
It's hard to say way you have troubles. What the field module does is this:

```
module_load_install($field['module']);
$schema = (array) module_invoke($field['module'], 'field_schema', $field);

```

You can try to load the created field manually and run the hook to see if it works. You need to load the `.install` file like shown above. My guess is that you have something misnamed somewhere, but it's hard to say where exactly. The above could should with your info look like this:

```
$field = field_info_field('field_name_here');
module_load_install('field_instagram');
$schema = (array) module_invoke('field_instagram', 'field_schema', $field);

```

If the above works, you can try to debug the actual field creation, the code is from field.crud.inc line 134.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Is there a reliable way to see what other users see when logged in?
I've found the Impersonate and Masquerade modules, but the first is for Drupal 5 (I remember the hardest thing about Drupal 5 development was having to keep an eye out to avoid being lunch for a hungry T Rex) and the second is still a release candidate (for Drupal 7) and is "minimally maintained".

Is there another, better way? Or can anyone vouch for the stability of Masquerade?

# Answer
I can't vouch for either of those modules, but I've been using the 'Switch' feature in the Devel module to do just that for years. I've used it on probably hundreds of sites and I've never found a problem with it.

When logged in with appropriate permissions you can visit /devel/switch/\[username\] and it will log you in as that user. There's also a list of users in the admin toolbar that you can choose from directly, but I'm not sure if that's only available if you have the Admin Menu module installed.

It doesn't add a link to log back in to the admin user like the Masquerade module does (it's more 'bare-bones' than that), but if you've got your admin password saved in the browser it'll only take a couple of clicks to log back in anyway.
> 4 votes

---
Tags: 7
---


# Question
Title: Is there a way to pass selected date from date_popup to another view in URL?
I'm using date module in Drupal 7. There are two views that I created; a link inside of one leads to another view. In the first view, I used exposed popup date filter to get the result. What I'm trying to achieve here is how to pass the selected date from the date popup, put it in the URL to use as contextual filter in the another view.

Thanks, Jake

# Answer
Definitely. When you expose a filter, it listens for a specific $\_GET ID in the URL. This ID can be set by expanding the "More" settings of the particular filter item and entering/modifying the string in the "Filter identifier" field.

In your case, you'd copy the first View's filter identifier and paste it into the second View's filter identifier, thus allowing both of them to use the same item in the URL.
> 0 votes

---
Tags: datetime, views
---


# Question
Title: Different approval for different user accounts
I would like user account *A* to require approval before granting access, and user account *B* not to require any approval.

How can this be achieved?

# Answer
I have not used any module that can provide this kind of control. What you can do is for the second option create your own form and from backend create the user on form submit after proper validation.
> 0 votes

# Answer
You could have all users create accounts without the need for approval, and have user account A apply for the extra access needed using a contrib module. See my previous answer about organic groups and apply for role modules.
> 0 votes

---
Tags: users
---


# Question
Title: Change region/block content based on current node
I am trying to figure out how to change the content of a region/block depending on the node being viewed.

Lets say I was creating a website for a grocery store. The home page will have several links for the various departments ... Meat, Seafood, Dairy, etc. When the user clicks on one of these departments they will go to a node where there is a menu that lists all the items in that department ...

* Meat =\> Steak, Hamburger, etc.
* Dairy =\> Milk, Eggs, Cheese, etc.
* Seafood =\> Shrimp, Tuna, Salmon, etc.

What I am trying to figure out is how to display the correct item menu for the selected department. How to I display the menu of all the dairy products when the user selected the "Dairy" node?

Ideally I would like to accomplish this without hard coding changes into the template as I would like the site owner to be able change things themselves.

Thanks for any suggestions!

# Answer
> 3 votes
An easy way is to:

1. Make a site section taxonomy, and add as a field to your nodes (eg, `field_site_section`). Probably want to make it a required field that only allows one value.
2. Set pathauto settings for the content types to include the term in the URL, eg `[node:field_site_section]/[node:title]`
3. There should be a block for each menu you have defined. Set the visibility to only appear on paths matching a wildcard based on the paths you defined above, eg `section/*`.

If you need a landing page for the section, just make a node, assign the site section, and set the alias manually to just be the section name. Then, add in this to the list of path for the menu block to appear on.

One more thing that can help with this approach is to add an entityref field to the site section taxonomy. Then for each term, set the field to the root node of the section. This can come in handy for some uses.

# Answer
> 3 votes
Try the context module.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

Refer the module page for documentation links.

# Answer
> 0 votes
You could use entity references http://drupal.org/project/entityreference on your nodes (make the name 'Parent Node' and machine name 'field\_parent\_node' to follow my full example). This will allow you to assign the nodes a parent node. Once done you can use views with a contextual filter

Contextual Filter Setup: Content: Parent Node, WHEN THE FILTER VALUE IS NOT AVAILABLE - Provide default value - Content ID from URL

This will then allow you to display a block of titles to make a menu or even display some teasers of child nodes for the parent.

It is also possible (although a little more complicated) to create a view of parents-children i.e. on the eggs page you could display milk, eggs, cheese etc. to do this create a view as before but the contextual filter needs some php.

Contextual Filter Setup: Content: Parent Node, WHEN THE FILTER VALUE IS NOT AVAILABLE - Provide default value - PHP Code

```
if ($node = menu_get_object()) {
  $query = &$view->build_info['query'];
  $parent_node = field_get_items('node', $node, 'field_parent_node');
  return($parent_node[0]['target_id']);
}

```

If you also want to exclude the current node from the view then you can add another contextual filter to this view:

Contextual Filter Setup: Content:nid, WHEN THE FILTER VALUE IS NOT AVAILABLE - Provide default value - Content ID from URL. Then open the more tab at the bottom and check exclude.

---
Tags: nodes, blocks, theming
---


# Question
Title: What is the difference between hide() function and unset()?
What is the difference between `hide()` and `unset()`? I want to hide some elements, I found `hide()` and `unset()`, but I don't know which one I should use.

# Answer
> 19 votes
`hide()` and `unset`() are not same. hide() is a Drupal function and unset() is a raw php function.

`unset()` simply destroys a variable. For an example,

```
<?php
$name = 'Drupal';
unset($name);
print $name; // this will result an error as $name is no longer set. `isset()` will return FALSE.

```

`hide()` does NOT destroy the variable. It's useful to *mark* some render-able array is already rendered so it will not be **rendered again**.

it simply adds/replaces the given argument's `#printed` to TRUE so `drupal_render` or `render()` won't execute the theme functions again - instead, it will use cached version *if available*.

A sample use case of `hide()` would be to hide comment form in a node template and show it somewhere else in the template. You will also find it useful when altering pages or blocks. Do **NOT** `unset()` a render array if you want to use it somewhere else.

If you want to hide some specific form element from the user but still want to keep the form structure, set `#access` of the element to `FALSE`.

hide()

drupal\_render()

unset()

---
Tags: 7, forms
---


# Question
Title: using a custom module, how to add a <style> tag after the theme's css files
I use Drupal 6.

Everytime I use `drupal_set_html_head`, my `<style>` code is being added before my theme's `<link>` entries.

Basically, I want to override the theme's css files with internal css, so I need my `<style>` to appear at the very end of `<head>`

I hope it is clear. Thanks!

# Answer
Everything you add with `drupal_set_html_head()` is added before the CSS styles added with `drupal_add_css()`. In fact, the page template outputs them using the following code.

```
<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
</head>

```

`$head` and `$styles` are initialized in template\_preprocess\_page() with the following code.

```
$variables['head'] = drupal_get_html_head();
$variables['styles'] = drupal_get_css();

```

As drupal\_add\_css() is used to add all the CSS styles used by a theme, including the ones defined in its .info file, you can change the order the CSS styles are added by changing the page template. If it would contain the following code, everything added with `drupal_set_html_head()` will come after everything added with `drupal_add_css()`. I would not suggest doing this, if not after verifying it doesn't cause any problem.

```
<head>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $head; ?>
  <?php print $scripts; ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
</head>

```

Notice that with Drupal 7, you can use drupal\_add\_css() to use inline CSS style too: Just pass the CSS styles as first argument, and pass `array('type' => 'inline', 'weight' => 100)` as second argument. You need also to use the group property. In that way, you don't need to alter the template file just to add your CSS styles after the ones added by Drupal.
Generally, it is preferable to add the CSS styles in a file; in that way, they can be aggregated/compressed.
> 1 votes

---
Tags: theming
---


title: Callback function in menu items field

text:
# Question
Title: Callback function in menu items field
Is it possible to put callback function here `$items['callback?']` ? I need to change this field every time when user make some changes. The biggest problem for me is that `hook_menu()` is cached and menu is rarely updating.

# Answer
> 0 votes
Technically, you can use a function to return an array of menu router items but practically it will not work because of caching.

However you can register wildcats paths like companies/*so your page callback will be fired on every companies/* pages.

To do so, set the key of the $items like this:

$items\['companies/%'\] = array(...menu router info here ...);

---
Tags: routes
---


# Question
Title: Can we add different fields to instances of the same entity?
I have a City entity with two fields (Title and Population), and I have created two instances of that entity.

Can I add different fields to these two instances?

Thank for you responses but I want different approach Let me put my question in this way

1) I have entity: City (with fields Population and Title)

2) of which I created two content (what should i call Chicago an New York ? contens of type City or anything else??):

Chicago and New York

3) now i know the entity City is fieldable i.e i can add custome fields to it, but those will be accesible to both ‘Chicago’ and ‘New York

4) What I want is ‘Chicago’ and ‘New York’ also be fieldable and have distinct field as well as common field

5) so, it should look like as Chicago : (Title - ‘Chicago’, Population - 1000, CField1 - ‘Hello’) New York: (Title - ‘Chicago’, Population - 1000, NField1 - ‘Hello’, NField2 - ‘Hello’)

Please tell me if above requirement is possible to implement

# Answer
In the same way fields are added to content types, and not to node instances, fields are added to entity's bundles, not to entity instances.

If you don't want to use two different bundles for the same entity (which IMO is the better solution), you can implement hook\_field\_access(), and make some fields editable/visible basing on on the value of some entity properties, such as the title, or the entity ID.
For example, the following code would make a field visible, and editable, only when the `title` property of the entity is equal to "New York"; not even the user #1 would be able to see it. Practically, it is like the field is not present.

```
function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'your field' && entity_type == 'your entity type' && $entity->title == "New York") {
    return FALSE;
  }

  return TRUE;
}

```

This example is very simplified. You should normally check the value of `$op`, just in case future versions of Drupal introduce new values for that parameter.
> 1 votes

# Answer
This single entity will use all of the fields you attach to it – it's still 1 instance (what we call a 'bundle') of an entity.

If you want to conditionally allow fields to be displayed on the entity edit form (or the display of the entity) use the Conditional Fields module: http://drupal.org/project/conditional\_fields

If you really want to use different sets of fields, you need 2 different bundles, i.e. a "city" entity of bundle "foo" and a "city" entity of bundle "bar".
> 1 votes

---
Tags: entities, database
---


title: Bold text from exposed filters

text:
# Question
Title: Bold text from exposed filters
I'm using an exposed filter in views to find nodes that contain that word in the body field.

I would like to show that word in the body in bold.

# Answer
> 2 votes
You can achieve this using search\_excerpt function.

for eg:

in your views tpl file add the following code

```
 <?php foreach ($rows as $id => $row):

      $keys = $_GET['body_value'];
      $row = search_excerpt($keys, $row);
 ?>

```

it will highlight the searched word, see the screenshot below

---
Tags: 7, views
---


# Question
Title: How can I add a "Back to Search" link to user profiles?
I have a view with exposed filters that allows users to search for other users on my site. The view displays users' profile pictures, and clicking a profile picture takes one to the relevant user's profile (put together using Panels).

I'd like to display a "Back to search results" link on the user profile whenever someone clicks on the link (picture) in the view and visits the profile. How might I go about doing this?

I'm using D7 with Panels and Views 3.

# Answer
You can do this wih a new module modifying the user profile view.

```
// Implements hook_user_view().
function MY_MODULE_user_view($account, $view_mode, $langcode) {
  $account->content['link'] = array(
    '#weight' => -10,
    0 => array(
      '#markup' => '<a href="/VIEW_URI">Back to Search</a>',
    ),
  );
}

```

Note: When adding a hook always remember to clear caches

If you also want to preserve the filter that the user has applied you can do so within your filter in the view by selecting 'remember the last selection' and selecting the roles that you want this for.
> 2 votes

---
Tags: views, panels
---


title: File Repository Module

text:
# Question
Title: File Repository Module
Is there anybody have ever used a moudle that like File Repository ? Who can tell me whether have the similar module in Drupal.org ?

This module should provide these following functions :

(1) Authorised user can create folder and sub folder, upload files into a folder.

(2) Role-based access control: a) Authorised user can config the attributes of folder, can assign which role can access this folder. b)Folder & sub folder both can set different access control attributes.

# Answer
Checkout filedepot module.

> The filedepot module is full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.
> 1 votes

---
Tags: files
---


# Question
Title: How can I track statistics on how often a hook/error message is triggered?
I am using the Privatemsg module in Drupal 7. I have a hook in a custom module that is triggered when users write a message that is too short. I set this up using the instructions here.

Basically, it looks like this:

```
function mymodule_privatemsg_message_validate($message) {
  $uid = $vars['message']->author->uid;

  //if root or help user, message should always go through regardless of length
  if ($uid !== '1') {
    if ($uid !== '3') {

      if (empty($message->thread_id) && strlen($message->body) < 200 ) {
    form_set_error('[body][value]', t('My custom message.'));
      }
    }
  }
}

```

I recently noticed there are not so many messages being sent on my site. I would like to know if it is because they are being blocked by this hook. How can I track how many times it is triggered (and even better if I can know which logged-in users are getting the error message)?

# Answer
> 2 votes
I don't think you'll get 'statistics' as such without some coding yourself, I've never seen a module that does that sort of thing (but hey it's Drupal so there probably is one somewhere).

Failing that I think your best bet would be to use the the `watchdog()` function, combined with enabling the dblog module on your site. You can use it like so:

```
if (empty($message->thread_id) && strlen($message->body) < 200 ) {
  form_set_error('[body][value]', t('My custom message.'));

  global $user;
  watchdog('mymodule', 'My custom message for user @username', array('@username' => $user->name));
}

```

Every time that `if` statement is entered you'll get a message on the 'Recent log messages' page, where you can even filter by entries for your own module, giving you a basic idea of what's happening, when, and for whom.

---
Tags: hooks, nodes
---


# Question
Title: Very slow loading on localhost (via. Uniform Server)
I've setup Drupal to run successfully on a Uniform Server installation on my local machine, but it's really slow. It's taking over 30 seconds to enable/disable modules, and around 3-10 seconds on most other pages. This is becoming time prohibitive.

Things I've observed/tested:

* PhpMyAdmin (running under the same server stack) doesn't seem to take any unnecessary time to load with any operations.
* As per this guide, disabling my firewall (while LAN/WAN disabled) has no effect.
* Modifying php.ini and my windows hosts file (also by that guide) have no effect.
* Firefox settings seem to have no effect (including the one mentioned in that guide).

My next move is simply to try a different server stack, but I'm wonder if I have to. Advice?

# Answer
> 6 votes
Well, for when I did run Windows last time with a webserver on it, I used Xampp, and it wasn't too slow out of the box. I found I still had to change portions of my.cnf to get it to run at a decent pace.

Several installs and jumps between Linux and Windows has made me realise that most of the Windows stacks I've come across have a lot to be desired performance wise and fiddling with my.cnf yields the best improvement.

Currently I use a 9 year old pc for most dev work, running Ubuntu server. It was painfully slow, but setting up MySQL caching to be a bit more reasonable and installing APC now has it running much, much faster than my quad core (with Xampp, admittedly no apc) at a mere 3 years of age. (The server only has 768mb of RAM).

My suggestion is to dive into my.cnf, though back it up first because if you get it set up wrong it may run much slower.

Alternatively get yourself set up with an Ubuntu server, made my life much easier (Though be prepared to lose several hours, maybe more if you are adverse to using a terminal) The Ubuntu Server guide walks you through pretty much everything you will need to do though.

As a disclaimer I have never used Uniform.

Edit from here on:

Relevant settings I use for my.cnf are:

```
[myslqd]
key_buffer              = 16M
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 8
# I keep this low to limit max memory usage, with 2 or less people we don't get near this
max_connections         = 50
# table_cache is quite large compared to default because of the massive amount of tables
# Drupal uses.
table_cache             = 512
# Increased for those large queries, though keep an eye on these queries exceeding this
# value on your production server/hosting.
query_cache_limit       = 3M
# Greatly increased due to the large numbers of queries Drupal does.
query_cache_size        = 32M
# Total size of InnoDB's buffer, larger is better, I keep it larger than the DB of the
# of the site I am currently working on.
innodb_buffer_pool_size = 128M
# This stops InnoDB flushing its log at every transaction, instead flushiong it once
# per second. Can be detrimental to the last 1 or 2 seconds of data in case of a crash.
# Imo provides the largest boost on desktops due to their usually limited I/O capacity.
innodb_flush_log_at_trx_commit = 2

```

I no longer use myisam tables so I haven't played with myisam specific settings in there.

Overall the biggest bottleneck is hard drive access time so I keep as much in memory as possible, my dev server (Which is that ancient desktop box) has PATA drives so even writing to its miserable 8MB cache is slow. If your computer is low on I/O you need more caching, APC also makes a big difference in these cases.

Just keep in mind that you should compare the production environment settings to your dev ones to make sure that you stay within the production environment capabilities, though even on shared hosting with dismal caching and no APC, the presence of RAID usually makes up for it (Granted though that the host we use currently is the fastest one we have used, and some shared hosts are going to be slow no matter what you do.).

Also look at http://www.mysqlperformanceblog.com/ but also maybe avoid it because that is more geared towards dedicated database servers with obese amounts of RAM.

# Answer
> 1 votes
In my experience I've found XAMPP much faster than other servers, especially vs MAMP.

It also runs better since the defaults are with much bigger RAM settings (128MB)

# Answer
> 1 votes
You might be having problems with IPv6: http://drupal.org/node/346392

See the testing steps in that issue. Then try modifying your hosts file (C:\windows\system32\drivers\etc\hosts) so that it reroutes IPv6 requests to localhost:

```
127.0.0.1 localhost
::1 127.0.0.1

```

# Answer
> 0 votes
Have you ever tried Acquia Dev Desktop? We use that when we are teaching classes. It's one of the fastest setup / most complete Drupal stacks for a localhost. I personally have no experience with Uniform - first I heard of it today.

If something is running slow I would ask how much RAM you have. Like you say, the "hosts" problem sometimes bites you in the butt too.

---
Tags: 7, performance
---


title: Commerce + Panels

text:
# Question
Title: Commerce + Panels
I am getting confused about how to add my product displays using Panels. If I am using Panels to display my products pages, do I need to make a regular node Content Type called 'Product Display,' then add the products there first before I do them in Panels?

And also, how do I set up Panels to display my product pages?

# Answer
Caveat : This is my experience as an advanced Site Builder, not developer.

You do not have to use Product Displays if you are using Panels. Using Panels instead of Product Displays is often done to replace Product Displays if you only have one display per product, so you don not need to replicate your Product -\> Product Display.

In your Panel setup, you need to create a page that uses the Product ID as a variable in your URL. Create a URL with a variable (e.g. /catalog/%products), then in the Arguments section you configure %products to use Commerce Product ID.

Then create your Page with the Panel layout desired, inserting fields where needed. In order to get a "Add to Cart" button, what I've done is create a single-item View of Product fields, and display the Add to Cart button in the Field list. I add a Contextual Filter (in Advanced) to fetch the correct Product ID value (Provide Default Value -\> Raw value from URL). I know there is another way to do this with a Views moudle for Panels, but I don't know the specifics - maybe someone else can help?

Of course there are more complicated things you may need to solve - multiple images, related products - but these can be solved with standard Drupal solutions (Views, Cloud Zoom / Gallery, etc).
> 3 votes

---
Tags: commerce, panels
---


# Question
Title: Is there a module to create a list of favorite nodes?
I am looking for module that would let users of a site save nodes as Favorite, so that these nodes can be found back later via a "My favorite" interface.

Has anyone heard about such a module?

# Answer
> 11 votes
I was thinking that would be a great idea, until I remembered that Drupal contributors have already offered quite a few solutions for this as demonstrated by a quick search of the Drupal site. Of course, Flag module provides a great abstract way of creating these types of systems. There's also Favorites and Add to favorites, but those are for Drupal 6 only right now. I would recommend Flag I think just because I've used it for precisely this type of thing as have many others (even though it's still in beta), and *quicksketch* and *fago* are great Drupal developers.

# Answer
> 1 votes
It is worth mentioning that you can do this with the Node Queue module.

For your particular scenario, you would also need Smart Queue per User, but unfortunately that is still being ported to Drupal 7. There's a sandbox version of the project available to work with, though.

# Answer
> 0 votes
Voting API is the way to go, you can use a module like Rate with a custom widget.

---
Tags: 7
---


# Question
Title: altering access callback in hook_menu_alter
So, I want to set a new function as access callbacks for URLs specified by registration module.

Specifically I want only users that have the update rights on the node to be able to manage registrations for the node.

I implemented hook\_menu\_alter in this manner:

```
function enge_events_menu_alter($items){
  $items['node/%entity_object/registrations']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/list']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/list']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/settings']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/settings']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/broadcast']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/broadcast']['access arguments'] = array(1);
}

```

but for some reason the function never fires.

If I instead redeclare the module's hook\_menu and change the access callback functions there, it works and it get's written in the database after a cache clear.

Is it possible to alter access callbacks in hook\_menu\_alter?

# Answer
> 6 votes
```
function enge_events_menu_alter(&$items){
  $items['node/%entity_object/registrations']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/list']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/list']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/settings']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/settings']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/broadcast']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/broadcast']['access arguments'] = array(1);
}

```

$items should be reference variable... For more information hook\_menu\_alter

---
Tags: 7, routes
---