title: Transforming system link into a button

text:
# Question
Title: Transforming system link into a button
I have created a "button" class in my style.css file.

I can easily create a button by assigning the "button" class to it. I can do this when I write the html code in, say, a block that I place wherever on the page.

But how do I transform an existing link (like one automatically created by a module) into a button?

Do I need to hack the module?

Any help on this riddle would be greatly appreciated.

Thanks.

:)

# Answer
> 0 votes
I definitely don't recommend hacking the module - it's not good Drupal form, and it limits your ability to get module updates in the future.

I think the answer depends on how the module creates the link in question. That is, how is the link HTML being generated? If it's being generated and printed directly to the screen, then you'd have to do some CSS/JS work to intercept the HTML being generated and alter it. We have done this when necessary on our site to bend certain modules and functionality to suit our display needs. If the link has a specific ID, just alter it with JS in a custom module or custom theme. If not, you may have to get at it via jQuery based on what elements it's contained within, but it can be done.

If you're lucky and the module is well-written, the link will be part of content that's passed through Drupal's theming engine first through a `theme()` call. In this case, you can write your own function to grab anything being themed, inspect it for whatever markers indicate that it should become a button, and then alter the link code as need be. If you're not familiar with the `theme()` functionality in Drupal, you'll want to read up on it on Drupal.org first. Hope this helps!

---
Tags: blocks, theming, navigation
---


# Question
Title: What is the Drupal API for reading Drupal configuration files (.info .make etc.)?
Drupal configurations such as `.info`, `.make` appear to follow common structure. There must be Drupal API for reading these configurations from code.

How does one load and read these configurations in his code?

# Answer
You want drupal\_parse\_info\_format.

> Data should be in an .ini-like format to specify values. White-space generally doesn't matter, except inside values.

```
  key = value
  key = "value"
  key = 'value'
  key = "multi-line
  value"
  key = 'multi-line
  value'
  key
  =
  'value'

```

> Arrays are created using a HTTP GET alike syntax:

```
  key[] = "numeric array"
  key[index] = "associative array"
  key[index][] = "nested numeric array"
  key[index][index] = "nested associative array"

```

> PHP constants are substituted in, but only when used as the entire value. Comments should start with a semi-colon at the beginning of a line.

I actually know this because the Profiler module uses it to parse out its `.info` file for profile configurations.
> 4 votes

---
Tags: 7, .info
---


# Question
Title: pass parameters drush_make or drush_make_process
I would like to call the following drush make command within drush script:

```
drush make someFile.make --no-core --contrib-destination=sites/all --yes

```

However, the Drush API for drush\_make and drush\_make\_process only takes the directory name of the make file(thats how i uderstand, but may be wrong). So, i tried something like:

```
  drush_set_option('no-core',true);
  drush_set_option('contrib-destination','sites/all');
  $status = drush_make_process('.');
  //$status = drush_make_process('someFile.make');

```

This doesn't work. It appears that the make file is not even processed. Any help i would much appreciate

# Answer
The most stable way to call Drush from a php script is to use `drush_invoke_process`.

For example:

```
$values = drush_invoke_process('@none', 'make', array('someFile.make'), array('no-core' => TRUE, 'contrib-destination' => 'sites/all', 'yes' => TRUE));

```
> 4 votes

---
Tags: drush
---


# Question
Title: where to find the variables that can be changed through drush vset
There are several variables which we can change through drush vset command like changing the file\_temporary\_path, maintenance\_mode, user\_register

I just need to know, how can I know the relevant variable names for which I need to make any changes through drush vset

# Answer
> 7 votes
Variables are saved in the `variables` table in the database. Every module can define its own variables. It is mostly common that the core and contributed modules save their configuration/settings as variables.

It is also mostly common that the modules add a prefix to their variables, so that you can look at the `variables` table in your database and search for the related module if they defined any variables.

Another approach would be looking in the source code of the configuration form for the related field. For example for `file_temporary_path`, you would see:

```
<input type="text" class="form-text" maxlength="255" size="60" value="/tmp"
name="file_temporary_path" id="edit-file-temporary-path">

```

Here is the `name` attribute hints that this configuration field will be saved in `file_temporary_path` variable.

Moreover, if you have Devel module installed, there is a **Variable Editor** under the path `devel/variable`, which lists all the variables defined in your site and gives you the possibility to edit or delete them.

# Answer
> 4 votes
There isn't a list as such, `vset` simply passes through to `variable_set()`, which will accept variables with literally any name.

To get the ones set in your current installation you could run this query:

```
SELECT name FROM variable

```

But bear in mind that variables can also have a default, and so don't necessarily need to be in the variables table to actually exist and be used in the site.

# Answer
> 3 votes
`drush vget` will list the names and values of all variables. If you have Features and Strongarm enabled (and you do, of course, you smart developer you), you can also do `drush fc variable`, which will show you the variable names without values.

But as with Clive's answer, these methods only show you variables which have values saved in the database; if a variable exists for which a value hasn't been saved yet and just the default value in code is being used, there's currently not a smart way for Drupal to know that it exists. D8 fixes this, I believe.

---
Tags: drush
---


title: Limit OG available on registration form

text:
# Question
Title: Limit OG available on registration form
I want to let my user to request membership to an OG through the user registration form (they should select the company you belong too). I found how to

I have two content type set as OG (company and committee). When I enable group audience selection in the registration form all my OG are displayed. I want to display only value related to the company OG.

Is this achievable?

# Answer
> 0 votes
This can be done with https://drupal.org/project/entityreference\_prepopulate.

You should create registrationlinks like this for it to work auto: /user/register?og\_user\_node=X where X is the groupid.

---
Tags: 7, organic-groups, users
---


# Question
Title: My drupal 7 messed up after installing a module and I just get an error, how do I debug it and trace the source of that error?
If I have a module that I installed and its causing a conflict with another module, how do I trace it down to see which is causing the conflict? Let's say the error message doesnt' give any useful information in finding the culprit module. How would one go about find the module causing the issue?

# Answer
Have a look in /var/log/httpd/error\_log.
> 1 votes

# Answer
You can use the debugging methods mentioned in the comments, especially ddebug\_backtrace.

Another, more manual option, is, to disable other enabled modules one by one, until the error goes away. Once you know the culprit, search the issue queue of that module (and the new module) and/or use the debug statement (or drupal\_debug from the devel module) to narrow down the problem.

Some pointers on how to debug: https://drupal.stackexchange.com/questions/545/how-do-i-debug-drupal How do I debug my Feeds import not importing a field

And then of course, you should look at the web-server logs (apache, etc). Another way to debug issues like that, when you get the white screen of death, is, to execute a drush command on the command line - like cc or something like that. Often, the error message gets printed to STDOUT.
> 2 votes

# Answer
My method was to edit the core set\_message() function in the /includes folder and add in PHP's debug\_backtrace() function in there to see the full output of where the module is causing the issue.

This way works for me since I don't have to have xdebug installed or have to go anywhere else. I think its the easiest way to do a backtrace from my point of view.

If there is a better more efficient way do let me know.
> 1 votes

---
Tags: debugging
---


# Question
Title: How to load block on link click with AJAX framework?
I have tried in my custom module:

Declaring a path for Ajax callback

```
function custom_menu() {

  $items['ajax-block/%'] = array(
    'title' => 'Ajax test callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'ajax_link_callback',
    'page arguments' => array(1),
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
  );

  return $items;
}

```

now the callback itself

```
/**
 * Callback ajax
 */
function ajax_link_callback($from_cid, $mode = NULL) {

  if ($mode != 'ajax') {
    drupal_set_message('Turn Javascript');
    drupal_goto(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '<front>');
  }

  $commands[] = ajax_command_html('.region-content', some_func());

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

I have a few manually created links:

```
<a class="use-ajax" href="/ajax-block/1/nojs">link1</a>
<a class="use-ajax" href="/ajax-block/2/nojs">link2</a>
<a class="use-ajax" href="/ajax-block/3/nojs">link3</a>

```

Now I need such functionality - when I press link1 - block1 loads content in to .region-content, when I click link2 - block2 and etc.

How can I do this?

# Answer
> 0 votes
Looks like your missing the ajax\_deliver command

```
$commands[] = ajax_command_html('.region-content', some_func());
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

```

---
Tags: 7, ajax
---


title: comment form custom validation

text:
# Question
Title: comment form custom validation
I am using a custom validation in my Drupal 7 comment form.
I want to match the `comment_body` against a word `"example"` so if someone just type `"example"`in the comment body then it will show a error message that only the word `"example"` is not allowed. After reading drupal api documentation i codded like this:

```
function mango_form_comment_node_news_form_alter(&$form, &$form_state, $form_id){
    $form['comment_body']['#prefix'] = '<div class="sm">Post your comment now!</div>';
    $form['actions']['submit']['#value'] = 'Post Your Comment';
    $form['#validate'][] = 'banana';
}

function banana($form, &$form_state) {
  if ($form_state['comment_body'] == "example") {
    form_set_error('comment_body', 'Your comment can not contain example!');
  }
}

```

Do not working `:'(` what i'm missing? Thanks

# Answer
The values for comment\_body is not stored in $form\_state but in something like:

```
$form_state['values']['comment_body']['und'][0]['value']

function banana($form, &$form_state) {
  if ($form_state['values']['comment_body']['und'][0]['value'] == "example") {
    form_set_error('comment_body', 'Your comment can not contain example!');
  }
}

```
> 0 votes

---
Tags: comments, forms
---


# Question
Title: How to add a "viewed" icon to pages that are visited
I have a Drupal 7 site where I have a bunch of videos and I could use a little help with understanding the best way to show a small icon next to my video links after a visitor has viewed it. Is there a way to do this if they are anonymous visitors? My site does not have user accounts. Also, each of my videos are on a separate page and have a unique url.

I've looked briefly into the Flag Module, but I'm not sure if this work work as I don't want viewers to click on anything. I only to track their browsing.

Any help in the right direction would be much appreciated!

# Answer
> 0 votes
In my opinion using a cookie could be a nice way to accomplish that need. (Maybe even the only way). A quick search came up with the `user_cookie_save` function \>\> https://api.drupal.org/api/drupal/modules!user!user.module/function/user\_cookie\_save/7

Use it to save the cookie with the video URL or another identifier and read that cookie when loading the page and set the viewed flag.

# Answer
> 0 votes
Personally I find the simplest way (for anonymous users) is to use the **:visited** CSS selector.

```
.video a {
  display: inline-block;
  background-image: none;
  background-repeat: no-repeat;
  background-position: right;
  padding-right: 16px;
}
.video a:visited {
  background-image: url(icon.png);
}

```

---
Tags: 7, flags
---


title: How to make user IDs start on 5000?

text:
# Question
Title: How to make user IDs start on 5000?
On our Drupal 7 social network site, we want the user ID (user number) to start from 5000. What is the easiest way to do it?

# Answer
> 2 votes
One could modify the auto increment field of the users table in the database. Similar to https://stackoverflow.com/questions/970597/change-auto-increment-starting-number.

```
ALTER TABLE users AUTO_INCREMENT = 5000;

```

# Answer
> 2 votes
Followin clive's answer, I realized that on Drupal 7, the next user ID is simply the next available free ID (current max + 1) from the users table.

There is no need to change the ID of an existing user to 5000, as this post suggests.

So the following sequance worked:

1. Create a new record on the users table:

`insert into users (uid, name, status, mail)
values (5000, 'tmp',1,'email@example.com');`
2. Register a new user throght the web. The user was added as #5001.
3. Delete the user record:

`delete from users where uid=5000;`

---
Tags: 7, users, database
---


# Question
Title: What are some alternatives to admin_menu module for Drupal 7?
Is there an alternative to the admin\_menu module for drupal 7? I like the fact that it contains all the site links in the dropdowns, but it seems to conflict with some of the modules I have installed and I have run into issues with this module. I'm not sure why its such a heavy module. I guess it has to transverse the entire admin link structure and rebuild it which causes issues.

What are some good admin\_menu alternatives that provide very similar functionality?

# Answer
you may use admin module in combination with coffee
> 0 votes

---
Tags: 7
---


# Question
Title: How can I improve running repeating background tasks?
I ran into an issue recently, where I have a piece of code that accesses content from an external source. The content generation from this source is quite slow (3-5 seconds), but it only needs to be refreshed every 30-60 seconds.

Currently it's a bit of a Russian roulette. Every minute a user will receive a generally slower page load, while the content is refreshed and cached, and then other people will receive the cached version. Naturally, this is a headache for the users and for our apdex score.

I was trying to find a way to refresh the content in a non-obtrusive way, either automatically via scheduled action sets, or in background process when the user load the page, but I've failed with both. Normally it would not be an issue (simple enough using Elysiacron), but on Pantheon I don't think it's possible to manipulate the crontab in the fashion I require it.

Did anyone face a similar issue on Pantheon so far? Is there any solution that would solve my problem within Pantheon? Can something like this be achieved with AJAX?

I have an idea for a workaround, which would involve a third party machine requesting the part of the module that generates and caches content every 30 seconds, but that is a really ugly and inelegant way to do this.

Thanks for any input regarding this!

# Answer
> 1 votes
Instead of updating a global cache of remote objects (which a visitor might see a stall on while data is being fetched ...)

Simply use 2 caches. 1 cache is what visitors see data from from say a Drupal `cache bin`. The second cache bin is another private drupal cache bin updated by your module from the remote host. You could make custom cache tables in Drupal or simply use raw MySQL tables without the Drupal API if you're not familiar with it.

Then on occasion do a database table flip (eg, `truncate cache2; select cache1.* INSERT INTO cache2;`, or sync from 1 Drupal cache bin to the other. This local cache store updating should be faster than the remote server.

---
Tags: caching, cron
---


# Question
Title: Stopping Drupal 7 spammers registering at mysite.com
I have a new Drupal 7 site at **mysite.com** (address changed) - a CentOS 5.5 Linux machine in my full control.

By reading registration mails (they run through my Gmail account) I've noticed, that Drupal spammers seem to refer to my site via the address **forum.mysite.com**. Since any requests to a subdomain.mysite.com are redirected by my hoster to mysite.com, this works for them.

I wonder, if anyone has noticed same pattern (seems to be some common spammer tool behaviour) and what have you done? I'm thinking of using mod\_rewrite to block access to forum.mysite.com, but maybe there is a better way? (Because I'm not sure if that spammer tool will go away if I close access to forum.mysite.com).

I've also thought of maybe changing my httpd.conf somehow:

```
NameVirtualHost 11.22.33.44:80

<VirtualHost 11.22.33.44:80>
    DocumentRoot /var/www/html/mysite.com

    ServerName mysite.com
    ServerAlias mysite.com *.mysite.com

```

I'm not asking about Mollom or Captcha modules, because they seem to be not-up-to-date for Drupal 7 yet. And the spam users aren't a too big problem for my site anyway, because it has a card game embedded at the front page and I have a cron job deleting users not playing that game.

# Answer
> 0 votes
My solution for now is to block access to **forum.mysite.com/user/reset/....** by using mod\_rewrite:

```
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^forum.mysite.com$
    RewriteCond %{REQUEST_URI} ^/user
    RewriteRule .* - [L,F]

```

I will see if it gets better with SPAM-robots in few days...

# Answer
> 9 votes
There is Honeypot as well

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site

Usually, forms take at least a few seconds to fill out when a human is entering data into them—especially surveys, user registration forms, etc. Spam bots try to fill out as many forms as they can in as little time as possible, so they will often fill out a form within a couple seconds at most. The Honeypot module requires at least 5 seconds to pass (by default - you can adjust this too!) before a form can be submitted.

**Alternative modules**

There are many spam-protection modules on drupal.org, some of which have more or less robust methods of dealing with form spam. Some of the most used and recommended include:

* Mollom - Offers spam protection through their premium service.
* CAPTCHA - A simple image-based CAPTCHA builder.
* reCAPTCHA - Implements reCAPTCHA for image-based CAPTCHAs.
* Hidden CAPTCHA - Similar to this module in it's effectiveness.

# Answer
> 3 votes
If there is any kind of form involved, try this:

I have had *great* success by using a fake e-mail field. The field named 'e-mail' was invisible and would never be filled out by users.

The e-mail field that I actually used was named something different, e.g. e-mail2.

Spammers would fill out the field named 'e-mail', which instantly marked them as spammers. Users would never even see that field.

If there are no forms involved or you cannot do this in Drupal, you can ignore this answer. ;)

Good luck!

# Answer
> 3 votes
As far as I can see, the Mollom module is ready for Drupal 7. Based on my Drupal 6 experience with Mollom, I would recommend it.

# Answer
> 2 votes
For the registration process, I would suggest the Spambot module. It will stop bots trying to register by verifying their IP address, email address and username on Stop Forum Spam website.

You can optionally contribute to that service by automatically submitting your website's registration attempts.

No hassle for human users like captchas!

# Answer
> 1 votes
You can also use a Captcha module to stop bot spammers. drupal 7 version is in beta, but does work.

> A CAPTCHA is a challenge-response test most often placed within web forms to determine whether the user is human. The purpose of CAPTCHA is to block form submissions by spambots, which are automated scripts that post spam content everywhere they can. The CAPTCHA module provides this feature to virtually any user facing web form on a Drupal site.

# Answer
> 0 votes
Coming to the party a bit late on this question, but here is a solution that has worked for me.

I have a local community based site. There is no reason for someone in Russia, for example, to ever access my site. Many of my spam posts originate from some other country. Analyzing my google site analytics I can see where those are, and, with geo ip location being solid enough to at least determine to overall country origin of, I can block them having access to any of the site. So far, I have never had anyone in my community tell me they were blocked or had problems with this, and the logs tell the same story.

# Answer
> 0 votes
I would also reccommend the Mollom module; it has helped reduce so much spam on my site, even though it still gets a little bit. Install Mollom Module for Drupal has a easy guide to installing Mollom.

# Answer
> 0 votes
So far my best experience has been adding a few fields to the registration form in combination with rules. I do like the geo IP approach even though we don't have a strictly locally based user base; past logs from a Wordpress hosted site shows that we don't have users from countries that a majority of SPAMMERS come from.

# Answer
> 0 votes
As a default, I include the following modules on Drupal 7 sites to prevent or drastically cut down on bogus accounts from being created, especially in cases where the client has requested new users only require a self-verification of their email (which spambots can sometimes get around):

---
Tags: 7
---


# Question
Title: How to set menu items on mobile as stacked full-width items?
I am using Superfish, and my menu is perfect for normal displays. However, for small smartphone displays, I want my menu items stacked and spanned the width of the display. Also, when an item is clicked with child items, the top level items go away and display the child items.

I can't figure out how to do this from the SF documentation or searching on the web.

# Answer
> 1 votes
@vintorg

Little late to the party here --

In theory, Responsive Menus should be compatible with any theme, granted it doesn't have JS in place trying to do the same thing.

Check out the MeanMenu style w/ Superfish. It creates a clone of the menu object keeping Superfish's js events *out* of the responsive version of menu.

# Answer
> 1 votes
I've only used Responsive menus on one project and it seemed to work fine, outputting the mobile menus when viewed by a device, and the normal menu when viewed by computer with some margin of error but in general it seemed to work well. You can see a demo here: http://drastikbydesign.com/demo/responsive-menus-demo-1-mean-menu and how it shows on a mobile and/or computer.

---
Tags: 7, navigation
---


# Question
Title: How does one override default icons used to dislpay uploaded files from within a module instead of a theme?
I'm attempting to add a custom icon for file uploads via a module. However, all I'm finding online is advice on using a theme function (How to change File field icons (without changing core)?). I want this in a module to make it work across various themes. I found file\_icon\_path, but am not sure how to implement it. How would this be done in a module?

# Answer
> 2 votes
I think you would want to do something along these lines:

```
function YOURMODULE_theme_registry_alter(&$theme_registry) {

  if (!empty($theme_registry['file_icon']['function'])) {
    $theme_registry['file_icon']['function'] = 'YOURMODULE_file_icon';
  }

}

```

and then create `YOURMODULE_file_icon()` based upon the core `theme_file_icon()`:

```
/**
 * Returns HTML for an image with an appropriate icon for the given file.
 *
 * @param $variables
 *   An associative array containing:
 *   - file: A file object for which to make an icon.
 *   - icon_directory: (optional) A path to a directory of icons to be used for
 *     files. Defaults to the value of the "file_icon_directory" variable.
 *
 * @ingroup themeable
 */
function YOURMODULE_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);

  return '<img class="file-icon" alt="" title="' . $mime . '" src="' . $icon_url . '" />';
}

```

and change up either `$icon_directory` to point within your module and include all of the various file type icons there, or do a `switch` or `if` on the `$mime` type and grab them from wherever you want, eg, if it's the special mime type you want, grab them from your module's directory, otherwise, grab them from the core/default directory.

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


# Question
Title: add an additional item to an array in Drupal Settings javascript from php
I've got a hook\_node\_view which I'm trying to add a property of the node to an array that I have created in the Drupal.settings

```
drupal_add_js(array('embedded_videos'=>array()));

```

So in the node\_view I can do

```
function mymod_node_view($node, $view_mode, $langcode) {
if($node->type == 'video'){
   drupal_add_js(array(
    'vimn_video' => array('embedded_videos' => $node->nid,
      ),
    ),
  'setting');
}

```

But this overwrites what is in there, whereas I want to add to the array. Because this node\_view is running multiple times as I have 2 video nodes embedded into an article node.

Any ideas appreciated. I am new to the usage of Drupal.settings javascript api.

edit: The issue was that I needed to put $node-\>nid into an array array($node-\>nid), then it will add an item to the array rather than overwriting it.

# Answer
> 4 votes
Your first declaration should indicate that you are passing a setting to drupal\_add\_js():

```
drupal_add_js(array('your_module' => array()), 'setting');

```

Then you can add other properties to your array in hook\_node\_view():

```
function your_module_node_view($node, $view_mode, $langcode) {
    $your_array = array(
      'vimn_video' => array(
        'embedded_videos' => array($node->nid), // NOTE: $node->nid as an array
      ),
    );
    drupal_add_js(array('your_module' => $your_array), 'setting');
}

```

You can retrieve the properties from javascript as:

```
Drupal.settings.your_module.vimn_video.embedded_videos; // an array with node ids.

```

# Answer
> 2 votes
I believe that you use **hook\_js\_alter** (and possibly drupal\_js\_defaults) https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_js\_alter/7

Something like (untested of course):

```
function mymodule_js_alter(&$javascript) {
  if ( true ) {
    $javascript['settings']['vimn_video']['embedded_videos'] = $node->nid;
  }
}

```

---
Tags: javascript
---


# Question
Title: How do I print a menu with links generated by my custom module?
If I use

```
theme('links', array('links' => menu_navigation_links('main-menu'),
'attributes' => array('class'=> array('links', 'main-menu')) ));

```

It will print the links in my Main Menu. I need to print the links that are created by my custom module, but I do not know what the system menu name is.

For instance:

```
 //hook_menu
 function custom_menu() {

     //admin page
     $items['admin/custom'] = array(
     'title' => t('Custom Admin Page'),
     'description' => t('Manage Custom Module'),
     'page callback' => 'custom_admin_page',
     'access arguments' => array('access toolbar'),
     'type' => MENU_NORMAL_ITEM,
     );

     //add event
     $items['admin/custom/add'] = array(
     'title' => t('Add Custom'),
     'decription' => t('Add custom'),
     'page callback' => 'custom_add',
     'access arguments' => array('add custom'),
     'type' => MENU_NORMAL_ITEM,
     'file' => 'custom_add.inc',
     'file path' => drupal_get_path('module', 'custom') . '/includes',
     );

```

The page 'admin/custom' automatically goes into my administration menu, and the page 'admin/custom/add' is seen under the admin/custom link when viewing all of the links in the administration menu, but I want to print that menu (admin/custom) on the 'admin/custom' page so that I can see the link 'admin/custom/add'.

# Answer
> 1 votes
Menus and paths are slightly different things...in `hook_menu()` you're defining paths that can be consumed; menus create the links to those paths - the two concepts aren't necessarily related (a path can exist without a menu link).

You can assign a particular router path to a menu using the `menu_name` property in your `hook_menu()` items, but that menu needs to exist already.

Fortunately Drupal provides a method for adding links to the top of a page through `hook_menu()`, and you only need to change one line:

```
$items['admin/custom/add'] = array(
  'title' => t('Add Custom'),
  'decription' => t('Add custom'),
  'page callback' => 'custom_add',
  'access arguments' => array('add custom'),
  'type' => MENU_LOCAL_ACTION, // <-- This one changed
  'file' => 'custom_add.inc',
  'file path' => drupal_get_path('module', 'custom') . '/includes',
);

```

That will put a link to 'Add Custom' at the top of the 'admin/custom' page; if you're using the Seven theme for administration it'll look like the 'Add Content' link on the content admin page:

# Answer
> -1 votes
You should see hook\_menu path added to navigation menu not showing up.

You need to change the following line of code.

```
'type' => MENU_NORMAL_ITEM,

```

---
Tags: 7, routes
---


# Question
Title: How do I preprocess_html() a panelized page?
My intentions is to take a panelized page and use fields provided in that page to create class names on the body element.

When I preprocess the page, I don't get the original node information and can't pull the information I need.

My panelized page has 1 pane that has the node-\> content pane in there.

If I could just get the NID of the current page, then it would be okay. But that doesn't even show up in the variables in the theme\_preprocess\_html() when a page has been panelized.

# Answer
Solution was to use menu\_get\_object(). Here is a nice article outline usages of it as well.

```
$node = menu_get_object('node');

```

Thanks you David for the answer.
> 4 votes

# Answer
If the nid is in the URL, you can use the arg function to get it.
> 0 votes

---
Tags: theming, panels
---


# Question
Title: Drupal 7:: create a page with views to show all the contents not authored by current user
I am creating two page with views module. First page will show all the contents authored by current user. Second page will show all the contents that current user can view but not created by him.

I am trying it with contextual filter but no luck yet.

# Answer
For your first problem, Create a content view with a relation **Content: Author**, than you will get **User: Current** in side the add filter, Add this filter to your view

Use **No** for Second problem.
> 0 votes

---
Tags: 7, views
---


title: How to "unhook" a hook from a module?

text:
# Question
Title: How to "unhook" a hook from a module?
I want to use the `email_auto_login` module. However it implements a `hook_mail_alter` which I don't want.

```
/**
 * Implements hook_mail_alter().
 */
function email_auto_login_mail_alter(&$message) {
  $user = user_load_by_mail($message['to']);

  // Don't add tokens for admin, anonymous or blocked.
  if (!isset($user->uid) || $user->uid == 1 || $user->status == 0) {
    return;
  }

  $token = _email_auto_login_generate_token($user);

  foreach ($message['body'] as &$body) {
    $body = _email_auto_login_add_token($body, $token);
  }
}

```

Is there a way to remove the hook without modifying the above code? I'm running Drupal7.

# Answer
You should be able to do it with `hook_module_implements_alter(&$implementations, $hook)` in your module. Simply test `$hook` and if it is the hook you don't want implemented, `unset($implementations['email_auto_login'])`.
> 3 votes

---
Tags: 7, hooks
---


title: db_update Query Issue

text:
# Question
Title: db_update Query Issue
I am using ubercart guest checkout module. I am able to submit the order as guest etc works fine.

After Reviewing the order and submitting it throws me this error

```
Recoverable fatal error: Argument 2 passed to db_query() must be an array,
string given, called in
/var/www/html/dev.demo.net/sites/all/modules/ubercart_guest_checkout/uc_guest_checkout.module
on line 263 and defined in db_query() (line 2342 of
/var/www/html/dev.demo.net/includes/database/database.inc).

```

This is the query which is causing that issue

```
db_query('UPDATE {users} SET name = "%s", mail = "%s" WHERE uid = %d', $name, $mail, $account->uid);

```

I tried to change this query like this

```
db_update('users')
->fields(array(
    'name' => $name,
    'mail' => $mail
))
->condition('uid',$account->uid,'=')
->execute();

```

still no luck, it throws me same above specified error.

How can i resolve the query of above one in order to avoid the error. Any suggestions w.r.t query will be nice.Thanks in advance.

# Answer
Drupal 7 doesn't use %placeholder style query placeholders. Furthermore, there's an error passing a list of strings to `db_query` instead of an array.

Your query would be

```
db_query('UPDATE {users} SET name = :name, mail = :mail WHERE uid = :uid',
           array(':name' => $name, ':mail' => $mail, ':uid' => $account->uid));

```

However, you should probably use `db_update` for update queries, in which case it would indeed be:

```
db_update('users')
->fields(array(
    'name' => $name,
    'mail' => $mail
))
->condition('uid', $account->uid)
->execute();

```

You error is occurring because the initial `db_query` accepts an array of parameters in D7.

More info: https://api.drupal.org/api/drupal/includes%21database%21database.inc/group/database/7
> 7 votes

# Answer
uid is an unique value so u cant update the existing value. If u want to update user details then modify the query as follows,

```
db_update('users')
    ->fields(array(
        'name' => $name,
        'mail' => $mail
    ))
    ->condition('uid',$account->uid,'=')
    ->execute();

```

Note : **You should add the uid in the condition as mentioned above**
> 1 votes

---
Tags: 7, ubercart, database
---


# Question
Title: Why is Drupal prepending 'node' to the link URL?
I am working on a Drupal site. My issue is that when a link is created either by using the `url()` or the `base_path` variable, it works OK on local development environment. But when the very same code is put on the server, the URL prepends `node` string in the path .

E.g. the path is `<drupal site>/latestnews`. The generated path is `<drupal site>/node/latestnode` and when clicked, it shows the `page not found` error. However I would like to mention that the links work fine (i.e generate correct path) when clicked from the home page.

Any help would be appreciated. If it can help, am using Pantheon hosting for testing.

**UPDATE**

menu link generation code is as under. (the code can show my proficiency in drupal :) )

```
function GetMainMenuItems()
{
    $menu = menu_tree("main-menu");

    $keys = array_keys($menu);

    $count = count($keys);

    unset($keys[$count-1]);
    unset($keys[$count-2]);

    $items = array();

    foreach ($keys as $key) {
        $temp = array(
            'title' => $menu[$key]["#title"],
            'url' =>   url($menu[$key]["#title"])
        );
        $items[] = $temp;
    }
    return $items;
}

```

# Answer
> 1 votes
the issue (for the current scenario) turned out to be hardcoded link in the page.tpl.php file. the front page was working ok as it had its own custom template but other pages were using the page.tpl template for rendering the links.

seems that sometimes small issues goes undetected. :) . just leaving this answer so that someone else may also look into such a possibility in their case.

---
Tags: uri
---


# Question
Title: Is there any performance implications in calling a view programmatically and set necessary filters?
I have a view that list some items depending on the current node loaded. I also want to add few exposed filters to the view. The exposed filters cannot be shown to users directly. I want to provide a separate set of filters (to display) for users and based on what user selected, I want to set one or more filters of the view.

For example: I want an option for user to show only nodes that are not older than 7 days, 14 days etc so I will provide a list with All, 7 days, 14 days etc and when user select any of these, I want to set the exposed filter for node created time and with the calculated value - the date 7 days or 14 days or so from now.

There are several filters like this - ie based on what the user selected, we need to apply different filters in view.

To implement this, I plan to implement a block, in which I can programmatically call a view

```
$my_view_name = 'the_view';
$my_display_name = 'block';
$my_view = views_get_view($my_view_name);
$my_view->set_display($my_display_name);

if ($option == FIRST_OPTION) {
  $my_view->exposed_input['filter1'] = $option1_calculated_value1;
  $my_view->exposed_input['filter2'] = $option1_calculated_value2;
}
else {
  $my_view->exposed_input['filter1'] = $option2_calculated_value1;
  $my_view->exposed_input['filter2'] = $option2_calculated_value2;
  $my_view->exposed_input['filter3'] = $option2_calculated_value3;
}

$my_view->execute();
unset($my_view->exposed_widgets);
return $my_view->preview();

```

Is there any problem in using this method? Is there any other way to do this? Is there any performance implications in using this method? Will views caching etc work in this case? I use Drupal 7 and Views 7.x-3.7

# Answer
> 1 votes
Definitely not an issue unless you overload the view (but you can do that with the UI also - so no difference there).

On our production architecture we have views UI disabled and all the views are in code under version control however we also have a content team that needs to build 'lightweight views' that pull data from a product catalog and displays it in a particular way. Unfortunately we don't want them running direct SQL or using views UI as they don't completely understand what it all means so we just programmatically create these views and expose a UI to them that they understand. Things like:

* What design they want on it
* How they want the sorting of the dataset
* Whether they need 'no results' text
* etc.

Some caveats to doing more complex versions of this are:

* Looking out for timing issues. I.e. not having an option available at that call point
* Ensuring the correct structure is used. Example: `$view->use_ajax` vs `$view->display[$dispay_id]->filters['use_ajax']`.

Neither the less, it is all definitely possible and scales without issues.

---
Tags: 7, views, performance
---


# Question
Title: Drupal 7 - Autoslave Master/Slave Failover Issue
I am using Autoslave (https://drupal.org/project/autoslave) project for implementing mysql high performance and failover. I have successfully setup the mysql master/slave replication at the server and it is working perfectly. With the following settings taken from Autoslave documentation (https://drupal.org/node/1952990) for Master/Slave, I am trying to implement the following use cases:

1. If Master is up and slave is down, master should entertain all the traffic (working fine)
2. If Master is down and slave is up, slave should entertain all traffic in readonly mode (NOT WORKING).

With 2, what happens is as soon as the master db is down, the requests to slave also stops. The following are the contents of autoslave-invalidation-default.inc file after i take master db down:

```
<?php
$databases["default"]["slave"][0]["status"] = FALSE;
$databases["default"]["master"][0]["status"] = FALSE;

```

Its showing that both servers are down, where as slave is up and running. I tried with manually changing this file and changing slave status to TRUE, and the traffic is then successfully routed to slave.

Following are the relative contents of my settings.php file:

```
$databases['default']['master'] = array (
  'database' => 'dbname',
  'username' => 'username',
  'password' => 'password',
  'host' => 'master.ip',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
);

$databases['default']['slave'][] = array (
  'database' => 'database',
  'username' => 'username',
  'password' => 'password',
  'host' => 'slave.ip',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
  'readonly' => TRUE
);

$databases['default']['default'] = array (
  'driver' => 'autoslave',
  'master' => array('master', 'slave'),
  'slave' => array('slave', 'master'),
  'invalidation path' => 'sites/default/files',
  'flag all tables' => TRUE
);

```

Following is the error shown:

```
Error
The website encountered an unexpected error. Please try again later.

Error message

The system is currently in read-only mode. Any changes you make will not be saved!
Warning: mt_rand(): max(0) is smaller than min(1) in DatabaseConnection_autoslave->rand_weighted() (line 1233 of /includes/database/autoslave/database.inc).
Warning: mt_rand(): max(0) is smaller than min(1) in DatabaseConnection_autoslave->rand_weighted() (line 1233 of /includes/database/autoslave/database.inc).
Exception: No master connection has been chosen in DatabaseConnection_autoslave->determineMasterTarget() (line 703 of /includes/database/autoslave/database.inc).

```

Kindly guide me of the any solutions/suggestions and/or possible reasons why is point 2 not working, where it's suppose to.

Thanks.

# Answer
For read-only mode to work properly you must apply the patch from https://drupal.org/node/1889328 (currently committed to 8.x but not backported yet).

The patch https://drupal.org/files/1889328-1-query-options\_1.patch will work for 7.x, though it has not yet been cleaned up according to review comments.

I'm not sure I've mentioned this in the documentation, but you must ensure that you use a read-only user for the slave connection when utilising the read-only functionality. Otherwise you may end up writing to the slave-db which could cause inconsistencies and consequently the replication to fail.

The mt\_rand() is possibly due to the result of no connections being available (both servers have status = FALSE in the invalidation file). Servers are only re-validated during cron. If you take down the slave to test that scenario, and then spin up the slave again and take down the master without running cron in between, you may end up with the kind of invalidation file you posted.
> 2 votes

# Answer
Personally, I wouldn't be using a Drupal module to engage this purely because this should be offloaded into a system process away from your application.

If possible, try to setup MySQL replication instead and have that sitting within a failover safe architecture. You and your application's users will thank you. :)
> 1 votes

---
Tags: database
---


title: Multi-site bulk module activation

text:
# Question
Title: Multi-site bulk module activation
For a Drupal multi-site installation, is there any method to activate a module for all sites on the system at once instead of logging into the admin for each site individually?

# Answer
I got an answer for this in the Drupal Community on Google+: Use `drush @sites en your_module -y`.
> 1 votes

# Answer
I wrote something to solve this a while back that iterates over every sub directory in the `sites` directory and performs the requested task - https://github.com/jacobbednarz/drupal-utils
> 0 votes

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


# Question
Title: Watchdog table inserts taking too much of time
On my localhost on Windows 7 sometimes a page load(after all cache clear/cron run) takes even 2 minutes. I've already enabled devel query log generated at the bottom of site showing query performance.

For a sample page total is 35 seconds, and following data is from this same page.

I've seperated queries taking more than 10ms in a separate file which totalled 25 seconds.

This is the first line of the query log:

> Executed 5881 queries in 27114.36 ms. Queries exceeding 10 ms are highlighted. Page execution time was 34811.37 ms. Memory used at: devel\_boot()=1.98 MB, devel\_shutdown()=75.65 MB, PHP peak=77.25 MB.

From all the queries the highest time taking( 1471.69 ms) query is this one:

> 1471.69 1 DrupalDatabaseCache::getMultiple P A E SELECT cid, data, created, expire, serialized FROM cache\_field WHERE cid IN (:cids\_0, :cids\_1, :cids\_2, :cids\_3, :cids\_4, :cids\_5, :cids\_6, :cids\_7, :cids\_8, :cids\_9, :cids\_10, :cids\_11, :cids\_12, :cids\_13, :cids\_14, :cids\_15, :cids\_16, :cids\_17, :cids\_18, :cids\_19, :cids\_20, :cids\_21, :cids\_22, :cids\_23, :cids\_24, :cids\_25, :cids\_26, :cids\_27, :cids\_28, :cids\_29, :cids\_30, :cids\_31, :cids\_32, :cids\_33, :cids\_34, :cids\_35, :cids\_36, :cids\_37, :cids\_38, :cids\_39, :cids\_40, :cids\_41, :cids\_42, :cids\_43, :cids\_44, :cids\_45, :cids\_46, :cids\_47, :cids\_48, :cids\_49, :cids\_50, :cids\_51, :cids\_52, :cids\_53, :cids\_54, :cids\_55, :cids\_56, :cids\_57, :cids\_58, :cids\_59, :cids\_60, :cids\_61, :cids\_62, :cids\_63, :cids\_64, :cids\_65, :cids\_66, :cids\_67, :cids\_68, :cids\_69, :cids\_70, :cids\_71, :cids\_72, :cids\_73, :cids\_74, :cids\_75, :cids\_76, :cids\_77, :cids\_78, :cids\_79, :cids\_80, :cids\_81, :cids\_82, :cids\_83, :cids\_84, :cids\_85, :cids\_86, :cids\_87, :cids\_88, :cids\_89, :cids\_90, :cids\_91, :cids\_92, :cids\_93, :cids\_94, :cids\_95, :cids\_96, :cids\_97, :cids\_98, :cids\_99, :cids\_100, :cids\_101, :cids\_102, :cids\_103, :cids\_104, :cids\_105, :cids\_106, :cids\_107, :cids\_108, :cids\_109, :cids\_110, :cids\_111, :cids\_112, :cids\_113, :cids\_114, :cids\_115, :cids\_116, :cids\_117, :cids\_118, :cids\_119, :cids\_120, :cids\_121, :cids\_122, :cids\_123, :cids\_124, :cids\_125, :cids\_126, :cids\_127, :cids\_128, :cids\_129, :cids\_130, :cids\_131, :cids\_132, :cids\_133, :cids\_134, :cids\_135, :cids\_136, :cids\_137, :cids\_138, :cids\_139, :cids\_140, :cids\_141, :cids\_142, :cids\_143, :cids\_144, :cids\_145, :cids\_146, :cids\_147, :cids\_148, :cids\_149, :cids\_150, :cids\_151, :cids\_152, :cids\_153, :cids\_154, :cids\_155, :cids\_156, :cids\_157, :cids\_158, :cids\_159, :cids\_160, :cids\_161, :cids\_162, :cids\_163, :cids\_164, :cids\_165, :cids\_166, :cids\_167, :cids\_168, :cids\_169, :cids\_170, :cids\_171, :cids\_172, :cids\_173, :cids\_174, :cids\_175, :cids\_176, :cids\_177, :cids\_178, :cids\_179, :cids\_180, :cids\_181, :cids\_182, :cids\_183, :cids\_184, :cids\_185, :cids\_186, :cids\_187, :cids\_188, :cids\_189, :cids\_190, :cids\_191, :cids\_192, :cids\_193, :cids\_194, :cids\_195, :cids\_196, :cids\_197, :cids\_198, :cids\_199, :cids\_200, :cids\_201, :cids\_202, :cids\_203, :cids\_204, :cids\_205, :cids\_206, :cids\_207, :cids\_208, :cids\_209, :cids\_210, :cids\_211, :cids\_212, :cids\_213, :cids\_214, :cids\_215, :cids\_216, :cids\_217, :cids\_218, :cids\_219, :cids\_220, :cids\_221, :cids\_222, :cids\_223, :cids\_224, :cids\_225, :cids\_226, :cids\_227, :cids\_228, :cids\_229, :cids\_230, :cids\_231, :cids\_232, :cids\_233, :cids\_234, :cids\_235, :cids\_236, :cids\_237, :cids\_238)

The second list of time hogging queries are from watchdog table insert queries. The watchdog table I've is of 1.2 MB site with mysql tables installed as default(Innodb). I totalled one continuous series of (135) watchdog insert queries all taking more than 10 ms totalling 9000 ms( 25% of total time). Here is the sample query:

> 104.91 272 dblog\_watchdog P A 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)

So I'm looking for ways to reduce this watchdog insert time .. Couldn't find anything in Google. Any ideas?

# Answer
Sorry I forgot to tell. This mysql optimization almost solved my problem. The rest with enabling Views caching, using mod\_deflate in Apache and using APC etc.
> 0 votes

# Answer
Even though database logging is huge overhead to have on any web server, the logging is still a very important part of development so instead of using `dblog`, try using `syslog` instead. It is cheaper in terms of performance overheads and you can use a third party tool like papertrail to slap a web based UI on it for easy searching and diagnosis.
> 0 votes

---
Tags: 7, performance, log-messages
---


# Question
Title: Generate Rate widget for specific user based on UID
Basically, I'm going to be displaying a list of users who have voted on a node, but then show in a modal what their rating was. Now I can use the voting api to get what they voted, but I can't generate a display only widget for what they voted based on the user ID.

Any ideas? This is the function from the Rate module.

```
/**
 * Generate a widget.
 *
 * @param int $widget_id Widget id
 * @param string $content_type "node" or "comment"
 * @param int $content_id Node id (nid) or comment id (cid)
 * @param bool $teaser
 * @param bool $include_div
 * @return array
 */
function rate_generate_widget($widget_id, $content_type, $content_id, $mode = RATE_FULL, $include_div = TRUE, $just_voted = FALSE, $displayed = NULL) {}

```

# Answer
What i understand that you want to display that Current logged in user Content ratings. for that you can use the **(Votes) Votes: Current user (True)** for filter and if you want to display all the voted content User-wise than you can Make a relation with **(Votes) Votes: User** and remove the **(Votes) Votes: Current user (True)** as the following image.
> 0 votes

---
Tags: users, rating
---


# Question
Title: How to avoid the error 'array expected string given' in db_query
I am getting this error: Argument 2 passed to db\_query() must be an array, string given. In **db\_query** in below function.

```
function uc_guest_checkout_uc_checkout_complete($order, $account) {
  if (!empty($_SESSION['uc_guest_checkout'])  && !user_is_logged_in()) {
    switch ($order->data['complete_sale']) {
      case 'new_user':
        // For guest checkout, we replace the ubercart generated username and email
        // for a new user with one that is more anonymous.
        $name = uniqid('anon-', TRUE);
        $mail = $name . '.' . uc_store_email();
        db_query('UPDATE {users} SET name = "%s", mail = "%s" WHERE uid = %d', $name, $mail, $account->uid);
   break;
  case 'logged_in':
    // If the order is marked logged in but anonymous, this means that
    // we must have set the uid to the default account, but still treat
    // this as a new user.
    $order->data['complete_sale'] = 'new_user';
    break;
    }
  }
  _uc_guest_checkout_end();
}

```

I tried this queries but none were creating account with valid names and emails as per db\_query which is throwing error but successfully creating user accounts.where as these below queries creating names with random names.

```
db_update('users')
        ->fields(array(
            'name' => $name,
            'mail' => $mail
        ))
        ->condition('uid', $account->uid)
        ->execute();

db_query('UPDATE {users} SET name = :name, mail = :mail WHERE uid = :uid',
                array(':name' => $name, ':mail' => $mail, ':uid' => $account->uid));

```

How do I resolve this?

# Answer
> 2 votes
You're using Drupal 6 syntax, you need to convert it to Drupal 7 syntax:

```
db_update('users')
  ->fields(array('name' => $name, 'mail' => $mail))
  ->condition('uid', $account->uid)
  ->execute();

```

See the Database API docs for more details.

---
Tags: 7, users, database
---


# Question
Title: What code should .htaccess of files directory hold in drupal 7.25?
The module Security Review gives the report my `.htaccess` in files directory is a security risk because says it has insufficient code to protect the site from anyone wanting to make php edits. However, have checked it with drupal org docs and I can see the .htaccess in files directory matches up with correct security script to keep out any such attempts.

Anyway I am trying to ascertain correct code input for .htaccess in the files directory. I remember there was a bug with this so maybe the security module is picking it up, I don't know.

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
# Override the handler again if we're run later in the evaluation list.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
php_flag engine off
</IfModule>

```

# Answer
> 5 votes
The `.htaccess` you show is correct - it is actually the default `.htaccess` that Drupal versions above 7.24 (including the current 7.28) will generate for the files directory if the `.htaccess` file is missing.

In other words, the warning you get from Security Review is a false postive. There is no malicious alteration.

Your issue is a known bug with Security Review that has already been raised in the module's issue queue at Drupal.org. There is a also a patch that is supposed to fix this issue in the module's issue queue.

You may help the community by applying and reviewing this patch.

---
Tags: security
---


# Question
Title: Do third party drupal modules pose a security risk?
This may very well be a stupid question but there is no avoiding it now. Unfortunately myself and many others succumbed to the temptation of skipping learning ubercart in lieu of obtaining a seemingly quick and easy 3rd party module for commerce.

Today drupal alerted me to an update for this 3rd party module but deleting it is not picked up by the refreshed module list, it simply vanishes and then when you try installing new version it remains stuck in checked position so that no new version can be installed and no uninstall can ever take place.

Of course the creator of this module has disappeared off the planet leaving myself and many others with less money in our pockets and red faced and some very angry with no support.

All of us say it is the first paid drupal module we've ever acquired because it did seem such a very good idea and easy to implement and the young man who made it was extremely helpful and professional at first.

It is still working on my site albeit unable to be updated but strange companies like soso.com in China have infiltrated this creator's site and are being listed in user's list of domains including mine so is this not a most terrible security risk for anyone using it with rest of the well maintained open source drupal?

update: the owner of these modules has actually returned and is back to usual professional good self. :) all's well that ends well.

# Answer
> 2 votes
Well, have you deleted that module without disabling & uninstalling it first? Some of your effects seems to be that way. Anyway, automatically updating a module from 3rd-party server is only as secure as his server. If you did it, and source server was compromised, you should consider yours compromised, too. Only safe way? Revert from backups to the last snapshot you are reasonably sure to be safe, and then do not update that module (possibly uninstalling it as soon as feasible).

# Answer
> 2 votes
> Do third party drupal modules pose a security risk?

Well if you use them, then yes, of course. You're inviting unknown code in to your codebase.

If you haven't sought contractual guarantees from the author of the module as to its fit-for-purpose and security, then it's **your** responsibility to perform the necessary security reviews, and declare it ready or not for a production site.

Broadly speaking, any piece of code, whether it be custom, contrib or from core itself, potentially introduces risk to your application. The difference with contrib/core code is that you can make some assumptions as to the level of security testing that has taken place, and perhaps view those as less of a risk because of that testing.

But there have been plenty of security holes found in core and contrib modules (some pretty major ones) in the last couple of years, so you need to be on the ball with your own security testing and standards.

None of this is really specific to Drupal by the way; auditing foreign code in any project, in any language/framework, is an absolute must.

---
Tags: security
---


title: How to translate Boolean field labels?

text:
# Question
Title: How to translate Boolean field labels?
I have created Boolean fields. I have set values 0/1 in database and No/Yes as labels to display in UI. But I cannot translate these labels. I have translated strings "Yes" and "No" using UI on link admin/config/regional/translate/translate but it does not work for field labels.

Can anybody help?

thanks Tomas

# Answer
I'm relatively new to Drupal but I've had the same problem recently and this is how I solved it:

* install the i18n module and enable the **"field translation"** sub-module (and its dependencies).
* in the boolean field settings (`admin/structure/types/manage/[your-content-type]/fields` and click the edit link next to the field) make sure you have specified a value for the **On** and **Off** states (e.g. Yes/No).
* then on the same page (boolean field settings), use the **translate** tab (on top of the page) and click "translate" for each language you need:
* under the **Field instance** tab, you can translate the label for the field.
* under the **Field settings** tab, you can translate the values for the On/Off states.
* lastly (and this is perhaps the less obvious step), go to **manage display** (for your content type), and as **"format"** for you boolean field, choose **"Default translated"** instead of "Default".

Hope this helps.
> 4 votes

# Answer
Try in field management Allowed values PHP code

```
return array(
  0 => t('No'),
  1 => t('Yes'),
);

```
> 0 votes

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


# Question
Title: Ajax button strange behaviour when clicked twice
I have a form where there is a dropdown with names, a button to add the names to a table and a table showing the list of names.

When clicking the button, an AJAX request is fired, the selection is added to a database table, the html table is reloaded and updated.

Everything works fine for the first click. The assigned ajax callback routine is called.

When I like to add the second name, the ajax callback is NOT called, but the standard submit function is called instead.

Here is some sample code - first the elements for the form:

```
$form['auctionpersons']['add_person'] = array(
  '#type' => 'select',
  '#title' => t('Select person to add'),
  '#options' => $aPersons,
);
$form['auctionpersons']['add_person_btn'] = array(
  '#type' => 'button',
  '#value' => 'Add person',
  '#description' => 'Click button to add person',
  '#ajax' => array(
      'callback' => 'add_auction_person_ajax_callback',
      'effect' => 'fade',
  ),
);
...
$form['auctionpersons']['ptable'] = array(
  '#theme' => 'table',
  '#header' => $pheader,
  '#rows' => isset($aPersonsTable)?$aPersonsTable:null,
  '#disabled' => TRUE,
  '#title' => 'Users currently assigned',
  '#empty' => t('No users assigned yet!'),
  '#prefix' => '<div id="ptable_wrapper">',
  '#suffix' => '</div>',
);

```

Now the function for the ajax callback:

```
function add_auction_person_ajax_callback($form, &$form_state) {
  dpm('172: add_auction_person_ajax_callback');
  dpm($form_state);
  add_person_to_table($form_state['values']['add_person']);
  $aPersonsTable=get_person_table_rows();
  $form['auctionpersons']['ptable']['#rows']=$aPersonsTable;
  $commands = array();
  $commands[] = ajax_command_html('#ptable_wrapper', render($form['auctionpersons']['ptable']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

Can anyone see the problem?

# Answer
Problem solved! The button must be of type "submit" instead of "button"! So the correct code is:

```
$form['auctionpersons']['add_person_btn'] = array(
  '#type' => 'submit',
  '#value' => 'Add person',
  '#description' => 'Click button to add person',
  '#ajax' => array(
      'callback' => 'add_auction_person_ajax_callback',
      'effect' => 'fade',
  ),
);

```

Thx for viewing this question :-)
> 0 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: Why ajax form submit stop working after set form submit #id?
My question is related to https://drupal.stackexchange.com/questions/98501/why-ajax-form-doesnt-work-after-paging-by-views-infinite-scroll

I try to do workaround by setting my own submit button id.

```
   $form['mymodule_submit'] = array(
      '#type' => 'submit',
      '#value' => $value,
      '#ajax' => array(
        'callback' => 'mymodule_like_form_ajax',
      ),
      '#attributes' => array(
        'class' => array($class),
        'id' => 'mymodule-like-form-' . $node->nid),
      )
   );

```

But in this case ajax submit doesn't work at all... What am I doing wrong here?

# Answer
> 1 votes
JS recognizes things by ID. But Drupal's AJAX only knows Drupal-generated ID. That's why when you change ID manually, it tries to attach click listeners to DOM nodes with IDs that are not there.

If you change ID to some custom value, you must also provide custom JS to attach all `.on` to the objects with new ID.

---
Tags: 7, forms, ajax
---


title: Drush restore to proper folder level

text:
# Question
Title: Drush restore to proper folder level
Before working on a site, I take a quick dump of a site via `drush arb --destination=/var/backup/latest.tgz --overwrite` from the root level `/var/www/html`.

However, on the rare occasion that I need to restore via `drush arr ../backup/latest.rgz --overwrite`, I end up with a restored database but the file structure is written to `/var/www/html/html`.

Would `drush arr ../backup/latest.rgz --overwrite --destination=/var/www/` solve this issue? Do I just continue to muddle through with`mv /var/www/html/html* /var/www/html`?

How can I get drush to write to the actual root level for the default drupal site?

# Answer
> 0 votes
the --destination flag surely works to say where. I'm not quite sure if the outcome would be a mix of the former and the latter system though. Probably the writing does not delete the old files. It would be safer to delete them manually prior to archive recover.

---
Tags: drush, backups
---


# Question
Title: Could not determine database connection parameters. Pass --db-url option when site-install
i am writing drush script to install drupal site

```
 $build_make_file = ($build_src = drush_get_option('build-src', FALSE)) ? $build_src : '../builds/build-drupal-core.make ';
    $dest .= ($build_dest = drush_get_option('build-dest', FALSE)) ? $build_dest : 'test';
    $options = array();
    $options['debug'] = drush_get_option('debug', FALSE);
    $options['no-core'] = drush_get_option('no-core', FALSE);
    ($contr_dest = drush_get_option('contrib-destination', FALSE)) ? $options['contrib-destination'] = $contr_dest : '' ;
    $status = drush_invoke_process('@none', 'make', array($build_make_file, $dest), $options);
    drush_print('Site Download '.(($status) ? "SUCCESS" : "FAILURE" ));

    // go to install directory before we do anything else
    drush_op('chdir', $dest);

    $dbHost="localhost";
    $dbName="drupal_test_db";
    $dbUser="test_user";
    $dbPassword="xxxxxx";
    $dbPort ="3306";
    $status = drush_invoke_process('@self',
                                   'si',
                                   array(
                                          'db-url' => 'mysql://'.$dbUser.':'.$dbPassword.'@'.$dbHost.':' . $dbPort . '/'.$dbName,
                                          'account-pass' => $AdminPassword,
                                      )
                                  );
    drush_print('Site Install - ' . (($status) ? 'SUCCESS' : 'FAILURE'));

```

The site download part works where it downloads the make file. The second part running 'site-install' returns an error:

```
Could not determine database connection parameters. Pass --db-url option

```

How to call 'site-install' command from the drush script correctly? I would appreciate much of your help. Thank you

# Answer
It appears, i passed one too few parameters to 'drush\_invoke\_process'. The documentation shows:

```
function drush_invoke_process($site_alias_record, $command_name, $commandline_args = array(), $commandline_options = array(),....)

```

In my case, I was not passing in the 'commandline\_args' making the 'commandline\_options' become 'commandline\_args' instead of options including 'db-url'

Here, is the correct one:

```
$status = drush_invoke_process('@self', 'si', array('standard'), array(
                                                        'db-url' => 'mysql://'.$dbUser.':'.$dbPassword.'@'.$dbHost.':' . $dbPort . '/'.$dbName,
                                                        'account-pass' => $AdminPassword,
                                                   )
                              );

```

I hope this helps anyone
> 1 votes

---
Tags: drush
---


# Question
Title: Default Theme disabled after Drupal Core Update
I have a strange problem on all my websites when I did an upgrade from drupal 7.22 to drupal 7.24: After the update my default theme ("atlas") has been disabled. My websites have been installed with the profile "atlas" based on drupal 7.22.

Does anybody have an idea why this happens? Is it safe just to enable the theme again? Does anybody have hints how I can investigate this problem?

thanks

# Answer
> 1 votes
Drupal doesn't support having the same name for modules/themes/profiles it requires them to all be separately name-spaced see https://drupal.org/node/371375 for more background.

You should rename your theme to something different and update all the themes hooks.

# Answer
> 0 votes
# Potential source of the problem and solution

As a developer I asked pointed out, the problem could be that I upgraded drupal core but in my installed version my initial profile "atlas" was still marked as active. He recommended

a) to set in the system table status=1 for the "standard" install profile

b) in the variable table change the install\_profile to "standard".

This is also described here: http://flipbit.ca/2012/05/drupal7-fix-install-profile-name/#20120518solution

I tested this and it worked. An upgrade after changing these two parameters did not disable the theme.

So, this worked for me. I am not programmer and can therefore not judge whether this is the final bug fix or only a fix by coincidence. Reading the many discussions about installation profiles and how they are designed in drupal leaves some open questions.... One user also asked whether I replaced the profile-directory during the udpate. I did this. I tested it without replacing, but the problem remained.

Unfortunately I could also nowhere find clear information about how to disable a profile. In my case I used the profile only for the first installation but will not use it in the future anymore.

---
Tags: theming, updating
---


# Question
Title: What causes DatabaseSchemaObjectExistsException error on existing table while reverting feature?
When trying to revert my updated exported changes on features from development site to production site via Drush, it returns DatabaseSchemaObjectExistsException error stating that there is an existing table already on the schema. Revert could not be completed, so the feature field\_base component status is always Rebuilding. Shouldn't features detect if the table is already existing and ignore field creation if it already is? What could have caused this issue? Any possible workaround for this issue?

# Answer
> 6 votes
This is usually caused when the initial feature revert or install went bad. The feature has attempted to created a field (I've only seen it happen with fields) and it's got as far as creating the base table and it's revision table but as far as features is concerned the field doesn't exist. Features then tries to re-create the field but Drupal errors out with that error message because the fields tables already exist.

My usual solution to this is to take a backup of the fields tables (including revisions) and then drop the effected tabled. You should then be able to revert the feature successfully and restore the data from your backup.

---
Tags: drush, features
---


# Question
Title: Drupal 7 Views 3 exposed filter preselected
I'm having a bit of a hard time configuring a preselected exposed filter on views.

I have a View `(mysite.com/view-path)` with an exposed filter as a select list with options:

```
Option 1
Option 2
Option 3

```

I want to be able to access the view with a preselected option in the exposed filter from another page `(mysite.com/page)` with a link like so `(mysite.com/view-path?option=1)`

Right now i've made a form alter on the exposed view filter with this:

```
if (!empty($_GET['option'])) {
   $form_state['input']['field_option_tid'] = $_GET['option'];
}

```

The problem is that this works, but when i try to click the select list and change the value to Option 2 for example, it will revert back to Option 1.

# Answer
> 1 votes
SOLVED IT!

Got it to work by not doing any form\_alter, instead i reconstructed the URL with the argument that sends me to the page view, with exactly the field\_filter ID

So, basically, when you use exposed filters on a view, it automatically changes the url to something like `mysite.com/view?field_filter=1`, i tried to use `mysite.com/view?option=1` and then make a form alter to rewrite the `$form_state[input]`, but this will always overwrite the user POST.

# Answer
> 3 votes
Use a custom module for this

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if (!isset($form_state['view']->exposed_input['<filter_field>'])) {
    // OK to set the default value
    $form_state['input']['<filter_field>'] = '<new_default_value>';
  }
}

```

Where `filter_field` is the name of the exposed filter and `new_default_value` is the key of the value you want as the default.

Got the idea from this article

# Answer
> 1 votes
Working with `POST` values didn't work on my form. And 4life's answer was close, but in the end this is the approach that worked for me complete with pretty paths:

```
    function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
      $current_path = current_path();
      $path_array = explode('/', $current_path);
        if(isset($path_array[1])){
          switch ($path_array[1]) {
            case 'new_value':
              unset($form_state['input']['field_nameoffield']);
              $form_state['input']['field_nameoffield']['new_value']= 'new_value';
              break;

            case 'new_value_2':
              unset($form_state['input']['field_nameoffield']);
              $form_state['input']['field_nameoffield']['new_value_2']= 'new_value_2';
              break;
          }
        }
     }

```

# Answer
> 0 votes
As 4life specified in his answer, do this in a custom module in `hook_form_FORM_ID_alter()`. The only difference is that you should set the `$form` element's `#default_value` property instead of injecting the default value into `$form_state['input']`. By doing that, you're overwriting whatever `$_POST` data the user has submitted.

Example:

```
<?php
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form_state['view']->name == 'your_view_name') {
    if (isset($_GET['option1'])) {
      $form['filter_field']['#default_value'] = $_GET['option1'];
    }
  }
}
?>

```

# Answer
> 0 votes
Did you try some jquery to act on the href attribute of the button to rewrite the link that gives access to the page views, something like :

```
$(".my-button-class").each(function() {
$(this).attr("href", "/view-path?option=1");
});

```

---
Tags: views
---


# Question
Title: Theming Print PDF module output when used on non-content page (views)
I have a View that has an enabled PDF version feature provided by the Print module (http://drupal.org/project/print). Its ok, but I'd like to tweak the output table with theming. According to the module documentation pdf output can be altered using these files:

```
- To modify the template of printer friendly pages, simply edit the
print.tpl.php or the css/print.css files.

- It is possible to set per-content-type and/or theme-specific templates
  which are searched for in the following order:
   1. print_[format].node-[type].tpl.php in the theme directory
   2. print_[format].node-[type].tpl.php in the module directory
   3. print_[format].tpl.php in the theme directory
   4. print_[format].tpl.php in the module directory
   5. print.node-[type].tpl.php in the theme directory
   6. print.node-[type].tpl.php in the module directory
   7. print.tpl.php in the theme directory
   8. print.tpl.php in the module directory (supplied by the module)

  format is either html, mail or pdf, and type is Drupal's node type (e.g.
  page, story, etc.)

```

My question is how to do the same when I use this module not on a specific node type but on a view? The views module's theming information table is unaware of the Print module so the possible theming \*.tpl.php files are not shown there.

Supposing that the name of my view is `foobar`, what tpl.php file should I use?

(Views PDF module is not an option for me as it fails on my special characters..)

# Answer
The .tpl file for a View with machine name "myview" would be `views-view--myview--page.tpl.php`. Following that convention and what the print module reports, I would try creating a .tpl called `print.views-view--myview--page.tpl.php`. Include `<?php print $content; ?>` in this file, clear Drupal's cache, visit the View's print page, and see if it registers.

**Edit:** Try and throw something like this in your theme's template.php file:

```
function mythemename_preprocess_node(&$vars) {
  // Something to make sure they're on your View.
  if (arg(0) == 'my_view' && arg(1) == 'print') {
    // Add a new template suggestion...
    $vars['theme_hook_suggestion'] = 'print__view_page'; // and then make a print--view-page.tpl.php file.
  }
}

```
> 1 votes

# Answer
I have achieved this implementing `template_preprocess_print()` function in my theme's `template.php` file.

```
function MYTHEME_preprocess_print(&$variables) {
  // Check if the page is not a node
  if (!isset($variables['node']->type)) {
    // Remove all other template suggestions, since they are for nodes, we don't need them.
    $variables['theme_hook_suggestions'] = array();
    // Check if the page is a view page
    $views_page = views_get_page_view();
    if (is_object($views_page)) {
      // Add template suggestions
      $variables['theme_hook_suggestions'][] = "print__view";
      $variables['theme_hook_suggestions'][] = "print__view__" . $views_page->name;
      $variables['theme_hook_suggestions'][] = "print__view__" . $views_page->name . '__' . $views_page->current_display;
    }
  }
}

```

With this code in template.php, after flushing the theme registry cache, you have following template suggestions:

* print--view.tpl.php
* print--view--VIEW-NAME.tpl.php
* print--view--VIEW-NAME--DISPLAY-NAME.tpl.php
> 0 votes

---
Tags: views, theming, files
---


# Question
Title: Using webform rules to create node after webform submission
First of all, let me explain my project. I want users to place orders of products using webforms and then create a node with a link/reference to the submission and others custom fields.

It looks like this :

CONTENT TYPE PRODUCT : \- Field name / Field image / Field category / Field description

Webform is enabled for PRODUCT content type. So I've created products examples and each of these products have their own CUSTOM webform (all the forms are differents)

For example :

PRODUCT A (product content type) \- fields values + custom webform fields

So what I want this kind of node beeing created after webform submission :

CONTENT TYPE ORDER NODE : \- webform sid reference (linking to the submission results) \- Some fields which will be the same for every product

Do you think is possible with a custom module or should I find another way to achieve this ? (I suppose replacing webform by a content type, but the problem is webform, in my case, is very usefull)

I have to point out that I'm a beginner in Drupal module's developpment.

Thank you ;-)

# Answer
You should use Rules module in the following way:

1. Install and enable Rules module
2. Install and enable Webform Rules (https://drupal.org/project/webform\_rules)
3. Create a new rule
4. Choose the "After a webform has been submitted" event
5. Optionally set your conditions
6. Add a new action "Create a new entity" of type "Content"
7. Add the neededs action to add properties to the created entity
8. Add the save action

I hope this helps.
> 3 votes

---
Tags: rules, webforms, forms
---


# Question
Title: Why is form api ignoring the weight that i'm giving to the action buttons? (node edit page)
So, I've implemented hook\_form\_alter in a custom module. I have added a button to the node edit form of a specific content type.

However, I can't for the life of me get the new button to display with the standard buttons ie save & preview. It just appears at the top of the page, regardless of the figure that i put in as the weight (I tried 100000000000000)... Fingers crossed that this is just a 'newbie' oversight :)

Here is the code that I'm using:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'CONTENTTYPE_node_form') {
    // Add validation for a file
        $form['field_CUSTOMFILE'][0]['#upload_validators']['custom_file_validation'] = array();

    // Add update site button to CONTENTYPE node add/edit form
         $form['actions']['update_site'] = array(
            '#type' => 'submit',
            '#value' => 'Update site',
            '#name' => 'op',
            '#submit' => array('MYMODULE_form_submit'), /* NEED this */
            '#weight' => 99,
            );
         $form['actions']['submit']['#weight'] = 101;
         $form['actions']['preview']['#weight'] = 100;

        return $form;

  }

}

```

These lines from above were only added today but made no difference...

```
$form['actions']['submit']['#weight'] = 101;
$form['actions']['preview']['#weight'] = 100;

```

As always, anyway pointers would be very much appreciated :)

Edit:

This question was not answered in the indicated "This question has already a answer" link above... That link explains Drupal 7 specific code, although the post isn't tagged as such... This post was specific to Drupal 6 as tagged... In fact the code in this post didn't work for me because it was using Drupal 7 code :)

# Answer
> 1 votes
I added a `cancel` button to some Drupal 6 node forms in this fashion:

```
  $form['buttons']['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#weight' => 7,
    '#submit' => array('MYMODULE_node_form_cancel_submit'),
  );

```

so I'd suggest changing `'actions'` to `'buttons'` and see if it works equally well for you.

---
Tags: 6, forms
---


# Question
Title: How do I group taxonomy by hierarchy, not node?
I am using Drupal 7 and Views.

I'm trying to use the generic Taxonomy/Term view and get a grouping I don't want. I want this:

* Taxonomy 1:

+ Node A
    + Node B
* Taxonomy 2:

+ Node B
    + Node C

(Notice Node B is in both taxonomies.)

What I'm getting is the following one:

* Taxonomy 1:

+ Node A
* Taxonomy 2:

+ Node C
* Taxonomy 1, Taxonomy 2

+ Node B

How do I get the first example to display, where Node B just appears under the different Taxonomies and doesn't create a new heading with multiple taxonomies?

# Answer
I started a new view of taxonomy terms (sometimes the default taxonomy term view is overkill) which created a view of my taxonomy terms. I then created a relationship to `Taxonomy term: Content with term` and then added a field `Content: Title` using the relationship just created.

Finally I changed the Settings of view under Format to group by by term and hid the actual term field.

My output ended up like the following, Product One was tagged with Shirts and Ties, product Two just with ties as expected.

* Shirts

+ Title: Product One
    + Title: Product Two
* Ties

+ Title: Product One
> 1 votes

# Answer
Two years later, Views Tree might have solved the problem, it renders hierarchical information with a nested list: https://drupal.org/project/views\_tree.
> 1 votes

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


title: Template file printing on every page

text:
# Question
Title: Template file printing on every page
I'm getting a really strange issue. I created a module that uses a template file:

```
/**
 * Implements hook_block_info().
 */
function emed_newsletter_block_info() {
  $blocks['newsletter_signup'] = array(
    'info' => t('Newsletter Signup'),
    'cache' => DRUPAL_NO_CACHE
  );

  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function emed_newsletter_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'newsletter_signup':
      $block['subject'] = t('');
      $block['content'] = array(
        '#theme' => 'newsletter_signup'
        );
      break;
  }
  return $block;
}
/**
 * Implements hook_theme().
 */
function emed_newsletter_theme($existing, $type, $theme, $path) {
  return array(
    'newsletter_signup' => array(
      'render element' => 'content',
      'file' => 'templates/newsletter.tpl.php',
    ),
  );
}

```

The template file just contains HTML.

The problem is that the text/html inside the template is being printed on every page at the top. Even on a `drush cc all`

Has anyone run into this issue before?

Core Version = 7.24

# Answer
> 2 votes
I'm pretty certain you want to be saying `'template'` in your hook\_theme():

`template`: If specified, this theme implementation is a template, and this is the template file without an extension. Do not put .tpl.php on this file; that extension will be added automatically by the default rendering engine (which is PHPTemplate). If 'path', above, is specified, the template should also be in this path.

instead of `'file'`, as...

`file`: The file the implementation resides in. This file will be included prior to the theme being rendered, to make sure that the function or preprocess function (as needed) is actually loaded; this makes it possible to split theme functions out into separate files quite easily.

...which would suggest the reason why all of this html is being spit out on top of each page because it is being included every time instead of being buffered with Drupal's theme engine as a template and then output later on.

# Answer
> 0 votes
Hi Check whether you have configured your block for a specific pages in the block configuration

> "admin/structure/block"

---
Tags: 7, theming
---


# Question
Title: Multiple Views on a page - How to exclude already shown nodes?
I'm showing many nodes on a page using a few different Views blocks with Panels.

For example there is a "Top Story" block that shows the latest sticky article. Then there are blocks for certain Sections (taxonomy) and important Special Sections (another taxonomy).

A node can appear in both blocks if it has a Section (say, *Culture*), a Special Section (*News*) and it may also be Sticky (so it's up in the Top story block too).

The problem here is that I can't just utilize offsets to hide things, but would need something that excludes nodes from later views that have already been shown. Older sticky nodes naturally should push down to their respected blocks when newer Nodes come etc.

Another way to put it:

Let's say we have Views, A, B, C and D. If a node is already in A, it wouldn't show up in B, C and D. If it's shown in B, it would not show up in C & D. It should be hierarchical from "promotion" style blocks to more simple listings when going lower on the page.

Is there any ready solution that would help me achieve this? I'm familiar with module coding, hooks etc so that sort of solutions are open to me as well.

# Answer
> 7 votes
You could load and display each view in your template. For each view you will have to get a list of `nid` values that you then will pass on as argument to the next view in line.

For this to work you should setup a `Contextual Filter` of type `Content: nid` and configure it to allow multiple values and exclude supplied nids.

In your template your could then do something like this:

```
// load and display view A
$viewA = views_get_view('VIEW_A');
$viewA->execute();
// get all nids from the result
foreach ($viewA->result as $result):
   $nids[] = $result->nid;
endforeach;
// render first view
print $viewA->render();

// now load view B
$viewB = views_get_view('VIEW_B');
// set arguments for view
$viewB->set_arguments(array(implode(",", $nids)));
// execute view
$viewB->execute();
// render
print $viewB->render();

```

If you would like to use just one view with multiple displays, you could use `set_display()` to select the display that should be used:

```
$view = views_get_view('VIEW');
$view->set_display('VIEW_DISPLAY_ID');
$view->execute();

```

# Answer
> 4 votes
So given your example (a view with displays A, B, C and D), this is how I would accomplish what you're proposing.

1. Add an nid field to each of the displays (except D).
2. Add a nid contextual filter to each display (except A).
3. For each contextual filter, selected "Provide default value" with Type: "PHP Code" and enter the following PHP Code:

```
$nids = array();
// This is written for display 'D' to illustrate how you could compile a list
// of all previous nids. Display 'C' would check 'A' and 'B', while 'B' would
// only need to check 'A' (thus eliminating the need for the first foreach).
foreach (array('A', 'B', 'C') as $display_name) {
  $rows = views_get_view_result('view_name', $display_name);
  foreach($rows as $row) {
    $nids[] = $row->nid;
  }
}
return implode('+', $nids);

```
4. Under "More" check both "Allow multiple values" and "Exclude".

# Answer
> 1 votes
i see 2 ways to do this, hoping others can see better ones :)

A dirty one would be with **Javascript**: add to each views the displayed nodes nids in classes, then gather them with JS and hide them from other views.

A more complex but cleaner one would be with **args and PhP**: you have to double each views with one rendering only nids like that : 1, 2, 3, 4.... Then you use a nodes:nid **contextual filter**, provide a default value in PhP and then use Views get results to have the nodes to exclude.

Without any further informations on your views that's the only ways I see how to do this :)

PS: when you choose a solution, don't hesitate to ask me for details :)

---
Tags: views
---


# Question
Title: Allow only certain user type to create account
I have to add new role, for users than can create accounts for others.

I create new role and add create profile content permission.

But when I am anonymous link 'clear new account' still appear and I can create account. I want only certain role to create account, not everyone.

Could somebody give me any advice?

# Answer
To disable account creation by anonymous:
At admin/user/settings check "Only site administrators can create new user accounts"

Allow the account-creator role to administer users:
At admin/user/permissions -\> user module -\> administer users

Use a module such a Protect Critical Users if the account-creator role should not be able to touch the superuser (user1).
> 3 votes

# Answer
In Drupal 7, under *Admin*, *Configuration*, *Account settings* (/admin/config/people/accounts), there is an option called *Who can register accounts?*, there you have to select *Administrators only*.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How can I get a relation by the endpoints using the "Fetch entity by property" action in rules?
**Short version**: I want to fetch a relation by the endpoints. The relation already exists in the database. How can I use the *Fetch entity by property* action to return the relation?

**Long version**:

I'm using the Rules and Relation modules on Drupal 7. I have a relation type that is created between two users (the endpoints are user entities). The relations I am trying to fetch have already been created.

When one user sends a message to another with the Private Message module, I want to fetch the relation between the sender and the recipient.

Here is the rule:

Event: *A message is sent* (from Privatemsg module)

Action: *Add a variable* (List of any entity items, `endpoint_list`)

Action: *Add an item to a list* (Add `privatemsg-message:author` to `endpoint_list`)

Action: *Add an item to a list* (Add `recipient` to `endpoint_list`)

Action: *Fetch entity by property* (Entity type: Relation, Property: Endpoints, Value: `endpoint_list`, Limit results: 10, provides `fetched_relation`)

However, when I try to perform another action (loop, data comparison, data set, etc.) on `fetched_relation`, I get the following error in the rules debug log:

> 4.468 ms Unable to get the data value for the variable or parameter value. Error: Missing data values.

It appears that the relation is not fetched. However,

1. I am sure the relation exists in the database with the correct endpoints (the relation appears in the UI correctly and I even checked the MYSQL table).
2. When I add an action *Print message* and print `privatemsg-message:author:name` and `recipient:name`, it shows me the names of the correct users, so those variables appear to be correct.
3. I have looked at the documentation for fetching relations with rules but I can't see what I am doing wrong.

# Answer
> 1 votes
I have managed to fetch relation by endpoint with the help of @marcusx and the patch of @MahmoudMostafa (drupal user names). You can find all in the issue Fetch Relation by Endpoints in rules.

I had also linked your issue to that one.

Resuming the steps here, you need to:

> 1. Create a list of any entiy
> 2. Put your endpoints in the list
> 3. Use the endpoint list to fetch the relation
>
> cited from marcusx comment

(I see you already know this).

Bear in mind that

> "fetch relation by endpoints" action in rules, \[...\] fetches all the relations for the endpoints in the chosen list, even if the list contains only one endpoint. In this (sub)case, the action fetches all relations pointing to the selected endpoint, whatever the other endpoint.
>
> cited from my comment

And that the resulting fetched\_relation is a list (I see you already know this as well).

I believe you only need to apply the patch, which you didn't mention in your question. Is it true?

---
Tags: rules, entities
---


# Question
Title: Event calendar help - creating view of event with all registered users in a block
I am new to Drupal so I encounter this problem. I've installed Event Callendar. Using tutorials found all over the web I made a signup content type and displaying list of registered users for each event using Eva reference.

I would like to make a block of latest event and registered users in the front page. The problem is that my list of registered users take context filter from node URL (where event content is displayed).

How can I put all of this in a single block and set context filter of users list to URL of the event?

This is very confusing. I am trying to do it for the last two days with no luck ...

# Answer
You can create a block and output your view with PHP, that way you can control which argument to pass:

```
<?php
  print views_embed_view('your_view_name', 'display_id', $your_argument);
?>

```

You can get `'your_view_name'` and `'display_id'`from the view's edit page:

* `'your_view_name'` from the URL, something like `admin/structure/views/view/your_view_name`
* `'display_id'` on the right side under "Other" \> "Machine Name". It's usually something simple like `'block_1'`, or if you have a single display, try `'default'`.

Also remember to set the text format to PHP code.
> 0 votes

---
Tags: datetime
---


# Question
Title: Apply only database updates for a single module
update.php and drush up --no-core both list several database updates pending across several modules. I'm being asked to only apply the database updates for a few specific modules because it is desired to do just these modules and test things in relation to that before running any of the other updates.

drush seems to only give me the option to apply all of the pending updates as does the update.php script. Is there a way to apply only the pending database updates for a particular module when there are pending updates for multiple?

# Answer
A quick and dirty solution is to comment out the pending update fuctions on the modules you won't update.

... but don't tell around that I suggested you this hack :-)
> 1 votes

# Answer
Drush allows you to just update a module you specify:

```
drush up module_machine_name

```

If you just want to apply pending database updates, for the modules that have already been updated:

```
drush updatedb

```

This case is relevant when updating the code base through git, or for multisite installations. In your specific case, this might be what you were looking for - just apply database updates (using this command: for all modules that require database updates), but don't update any additional codebase.

If you want to just apply the updates for a certain module, you can do this also manually. The updates can be found in the module.install file:

```
function modulename_update_prioritynumber
(e.g. devel_update_7000)

```

The priority number determines the order of the updates to be applied. You can manually execute the code for the updates using drush:

```
drush eval "the update code"

```

for example:

```
drush eval "variable_del('dev_query');
drush @yoursite eval "variable_del('dev_query');

```

(@yoursite added if bootstrapping is needed for multisite installations)

This example will delete the variable dev\_query from the variable database table (from the function `devel_update_7002`).

For more discussion on this, see: drush updatedb for a single module \- especially the answer from moshe weitzman, the drush maintainer, about applying individual updates. I'd recommend applying the updates of the module you are concerned about over uncommenting the updatedb statements in other modules - as the other answer suggests.
> 3 votes

---
Tags: 7, updating
---


# Question
Title: Setting a URL alias breaks the relative image paths on those pages. Is there a way to fix this?
I set a URL alias for one of my content type pages. So now every 'newsroom' content type is at `http://myurl.com/newsroom/name-of-article`. That's perfect. But that page also has blocks that contain images and now the paths to those images are broken.

my block contains: `scr="sites/default/files/mobile-nav.png">` but the page is trying to find the image at `src="NEWSROOM/sites/default/files/mobile_nav.png"`

The block that contains the image is on every page of the site because it's the mobile nav.

How do I change my url alias? Or what do I need to do to tell drupal how to find the images correctly while keeping the image path relative?

# Answer
src="sites/default/files/mobile-nav.png"\> should be src="/sites/default/files/mobile-nav.png"\>

Please note the additional "/" before "sites." Without the forward slash the image will always be called from wherever you're at on the site so if you were at say site.com/news/ it would look for the images in site.com/news/sites/default.... if you don't have the forward slash before sites.
> 1 votes

# Answer
You should try to keep your code independent from your base path, so that if later on your install path changes to a subdirectory or another domain, paths will still work. Try this:

```
<?php global $base_path; ?>
... src="<?php print $base_path; ?>sites/default/files/mobile-nav.png"

```

`$base_path` contains the path to the Drupal installation (at least a "/" - see Drupal docs for details). Notice that it must be declared as global before use.
> 0 votes

---
Tags: path-aliases
---