# Question
Title: Exclude a block from specific parts of the website with the Context module
I have a view/block that is showing on the right sidebar. I don't want to show that block on specific parts of the website.

I do know there is the "Show block on specific pages -\> All pages except those listed" option where you can put the URL and shouldn't appear, but it does not work.

This Drupal site is using Context to draw the content, so the problem may be there; I think there is another place where I can configure the URLs the same way I explained before on the context, but I cannot find it.

# Answer
> 4 votes
You can achieve this with the following steps in Context:

1. Conditions Type: Path Configuration:

*

~/user
2. Reactions Type: Blocks Configuration: What you want.

The trick is inside the configuration part of Conditions With the * you say it should be on all pages and you can exclude path(s) with the ~

# Answer
> 0 votes
The issue to understand is that multiple contexts can be active in parallel. Each context can add it's own block to the theme regions and all works great! But how to define which block comes first in case there are blocks coming from different contexts is an interesting question.

---
Tags: blocks
---


# Question
Title: Adding checkbox to select records in a view
I have a list of students and I have added a custom handler to add checkboxes against each student to mark as present. When I use filter, I loose the state of checkbox and I have to use filters because I have many students in the list and are on many pages. Same happen when I move to the next page. How can I retain the state of checked text boxes.

Thanks in advance.

# Answer
> 4 votes
This sounds like a task for VBO, this module provides a new view style with checkboxes for a wide array of actions you can perform on the row returned. This also comes with javascript which will allow you to remember selections between paginated pages etc which should also help with your issue.

---
Tags: views
---


# Question
Title: Rewrite content of view field based on value
On a business review page, I have a views block which shows each individual review submitted for the business. In the review form available to the user, I am using integer fields to allow the user to select their choices and to store the submitted information in the database. For instance, if a user selected in their review that the staff was "Very Helpful," then a 5 is stored in the database. This allows me to show the average value on the main business page and change the output based on php (using computed field). However, because of the way that the data is stored, the view block displays a "5" in the field for Staff Helpfulness instead of "Very Helpful."

So, the topic of the question, how can I rewrite text in a view field based on its value (i.e. replace the displayed "5" with "very helpful")?

# Answer
You need to create a template for your field. Field templates are extremely simple. Their content is:

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

```

So you should go and change the template to something like this:

```
<?php
 if($output == 5) {
    print "very helpful";
  }
  else if($output == 4){...}
?>

```

and so on. In the advanced section of your view hit "Theme" to see a list of available templates you can create. If you want to do all this through drupal interface you can do it using Rewrite the output but you will need to enable another module to be able to write php code inside the box. Take a look at Views PHP, Views Custom Field. I suggest you choose the template way. Your template is fairly simple.
> 0 votes

# Answer
you can rewrite the output of a field using "Rewrite the output" option in views.

In your case, you might also need php code: ex:

```
   $selectedValue=5; // this you can get from the replacement tokens easily

   // this array can be populated using some db query too.
   $selectedText=array('1'=>'satisfactory','5'=>'Very helpful');

   $selectedDisplayTitle=$selectedText[$selectedValue];
   return $selectedDisplayTitle;

```

Hope this helps. Let us know if you come across a better solution.
> 0 votes

---
Tags: views
---


# Question
Title: Does it make sense to set a constant like THEME_IMAGE_DIR?
Doesn't it make sense to assemble the theme's image path once, in a constant (eg THEME\_IMAGE\_DIR) and use this throughout the theme? This seems like too obvious, maybe I'm missing something...

Where would the ideal place for this initialization be? Module, theme, dark side of the moon? Inspired by Clive's answer

Declaration:

```
global $base_path;
$theme_path = drupal_get_path('theme', 'my_theme_name');
define('THEME_IMAGE_DIR', $base_path . $theme_path . '/images');

```

Usage:

```
$content['something'] = '<img src="' . THEME_IMAGE_DIR . '/inner-book.gif" />';

```

# Answer
Dark side of the moon. Definitely ;)

Seriously though...any file that's included in every page load should be fair game to put this in. Personally I'd put it in a .module file so it's included before the theme level is even considered, but if you're only *using* it at the theme level then your theme's template.php file would be fine too.

As for whether or not it makes sense...if you find yourself repeating code of *any* kind then it makes sense to implement a constant/global/function to wrap around it. As the value in your particular case will not change in a single page load, a constant makes perfect sense to me.
> 1 votes

---
Tags: theming
---


# Question
Title: Why xmlsitemap module implements hook_node_comment_delete this way?
Does someone know why xmlsitemap.module implements every hook\_node\_comment\_ hooks, with a StdClass casting for the object passed in param ? example :

```
/**
 * Implements hook_comment_delete().
 */
function xmlsitemap_node_comment_delete(stdClass $comment) {
  xmlsitemap_node_comment_update($comment);
}

(xmlsitemap_node.module l.95)

```

A teammate overrides some Drupal default comment behaviours by declaring a new entity, with CustomComment as "entity class" name.

Then, when we want to delete a comment, this xmlsitemap's casting fires an error because the loaded comment is not anymore a StdClass object, but a CustomComment object.

Do I have to hack that module ? Any Idea ?

# Answer
> 0 votes
It seems like the author of that function might just have been a tiny bit over-zealous in trying to strongly-type the `$comment` parameter.

The `hook_comment_delete()` docs don't really give any indication that it *should* be implemented in this manner; but if you look at the signature for the Drupal 8 version of the function, you'll see the parameters *are* typed. It might be that the author was following that 'pattern' when creating the function (rightly or wrongly). That's a complete guess though.

I haven't seen hook parameters being typed like this in any other contrib modules that I can think of, so it's probably an isolated incident (although this format is consistent across most of the hooks for the xmlsitemap node module).

I think the best way forward would be to create a patch that fixes the issue, and perhaps submit it to the XmlSitemap issue queue for others to review.

---
Tags: 7, hooks, entities, xml-sitemap
---


# Question
Title: Should separate Drupal installations have separate temporary directories?
Assuming one installs several Drupal sites on the same server (i.e., with multiple top-level directories, not multiple sites under a single top-level directory), can these installations share the same temporary directory or should they each have their own temporary directory?

# Answer
> 2 votes
They can all share the same folder if you want them to, but if you want to give each domain it's own tmp folder that's fine too...it really depends on how you want to set your server up.

Aside from being able to identify which tmp files have come from which site (which personally I've found no need to do up to this point in my life) I can't think of an argument either way to be honest.

*Edit*: Thinking about it a bit more, if you're running a shared host of any description it might make sense to provide a tmp folder for each domain so it's sandboxed from other sites, and from the main system tmp folder (and subsequently other parts of the system that don't relate to web).

---
Tags: 7, files
---


title: Splitting 'unlimited' body fields

text:
# Question
Title: Splitting 'unlimited' body fields
I have set the 'Body field settings' \> 'Number of values' to 'Unlimited'; so the user can add as many 'body' fields as they like.

I have then added the following piece of code to my themes 'node.tpl.php' file:

```
<?php $i=0;
while ($i<=10) : ?>
<section class="box page-box">
<?php print render($content['body'][$i]);
$i++; ?>
</section>
<?php endwhile; ?>

```

This code outputs each of the 'body' fields in a section/div and then adds a number of blank sections/divs until it hits 10!

How would I find out the total number of 'body' fields so that it only outputs the available number and not all 10? I was trying to use 'foreach' but couldn't seem to get it working.

# Answer
> 1 votes
This issue was solved using a function in my template.php file to get the field data out of entities, which I found here.

```
/**
 * Returns field values as actual entities where possible,
 * also allows selection of individual items to be returned
 */
function field_fetch_field_values($entity_type, $entity, $field_name, $get_delta = NULL, $get_key = NULL) {
  $values = array();
  if (isset($entity->$field_name) && !empty($entity->$field_name)) {
    foreach (field_get_items($entity_type, $entity, $field_name) as $delta => $item) {
      $value = $item;
      $keys = array_keys($item);
      if (count($keys)==1) {
        $key = $keys[0];
        switch ($key) {
          case 'nid':
            $value = array_shift(entity_load('node', array($item[$key])));
            break;
          case 'uid':
            $value = array_shift(entity_load('user', array($item[$key])));
            break;
          case 'tid':
            $value = array_shift(entity_load('taxonomy_term', array($item[$key])));
            break;
          case 'vid':
            $value = array_shift(entity_load('taxonomy_vocabulary', array($item[$key])));
            break;
          case 'value':
            $value = $item['value'];
            break;
        }
      }
      else {
        if ($get_key && isset($item[$get_key])) {
          $value = $item[$get_key];
        }
        elseif (array_key_exists('value', $item)) {
          $value = isset($item['safe_value']) ? $item['safe_value'] : $item['value'];
        }
      }
      $values[$delta] = $value;
    }
  }
  if (is_numeric($get_delta)) {
    return isset($values[$get_delta]) ? $values[$get_delta] : NULL;
  }
  return $values;
}

```

I then created the code below in my node.tpl page to check how many 'body' fields were in the array.

```
<?php if (render($content)) :
$contArray = array();
$summary = field_fetch_field_values('node', $node, 'body');
$contArray = $summary;
foreach ($contArray as $value) : ?>
<section class="box page-box">
<?php print $value; ?>
</section>
<?php endforeach; else : ?>
<section class="box page-box">
<h2>There is currently no content for this page.</h2>
</section>
<?php endif; ?>

```

# Answer
> 0 votes
Well, first of all, you can inspect the contents of the `$content['body']` array using the php native `print_r()` function.

If the assumptions you have prove to be correct, there is no reason why `foreach` would not work. However, you can find out the number of an array's elements using the function `count()`. In this case, you would use it on `$content['body']`.

---
Tags: theming
---


# Question
Title: Why does drupal_http_request return a 400?
I am having issues sending a POST via my module.

In my browser's REST client I get a 200 with

```
POST https://mydomain.com
username=myuser&password=password1

```

So I know that the service is working fine. I tried to replicate this call in my Drupal module with

```
$url = "https://mydomain.com";
$data = array(
    'username' => 'myuser',
    'password' => 'password1',
);

$data = http_build_query($data, '', '&');
$options = array(
  'method' => 'POST',
  'data' => $data
);

$response = drupal_http_request($url, $options);

```

The response I get is a 400. according to this I am not constructing the request correctly.

Question: How should I change my code in order to get a 200?

Note: I am using Drupal 7.

Thanks.

# Answer
> 4 votes
It's probably that you are missing the Content-Type header, as detailed here. For Drupal 7, this should look like this:

```
<?php
$response = drupal_http_request(
 'http://www.example.com',
 array('headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
 'method' => 'POST',
 'data' => 'param1=value1&param2=value2'));
?>

```

---
Tags: 8, http-request
---


title: How to make user pictures public files?

text:
# Question
Title: How to make user pictures public files?
I need to pass some URLs to user pictures via AJAX. I can't, however, pass **private://filename.jpg** because client can't open it. Are there some settings to configure where I can change to public space?

# Answer
> 2 votes
You need to change the image field associated with the user profile to Public, and then you need to migrate any existing private image files to the new public directory. Here's a write-up on working with files in Drupal 7.

# Answer
> 0 votes
I think you use`file_create_url()` to turn your URI into a public URL:

```
$path = 'private://test/test.jpg';
print file_create_url($path);

```

The above prints *http://site.com/system/files/test/test.jpg*.

This still means that visiting user should have permission to view that file (as it's a drupal private file).

If thats not true Lester Peabody's answer look good

---
Tags: files
---


# Question
Title: What modules do I need to implement web services?
We have planned to create a bank loan application in Drupal. The Application does not have any own users records, but it completely depends on external service provider.

For example, when we log in to the application, the username and password should hit the service provider, and fetch the result from the provider; the login information should be validated into the application.

How do I implement the web service in Drupal? What type of modules do I need to use?

I need to be able to do CRUD operations using web services.

# Answer
> 1 votes
I use services module to create content in drupal 7. It is very complete and as Rama mentioned it provides with json and other formats. The following resources helped me to understand services in drupal.

1. create a custom web service
2. book drupal 7 web services

Hope it helps

# Answer
> 1 votes
I've used the soapclient module in D6 for my cause with a SOAP server. It works by making SOAP calls and keeps things really simple. One method to instantiate the SOAP object and another to make the call. It has a good test page where you could enter the webservice end point, the mode like XML RPC etc. and other options such as the service method and service parameters and test the response which is quite good as you can test the service without any actual code. If you plan on implementing webservice with SOAP it is a nice module.

# Answer
> 1 votes
in Drupal 7 services 3.x is default module. U can use REST server as can handle CRUD operations. In few simple steps you can create an end point and choose your resources. It also offers you the json,xml formats

---
Tags: 7, services
---


title: strange PDOException error 1153

text:
# Question
Title: strange PDOException error 1153
This morning my Drupal 7 site suddenly not working. I get the "PDOException: SQLSTATE\[08S01\]: Communication link failure: 1153" error. The error goes away when I disabled "Aggregate JavaScript files." in config/development/performance page. I clear the cache several time, but when I re-enable "Aggregate JavaScript files" the error comes back.

This error happens only on certain pagee.

Can anyone shed some light on this problem? It doesn't make any sense to me. Thansk.

# Answer
> 4 votes
i think you need to increase your `max_allowed_packet` in your my.cnf/my.ini in mysql, maybe the problem is with packet size.

# Answer
> 3 votes
Error 1153 is to do with the MySQL configuration option, `max_allowed_packet`. If you increase this then you shouldn't have this problem anymore.

---
Tags: javascript, database, css-js-aggregation
---


# Question
Title: How to allow a role to add users without giving them a password?
I have a situation where I would like a specific user role be able to add users without assigning them a password but I can't seem to find a way to do this. Has anyone done this before? I feel like this is something commonly done. Any help would be appreciated.

Here is the module I have and currently, this code just outputs at the top of the screen for all pages? This is my first module.

Here is my hide\_some\_fields.module file

```
function hide_some_fields_form_alter(&$form, $form_state, $form_id)
{

  global $user;

  if($form_id == 'user_register_form')
  {
    if(in_array('operator', array_values($user->roles)))
    {
      unset($form['account']['pass']);

    }
  }
}

```

Here is my .info file as well:

```
name = Hide Some Fields
description = Hides some fields. The password field when the operator adds patients.
core = 7.x

```

# Answer
> 0 votes
```
function modulename_form_alter(&$form, $form_state, $form_id) {
  global $user;

  if($form_id == 'user_register_form') {
    if (in_array('your_role', array_values($user->roles))) {
      unset($form['account']['pass']);
    }
  }
}

```

This should work for you - just remember to change modulename to your module.

# Answer
> 2 votes
People need a password in order to log in to the site.
Therefore you need to allways insert a password when creating new users.
You can add a default password and set the field as hidden on a specific role but new users will need to know the default password in order to log in.

```

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;
  if($form_id == 'user_register_form') {

    $default_value = isset($form_state['build_info']['args'][0]['pass'] ? $form_state['build_info']['args'][0]['pass'] : 'DEFAULT PASSWORD';

    if (in_array('YOUR ROLE', array_values($user->roles))) {
      $form['account']['pass']['#default_value'] = $default_value;
      $form['account']['pass']['#access'] = FALSE;
    }
  }
}

```

EDIT:

Ok I took the time to work this out and therefor I want to adjust my solution:
In order to get this properly working you need to override the full $form\['account'\]\['pass'\] array. This is because it has the password\_confirm type as default, which has the extra confirm field, keeping this type will result in an empty password field on the node submit.
Clive is absolutely right, using a #default\_value on a password field results in an error so we need to use the #value. Thas was the unsupported operand types error.
Also, in my first answer I added a condition so see if the form is used to edit a user but now I know that the registration form and edit form are two different forms calling the same user\_account\_form so we can remove the condition.

```

function mymodule_form_alter(&$form, $form_state, $form_id) {
  global $user;
  if($form_id == 'user_register_form') {
    if (in_array('USER ROLE', array_values($user->roles))) {
      $form['account']['pass'] = array(
        '#type' => 'password',
        '#size' => 25,
        '#access' => FALSE,
        '#value' => 'DEFAULT PASSWORD',
      );
    }
  }
}

```

I tested this code and it works like a charm so if you have any problems with it feel free to contact me.

---
Tags: entities, users
---


title: What does check_markup() actually do?

text:
# Question
Title: What does check_markup() actually do?
The following code:

```
var_dump(check_markup('This is a test', 'plain_text'));

```

outputs:

```
string(22) "<p>This is a test</p>"

```

Why does it do this?

# Answer
`check_markup()` will:

> Run all the enabled filters on a piece of text.

Since one of those filters will probably be the HTML corrector, you'll get the `<p></p>` tags wrapping your text string.
> 9 votes

# Answer
It depends from the input filters enabled for the input format. By default, for the "Plain text" input format, they are the following ones.

"Convert URLs into links," and "Convert line breaks into HTML" add HTML tags into the text.
> 7 votes

---
Tags: input-formats
---


# Question
Title: How to dpm() the Drupal.settings.basePath var
For debugging purposes I need to use dpm to output the value of Drupal.settings.basePath. I tried this (but not working):

```
dpm(Drupal.settings.basePath); // not working

```

# Answer
> 2 votes
`Drupal.settings.basePath` is a value available from JavaScript, as Clive said, while `dpm()` is a PHP function. If you look at drupal\_add\_js(), you will notice that value is set using the following code.

```
  $javascript = array(
    'settings' => array(
      'data' => array(
        array('basePath' => base_path()),
        array('pathPrefix' => empty($prefix) ? '' : $prefix),
      ),
      'type' => 'setting',
      'scope' => 'header',
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
      'weight' => 0,
    ),
    'misc/drupal.js' => array(
      'data' => 'misc/drupal.js',
      'type' => 'file',
      'scope' => 'header',
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
      'weight' => -1,
      'preprocess' => TRUE,
      'cache' => TRUE,
      'defer' => FALSE,
    ),
  );

```

If you want to get in PHP the value assigned to `Drupal.settings.basePath` in JavaScript, you just use `dpm(base_path())`. Clive's answer already tells you how to print the JavaScript value from JavaScript.

# Answer
> 2 votes
`Drupal.settings.basePath` is a javascript variable, not PHP...you can't access it on the server side like that.

I imagine the output you're getting in the message area is 'DrupalsettingsbasePath', which is how PHP would interpret `Drupal.settings.basePath`, along with a few PHP Notices complaining about the use of an undefined constant.

Assuming you're using a browser that supports `console.log`, to debug the base path just add the following in a javascript file that's included in your page:

```
console.log(Drupal.settings.basePath);

```

The variable will then be printed to your browser's console area.

---
Tags: debugging
---


# Question
Title: Displaying follow up fields for a content type
I have a form that asks the user to answer several yes or no health questions. These questions are radio button widgets and what I've been trying to do is ask the user to fill out a follow up question, a text area which should be invisible until when the user selects the 'Yes' radio button. I have one method which involved some Javascript, but my I'm mostly a backend developer so I'm really struggling.

Anyone know how I can do this?

# Answer
> 8 votes
Drupal 7 introduced the `#states` property for form elements. It:

> Adds JavaScript to the element to allow it to have different active states.

Here's a short example that applies to your use case:

```
function MYMODULE_my_form($form, &$form_state) {
  $form['my_radios'] = array(
    '#type' => 'radios',
    '#title' => 'Radios',
    '#options' => array('no' => 'No', 'yes' => 'Yes'),
    '#default_value' => 'no'
  );

  $form['textarea'] = array(
    '#type' => 'textarea',
    '#title' => 'Textarea',
    '#states' => array(
      'visible' => array(
        ':input[name="my_radios"]' => array('value' => 'yes')
      )
    )
  );

  return $form;
}

```

The above assumes you're building the form yourself; if you're not, you can combine this logic with a `hook_form_alter()` function. This example assumes you're adding it to a node add/edit form for the Basic Page content type:

```
function MYMODULE_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['textarea']['#states'] = array(
    'visible' => array(
      ':input[name="name_of_radios_element"]' => array('value' => 'yes')
    )
  );
}

```

If you're using the second method you'll need to do some digging into the `$form` array to find out exactly which element you need to target. If you don't already have it I recommend installing the Devel module and using it's excellent `dpm()` function for your debugging.

There's more information on the various different options for `#states` on the `drupal_process_states()` docs page.

# Answer
> 2 votes
May be this modules can help:

* Conditional Fields
Conditional Fields allows you to manage sets of dependencies between fields. When a field is "dependent", it will only be available for editing and displayed if the state of the "dependee" field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.
* Webform Conditional (Same Page Conditionals)
This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components (i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.

Webform *already* has support for conditional fields on multi-page forms. For example Field C on Page 2 can be dependent on Field A on Page 1. This module adds the ability to have conditional fields on the same page. This module adds the ability to have Field B on page 1 be dependent on Field A also on Page 1.

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


# Question
Title: How to display associated content through shared taxonomy?
I have two content types, 'Topic Summary' and 'Clip Page.' Both can share the same taxonomy. For example, they might share the taxonomy 'raccoons.'

When a user clicks on a 'topic summary' I would like to display links to the related 'clip pages' through their shared taxonomy in a block underneath the content of the 'topic summary.'

I've tried doing this using views and contextual filters but I'm having no luck. I wonder if anyone could tell me how do achieve this? Specifically, it would be good to know the Drupal way of doing so.

# Answer
I managed to get this working with 'Views Node Taxonomy Filter.' It allows you to filter by the taxonomy of the current node and appears to be under active development.

http://drupal.org/project/vntf
> 1 votes

# Answer
If I am understanding your situation correctly you want to display a list of clip pages grouped by topic summary.

In Drupal 6 you can use the http://drupal.org/project/views\_groupby module, in Drupal 7 it's built in to views.

HTH
> 1 votes

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


title: Server IP Address in Drupal PHP Status

text:
# Question
Title: Server IP Address in Drupal PHP Status
How does one get the server IP address of the server you are on to appear at http://examplehost.com/admin/reports/status/php -- at the very bottom ? I keep getting 127.0.0.1. This is on two web servers that are behind a load balancer.

# Answer
> 1 votes
The admin/reports/status/php is actually the output of phpinfo() and it simply shows your PHP configuration summary.

https://stackoverflow.com/questions/3202872/php-serverserver-addr-variable-always-returns-127-0-0-1 suggests using this code to get the real IP:

```
getHostByName(php_uname('n'));

```

---
Tags: 6, log-messages
---


# Question
Title: How can I upload multiple images all at once?
Is there a way to upload multiple images all at the same time in Drupal 7?

# Answer
> 10 votes
See the Plupload integration module. From the project page:

> Provides integration between for the Plupload widget to upload multiple files and Drupal. Plupload is a GPL licensed multiple file uploading tool that can present widgets in Flash, Gears, HTML 5, Silverlight, BrowserPlus, and HTML4 depending on the capabilities of the client computer.

# Answer
> 8 votes
You can use the Plup module.

> This module integrates a modern Plupload library with file field in Drupal 7. It provides a field widget for image field that allow user to upload multiple images at once using Plupload library. It depends on Libraries module.

# Answer
> 4 votes
You may use the Multiupload Imagefield Widget module.

> As an extension to the Multiupload Filefield Widget module, this module presents the same widget to Image fields.

# Answer
> -3 votes
For an Image field, you can set the number of images you wish the user to upload.

(Image module must be enabled)

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


title: db_select doesnt work with me

text:
# Question
Title: db_select doesnt work with me
i've problem using db\_select it return strange object instead of the result here is the code

```
function _table_subscrib(){
  $result = db_select('user_company','uc')
->fields('uc',array('user_company_uid','user_company_nid','user_company_sub_number','user_co    mpany_date'))
          ->extend('TableSort')
         ->extend('PagerDefault')
         ->limit(50)
         ->execute();

$header = array('User Name','Company Name','Subscribtion Number','Date');

$rows = array();
while($data = $result->fetchAssoc());
{
    $rows[] = array(
        $data['user_company_uid'],
        $data['user_company_nid'],
        $data['user_company_sub_number'],
        $data['user_company_date']
    );
    drupal_set_message("ssdsd");
}

$output = theme_table(
            array(
                "header" => $header,
                "rows" => $rows,
                "attributes" => array(),
                "sticky" => true,
                "caption" => "",
                "colgroups" => array(),
                "empty" => t("Table has no row!") // The message to be displayed if table is empty
                )
            ).theme("pager");

return $output;

```

}

here is the object returned too

DatabaseStatementBase Object ( \[dbh\] =\> DatabaseConnection\_mysql Object ( \[shutdownRegistered:protected\] =\> \[target:protected\] =\> default \[key:protected\] =\> default \[logger:protected\] =\> \[transactionLayers:protected\] =\> Array ( ) \[driverClasses:protected\] =\> Array ( \[SelectQuery\] drupal......

thanks

# Answer
> 0 votes
You set incorrect semicolon at the end, remove it: `while($data = $result->fetchAssoc());`

And next manner looks more clear, instead using `while`:

```
foreach($result as $data) {
    $rows[] = array(
        $data->user_company_uid,
        $data->user_company_nid,
        $data->user_company_sub_number,
        $data->user_company_date,
    );
}

```

---
Tags: database
---


# Question
Title: How can I implement a custom display widget for an existing field?
Basically I want to have my own widget as a choice in the widget drop down of an existing field type; and/or I want to be able to call field\_view\_field on a field and have it display the way I need, using info from the field itself and elsewhere.

I can probabaly do what I need with template\_preprocess\_field but I would prefer to hook the existing admin interface for selecting the output of the form.

I'm assuming that a solution is available that would allow the output of the field to be the way I configure it any place the field can be displayed, Views, etc.

Thanks in advance.

# Answer
> 2 votes
The Examples project on drupal.org has a field example, showing how to implement a widget.

Basically you need to implement `hook_field_widget_info()`, and for 'field types' include the field type your widget is for.

---
Tags: 7, entities
---


# Question
Title: Ampersand does not get urlencoded and breaks my GET parameters
I am using views to create a dynamic url that contains some parameters. Unfortunately I am including the node title as a parameter and it just so happens that many of the titles contain &.

So my custom url in views looks something like this: seminar?c=\[field\_seminar\_cycle\]&n=\[field\_seminar\_num\]&t=\[title\]

But it seems that when creating the view the ampersands inside the \[title\] don't get urlencoded. I am guessing that the drupal way of building a link is to split the url based on special chars and then urlencode the others parts before joining them all together.

Is there a way to urlencode the title field before adding it to the link? Can it only be done though templates or is there any workaround though views' gui?

# Answer
> 1 votes
I'd wager you could refactor a bit, and substitute the id for the title and avoid the problem altogether.

However, you can see similar problems being worked on throughout the Views issue queue. Like this one, for instance.

# Answer
> 0 votes
Why not use the path field instead of title? Assuming you have the pathauto module running on your set up you could use path as a replacement and & would be filtered out.

For even better results used transliteration in addition to pathauto.

---
Tags: views, entities, uri
---


# Question
Title: Taxonomy translation Localize option not working correctly. thoughts?
I have a multilingual drupal 7 site. I have a series of taxonomy terms to choose from. I have the il8n Translate Taxonomy enabled and using it.

For my taxonomy I have selected "Localize. Terms are common for all languages, but their name and description may be localized."

However, despite being able to use the translate interface to correctly translate them, the terms still show up in English, the default language, regardless of what language I am viewing the content in. Here are links to the issues. Please see the tables.

```
http://tourismbuilder1.hokkaido-select.com/content/dai-ichi-takimotokan

http://tourismbuilder1.hokkaido-select.com/ja/content/%E7%AC%AC%E4%B8%80%E6%BB%9D%E6%9C%AC%E9%A4%A8

```

Thoughts as to why?

EDIT: I found this link to the issue, which is unresolved. drupal.org/node/1070256

# Answer
The answer to this is to change the taxonomy link preferences under 'Manage Display' in the content type - here is a link to a thread on the issue.

http://drupal.org/node/1070256
> 3 votes

---
Tags: 7, taxonomy-terms, i18n-l10n
---


# Question
Title: Customizing the way the form is displayed to admin user
I am developing a module which requires an administrator form.The admin will enter some settings data which will be saved in database.Then i will use these settings to display information to the website users depending on the settings chosen by admin.

So for administrator screen i need the form to be displayed like this

HEADING\_ONE HEADING\_TWO HEADING\_THREE HEADING\_FOUR
TEXTFIELD\_ONE TEXTFIELD\_TWO TEXTFIELD\_THREE TEXTFIELD\_FOUR

I need to have a table like structure. How can this be done?

# Answer
> 1 votes
You can make use of `system_settings_form` to make admin form and `theme_table` to make a table output.

---
Tags: forms, theming
---


# Question
Title: Is there a way to access the full list of results in a Solr search page?
I would like to manipulate the order of the results in an Apache Solr search result.

I'm using apachesolr together with apachesolr\_panels. In hook\_apachesolr\_process\_results() I can get the `$results` for the current page, but I'm looking for a way to find the full list prior to pagination.

**Edit:** I'm asking about the result set as I'm not in control of the solr server and can't manipulate the XML file.

# Answer
> 1 votes
Yes and no. In any sane situation, it is the solr server that is handling the pagination. In essence, the server receives parameters, `rows` and `start` that tell it which "page" it will send.

You could write custom code that would get you all the rows but that would require at keast one more query to the solr server. The first query (the default one) would find out how many results there are in total; the second one would fetch the whole set, setting `rows` to the total amount and `start` to 0.

---
Tags: search, panels
---


title: $content variable in block.tpl.php

text:
# Question
Title: $content variable in block.tpl.php
I have customized a `block.tpl.php` file and I want to access the individual fields in it. But when I put `print render($content['field_name'])` in my code nothing is printed out. And also `print_r(array_keys($content))` doesn't give anything.

I have used the above codes in my `page.tpl` and `node.tpl` files successfully before.

I'm on D7.

So is it done somehow differently in block template? What's going on?

# Answer
If you have a look at the code for the original block.tpl.php file, `$content` doesn't actually get run through `render()`, as it's already been rendered to a string.

If you want to alter the block content while it's still in a structured array you should use a `hook_block_view_alter()` implementation in a custom module. This is the example from the docs page:

```
function hook_block_view_alter(&$data, $block) {
  // Remove the contextual links on all blocks that provide them.
  if (is_array($data['content']) && isset($data['content']['#contextual_links'])) {
    unset($data['content']['#contextual_links']);
  }
  // Add a theme wrapper function defined by the current module to all blocks
  // provided by the "somemodule" module.
  if (is_array($data['content']) && $block->module == 'somemodule') {
    $data['content']['#theme_wrappers'][] = 'mymodule_special_block';
  }
}

```

How successful you'll be using this method depends on how well the modules that provide the blocks respect render arrays. If an implementation of `hook_block()` by a particular module flattens the block content to a string before it is made alterable, then you'll have to make the changes somewhere else in the process (probably using a theme preprocess/override).
> 1 votes

---
Tags: blocks
---


# Question
Title: How can I add a flag for reporting abuse on private messages using hook_privatemsg_message_view_alter()?
I have a flag on my Drupal 7 site for alerting moderators regarding potential abuse.

I want a link to this flag to be displayed next to the `Delete` and `Block` links on the view private message screen (messages/view) provided by the Private Message module.

By inserting the following code below the code for the delete link (line 769) in the latest version of the module, I can render the link correctly.

```
$author = $vars['message']->author;
$vars['message_actions'][] = array('title' => t('Report abuse'), 'href' => 'flag/confirm/flag/abuse/flag/block/' . $author->uid .  '?destination=user/' . $author->uid );

```

However, I don't want to hack the module; I want to add this code to a custom module. hook\_privatemsg\_message\_view\_alter() appears to be the function for this, but I don't understand how to use it. Simply inserting the above code and calling the function from within my custom module does not result in any errors but the link is not displayed. What do I need to show the link?

EDIT: The solution need not use `hook_privatemsg_message_view_alter()`; if there is a better way that doesn't involve hacking privatemsg, I'd be happy to hear of it.

# Answer
> 8 votes
I really don't know why you don't like the answer by Rene.

Let me show a more detailed example. You have to replace `YOURMODULE` with name of your module or theme.

```
/**
 * Implements hook_privatemsg_message_view_alter().
 * The & for param $vars is important: we pass it by reference.
 */
function YOURMODULE_privatemsg_message_view_alter(&$vars) {
  // Message author
  $uid = $vars['message']->author->uid;
  // Get flag for abusing user
  $flag = flag_get_flag('abuse_user');
  // Make flag module to check permissions
  if ($flag->access($uid)) {
    // Use flag API to show a flag according to flag preferences
    $vars['message_actions']['flag-'. $flag->name] = array(
      'title' => $flag->theme($flag->is_flagged($uid) ? 'unflag' : 'flag', $uid),
      'html' => TRUE,
    );
  }
}

```

Here I'm using a flag with name 'abuse\_user':
You can edit Flag labels, link type and permissions here.
The result:

Please, feel free to ask questions.

# Answer
> 2 votes
Hooks are a way of extending contrib modules without having to hack them. It's saying when this function runs in the the contrib module run all other functions that match the hook signature more or less (there would be a more accurate and concise explenation on drupal.org somwehere).

You need to add the code to you custom .module file and replace the word hook with your custom module name ie..

```
function my_custom_module_name_privatemsg_message_view_alter(&$vars) {
  // add a link to each message
  $vars['message_links'][] = array(
  'title' => t('My link'),
  'href' => '/path/to/my/action/' . $vars['message']['mid'],
  );
}

```

---
Tags: 7, hooks, flags, privatemsg
---


# Question
Title: How to quickly update/reinstall using Drush 4.x
Whilst trying to update Drupal 7.0 core and installed modules using Drush 4.x I appear to have broken a project site (Ubuntu 11.04 box using pure LAMP) and hence I get the dreaded 'white screen' so cannot get past it or get into the backend of the site. I would like to simply get D7 core/and all current modules (which there is a good 40 modules or so) updated and back working. It is a project for learning but I have done a good fair amount of work on it over the past 6 months and really I don't want to trash the mySQL DB and start all over again as I'll lose a fair amount of hours work. Can anyone provide a Drush command to get it back up and running whilst also updating the D7 core/modules and get it back on track. I understand the concept of the Drush CLI, but am really a 'learning' novice at present across all of the Drupal framework. The modules included are the general Panels/Rules/Views (PRV) etc along with Ubercart and subscriptions etc so a fair amount of PRV work has already been done.

I also get the following:

> PHP Fatal error: Class 'RulesIdentifiableDataWrapper' not found in /var/www/sitename/sites/all/modules/flag/flag.rules.inc on line 27 Drush command terminated abnormally due to an unrecoverable error.

So what do I do now??, I really don't want to start the whole project all over again after spending a good 6 months on this project.

Concluding: The whole process trashed my project site. Some 6 months work (with a lot of typing input) may have gone. the mySQL tables are still there and the data has been backed up, but whether I can get d7.14 and the current used modules and all the P/R/V and Ubercart user subscrition data to work is still to be seen. I'm sure this is NOT the way to be efficient in web building and management.

# Answer
It's best practice to always backup your database first when updating modules (especially when working with -dev versions). A useful module is Backup and Migrate, when installed it also provides a Drush command to backup the database (`drush bb`). (But avoid GZ compression at the moment, bug introduced with version 2.3). Since you currently have a fatal error, you'll probably have to make a backup of your database via your database management tool in Ubuntu, or use something like phpMyAdmin. You should also note which modules you will update and what the currently installed versions are. If you do all upgrading via Drush, it creates a backup of all modules it updates (so you don't have to keep track manually), and if something goes really wrong you can go back to the previously working code and if necessary put your backed-up database in place.

It looks like the current version of your Flag module is throwing the fatal error which is preventing you from updating / accessing the site. I assume this is still an old version (cf. e.g. this report), and it's likely that if you put the latest recommended relase of Flag in place the error goes away (remove the current flag module folder and replace with the 7.x-2.0-beta6 version). (If this doesn't solve the Fatal error, you should provide some more details on what versions of Flag and Rules you were using previously, and what version they are at now).

Once you get the site back working, it's a matter of doing the regular Drush commands from your Drupal directory. For example:

```
# If you have many sites you can check to make sure you're working on the right site
drush status

# update all modules but not Drupal core
drush up --no-core

# make sure update.php is run (in my experience sometimes some updates aren't run)
drush updatedb

```

Now check that your site is still working properly and then update Drupal core.

```
drush up drupal

```

And check your site again. The status report will show you if all modules and themes are up to date and if there are any database upgrades that still have to be executed.

For more info on Drush also check out drush.org.
> 1 votes

---
Tags: drush
---


title: Drupal 7 Views - Get link to node

text:
# Question
Title: Drupal 7 Views - Get link to node
I use theme information to style the output of my view. I'm overriding this file: @file views-view-fields.tpl.php

I access my custom fields by using:

```
$fields['field_FIELD_NAME']->content

```

Now I want to get the link to the node. I know I can get the link by choosing "link field to node" in the view settings. However, I don't want each field to link individually, I want to wrap them in a link. Any ideas ? Thanks!!

# Answer
Select the following fields to output:

1- title, body, path, (Global: Custom text) and any other fields you want. and make sure that (Global: Custom text) is ordered last, and all other fields are excluded from display.

2- in (Global: Custom text) settings, use the fields' tokens in the body. \[title\], \[body\], then choose "Output this field as link" and in the path just enter the \[path\] token. (See Replacement Patterns for more details)

Hope this works... Muhammad.
> 1 votes

# Answer
I have 1 suggestion for you, you can exclude fields from display then use its tokens in Rewrite result tabs, then you can add link to this group of fields with "Output this field as link".
> 0 votes

---
Tags: views, theming
---


# Question
Title: Limit account applicants with certain email addresses
Hi I am working on a website for a student organization of my college. In order to prevent spams, I have been looking for ways to limit account applicants only with email addresses from the college but haven't figure out how

# Answer
> 3 votes
In drupal 6 you can use the built in Access Rules to limit user sign ups to certain domains. It can be found at admin/user/rules/add

This no longer exists in drupal 7 because the functionality was moved into a contrib module called User Restrictions

# Answer
> 3 votes
You can write a custom module that adds a validation function to the user register form, so the form does not validate if the e-mail address is not correct.

First, tell Drupal about the validation function for the user\_register\_form form using hook\_form\_FORM\_ID\_alter:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'mymodule_user_register_validate';
}

```

Next, we write the validation function. If I'm not mistaken, the email address should be available as `$form_state['values']['mail']` here.

```
function mymodule_user_register_validate($form, &$form_state) {
  $valid_email = false;

  // Write your own code here to check if the email address is valid.
  // If so, set $valid_email to true.

  // If the email address is not valid, tell Drupal that validation failed.
  if (!$valid_email) {
    form_set_error('mail', t('The e-mail address %email is not valid for this site.', array('%email' => $form_state['values']['mail'])));
  }
}

```

Please note that the code above is written with best intentions, but untested.

# Answer
> 1 votes
To build on digital's answer, I had the same issue, with the same Drupal version. I looked into the built-in Access Rules and created two rules: one that denies all email addresses fitting the mask "%" (i.e. all email addresses) and one that allows only email addresses fitting the mask "%@%.edu". Even if the rules conflict on the ".edu" addresses, it works and results in only allowing the registrations of ".edu" email addresses.

Thanks user4109 for asking that question, and thanks digital for pointing in the right and easy solution.

---
Tags: users, emails
---


# Question
Title: After adding data to nodes using hook_node_load(), will this data be saved in the cache?
When using hook\_load() or hook\_node\_load() to add information to the node object, is it possible to have this data stored in the cache? I'd like to add several different pieces of data and it would be difficult / impossible to get this data in one database query, however, if it's caching the data with the rest of the node object, it should be fine. How do I do this if it doesn't already?

thanks!

# Answer
First of all, you generally don't want to implement `hook_load()` and `hook_node_load()` for the same node type. So just FYI.

Secondly: There's a bunch of different caching you could mean... The caching you implement depends on why you need it.

If you trace back the functions that call `hook_node_load()`, you end up at `NodeController::attachLoad()`. It just invokes the hooks and then bails to its superclass, DrupalDefaultEntityController. Basically this means that node itself doesn't do any caching.

This gives you a few options:

1) Come up with your own caching system for your own subset of the node's data, which means that you have to mark all nodes using it as uncacheable, since you're caching a little bit of it.

2) Install EntityCache. :-) EntityCache does what you'd do anyway but does it for the whole node entity at the entity layer.

BUT... If the real problem we're solving here is to have a next and previous reference per node, then you want EntityReference, which lets you set that up as fields, and which can then be used with Views and whatnot, for free, without coding anything. :-)
> 1 votes

# Answer
I think by default it won't be cached, so you'll have to do it yourself. There's a really useful post by Jeff Eaton here on caching data in Drupal 7 (see this if anyone's interested in Drupal 6).

I think you'll be looking at something like the following (adapted from the previous link and without a Drupal backend):

```
function my_module_node_load($nodes, $types) {

  //The other hook_node_load stuff you normally do is here

  $my_data = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
      cache_set('my_module_data', $my_data, 'cache');
    }
  }
  $node->my_stuff = $my_data;
}

```
> 0 votes

# Answer
> After adding data to nodes using hook\_node\_load(), will this data be saved in the cache?

No, it will be not. `hook_load()` and `hook_node_load()` are invoked by NodeController::attachLoad(), which contains the following code.

```
  // Call object type specific callbacks on each typed array of nodes.
  foreach ($typed_nodes as $node_type => $nodes_of_type) {
    if (node_hook($node_type, 'load')) {
      $function = node_type_get_base($node_type) . '_load';
      $function($nodes_of_type);
    }
  }
  // Besides the list of nodes, pass one additional argument to
  // hook_node_load(), containing a list of node types that were loaded.
  $argument = array_keys($typed_nodes);
  $this->hookLoadArguments = array($argument);
  parent::attachLoad($nodes, $revision_id);

```

`NodeController::attachLoad()` is called from DrupalDefaultEntityController::load() (`DrupalDefaultEntityController` is the base class of `NodeController`) after the method loaded the entities from the cache.

Don't get confused from the following code.

```
  if ($this->cache) {
    // Add entities to the cache if we are not loading a revision.
    if (!empty($queried_entities) && !$revision_id) {
      $this->cacheSet($queried_entities);
    }
  }

```

What DrupalDefaultEntityController::cacheSet() does is setting `DrupalDefaultEntityController::$entityCache`; it doesn't use any database cache.

What you can do is using the cache function in your implementation of `hook_node_load()`, possibly using a static variable to save the content of the cache once retrieved. You should use drupal\_static() only if the value would need to be reset (or changed) from an external function. For example, your implementation of hook\_node\_delete() could remove the reference to the nodes being deleted from that static variable.

If the value needs to be cached per node, I would use code similar to the following one.

```
function mymodule_node_load($nodes, $types) {
  global $language_content;

  $data = &drupal_static(__FUNCTION__, array());
  $langcode = $language_content->language;

  if (empty($data) && ($cache = cache_get("mymodule_cache:$langcode"))) {
    $data[$langcode] = $cache->data;
  }

  foreach ($nodes as $nid => $node) {
    if (isset($data[$langcode][$nid]) {
      $node->field = $data[$langcode][$nid];
    }
    else {
      // Get the field value.
      // Save the value in $node->field.
      $update_cache = TRUE;
    }
  }

  if (!empty($update_cache)) {
    cache_set('mymodule_cache', $data, 'cache');
  }
}

```

The code I shown considers the language currently set; if the value of the field doesn't depend from the language, you can replace `"mymodule_cache:$langcode"` with `"mymodule_cache"`.
> 0 votes

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


title: How do I add JavaScript to a page?

text:
# Question
Title: How do I add JavaScript to a page?
I made a module, and I want to add a JavaScript file to that module; I enable the module and obvious it works, but I didn't see the JavaScript file that module should take with.

I just put code similar to the following in `hook_menu()`:

```
function my2form_menu() {
      drupal_add_js(drupal_get_path('module', 'my2form') . '/abc.js');
}

```

Is it OK?

# Answer
> 6 votes
Adding a call to `drupal_add_js()` directly in `hook_menu()` doesn't work; the call to `drupal_add_js()` should be added on the code that is executed when Drupal is outputting a page. This means:

Within a form, Drupal 7 modules can use something similar to the following code, to add a JavaScript file to the currently output page.

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'my2form') . '/abc.js',
);

```

As alternative, if you write the following line in the .info file of a module, the JavaScript file will be added to any page.

```
scripts[] = abc.js

```

The path needs to be relative to the directory containing the module; if the file is contained in a sub-directory of that directory, e.g. javascript, the line should be the following one.

```
scripts[] = javascript/abc.js

```

# Answer
> 0 votes
If you want to add your js to every page, use hook\_init, if you only need to add it to some existing forms use hook\_form\_alter. It all depends on what your module is doing, so a little more background information will get you a better answer.

---
Tags: javascript
---


# Question
Title: in drupal 7, views_get_view('VIEWNAME') get a error?
I want to embed a view in the tpl.php, so I am using the views\_get\_view('VIEWNAME') function.Here is what I am doing the tpl.php.

```
<?php
   $view = views_get_view('MapView');
   print $view->preview('default');
?>

```

"MapView" is the view's name, I am not sure the argument in the views\_get\_view is the machine name or human readable name, in fact in my example is using the human readable name, because I can't find the machine name in the drupal view configuration

anyway, I get a error saying "Fatal error: Call to a member function preview() on a non-object", seems like I didn't fetch the view in the correct ?

any idea ?

# Answer
Even thought the documentation for views\_get\_view() refers to `$name` as the name of the view, what the function wants is the machine name of the view.

You should always check the value returned from the function is not `NULL`, as the function doesn't return any value, if it doesn't find the view with that name.

```
  ctools_include('export');
  $view = ctools_export_crud_load('views_view', $name);
  if ($view) {
    $view->update();
    return $view->clone_view();
  }

```

views\_embed\_view(), for example, uses the following code.

```
  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);

```

You should use similar code, avoiding to call `$view->access()` if the view should always be visible, independently from the permission the currently logged-in user has. If you need to show the view only when the user has the permission to see it, then you should consider using `views_embed_view()`.
> 3 votes

---
Tags: views
---


# Question
Title: Why isn't Drupal aggregator configurable?
I am trying to display the RSS feed of this page: http://groups.yahoo.com/group/actventurers/, on a drupal website.

I have the aggregator module enabled, but when I go to `/admin/config/services`, only RSS Publishing is available.

Any ideas as to why it won't allow me to add any feeds?

# Answer
Use Feeds, it's import or aggregate RSS/Atom feeds to Drupal.
> 1 votes

---
Tags: feeds
---


# Question
Title: How do I create a taxonomy tag from node title
I have a "Tags" vocabulary, and I would like to automatically add the node title to this vocabulary as a tag on saving the node. I have tried to use the Rules module to do this, but I can't get it to work.

Can you help me?

# Answer
I wouldn't recommend you doing that, you might get crazy node title names like "hello world I love peaches" and you dont want that tag.

anyway you can do a Hook\_node\_insert in your custom module to add your code after creating a node, then you should use taxanomy\_term\_save to insert your new term.

let me know if you need more on this.
> 1 votes

# Answer
Give Taxonomy\_node a chance, in the issue queue are patches to add the term to the node itself.

Nodes and terms are created, changed and deleted synchroniosly, it sounds like youu are searching for this. This module is for D6 in the moment.

There is a similar module: Node Auto Term but I have not worked with it, it has a D7 - version.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Custom target URL for Views content pane exposed filter (block)
Here is the situation:

There are 2 pages in Page manager

1. Overridden page of the Taxonomy term (i.e. Path: /%term )
2. Page with Taxonomy term filters (i.e. Path: /%term/filter )

And a View with 2 displays (content panes) :

1. Show all from term
2. Show filtered (with exposed filters in block).

How to place the exposed filter block on /%term page but when the filter is submitted, redirect and apply it to the /%term/filter path ?

Thank you

# Answer
Use form redirection in hook\_form\_alter.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I add just one extra node to a view? Display OG contents plus OG group node
I have created an ajax view that displays the contents of a group. It shows one page at a time, with a nice jquery pageturn effect when you go to the next page.

I now want to insert the actual group node at the start of this view. I can't put it in header or template files, as then it wont work with the ajax pagination.

I have worked out the SQL I need to get the results I want... `SELECT node.nid AS nid FROM d7_node node
LEFT JOIN d7_og_membership og_membership_node ON node.nid = og_membership_node.etid AND og_membership_node.entity_type = 'node'
WHERE (( (node.status = '1') AND (og_membership_node.gid = '42' ) )) OR (node.nid = '294')
ORDER ASC`

The SQL my view is currently using is... `SELECT node.nid AS nid FROM d7_node node
LEFT JOIN d7_og_membership og_membership_node ON node.nid = og_membership_node.etid AND og_membership_node.entity_type = 'node'
WHERE (( (node.status = '1') AND (og_membership_node.gid = '42' ) ))
ORDER ASC`

So basically I just need to tag on 'OR (node.nid = '294')' to the WHERE.

I'm trying to use this custom module

```
function hook_views_views_query_alter(&$view, &$query) {
if ($view->name == 'flipbook_ii') {
    $nid = $view->args['0'];
    $query->where[] = array(
      'conditions' => array(
        '0' => array(
          'field' => 'node.nid',
          'value' => $nid,
          'operator' => '=',
        ),
      ),
      'type' => 'OR',
    );
  }
}

```

But that is still setting the WHERE query `WHERE (( (node.status = '1') AND (og_membership_node.gid = '42' ) AND (node.nid = '294') ))`

Can anyone explain a way that works?

# Answer
Took me a while but eventually solved this....

Needed to add

$query-\>group\_operator = 'OR';

into my hook\_views\_query\_alter.
> 0 votes

---
Tags: views, organic-groups
---


title: Drupal 7.x - Webforms and nodes

text:
# Question
Title: Drupal 7.x - Webforms and nodes
I am using the webforms module and created a new webform. Now my problem is... after I have created a specific content type, I would like to diplay this webform...

Imagine: Create a new event with title, start, end und location.

After this, Visitors should see the webform below:

webform contains attend=yes/no, name, email and a submit button that sends an email.

How can I achieve that?

Thanks!

# Answer
> 1 votes
Are you going to use the same webform for all your node events?

Then maybe you should consider creating a url pointing to your webform with parameters. In your webform you can catch the parameters with %get\[parameter\].

Although I should warn you that when I tried something similar I had this problem: Ampersand does not get urlencoded and breaks my GET parameters

---
Tags: webforms
---


# Question
Title: Content listing to show custom fields of associated terms instead of title
I'm using Drupal 7 with views 3.

I have a Content Type of "Flag" associated with a vocabulary named "Colors", and its terms are Red, Blue, White, Yellow, etc. Each color has a custom field named field\_color\_image where I upload a small color thumbnail.

Currently I have a following 'Content' view set up, that lists flag names and it's colors(terms).

In my Views, the Fields is set to display 'Content: title' and 'Content: field\_color'

The output looks like this:

```
- American Flag
Terms : Red, Blue, White

- Russia Flag
Terms : Red, Blue, White

- Sweden Flag
Terms : Blue, Yellow

```

How can I output the field\_color\_image of the term instead of the title?

Notes: I have checked under replacement patterns and they don't have custom taxonomy field support.

Thanks.

# Answer
> 0 votes
In Views under `Contextual Filters` select your vocabulary field. Now you can find your required image field under `add` button in fields. Add that field to your view.

---
Tags: 7, views
---


# Question
Title: How to dynamically change the title of a menu item
I have a "new comments" menu item in the user-menu that is generated by a view. I would like to change the title of the menu to include the number of new comments.

I tried using hook\_menu\_alter without success. I cleared the cache and rebuilt the menu using the devel function.

```
function newcomments_menu_alter(&$items){
  $items['newcomments']['title'] = '5 New Comments';
}

```

When I add a menu item with hook\_menu() I can dynamically change the title with a custom "title callback" function. But I can't figure out what the "page callback" is to display the view.

# Answer
Views doesn't implement `hook_menu()` to add it's items, it uses the menu link API directly to add links. This makes it a bit trickier to do what you want as `hook_menu_link_alter()` isn't necessarily called when the caches are flushed, but only when the link is edited via the admin UI.

The links in menus don't even necessarily go through `theme_menu_link()` so you can't override the title at the theme level with that hook. Instead the only way I could find to do it was to implement `hook_preprocess_link()`, check the path, and change the title.

It's not a very pleasing solution, as `theme_link()` seems far too generic a place to be hooking into to change just one link title, but it might do the trick:

```
function MYMODULE_preprocess_link(&$vars) {
  if ($vars['path'] == 'newcomments') {
    $num_comments = MYMODULE_num_comments();
    $vars['text'] = format_plural($num_comments, '1 New Comment', '@count New Comments');
  }
}

```

The only problem is that if there are other links on the page that point to the same URL their title will also be changed. Hopefully this can be a 'feature' rather than a 'bug' ;)
> 4 votes

---
Tags: 7, routes
---


title: PHP rule for views exposed filter

text:
# Question
Title: PHP rule for views exposed filter
I'm writing a visibility rule for an element on a Panel page that also has a view with exposed filter. The goal is to show this element only when the filter isn't set. Is there a way to check weather the view on the current page was filtered with exposed filter or not?

# Answer
> 1 votes
There might be other more convenient solutions but this is a quick one, in some cases it wont work or suit at all (it will work on pages with clean urls), but you can perform current path validation by this code:

```
$destination = drupal_get_destination();
$destination = $destination['destination'];

// validate if path contains "?" from exposed filter

if (preg_match("/\?/", $destination)) {
return FALSE;
}
else {
return TRUE;
}

```

---
Tags: 7, panels, views
---


# Question
Title: Is it possible to notify users by e-mail when receiving a private message except when a specific user sends a message?
I also opened a thread on this on Drupal.org but since it's been awhile I thought I'd try asking here.

Use Case: In general, I want users to receive notifications for new private messages. I can do this using the included submodule for e-mailing private messages.

So that the private message inbox has a message when users log in for the first time, I used the Rules module to automatically send a "welcome" private message upon registration on behalf of an administrator account. However, this triggers the "send e-mail on private message" behavior. Since users already are receiving a "please validate your e-mail address" e-mail, I don't want them to receive a second e-mail notifying them that they have received the "Welcome" private message.

Is there a way to prevent messages from certain users (or, alternately, certain messages) from triggering the e-mail notification?

I also looked into implementing this using rules instead of the included submodule but this would mean I couldn't use the functionality for reducing the number of notifications (currently, I have it set to not send additional e-mails if the user has yet to log in and read the first e-mail in a thread from a given user).

# Answer
> 4 votes
*Note: this is answer for Drupal 7.*

As Letharion said, you can use `hook_mail_alter()` but you should detect somehow is this a welcome message from admin or not.
I suggest Context module for this task, but you really can just compare a subject of message in this hook.

## Update

> First I suggested to use Context module, but it is no so simple to set context in Rules. If you are interested in that way, you can see history of an answer.
> Current code is using information about Author id and subject of message:

```
/**
 * Implements hook_mail_alter().
 */
function YOURMODULE_mail_alter(&$message) {
  $WELCOME_USER_ID = 1; // PM author from your rule
  $WELCOME_SUBJECT = 'Welcome to the site'; // PM subject from your rule
  // 'pm_email_notify_notice' is an ID for message notifications
  // from Privatemsg Email Notification module
  if($message['id'] == 'pm_email_notify_notice') {
    $privatemsg = $message['params']['message'];
    if ($privatemsg->author->uid == $WELCOME_USER_ID && $privatemsg->subject == $WELCOME_SUBJECT) {
    // If special context is set it means that we don't want to send an email
    //if(context_isset('context', 'my_privatemsg_stop_email')) {
      // Stop email
      $message['send'] = FALSE;
    }
  }
}

```

# Answer
> 3 votes
Using hook\_mail\_alter you can stop the sending from happening with `$message['send'] = FALSE`.

Unfortunately this gives no direct way of knowing that the mail is "the first mail", or "from uid 1". I believe that would need to be a match directly against the body text. The calling `$module` is however available, so you can limit the manipulation that way.

# Answer
> 0 votes
It could take some reengineering, but I would write a custom module that adds a row to the PM table (and any other linked tables, I don't have the PM database schema in front of me).

You could use rules to trigger the module after the "account has been created" event.

That might be more hand coding than you're wanting though.

---
Tags: privatemsg
---


# Question
Title: db_set_active() and node_save() not working as expected
I'm writing a module to use on a multisite setup that enables nodes to be published to another site on the same installation.

Suppose I have **Site A** and **Site B**. I want this module to provide the ability to save a given node from **Site A** to **Site B**. Naturally, the way I have the database info set up in settings.php for **Site A** is as follows:

```
$databases['default']['default'] = array (
    'database'  => $db_name,
    'username'  => $db_user,
    'password'  => $db_pass,
    'host'      => 'localhost',
    'port'      => '',
    'driver'    => 'mysql',
    'prefix'    => $db_tables,
);

$databases['site_b']['default'] = array (
    'database'  => 'site_b',
    'username'  => $db_user,
    'password'  => $db_pass,
    'host'      => 'localhost',
    'port'      => '',
    'driver'    => 'mysql',
    'prefix'    => '',
);

```

...thus giving **Site A** the info it needs to access **Site B**'s database.

When I execute the following code in the module via the `hook_node_insert` and `hook_node_update` hooks:

```
// Switch to Site B database
db_set_active('site_b');

// Save the node on Site B
node_save($node);

```

...it attempts to save the node on the current database instead, resulting in an SQL error (duplicate node ID). (Also, as a side note, I'm utilising a boolean property on the $node object to prevent the hooks and node\_save() from throwing each other into an endless loop.)

I tried using `drupal_get_schema(NULL, TRUE);` directly after `db_set_active('site_b')`, but that made no difference. I've also cleared the cache in between every code change and test. No luck.

I don't know what's preventing it from working... maybe my $databases array is structured incorrectly?

# Answer
> 1 votes
Here is some help:

> ```
> The general format for the $databases array is as follows:
>  * @code
>  * $databases['default']['default'] = $info_array;
>  * $databases['default']['slave'][] = $info_array;
>  * $databases['default']['slave'][] = $info_array;
>  * $databases['extra']['default'] = $info_array;
>  * @endcode
>  *
>  * In the above example, $info_array is an array of settings described above.
>  * The first line sets a "default" database that has one master database
>  * (the second level default).  The second and third lines create an array
>  * of potential slave databases.  Drupal will select one at random for a given
>  * request as needed.  The fourth line creates a new database with a name of
>  * "extra".
>
> ```

Are you sure Drupal can connect to the second database? Check your login credential, put some dummy table and do a db\_query to verify they exist only in the second one.

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


# Question
Title: Aggregator custom template file is not overriding the default one on Drupal 7
I have the Aggregator module enabled in Drupal 7. I have one feed and I'm showing it on the front page in a block. The block has under the feed a 'more-link'.

I want to change the text depending on the language and feed that I'm showing.

I added a copy of aggregator-summary-items.tpl.php to my theme folder and customized the file.

My problem is that is still showing the default one. Is there something I'm missing?

# Answer
Your template file is either badly named or you put it in the wrong place, which can change depending on the theme.

To know which files may be candidates for templating, you can use Devel Themer which was quite buggy last time I checked, but does a good job at listing candidate template files. Just enable it long enough to check them, and then get rid of it.
> 0 votes

# Answer
I don't think it uses template files.

Just override the function in your template.php. (replace 'mytheme' with your theme's name).

```
/**
 * Returns HTML for an individual feed item for display in the block.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: The item to be displayed.
 *   - feed: Not used.
 *
 * @ingroup themeable
 */
function mytheme_aggregator_block_item($variables) {
  // Display the external link to the item.
  return '<a href="' . check_url($variables['item']->link) . '">' . check_plain($variables['item']->title) . "</a>\n";
}

```
> 1 votes

---
Tags: 7, theming, feeds
---


title: User One specifics

text:
# Question
Title: User One specifics
Until now, I used to create admin user with one of my private nicknames, hoping that not having a user named obviously `admin` would be some kind of a security measure for the site. Now I began to see that the user id 1 can have a special meaning for some modules (regardless of whether there is another user with admin role) and that nickname - along with my own style of password - will have to be used at some situations. That's OK as long as I'm involved in admin jobs, but will be a slight mental discomfort once I give up the role and yield it to someone else.

My question is: is there any way to add a user with admin role and then SWAP the IDs with Number One? It would probably be easy to do via PhpMyAdmin, if the tables did not have so much dependencies. Is there a module for that?

# Answer
I presume you are using Drupal 6, as the admin role module is part of Drupal 7 core. If you install and enable admin role on your D6 site, it will make it easier to manage your non-ID-1 administrators, as you can just assign them the administrator role. You can just do this out of the box in D7.

On a related note, I also like to use the sudo module, and only apply the administrator role to my account when I need to do admin tasks on the site. The advantage of this is that I see the same set of menus and pages as other ordinary-permissioned users most of the time, which keeps me more in touch with the standard user experience for the site.
> 1 votes

# Answer
Just give the admin role all permissions and he can do everything that the user with id 1 can do. The reason why modules do a check on user id 1 is because user id 1 doesn't need to have the admin role in order to have all privileges. The user id 1 allways has all privileges no matter what role he has.
You can easily check this looking at the permissions for content types, each new content type has a set of permissions which are disabled by default but the user with user id 1 can access all of them.
Swapping the user IDs seems like a very bad approach to handle this situation, certainly because it doesn't add extra value to the situation. It can be a bit of work to activate all privileges for the admin role but this seems to me like the only good way.
> 0 votes

---
Tags: users
---


# Question
Title: Using hook_page_alter to move node render items into blocks
I have a gallery page where I want to move the thumbnails into the sidebar-first region as a block. I'm trying to get a handle on using the code in Drupal 7 so am attempting to do this via hook\_page\_alter.

In my template.php file I currently have...

```
/**
* Implements hook_page_alter()
*/
function MYTHEME_page_alter(&$page) {
  $node = menu_get_object();
  if($node && $node->type == "imagegallery") {
    // edit only imagegallery nodes
    debug($page['content']['system_main']['nodes'][$node->nid]['#node']->field_image);
    $page['sidebar_first']['thumbs']['content'] = $page['content']['system_main']['nodes'][$node->nid]['#node']->field_image;
    unset($page['content']['system_main']['nodes'][$node->nid]['#node']->field_image);
  }
}

```

Debug is showing the array for the field\_image from the language (\['und'\]) and each of the thumbnails but nothing is rendered out into the sidebar-first region and the field\_image is not unset from the node. I had also tried the hide() function unsuccessfully.

What is the correct way to move render objects from the main content to a region?

# Answer
Well this ended up being a real pain in the bum - but ultimately got it solved. There may be a cleaner way of shifting the content so please comment if it could be done better.

I'll start by answering the question, then I'll try to go through what I think was going on under the hood to exacerbate the problem(s).

The answer is to use **hook\_page\_build()** instead of hook\_page\_alter(). hook\_page\_build() doesn't trigger from template.php so you need to build a custom module.

MYMODULE.module simply contains:

```
<?php
/**
 * Implements hook_page_build()
 */
function MYMODULE_page_build(&$page) {
  $node = menu_get_object();
  if($node && $node->type == "imagegallery") {
    // edit only imagegallery nodes
    $page['sidebar_first']['thumbs'] = array(
      'content' => $page['content']['system_main']['nodes'][$node->nid]['field_image'],
      '#prefix' => '<div class="thumbs">',
      '#suffix' => '</div>',
    );
    unset($page['content']['system_main']['nodes'][$node->nid]['field_image']);
  }
}

```

And that's all there is to it.

Now to go through the various 'gotchas!'.

`$page['content']['system_main']['nodes'][$node->nid]['#node']->field_image` is not `$page['content']['system_main']['nodes'][$node->nid]['field_image']`! This took a freaking day to find. Using devel\_themer I kept on inspecting the node-level elements rather than the block-level elements. No matter what I did `['#node']->field_image` stayed where it was but I think that #node is just a reference of what was generated and isn't even ultimately rendered. Once I found that `['nodes'][$node->nid]['field_image']` was the render element for the thumbnails it was down-hill from that point. Lesson learned: Even if you find what you think is the actual render element keep checking up the tree.

`hook_page_alter()` is great if you are ALTERING existing content but not great if you are moving stuff around. By that I mean if you have content in a region and you just want to clean stuff up then fine, use hook\_page\_alter. But one of the problems I had was that I had no existing content in the sidebar\_first region so by moving things across using this hook, the system already thought that sidebar\_first was empty. So while it placed the content where the region should have been, it didn't actually render the region itself. This really screwed up my page display. I'm guessing that Drupal builds the page elements during `hook_page_build()`, then works out what is what as far as the regions it is going to render out, then allows final altering during hook\_page\_alter() for the absolute last-step tweaking before render() is run. By using hook\_page\_build() the system then knew that the sidebar\_first region was active.

It also took a little while to figure out hook\_page\_build() didn't trigger from template.php. I should have started with a debug message in there to test that as well.
> 3 votes

---
Tags: hooks
---


title: Different theme for different languages

text:
# Question
Title: Different theme for different languages
In drupal 7 how do I change site's theme based on current language?

# Answer
The Themekey module will handle that for you.
> 3 votes

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


# Question
Title: Can I remove unused core modules from Drupal?
I am about to start a new website that is supposed to handle thousands of users at once. It is having some mobile application, and I need to use web service.
As a matter of performance, and the link I found here, I am planning to remove core modules such as the Blog module, the Forum module, and maybe the Search module too.

Is it a best practice? What can I do to increase the performance, as I am not planning to purchase a VPS or something like that for hosting?

# Answer
> 5 votes
Modules that have never been enabled are not a performance issue.

The issue report you linked is referring to what Drupal does when it doesn't find an enabled module; in such case, Drupal rescan the directories where the modules are placed, causing performance issues. To avoid it, modules should be uninstalled from the module page, and then deleted from the server directories; if you do this, you will never have any performance issue.

If you are thinking of removing the database rows found in the "system" table referring to those core modules that you don't use, then it is useless, as Drupal adds those rows back every time you visit the module page.
If Drupal were not doing that, you would not be able to install new modules. When you visit the modules page (admin/modules in Drupal 7), Drupal rescans the directories where modules are placed, to list the new modules you could have copied on the server. If it finds a module that doesn't have a row in the "system" table, it adds it; it cannot know if you removed that row from the table, or it is a module that you copied on the server, and you want to install.

If you are thinking of removing the module files for those core modules you don't use, you should keep doing it every time you update Drupal; as there isn't any gain, it's useless doing it.

---
Tags: 7, performance
---


# Question
Title: How to have a 'Has Photo' (true or false) views filter
I am looking to list a views result set based on whether it does or does not have a photo in the photo field. I think I remember this being part of d6? d5 maybe? Regardless, I cannot find it for d7 if it exists.

If there is no such option, thoughts on how to limit a result set based on whether the field contains a photo / file or not?

Thanks

# Answer
You definitely can do that in D7/V3.3. Just add a filter field that reads like: `Content: IMAGE_FIELD_NAME:fid (not empty)`
> 1 votes

# Answer
You can add this field as a filter criteria on your view. Choose the "User: Picture" field and check if its empty or not. Probably you need to create a relation to the user if you have a "Content" related view.
> 0 votes

---
Tags: 7, views
---


title: Get taxonomy term ID in node

text:
# Question
Title: Get taxonomy term ID in node
I have the following content types: *hotels*, and *taxonomy terms*; *in hotels* I have a taxonomy field.

How do I retrieve the taxonomy term ID in a node? Is it possible to retrieve the self and parent taxonomy term ID and name?

I have also tried this, but it does not work.

# Answer
> 3 votes
You can use field\_get\_items(), which returns you the value of a field in the language they would be displayed, or in the language whose code is passed as argument to the function. Generally, you are interested to the field's value in the language that would be used to show the field, and you don't pass any language code to the function.

```
$items = field_get_items('node', $node, $field_name);

```

`$node` contains the node object, and `$field_name` the name of the taxonomy term field.

What returned in `$items` is an array containing (possibly) multiple values; each value is an array containing the "tid" index, and the term ID. For a taxonomy term for which users can enter more than a value, this is what the function returns.

# Answer
> 1 votes
You can use field\_info\_instance(), as in the following snippet.

```
$info = field_info_instance('node','enter_your_field_name','enter_content_type_name');
foreach ($info as $ps2 => $key) {
  echo "Info [ $ps2 ] : " . $key . "<br />";
}

```

In this way, you get the term ID.

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


# Question
Title: Publishing option is not available for one content type
I have drupal 6.25. I have some content types like article, editors, slideshow and others.
publishing options are listed normally for all content types except "article" (although i gave "administer nodes" permission to my editors). i have tried some modules like Override Node Options but i still have the same problem for this content type for all users (of course except the admin user, admin can see it normally).
any idea of what might cause this and how to fix it?
Thanks for your help

# Answer
I have managed it already. I found a form\_alter hook in one of my modules. and in this hook there was the line below (i just commented it)

```
$form['options']['#attributes'] = array('style' => 'display:none');

```
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: Registration form in a popup window (colorbox or jQuery ui)?
How to embed a registration form in a popup window?

I would like to use Colorbox or jQuery UI:

```
drupal_add_library('system', 'ui.dialog');

```

# Answer
> 2 votes
There's already a module for that, Ajax Login/Register:

> This module provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.
>
> Features:
>
> * This module provides a block with 2 links (Login, Register) for the anonymous user.
> * When the user clicks on Login or register the requested form appears in a nice ajax popup.
> * The login and register forms can validate using ajax and not redirect on error.
> * On success the module redirects to the user page.
> * When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
> * This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.

---
Tags: 7, users, javascript
---


title: Problems to add a form in a block

text:
# Question
Title: Problems to add a form in a block
I have a very small experience with Drupal but I have to add a little form in a block (for a newsletter) in a custom module.

I write this code for the moment :

```
function block_contact_default() {
  $content = array();
  $content[] = '<div class="logo">My.<span>Site</span></div>';
  $items[] = array('class' => 'mail', 'data' => l(t("By mail"), 'node/'.variable_get('webform_contact_default_nid', FALSE)));
  $chat = variable_get('default_chat', "");
  if(!empty($chat)){
    $items[] = array('class' => 'chat', 'data' => l(t("By chat"), variable_get('ot_default_chat', "")));
  }
  $facebook = variable_get('default_facebook', "");
  if(!empty($facebook)) {
      $items[] = array('class' => 'facebook', 'data' => l("Facebook", $facebook));
    }
    $twitter = variable_get('default_twitter', "");
  if(!empty($twitter)) {
    $items[] = array('class' => 'twitter', 'data' => l("Twitter", 'http://twitter.com/'. $twitter));
  }

    $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), $language->language);
    if(strstr($path_newsletter, 'node/') !== FALSE){
        $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), 'fr');
    }

    $form['#method'] = 'post';
    $form['newsletter_form'] = array(
      '#type' => 'fieldset',
      '#title' => t('Suscribe to Newsletter !'),
      '#tree' => TRUE
    );
    $form['newsletter_form']['newsletter_mail'] = array(
      '#type' => 'textfield',
      '#title' => t('E-mail'),
      '#default_value' => t('E-mail')
    );
    $form['submit'] = array('#type' => 'submit', '#value' => t('OK'));
    $items[] = array('class' => 'newsletter_form', 'data' => $form);

    $content[] = theme('item_list', $items);
    $content[] = $form;

    return array(
      'subject' => t("Contacts"),
      'content' => implode('', $content),
      'classes' => array('block-contact')
    );
}

```

I'm using Drupal 6.25 But when I go on my page I get only a string "Array", not really what I wanted... I'm sure I don't do this properly. Could you help me ? Thank you with advance.

# Answer
> 0 votes
More information would be more helpful to answering this question. I have no idea what file/function you have put this code into, if you have in your module any of the other hooks necessary to display a block or what your actual end-goal is here (are you printing a form in a block created by another module?). However, this code doesn't seem to correlate to any of the hooks necessary for creating a block within a module in Drupal 6.

You should take a look at the Examples for Developers module and its examples of a module that creates a block and a module that creates a form. By following those examples, you should be able to easily build a module that will create a form and a custom block that outputs that form.

# Answer
> 0 votes
I think you want to create a form in a block.For this you have to use hook\_block. You will be able to add your module as a block in the existing regions (Administer-\>site building-\>blocks) . See this example.

http://drupal.org/node/206753

---
Tags: 7, forms
---


# Question
Title: Restrict admin from disabling userprotect
I've installed the user protect module on a site to allow another user to have complete admin access to the site, without the ability to edit my own administrator account. The problem with this it, they need to be able to access pretty much absolutely everything else, except for the ability to circumvent user protect. At the moment, it is set up to stop them from editing my user, which works fine, unfortunately they are easily able to simply disable user protect.

What can I do to let them do almost everything except lock me out? So they shouldn't be able to disable that module, and they shouldn't be able to change their own permissions to be able to access that module.

# Answer
> 0 votes
I don't think there's an existing module to do that (might be wrong though), but if you're ok to write a small custom module it would be fairly straightforward.

The two things you need to do are:

* Alter the module list form and disable the checkbox for the User Protect module
* Alter the permissions form to disable the checkboxes for the *administer userprotect* permission (and any others you might want to disable access for, see the `userprotect_permission()` function in the userprotect.module file for a full list).

The code would look something like this:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // We only need to do this for a non super-user
  global $user;
  if ($user->uid == 1) {
    return;
  }

  // User permissions form
  if ($form_id == 'user_admin_permissions') {
    // Choose the permissions to hide
    $permissions = array(
      'administer userprotect'
    );

    // Disable the checkbox for each permission for each role
    foreach (element_children($form['checkboxes']) as $key) {
      // Loop through each permission and disable
      foreach ($permissions as $perm) {
        $form['checkboxes'][$key][$perm]['#disabled'] = TRUE;
      }
    }
  }

  // Module list page
  else if ($form_id == 'system_modules') {
    // The group the module lives in (User Protect is in 'Other' by default).
    $group = 'Other';

    // Disable the checkbox
    $form['modules'][$group]['userprotect']['enable']['#disabled'] = TRUE;
  }
}

```

Now the checkboxes for both will be disabled unless you access the forms logged in as user 1.

# Answer
> 1 votes
Create another custom role, and add all of the permissions they will need, to that role. Leaving out the ability to administer user roles, and such.

It probably sounds tedious, considering you'll be adding back *almost* all of the same permissions that admin has. But, that "almost" is important and makes all the world of a difference with regard to security of your website.

# Answer
> -1 votes
"Hide the Administrator role selection in admin/config/people/accounts unless the user has the 'administer permissions'"

http://drupal.org/node/1356964 (roleassign module)

http://drupal.org/project/fixcore

---
Tags: users
---


# Question
Title: Merging duplicated nodes, and their fields
I am looking for a coded way of merging two nodes (of same type), with user interaction ("guided merge").

In my case,I made a simple contact manager. It imports (Feeds csv import) from, and exports (node export to CSV) to various sources, e.g. some social networks contact lists, webmail and thunderbird files. I want to manage the people data from there exclusively.

I use in first place a content type "person" with mostly simple text fields (e.g. name, email, phone, city).
As you might have encounterd, frequently there will be duplicate nodes, but one of them most of the time holds the more accurate info about the person.

So I am in need of a tool to:

* Let me checkbox-click two nodes (from the generic view)
* Show both nodes side by side
* Let me choose one as master
* Click "Go" to start the merging:
    + Merge automatically all new fields from secondary node into master
    + For fields with values in both nodes, show them both
    + Let me click, which one should be used and provide an prefilled form to edit the value
    + Submit the field value, then show the next field
    + Continue until the node is done
    + Save the updated master node, and delete the second node

My research until now has not shown results (discussions, modules) in that direction.

Do you have any hint on what to search for? Should I start a new module?

# Answer
I have never heard of such functionality.

The first idea that comes to mind: Ctools has *contexts* for both *Node view* and *Node edit*. One could use such contexts to display two nodes side by side on a page, in either view or edit mode. With some custom form logic for picking, "left", "right" etc, on top; one could get very far in this.

Ctools also provides other niceties such as an object cache and a modal framework that could potentially be useful for developing this.
> 2 votes

---
Tags: nodes, entities
---


# Question
Title: Accessing field values in node--mycustomtype.tpl.php
I have a content type that contains a field called headshot. This is a file field. In my custom node template file, I need to access the value of the headshot's filename property. `dpr($content)` produces this for the field:

```
[field_headshot] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [fid] => 53
                                            [display] => 1
                                            [description] =>
                                            [uid] => 10
                                            [filename] => kanderson.jpg
                                            [uri] => public://headshot/kanderson.jpg
                                            [filemime] => image/jpeg
                                            [filesize] => 21669
                                            [status] => 1
                                            [timestamp] => 1337356962
                                            [type] => image
                                            [rdf_mapping] => Array
                                                (
                                                )

                                            [image_dimensions] => Array
                                                (
                                                    [width] => 180
                                                    [height] => 252
                                                )

                                        )

                                )

                        )

```

I've tried

```
<img class="speaker_headshot" src="sites/default/files/styles/large/public/headshot/<?php print render($content['field_headshot'][0]['filename']); ?>" alt="<?php print $title; ?>" />

```

and

```
<img class="speaker_headshot" src="sites/default/files/styles/large/public/headshot/<?php print render($content['field_headshot']['filename']); ?>" alt="<?php print $title; ?>" />

```

with no success. How do I access this property?

# Answer
> 2 votes
To get a web-accessible URL for the file you need to use `file_create_url()` on the field's `uri` property. You can also make use of `theme_image()` so you don't have to write the HTML yourself:

```
$vars = array(
  'path' => file_create_url($content['field_headshot'][LANGUAGE_NONE][0]['uri']),
  'alt' => $title,
  'attributes' => array(
    'class' => array('speaker_headshot')
  )
);

$img = theme('image', $vars);

print $img;

```

Since this code will clutter up your template file you might want to consider putting in a preprocess function instead, something like:

```
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'headshot') {
    $items = field_get_items('node', $vars['node'], 'field_headshot');
    $image = array_shift($items);

    $image_vars = array(
      'path' => file_create_url($image['uri']),
      'alt' => $vars['title'],
      'attributes' => array(
        'class' => array('speaker_headshot')
      )
    );

    $vars['image'] = theme('image', $image_vars);
  }
}

```

Then in your template file you can just `print $image;` to get the HTML output.

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


# Question
Title: form_alter to change value of default in dropdown list
I need to change the first value (the default one) in one of my taxonomy based dropdown menus. It is currently set to '- CHose a value -', and I need it to be changed to: '- Chose city -'.

I thought I might use form\_alter for this, But I cant get further then to the correct form\_id.

What to I do next?

# Answer
First you need to find out where the element that you're trying to manipulate is within the form array. The best way to do that is to install the Devel module and use the `dpm()` function to inspect the `$form` variable:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
    dpm($form);
  }
}

```

When you see the variable outputted to the message you can drill down until you find the particular element. Note the keys of the element's parents in the array as you'll need them too.

If this is a node form and the taxonomy list is provided by a term reference field the actual form element will be found somewhere like this:

```
$form['field_field_name']['und'][0]['tid']

```

Using that example your form alter would look like this:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
    $form['field_field_name']['und'][0]['tid']['#options'][0] = '- Choose City -';
  }
}

```

Again you'll have to confirm using `dpm()` whether `0` is the right array key for the default select option that you're changing.
> 2 votes

---
Tags: forms, database
---