# Question
Title: How can I open Poll for Anonymous users?
I wonder how I can open my poll for everyone including anonymous users, not just registered users.

# Answer
> 3 votes
Visit admin/user/permissions and check the checkbox for vote on polls for anonymous.

---
Tags: 6, polls
---


# Question
Title: Is it possible to change a view from a user view to a node view?
I have a view that has a couple of displays and a lot of complex field definitions. I now realize the view may have been created by cloning the wrong starter view. Something went wrong such that the view is based on user and the base\_table = 'user' when it should be based on nodes. Can I change it to be based on nodes? Or is there a quick way to add my display and field definitions to a newly created node view, perhaps by exporting both and copying over bits of the code? I'm using Views 2.

# Answer
> 0 votes
There is no automatic way to convert a user view to a node view or vice versa.

Although you probably could get away with manually combining the fields from the export of your user view with a plain export of a new node view, it would be faster and a lot less problematic to just open the old view and your new view side by side in two browser windows and recreate everything.

Unfortunately a lot of Drupal site building is just checking checkboxes...

---
Tags: 6, views
---


title: How to add multiple items to cart?

text:
# Question
Title: How to add multiple items to cart?
I came across this other question and wondered whether it was compatible with Drupal 6/UC 2: Add multiple items to cart

I would like to create a page that shows the thumbnail and title of all products in a category, with a checkbox next to each one. Then, when a shopper checks three, four, five products and clicks "add to cart", those products are all added to the cart.

Or... even better would be if the product automatically gets added to the cart when they click the checkbox, and they can then click a link to go to the cart and finalize their order after they have added all of the products they want... but I know that may be asking a bit too much. ;)

I'm thinking it would be nice for the mobile environment too... the phone/tablet user could simply tap-tap-tap the products they want and then proceed to their cart.

Can anyone point me in the right direction for this?

# Answer
For a list with checkboxes I suggest looking at this issue about using Views Bulk Operations.
> 0 votes

---
Tags: 6, ubercart
---


# Question
Title: How to build a custom block with a image field
I want to build a custom block in Drupal 7 that instead of the standard title/text-format contains a single image field. It will be used on the front-page and allow a non-HTML-speaking editor to easily upload and update the big front image that will be shown there. Since there will be only one block I feel a block is more appropriate than a content type. I've built a bunch of custom blocks for Drupal 6, but they were all textfield-based, and I'm not sure how I should approach the problem now that I need a image-upload-field. Does anyone want to point me in the right direction? How do I build the image field from within `hook_block_view`?

# Answer
You could create (anyway) a content type and use the module Node Blocks. Every content you create with this content type are automatically available as block. Maybe a bit overhead if you just need to create one.

Another solution may be the BEAN Module. But just dropping the module name, never worked with it.
> 2 votes

# Answer
If you've made blocks before (in code). Make a block in code that pulls an uploaded image from the site to display within your frontpage block.

Then make an admin menu item / page for your user, with a simple FAPI form that uses the managed\_file element type to allow them to upload an image.

Then in the form\_submit function save the fid of the uploaded image using like `variable_set('mytheme_frontpage_image', $form_values['values']['fid'])`.

It's not tons of code: hook\_block ... you can use image\_styles if you want, hook\_menu and FAPI for the admin form.
> 0 votes

# Answer
After some research I stumbled upon the Image Block-module which solved the problem for this time though I'm not totally sold on the UX. But it has some advantages over the suggested solutions:

* It provides a single image-field without the possibility to screw it up by accidently enter other text (as would be the case with a regular text-field+wysiwyg solution)
* It gives the editor the ability to reach the edit screen when he/she can change the image via a context-menu attached to the image itself: no need for a settings page somewhere else in the system, and easy to remember.
* It doesn't rely on a content-type, which I feel would be a bit over the top (as suggested) since I would just have needed one node.

Thanks for all the suggestions though!
> 0 votes

---
Tags: 7, entities, blocks
---


title: Get path like path/*

text:
# Question
Title: Get path like path/*
I'm writing a module and there is a text area where the users have to add paths; then, I explode these paths, and run some commands.

I would like to let users add something like "path/\*" (as in context conditions).
Is it possible?

# Answer
First get a list of all paths, and then check each path. Here is a quick example, and see drupal\_match\_path():

```
<?php
  // $paths would be the value of the textarea,
  //    with path expressions separated by newlines
  $paths = "mypath/*\nmy-page-name\ntopics/cheese*";
  $aliases = db_query("SELECT alias FROM {url_alias}")->fetchCol();

  $matches = array();

  foreach ($aliases as $alias) {
    if (drupal_match_path($alias, $paths)) {
      $matches[] = $alias;
    }
  }

?>

```
> 1 votes

---
Tags: uri
---


title: How do you theme a Quiz Question?

text:
# Question
Title: How do you theme a Quiz Question?
I have a True/False Quiz module question that I want to theme the output on...basically wrap the question with some extra stuff. I grabbed the truefalse-answering-form.tpl.php file from the module folder, copied it to my theme folder and made the needed changes, but my overriden theme file isn't being loaded.

I cleared the caches and still no luck.

Devel Themer isn't really providing me with useful info either...

Has anyone successfully themed a Quiz Module Question? Is there something extra that needs to be done?

# Answer
> 1 votes
Override quiz-single-question-node.tpl.php

---
Tags: theming, quiz
---


# Question
Title: Set up a Git version control repository that integrates with OpenAtrium
Is it possible to have OpenAtrium function like the git repository on Drupal.org?

If so, then how can I do it?

# Answer
> 1 votes
Check out the "What theme and modules does Drupal.org use?" page.

Specifically for Git repository management, you'll want to use this set of modules:

And if you want a project release / issue tracking section like drupal.org, see:

---
Tags: version-control, distributions
---


# Question
Title: How can I tell if module_load_include() is working?
I'm getting errors such as

```
Fatal error: Call to undefined function webform_expand_select_ids()

```

and so I'm trying to include all the includes in `/sites/all/modules/webform/components`.

I'm not even sure if that's going to help, but to help figure that out I was hoping that I could at least check and see whether `module_load_include()` is successfully including files?

```
  if ($form['#form_id'] == 'quiz_answer_key_node_form'){
    $url = "./sites/all/modules/webform/components/*.inc";
    $filenames = glob("$url");
    $type = 'inc';
    $module = 'webform';
    foreach ($filenames as $filename)
    {
       dsm(module_load_include($type, $module, $filename));
    }
}

```

# Answer
`module_load_include()` returns `FALSE` if it can't find the file, and the full path to the file included if it can find the file, and it was successfully included. In addition to that, it uses `require_once` which will throw a fatal `E_COMPILE_ERROR` error if the file is not found.

An easy way to debug would be to use code like this in your loop:

```
$file_path = module_load_include($type, $module, $filename);

if ($file_path === FALSE) {
  dpm('Failed to include: ' . $filename);
}
else {
  dpm('Successfully included: ' . $file_path);
}

```

That will give you a pretty solid answer as to whether or not the files are being included. If you get no debug messages, you know that the `glob()` isn't returning the list of files that it should be.
> 1 votes

---
Tags: debugging
---


# Question
Title: What's the coding standard for class constants?
For general constants, Coding standards / Naming Conventions says that constants should always be all-uppercase, with underscores to separate words and that module-defined constant names should also be prefixed by the module module machine name, all-uppercase, and an underscore character.

Object-oriented names don't follow the normal conventions of prefixing the name with the module or using underscores; instead, they opt for various forms of camel case.

Unfortunately, Object-oriented code doesn't mention class constants at all.

Which of the following is correct?

* `const FOO_CONSTANT_VALUE = 'bar';`
* `const CONSTANT_VALUE = 'bar';`
* `const constantValue = 'bar';`

# Answer
> 3 votes
The correct one would be:

```
class Foo {
  const CONSTANT_VALUE = 'bar';
}

```

For example, quoting after Zend Framework naming conventions (however there are many others for different frameworks, just Google around):

> Constants may contain both alphanumeric characters and underscores. Numbers are permitted in constant names.
>
> All letters used in a constant name must be capitalized, while all words in a constant name must be separated by underscore characters.
>
> For example, EMBED\_SUPPRESS\_EMBED\_EXCEPTION is permitted but EMBED\_SUPPRESSEMBEDEXCEPTION is not.
>
> Constants must be defined as class members with the "const" modifier. Defining constants in the global scope with the "define" function is permitted but strongly discouraged.

It does not explicitely say anything about `FOO_CONSTANT_VALUE` vs `CONSTANT_VALUE`, but not using class name in constant name is general practice. Which perfectly makes sense, considering that you are in class scope.

# Answer
> 1 votes
What reported from the Drupal coding standards about constants is still valid for constants defined in classes. The only difference is that constants defined from a class don't need any prefix that identify the module that defines the constants; that prefix would be eventually added to the class name.

There isn't the need to add a prefix that is derived from the class name to the constant name, as `Foo::CONSTANT_NAME` is different from `Bar::CONSTANT_NAME`, and PHP will not throw an error when both the constants are defined.

---
Tags: coding-standards
---


title: How do I asynchronously run things?

text:
# Question
Title: How do I asynchronously run things?
I used Drupal 7.14, Video Module 7.x-2.5, VideoJS 7.x-2.0 HTML5 player, and ffmpeg 0.7.2 to transcode a 200mb mp4 video into Ogg, Flv, MP4 formats. The process worked, but took over 1 hour. Using the command line, I can file transfer and transcode same file in under 15 minutes.

Aside from upping server processing power, or wishing that Drush handled video transcoding via ffmpeg, is anyone else off-loading Drupal processes via PhP Process Forking, or Asynchronously via Javascript, ie. node.js?

Ideally, once I click save on any Drupal form, a child process should spawn and work on the side, as I go about doing other things, without my admin interface locking up to process one thing (synchronous coding). Thanks for your time,

# Answer
Look into the HTTP Parallel Request & Threading Library. The Imageinfo Cache module uses it to generate imagecache presets when a file is uploaded on a node form, and does a final check on node save; all in the background. The other module to look into using is Background Process, it does similar thing as HTTPRL and the 2 modules are actually looking to merge together (http://drupal.org/node/1357652).

An example of how to flush caches in the background is in the httprl readme
> 4 votes

# Answer
You can use hook\_cron() to add this to the next cron job.
> 0 votes

---
Tags: performance
---


# Question
Title: Creating a file object from a file already in public:// (drupal 7)
I am currently writing a module that will unzip a .zip file after it has been uploaded. Once this file is unzipped I want to search through it and find certain types of files and create content types that have file or image fields that reference these files, but in order to populate the image and file fields I need to create a file object. How could I do this without having to duplicate the files that have already been uploaded and unzipped?

# Answer
> 16 votes
I think the easiest way would be to create a file object manually, populate it with the file details, and save it using `file_save()`:

```
global $user;
$uri = 'public://path/to/file.txt';
$filename = 'file.txt';

$file = new stdClass;
$file->uid = $user->uid;
$file->filename = $filename;
$file->uri = $uri;
$file->filemime = 'text/plain';
$file->filesize = filesize($uri);
$file->status = 1;

file_save($file);

```

After you've done that you'll probably also want to use the `file_usage_add()` function to declare a vested interest in the file, so that it doesn't get deleted by any other system process:

```
$type = 'some_type'; // A string used by your module to identify this type of file entry
$id = 'some_id'; // An identifier used by your module to identify this particular file

file_usage_add($file, 'MYMODULE', $type, $id);

```

---
Tags: 7, files
---


# Question
Title: Views Output Field as Link: Change link text
I've got a View showing some images. I want to include a link to the image which automatically downloads the file. I'm using the DownloadFile module which makes sure the browser actually downloads the image instead of just displaying it.

I've added the Image field that I want displayed in my View, and I'm checking the `Output this field as a link` but I don't see any field where I can control the link text. I see title, rel, etc., but I want the actual link text to simply say "Download".

i.e.:

```
<a href='...'>Download</a>

```

How can I control the link text of the link being rendered by Views?

# Answer
While editing your view, open the field you want to modify. In your case it would be your Image field that current output's `<a href='...'>Download</a>`

Scroll to 'Rewrite Results' and check the box next to 'Rewrite the output of this field.'

Enter the text that you would like to display instead of 'Download.'

I believe if you use the Tokens module, you will have several variables accessible to you as well. See "Replacement Patterns" in the same menu to see what is available.
> 5 votes

---
Tags: 7, views
---


# Question
Title: How can I serve js and css from Drupal 7
I'm very new to Drupal and I have a bunch of sites to manage that are in different cms's like wordpress, sharepoint and others. My goal is to merge all the content into drupal over time.

I want to manage a master menu in Drupal and when items are added or removed generate a html code snippet representing the menu that the other sites can pick up from the local file system or via a url if they are not.

How can I serve content from a url without the themes and drupal html being applied?

eg

have this url serve a css file

```
http://localhost/css/global.css

```

or get a js file from

```
http://localhost/js/app.js

```

or from a url like this

```
 http://localhost/globalmenu.html

```

get this html snippet ONLY

```
 <div class="nav">
   <ul>
     <li><a href="">Menu Item 1</a></li>
     <li><a href="">Menu Item 2</a></li>
     <li><a href="">Menu Item 3</a></li>
   </ul>
 </div>

```

*** EDIT *** The answer about the menu hook is really close to what i want, but I think i may have confused things by mentioning menus at all.

So I apologise as I didn't make what I am after very clear. Ill try and reword it.

For an arbitrary url I want to return content of any kind from the drupal 7 cms.

Which 'hook' takes the url, matches it to a pattern, and then allows me to send anything back on the response stream, and how do I change the mime types.

# Answer
You'll need a custom module for this (see the Module Developer's Guide if you're not already familiar with creating modules, it's pretty straightforward).

Once you've got your custom module set up you need to implement `hook_menu()` and define a callback function for your URL:

```
function MYMODULE_menu() {
  $items['globalmenu.html'] = array(
    'title' => 'Global Menu',
    'access callback' => TRUE, // If you want any source to be able to access this page
    'page callback' => 'MYMODULE_deliver_global_menu'
  );

  return $items;
}

function MYMODULE_deliver_global_menu() {
  print '<div class="nav">...';
  drupal_exit();
}

```

Since Drupal will only actually apply the theme wrappers to a page if something is returned from the page callback, simply printing your HTML and calling `drupal_exit()` is all you need to do.

Sorry if some of that is stuff you already know, I thought it best to err on the side of caution.
> 1 votes

# Answer
There is another simplest way using hook\_preprocess.

```
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  if (!empty($node) && $node->nid == $the_specific_node_id) {
    drupal_add_js(path_to_theme() . "/file.js", "theme");
    drupal_add_css(path_to_theme(). "/file.css", "theme");
  }
}

```

Insert this function in your theme's `template.php` file

See theme functions here
> 1 votes

---
Tags: 7, nodes
---


title: Content types do not get listed

text:
# Question
Title: Content types do not get listed
When I am logged-in as administrator, I click on *content*, then *add content*, and I get a message saying I have no content types created, and I must create new ones. In fact, though, I have several content types, and I have been using them for days to build my site.

Do you have any idea on where the glitch is?

# Answer
It would appear that this is a very good candidate for your issue:

http://drupal.org/node/997444

Assuming you have altered your navigation menu, which many people will do when they are new, you may have inadvertently removed your access. Re-enable this access and you should be good to go. If this does not solve the problem I do not know what it would be.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Altering a form to set it's target to _parent
I have a form in an iframe, when the form gets submitted I need the target to be \_parent.

How do we add `target="_parent"` to a form element in drupal 7. I am pretty sure hook\_form\_alter is the best way to go just not sure about what var gets edited and how.

-thanks.

# Answer
> 0 votes
Just use `$form['#attributes']['target'] = '_parent'`. If the form is implemented from another module, you can use hook\_form\_alter(), or hook\_FORM\_ID\_alter() to add that attribute.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form ID for the form you need to target') {
    $form['#attributes']['target'] = '_parent';
  }
}

```

# Answer
> 0 votes
to change your form you can use hook\_form\_alter example

```
function login_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id=="user_login_block")
    {
         $items[] = '<a id="fpassword" target="_parent" title ="'.t('Request new password via e-mail.').'" href="#">'.t('Request new password').'<a>';
         $form['links'] = array('#markup' => theme('item_list', array('items' => $items)));
    }
}

```

---
Tags: forms
---


# Question
Title: How can I show images upon click in a lightbox using the Full HTML text format?
I'm using the Lightbox 2 module on Drupal 7. I have added an image field to my Basic Page content type. On one particular page, I have uploaded several images into that field, which I then inserted into the body (text format: Full HTML) using the Insert module.

Since the images are small, I want to allow users to click on them to open them in a lightbox on the same page. I read through the lightbox documentation but it seems like it hasn't really been updated for Drupal 7.

I tried the following:

```
<a href="/sites/default/files/styles/medium/public/page_screenshots/review.png" rel="lightbox" class="image-large" title="review">
<div style="text-align: center;"><img src="/sites/default/files/styles/medium/public/page_screenshots/review.png" alt="review" title="review" class="image-medium" /></div>
</a>

```

However, in this case, when I click the image, nothing happens. When I add some text, however, like this:

```
<a href="/sites/default/files/styles/medium/public/page_screenshots/review.png" rel="lightbox" class="image-large" title="review">
click here for the image</a>

```

The lightbox appears when the text is clicked. However, I want to show the lightbox when an image is clicked, not when text is clicked. How can I do this?

# Answer
> 1 votes
I think the Lightbox is not really the best choice for Drupal 7. Have a look at the very powerfull Colorbox Module.

---
Tags: media, javascript
---


# Question
Title: Call to undefined function node_mass_update()
In `hook_form_alter()`, I am using the following code.

```
if ($form_id == 'album_node_form') {
  $form['actions']['unpublish'] = array(
    '#type' => 'submit',
    '#value' => t('Unpublish'),
    '#submit' => array('az_alter_unpublish')
  );

  // …
}

```

In `az_alter_unpublish()`, I am using the following code.

```
function az_alter_unpublish($form, $form_state) {
  $nodes = array();
  // $nodes is an array of node IDs for the nodes I want to unpublish.
  node_mass_update($nodes, array(array('status' => 0)));

  // …
}

```

This returns a fatal error.

I read the function documentation, but I can't find out the problem.

# Answer
> 0 votes
The solution for this problem is to include the node.admin.inc file.

```
 module_load_include('inc', 'node', 'node.admin');
 node_mass_update($nodes,array(array('status' => 0)));

```

---
Tags: forms
---


# Question
Title: How do I remove the arrows from the breadcrumbs?
How do I remove "\>\>" from the breadcrumbs?

I need to remove those characters because in my site, the breadcrumbs appear like in the following screenshot.

This is the code that generates the breadcrumbs.

```
$temp = "</a>" . $title . "</a></div>";
$breadcrumb = str_replace("</a></div>", $temp, $breadcrumb);
print($breadcrumb);

```

# Answer
> 2 votes
You can override theme\_breadcrumb() function in your theme. As mentioned in the below code.

```
function yourthemename_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';

    $output .= '<div class="breadcrumb">' . implode(' » ', $breadcrumb) . '</div>';
    return $output;
  }
}

```

Just write above code in your template.php and change *\>\>* to whatever you want.

# Answer
> 0 votes
You can fully customize how you'd like to have your breadcrumps, see http://api.drupal.org/api/drupal/includes!theme.inc/function/theme\_breadcrumb/7

---
Tags: breadcrumbs
---


# Question
Title: How to call default node validation functions
I have a custom node-creation form for which I have my own validation function. How can I make sure that after my validation function the form goes through the same validation that it would have done on the original node-creation form?
Some thing like `node_validate` looks like the kind of thing I need, but it works on `$node` objects rather than forms.
The order of operations I perceive to be the best is

1. On submit run custom validation
2. If custom validation passes run the normal node validation
3. If node validation succeeds insert values in the database

Is that a good and Drupal way?

# Answer
> 2 votes
If your form has a structure similar to the one used for the node edit form, then you can use `node_validate()`, which is called from the form validation handler for the node edit form.

```
function node_form_validate($form, &$form_state) {
  node_validate($form_state['values'], $form);
}

```

`node_validate()` converts the first argument in an object using the following code.

```
  // Convert the node to an object, if necessary.
  $node = (object) $node;
  $type = node_get_types('type', $node);

```

Your form validation handler's code should be similar to the following one.

```
function mymodule_form_validate($form, &$form_state) {
  // Run your validation code.
  node_validate($form_state['values'], $form);
}

```

As general rule, the validation code should go in the form validation handler. If the form validation handler set any error, the form submission handler is not called, and the user is returned to the form to correct what is wrong in the data that has been submitted.

# Answer
> 1 votes
`node_validate()` will solve the problem. The original validation process will not be affected.

---
Tags: nodes, forms
---


# Question
Title: Problem in uploading an image to my drupal site
My Drupal site contains images and videos of an event. I got a problem with image module. When I am uploading image an error `"The file could not be uploaded"` is displayed. I set the formats as jpg, jpeg, png.

I have a similar site in another server but it is free from this issue. It is uploading images smoothly.

How can I solve this?

# Answer
You check the permissions on the `sites/default/files` folder. Using linux you could execute `sudo chmod -R 755 <foldername>` from your terminal.

A good idea could also be to check your log files in order to track down the error. For example if you are running apache you could check the `/var/log/apache2/error_log` to see what goes wrong.
> 4 votes

# Answer
The problem may be in the size of image check the file upload limit and also the permission because image module works with proper permission.
> 2 votes

---
Tags: media
---


# Question
Title: Password-protect page and its dependencies
I haved a Views-generated page, listing links to some downloadable files. The page itself is restricted to a certain role, and this obviously works ok, but I would also like to protect all the links listed on the page.

Currently, an authenticated user with a privilege to view the page, can send a working download link to anonymous user, which is not ok.

Of course, I could certainly protect the files directory with htaccess, but I would like to manage the access and session validity from Drupal.

Has anybody solved a similar setup? Are there any modules for that?

# Answer
> 2 votes
Webform protected downloads seems to be an answer.

# Answer
> 0 votes
If you are using D6, http://drupal.org/project/filefield\_stats might be of help in that it would at least not allow the sending of a working link to another user.

---
Tags: 7, files, users
---


title: Storing User preferences in Drupal

text:
# Question
Title: Storing User preferences in Drupal
I recently developed a module where I used the `function hook_form_user_profile_form_alter(&$form, &$form_state)` to capture user preferences and saved them using `function hook_user_presave(&$edit, $account, $category)` . Then I accessed the data using $user-\>data\['field'\] in a module . That worked fine .

But now I want to store the same preferences using another form (not the user profile form). So is there any other hook to store them ?

I want to give a link to each user to the page(form other than the user profile ) where he can store his preferences .

Thanks in advance.

# Answer
You don't need to use a hook you need to use the API function `user_save()`. Which is a very weird function because unlike all other save functions, it has a separate argument for the things that you want to change.

Something like this should work, in your submit callback:

```
<?php
// Make sure you are working with the fully loaded user object.
$account = user_load($GLOBALS['user']->uid);
$edit['data']['your_stuff'] = $whatever;
user_save($account, $edit);
?>

```

FYI: user\_save() is no more in Drupal 8 and instead behaves like all other entity save functions/methods in 8.x, by calling $account-\>save() after changing $account. See the following change record for details: http://drupal.org/node/1554986
> 8 votes

# Answer
Well you can always create your own form using the Form API with a validate and submit function and save the data where ever you want. That could be in the user data array as well, as it looks to be the perfect place for user related data. You could also create your own table with the Schema API. I think the "submit" function for the form is the "hook" you are looking for.

Form API: http://api.drupal.org/api/drupal/includes%21form.inc/group/form\_api/7

Schema API: http://api.drupal.org/api/drupal/includes%21database%21schema.inc/group/schemaapi/7
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to get All options of a 'select' field?
How can I get all options for a cck field?

For example, There is a field with 3 options in allowed values, like option1, option2, option3.Is there any function which receive the field name and returns option1 to option3?

# Answer
In Drupal 7 you can use field\_info\_field(), while in Drupal 6 you can use content\_field\_instance\_read(), which is defined in the CCK module.

As @Lauri said:

You can also use list\_allowed\_values().

```
$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);

```
> 8 votes

# Answer
You can also use list\_allowed\_values().

```
$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);

```
> 41 votes

---
Tags: 7
---


# Question
Title: Correct way to display a custom field in a custom content type page template
I'm using Drupal 7 with a custom content type called "lesson". In this custom content type I have a custom field named "field\_lesson\_objective". I'd like to be able to wrap this in a custom div, so I thought it would be pretty simple to open up my custom page template "page--lesson.tpl.php", remove "", and replace that with something that would display the field, but I'm having no luck finding a solution.

Perhaps I'm going about this all wrong.

# Answer
Ok, figured this out. I copied node.tpl.php to my templates directory in my theme, and then duplicated that with the name of of custom content type:

node--lesson.tpl.php

I was then able to display my custom field with this:

```
<?php
   echo render($content['field_lesson_objective']);
?>

```
> 2 votes

---
Tags: entities
---


# Question
Title: Alter the results returned by "Display a summary" for the Addressfield module
When I set contextual filters in a view for *Content: my field: country* and *Content: my field: administrative area* (state/province) and select "Display a summary" for "When the filter value is not available", it returns a list of country/administrative area codes (e.g. "JP"), not the names of the country/administrative area (e.g. "Japan").

How can I show the names of the countries/administrative areas instead of the codes?

# Answer
Okay, well the major issue with this particular field is that id doesn't have all the properties you need to go through the standard routes to display the term instead of the id.

So, without a major rewrite of the module I would do this if you really need this feature.

Copy the views-view-summary-unformatted.tpl.php to your admin theme directory and edit it to include a large switch statement with all of the country codes you are interested in, probably copied in from the module itself. Here is a working example of one such modification for your example of Japan. Obviously this is not ideal, but without altering the field information of the module there is no good way to link the Key used here with the value. Sorry there does not seem to be a better way.

```
    <?php
    /**
     * @file views-view-summary-unformatted.tpl.php
     */
    ?>
    <?php foreach ($rows as $id => $row): ?>
      <?php print (!empty($options['inline']) ? '<span' : '<div') . ' class="views-summary views-summary-unformatted">'; ?>
        <?php if (!empty($row->separator)) { print $row->separator; } ?>
        <a href="<?php print $row->url; ?>"<?php print !empty($row_classes[$id]) ? ' class="' . $row_classes[$id] . '"' : ''; ?>>
        <?php
         include_once DRUPAL_ROOT . '/includes/locale.inc';
         $countries = country_get_list();
         if($countries[$row->link]) {
            print $countries[$row->link];
         }
         else {
          print $row->link;
         }
        ?></a>
        <?php if (!empty($options['count'])): ?>
          (<?php print $row->count; ?>)
        <?php endif; ?>
      <?php print !empty($options['inline']) ? '</span>' : '</div>'; ?>
    <?php endforeach; ?>

```
> 3 votes

# Answer
Here is an alternative to @Kenny and @Bearden solution, using template preprocess instead of overriding the template. Not only it makes for a more readable solution, you can reuse it for other views. It should also work for list summaries, just remove `_unformatted` from the function name.

```
/**
 * Implements hook_preprocess_views_view_summary_unformatted().
 */
function MYTHEME_preprocess_views_view_summary_unformatted($variables) {
  if ($variables['view']->name == MYVIEW) {
    // Necessary for country_get_list().
    include_once DRUPAL_ROOT . '/includes/locale.inc';
    $countries = country_get_list();

    // Looping through the row keys for performance reasons.
    foreach (array_keys($variables['rows']) as $rowid) {
      $countryid = $variables['rows'][$rowid]->link;
      if (!empty($countries[$countryid])) {
        $variables['rows'][$rowid]->link = $countries[$countryid];
      }
    }
  }
}

```
> 4 votes

# Answer
You can use the locale.module function country\_get\_list() which will give you an array of country codes and their full names. You should be able to simply use this array to find your code (as the key) and get the resulting country name.

As an example you should be able to do something like this to find the readable name of the US (untested):

```
$countries = country_get_list()
$us_code = $countries['US'];
return $us_code;

```
> 2 votes

---
Tags: 7, location, entities
---


# Question
Title: Drupal 7 View - How to show content based on conditions
I've a travel portal and I've create a content type Destinations which I use to create content for main Destination page Continent, Countries, states and cities. This content type has uses Location module as a field.

Then I create a page e.g. Thailand which is of type Destinations.

I've create a block view to show the links to cities/countries/continents on country/continent/main destination pages.

So on my main Destination page I want to list all continents and countries, then on countries pages I want to list all states and cities, on state pages I want to show all cities.

Would it be possible to utilize the Location module to achieve this?

I'm using location to identify many type of content, e.g. Hotels, Places, Museums etc.

Or shall I use Taxonomy/Terms.

Or any other alternative ways to achieve this?

# Answer
I think it would be easier to use hierarchical taxonomy tree, this would definitely make your life much easier when creating views listing child taxonomy terms or content tagged with child terms...
> 2 votes

# Answer
I dare to say that a simple text list (dropdown): City/Country/Continent/ etc would suffice, unless the tagging has to be open for public to add more terms.
> 0 votes

---
Tags: views, entities, location
---


# Question
Title: using hook_update to add a new cck field
I am using d6.

I have a live site with an already built content type. I needed an extra column in the table, so I added this on install... I know realize how limiting this is and have rebuilt the content type to include this column as a field and I have unset the field in the form.

I have updated the code for this content type to include the new field, but when I move the code to my dev site, I do not see the new field.

Note: The content type was exported to code using the features module.

I thought maybe I need to run hook\_update, but I haven't worked out how to do this.

This is what I have so far.

```
function mymoduel_update_6004(){
  #REF: http://drupal.org/node/1031548
  drupal_load('module', 'content');
  drupal_load('module', 'mymodule');
  content_notify('install', 'mymodule');
  content_notify('enable', 'mymodule');
  return array();
}

```

I run update.php... but no visible changes :(

Has anyone got any ideas how I can update my cck content types?

# Answer
After hours of searching, I finally found a post by Drewish that solves this.

http://drewish.com/node/118

The key to this is letting drupal core know you want to create a new field instance using

content\_field\_instance\_create()
> 1 votes

---
Tags: 6, entities, updating, features
---


# Question
Title: Using drupal login system for another platform
I want to create another site that uses the drupal user login / registration system so that it is integrated with my drupal site. This would allow current users to use this other service without having to register again. Can someone let me know if this is possible? Sharing login cookie / registration / user validation...etc.

I am using drupal 7.

# Answer
The Services module provides an HTTP REST API for authentication (amongst other things). So it should be easily usable to let a remote/separated site re-use your Drupal web site user authentication. The following code comes from its documentation and illustrate how to use it for user authentication. The returned user object will contain the session name and id to use in future REST request if more data from the Drupal are needed (for instance to retrieve user profile or content).

```
// REST Server URL
$request_url = 'http://your-drupal/rest_server_endpoint/user/login';

// User data
$user_data = array(
  'username' => 'user_name',
  'password' => 'user_password',
);
$user_data = http_build_query($user_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $logged_user = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die($http_message);
}

```
> 4 votes

---
Tags: users
---


# Question
Title: Add 2 filters for a single field in views
I am writing a view code for my module, stuck with writing 2 filters for a single field.

```
 $data['taguser']['tag_uid'] = array(
    'title' => t('Tagged user'),
    'field' => array(
      'handler' => 'taguser_views_handler_field_user_name',
      'help' => t('Display the user name the Item has been assigned to.'),
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'taguser_views_handler_filter_user_options',
      'help' => t('Filter Action Items by the assigned user.'),
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_user_uid',
      'help' => t('Filter Acton Item by the assigned user.'),
    ),
    'relationship' => array(
      'help' => t('Relate a case to the user who have been assigned to the case.'),
      'handler' => 'views_handler_relationship',
      'base' => 'users',
      'base field' => 'uid',
      'label' => t('Assigned to'),
    ),
  );

```

i want another filter for this field like

```
'filter' => array(
  'handler' => 'taguser_views_handler_filter_user_options_list',
  'help' => t('Only limited user.'),
),

```

how can i add to it ??

# Answer
It depends on your version of views, best way is to create the view in views and then export it, you can then tweak the code as needed.

Here is an example if you had a **Node Type** Filter and a **Date** Filter

```
/* Filter: Node: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'rfp' => 'rfp',
);
/* Filter: Date: Date (node) */
$handler->display->display_options['filters']['date_filter']['id'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['table'] = 'node';
$handler->display->display_options['filters']['date_filter']['field'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['operator'] = '>=';
$handler->display->display_options['filters']['date_filter']['value']['min'] = '2012-01-01 00:00:00';
$handler->display->display_options['filters']['date_filter']['value']['max'] = '2012-01-01 00:00:00';
$handler->display->display_options['filters']['date_filter']['exposed'] = TRUE;
$handler->display->display_options['filters']['date_filter']['expose']['operator'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['label'] = 'Date: Date (node)';
$handler->display->display_options['filters']['date_filter']['expose']['identifier'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['expose']['single'] = TRUE;
$handler->display->display_options['filters']['date_filter']['date_fields'] = array(
  'node.changed' => 'node.changed',
);

```
> 0 votes

---
Tags: views, 6
---


# Question
Title: How to properly specify context for Drupal behaviours
I have this code that does not work. I know why it does not work - first time page is loaded 'context' is all page and jquery easely finds '.view-SPECIFICVIEW .view-content'. After AJAX 'context' has changed and it is now just '.view-SPECIFICVIEW' and inside that there is no class '.view-SPECIFICVIEW' and therefore nothing happens. Script works if I remove '.view-SPECIFICVIEW' from find(), but then all views are selected.

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
      attach: function(context, settings) {
        $(context).find('.view-SPECIFICVIEW .view-content').masonry({
          columnWidth : 300,
          gutterWidth : 20
        });
      }
    }
})(jQuery, Drupal, this, this.document);

```

I would like to have this code to work with '.view-SPECIFICVIEW' and also I would like to know how code changes if multiple, different specific views should be targeted.

# Answer
> 3 votes
Just stop using `context` in this case. I've been playing around with jQuery Masonry and I've not needed to use it.

```
(function ($){
  Drupal.behaviors.myModule ={
    attach: function(context, settings) {
      $('.view-SPECIFICVIEW .view-content').masonry({
        columnWidth : 300,
        gutterWidth : 20
      })
    }
  }
})(jQuery);

```

FYI, I'd also take a look at the Masonry recommendation to use the imagesLoaded plugin if there are images in your view. It takes a LOT of future frustration out.

# Answer
> 0 votes
Give this a try, Context acts as "live" so doing it this way will attach it to each instance of view-SPECIFICVIEW (this is if I understand what your asking)

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
      attach: function(context, settings) {
        $('.view-content',context).each(function(){
         /* ADD CODE HERE */
        });
      }
    }
})(jQuery, Drupal, this, this.document);

```

---
Tags: theming, javascript
---


# Question
Title: Login destination to file download - prompt user
we have some private file links that are pasted into emails. When a user clicks the link, if they are not logged in they get something like this:

http://mysite.com/user/login?destination=/system/files/private/myfile.docx

Once they login and authenticate, the file starts to download in the user's browser.

I'd like to override the automatic download behavior and provide a "download this file?" type prompt first, since users don't often realize the file download starts automatically.

Any ideas? Thanks in advance.

# Answer
Well, there are a few ways you could handle this. All of them are going to involve some code to handle these type of requests. One way I can think of would be to catch these requests on your custom 404 page and redirect the user to the login page with a new destination and keep the file name as a parameter. Then, on the new destination page grab the file download parameter and provide them a big fat button that links to that file.

If they are already logged in and you want to do the same thing you would need some sort of pre-processing filter to capture these and do the same as above.
> 1 votes

---
Tags: files
---


title: How to optimize D7 Views?

text:
# Question
Title: How to optimize D7 Views?
I would like to optimize Views as they cause most of my performance bottlenecks.

The MySQL slowlog shows not only Views related query times \> 5s but, what is more scary, selects with over 10 LEFT JOINs. I have already manually removed some columns from views. It was over 14 LEFT JOINs before...

Are there any solutions (without writing custom module queries) to eliminate or limit LEFT JOINs in Views select queries ?

I found there is the Shadow contrib module available. Is it ready for production website?

# Answer
I would use that contrib module. Beta releases are generally darn tight and seeing that it is beta3 would lend to the idea that it will soon be out of beta. (Of course it may never come out so that doesn't say much.) Also, the maintainer group seems to be high quality which gives me even more confidence.

To answer your other question I do not thing there is anything else you can do besides write something yourself. I was looking around and saw some initial phases of work being done on this but nothing as far along as that project you linked. I imagine this is something they will work on for D8. Your find is surprising. The only other place I might check if I were is IRC just to make sure that there isn't some other optimization technique or module out there that isn't Views specific but that will help. (Probably not, but worth a try.)
> 1 votes

---
Tags: 7, views
---


# Question
Title: How can I print something conditionally on node.tpl.php depending on what taxonomy term the node is tagged with?
For example, I would like to print something only when the currently viewed node is tagged with tid = 100. How can I do this?

# Answer
Can you try this...

```
<?php if ($node->taxonomy[100]): ?>
    print anything here
<?php endif; ?>

```
> 0 votes

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


# Question
Title: How to add extra menu source and access it in a theme
The Menu module contains 2 sources to assign menus to my site.

How do I add a 3rd source?

Reading through the Zen theme code, I see the variables `$main_menu`, and `$secondary_menu`.

I would like to access this 3rd menu source through a variable called `$global_menu`.

How do I set this variable from a module?

EDIT

I put this at the bottom of the zen\_proprocess\_page hook in template.php

```
$global_menu = menu_navigation_links('menu-global-menu');

```

and was able to access it with this in page.tpl.php so thank you for that advice

```
<?php if ($global_menu): ?>
   <div class="global-navigation">
      <ul class="nav">
      <?php foreach ($global_menu as $key => $value): ?>
        <li>
          <a href="<?php print($value["href"]); ?>" class="global-link" ><?php print($value["title"]); ?></a>
        </li>
      <?php endforeach;  ?>
    </ul>
    </div>
 <?php endif; ?>

```

EDIT

Moved multipart question to new question

# Answer
To be able to put it in a theme variable I think you're looking at something like the following. Please note I haven't tested this, but i should put you in the right direction.

In your `template.php` or a module:

```
function MYTHEME_preprocess_page($vars){
  $global_menu = menu_navigation_links('menu-global-menu');
  $vars['global_menu'] = theme('links__menu_global_menu', array('links' => $global_menu));
}

```

Then clear your theme registry/caches.
> 1 votes

# Answer
From what I understand you want a create a menu (called 'global menu') separate from the 'Main' and 'Secondary' menus,and you want to display that at a desired location in your theme.

The best way to do this is -

1. Create a new Menu from - YOURSITE/admin/structure/menu/add. Call it 'global menu'
2. Add links to it
3. Goto the blocks page and place the 'global menu' block (which is automatically generated for you after step #1) in the theme region of your choice - YOURSITE/admin/structure/block
> 0 votes

---
Tags: 7, routes
---


# Question
Title: $form_state['node'] Values Being Lost in Multistep Node Form After Ajax Click
I am really hoping someone might have an insight into this really troubling issue. I have got a custom node form which is presented as 4 multistep pages. In my third step, I have a bunch of ajax buttons which allow the user to save information. The problem is, after the ajax button has been clicked and we click the next 'page' button, all the $form\_state\['node'\] values from the previous pages are being lost. So, consequently, when I get to hook\_node\_insert, I have empty values from the first 3 pages.

However, the weird thing is, this only happens in a couple of my ajax buttons in that page. I have a few other ajax buttons, which, don't cause any such problem. This is the definition for one of the problematic buttons:

```
<?php
    //Add the cancel button to cancel the "Add New Product" form
    $form['newproduct']['fieldset']['cancel'] = array(
      '#type' => 'button',
      '#name' => 'Add New Product Cancel',
      '#value' => 'Cancel',
      '#ajax' => array(
        'callback' => 'MyModule_NewProduct_Cancel_ajax_callback',
        'wrapper' => 'MyModule_NewProduct_wrapper',
        'method' => 'replace',
      ),
      '#limit_validation_errors' => array(),
      '#submit' => array(),
    );
?>

```

This is the callback for that button:

```
<?php
function MyModule_NewProduct_Cancel_ajax_callback($form, &$form_state) {
  //Return the add new product button
  return $form['newproduct']['addnewproduct'];
}
?>

```

I know that I might not have included enough code to see the full problem, but was wondering if there was any problem with the my ajax button element definition. Would appreciate any help on this. Thank you.

Update!! - SOLVED - It was a limit\_validation\_errors problem. I didn't have that set for my 'next' buttons in hook\_form\_formid\_alter().

# Answer
You need to add a submit handler that has

```
$form_state['rebuild'] = TRUE;

```

Otherwise the form will actually submit, and the form\_state values will be purged.
> 1 votes

---
Tags: ajax, javascript
---


# Question
Title: Send login link in email to registered users
On my Drupal 6 website, there are around 400 users registered by site admin and none of then know that they are registered on the site. Now I want to increase the number of registered users but in a secure manner.

I want the registered users to be able to invite at most 5 people whom they think are the most eligible. This is very easy and has been done.

The problem is that to invite new users, the current users will need to login and I dont want them to know their username and password as they will be given to them later.

So the only solution that remains is that I send them a login link in their e-mail so that they can click on the link and get automatically logged in so they can invite 5 other people of their choice.

# Answer
You should be able to use the Login one time module for this.

> Login one time provides the ability to email one-time login links to users. You can also choose the pages they will land on.

I would imagine that the users might be able to change their own paswords after using this one time link. To prevent this, you should be able to use the Edit own user account permission module.

> This module manage edit permissions to the name, mail and password profile filed. You can manage permissions to the other profile entities by other admin menu settings.
> 1 votes

---
Tags: users
---


# Question
Title: D7 Simple form with an items catalog grid table
I need a form with a simple items catalog, user will enter quantities for each item and it will auto calculate sub total and total using javascript.

I am looking something like this:

Name: **_**

Email: **_**

Address: **_**

please select your items:

ID | Name | Price | Quantity | Sub Total

1 | Item 1 | $10 | \[**_**\] |

2 | Item 2 | $10 | \[**_**\] |

3 | Item 3 | $10 | \[**_**\] |

Total |

\[Submit\]

Is there some module available to develop this kind of form, or I'll have to develop some custom module? I tried with Webform module but with no luck.

Thanks

# Answer
I did it myself with the help of webform, webform\_table\_element module and by implementing a couple of hooks and a little jQuery snippet. A complete howto can be found here:

Drupal 7 Webform with an item catalog table element

Thanks.
> 1 votes

# Answer
If the Webform module gets you close to the result you want you could try altering the created form and adding additional bits that you need with hook\_form\_alter(). Creating a custom module and form is always an option and will offer you the most flexibility, but it might be quite a bit more work depending of your needs. If you start working with Drupal forms on the code level you can check out the Form API Reference page for a good source of information.
> 0 votes

---
Tags: 7, forms, webforms
---


title: Date argument as view filter

text:
# Question
Title: Date argument as view filter
I'm using Drupal 6.

I have a custom view that needs to be filtered by an argument passed by the user.

The argument is a simple date, and I need my query to be filtered like the following:

```
WHERE created >= %argument&

```

Where %argument% is the user argument passed within the URL.

The thing is, I manage to filter it, but only as equals, like this:

```
WHERE created = %argument&

```

Is there any way I can make it filter as `greater or equal to`?

# Answer
> 2 votes
I've found that Drupal 6 views dont support such feature.

The solution was to implement the `module_views_query_substitutions` hook and alter the query manually:

```
function module_views_query_substitutions($view)
{
    $view->query->where[0]['clauses'][3] =
        str_replace('=', '>=', $view->query->where[0]['clauses'][3]);
}

```

---
Tags: views
---


title: Webform in Lightbox, close in submit

text:
# Question
Title: Webform in Lightbox, close in submit
I have a form (webform) in a lightbox. I created a link:

```
<a class="lightbox-processed" rel="lightframe" href="?q=node/29/lightbox2">show Form</a>

```

and change 'page--node--lightbox2.tpl.php' (tpl from lightbox2 module) for this:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">
<head>
</head>
<body id="lightboxnode-<?php print $node->type ?>">

<?php //dsm($node); ?>

<?php if ($title): ?>
<h1 class="title"><?php print $title; ?></h1>
<?php endif; ?>
<?php
    $nodo = $node->nid;
    print render(node_view(node_load($nodo), 'full', NULL));
?>
</body>
 </html>

```

How can I do for when I click submit, send the form and close the lightbox?

# Answer
> 2 votes
I would use jQuery to detect the button click on the submit button and then force the action of closing the lightbox with `parent.Lightbox.end();`.

The reason I would use jQuery to attach to the event is that you don't have to alter the webform in any way, and can do this passively.

---
Tags: webforms, forms, javascript
---


# Question
Title: Changing default file permissions for group?
I'm not super familiar with the permissions structure in Drupal 7 so I'm not sure if this is actually an Apache question or a Drupal question.

I have a style.css file in /sites/all/themes/mytheme/css/ that I need to edit via FTP. That css folder also contains files that are edited via the Omega Tools UI. It appears that each time I use the UI to change style information, Drupal changes the owner of the css folder from ftpuser to www and gives it permissions 754 (group cannot write).

I am okay with the owner changing to www but I need to be able to edit my style.css file via FTP, so I need permissions to be 774. Is there a way I can set a default permissions structure on a folder or on Drupal in general that sets permissions to 774 instead of 754 whenever the system changes the owner of a folder?

# Answer
I don't believe Drupal or Omega will be setting the default permissions to 754, more likely it's a default that your webhost has configured. Things I would check would be:

* If you upload a file as ftpuser, does it default to 754? If so, then they have a default permission set to 754. You could contact the host to see if they are able to change that.
* If you manually create a file using PHP, does the file get created at 754? If so, same as above.
* If they're created at something other than 754, then it's likely Omega or Drupal that is doing that, but again I don't believe that's the case.

In any event, I've successfully gotten around this problem for many users by integrating a web-based file manager like IMCE, which allows you to manage files without using FTP.
> 1 votes

---
Tags: files
---


title: render full form

text:
# Question
Title: render full form
I need to render a full form, including the `<form>....</form>` tags. Any ideas how can I do that?

I tried `drupal_render()` and `render()`. The form elements are rendered but there is no `<form>` tag in the markup.

# Answer
> 1 votes
You need a properly formatted form array to render, which you get by calling `drupal_get_form()`. After that you just run it through `render()` as you're currently doing:

```
$form = drupal_get_form('form_id');
print render($form);

```

# Answer
> -1 votes
You need `theme_form()` in your form theme: `drupal_render()` your #children, then `theme_form()`.
And you can put HTML around the elements.

```
$buildform = '<div>'. drupal_render($form['element1']) .'</div>';
$buildform .= drupal_render($form['element2']);
$buildform .= drupal_render($form['form_build_id']);
$buildform .= drupal_render($form['form_id']);
$buildform .= drupal_render($form['form_token']);
$form['element']['#children'] = $buildform;
$output = theme_form($form);

```

---
Tags: 7, forms
---


# Question
Title: Change permissions or add roles on the fly
Is it possible to add permissions or add a different role to a user on one particular form/page and for those to be removed after the form has been submitted?

It is particularly for when one user creates a new user (using subuser module). They need "Administer Organic groups permissions: Administer all groups and permissions." permissions to set the new users organic group on creation, but they must not be allowed to edit other groups!

# Answer
Adding permissions on the fly would be hard without writing your own module.

However, maybe there are round-about ways of accomplishing what you need. Two suggestions:

1) You can add a taxonomy field to your user account that can be set and then use the rules module to automatically add new users to a certain group based on the terms they were tagged with during creation...

2) If you go to: admin/config/group/permissions/node/group, you can see that you can set permissions for members, non-members and admin members of a group, and you can set the 'add user' permission depending on those user group roles. If you set those to your liking, your workflow can then be a 2-step process: 1) create user account, 2) add user to whatever groups you need. It's more cumbersome, since it's a 2-step process, but only members or managers of a group will be able to add users to that group.

**Final note**: creating/editing permissions on the fly like you're thinking may have unintended consequences. You're saying that users should not be allowed to edit other groups, but if you try granting and revoking permissions based on opening and then submitting a form, you'll actually be giving users the ability to administer all groups until they submit that form! If they forget and don't submit it or leave it open in their browser for a long time, they'll potentially have that admin-level permission and see all relevant links, blocks and associated admin sections for a long time. So I suggest you try an approach like the above then attempting to grant 'temporary' permissions. :-)
> 1 votes

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


# Question
Title: Views: Display only first value from content field in a staff directory
I'm creating a staff directory for my library in Views. In one of the display field, Departments, staff often are assigned more than one departmental affiliation when I create their Content Profile. In this tabular view I'm creating, how can I make it so only the first value of the field representing departmental affiliation is displayed? It really clutters things up to display two or more departments in this table. I'd be happy to export the view & post it if that will help solve my problem.

Thanks,

Jason

# Answer
> 1 votes
I am assuming you are using Drupal 7 and Views 3. If that is true, then you could use the below -

Quoting from the comment here - http://drupal.org/node/1024158#comment-5064416

> Under fields, when you add your image field, one of the configuration options is "Multiple Field Settings". Under that make sure you check the box for "Display all values in the same row". The last line under this will ask how many items you want to display. Type "1". You can also specify which number to start with if you like. Hope this helps.

---
Tags: views, entities
---


# Question
Title: View fields from the same database column
So, I have serialized data within the uc\_orders table. This data has several parameters of interest each of which I want to create a unique field from.

Each one of these $data values work on their own. Obviously I am rewriting the value on the second declaration. How can I reference the same data location twice so that both of the fields can be used and I can explode all of my serialized data into separate fields?

```
  function uc_order_views_data() {
    $data['uc_orders']['data'] = array(
      'group' => t('Order') . ':data',
      'title' => t('Arrival Date'),
      'help' => t('Arrival date choosen by customer during checkout.'),
      'field' => array(
      'handler' =>'uc_order_handler_field_arrive_date',
        'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
    );

    $data['uc_orders']['data'] = array(
      'group' => t('Order') . ':data',
      'title' => t('Ship Date'),
      'help' => t('The date to ship the order by.'),
      'field' => array(
      'handler' =>'uc_order_handler_field_ship_date',
        'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
    );
  }

```

# Answer
> 0 votes
I finally found the answer.

```

  $data['uc_orders']['data2'] = array(
    'group' => t('Order') . ':data',
    'title' => t('Arrival Date'),
    'real field' => 'data',
    'help' => t('Arrival date choosen by customer during checkout.'),
    'field' => array(
    'handler' =>'uc_order_handler_field_arrive_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_string',
     ),
  );

  $data['uc_orders']['data'] = array(
    'group' => t('Order') . ':data',
    'title' => t('Ship Date'),
    'help' => t('The date to ship the order.'),
    'field' => array(
    'handler' =>'uc_order_handler_field_ship_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_string',
     ),
  );

```

The solution is to add `'real field' => 'field name',` and change the $data id.

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


# Question
Title: Different payment methods for different product types
Is there a way to have different payment methods available for different product types?

This is my scenario and what I've figured out so far:

I have two product types on my Drupal Commerce site, for selling bus travel passes. One type is just to book the bus pass where you select the date and times (custom line items) for your buss tickets. The other type is for actual payments, where you can choose a buss pass, add additional tours (with custom line items too) and then pay with Paypal.

I am using a customized version of the example payment module, for the booking payment type, and using the Drupal Commerce Paypal module for the actual payments.

What I need is to have the custom booking payment method available for one product type, and the paypal payment method for the other product type.

I have tried to add a condition for the product type and haven't been able to do this. We can add a condition for a particular product, but not for a product type. This would be ideal: https://skitch.com/ipwa/eywxa/add-a-new-condition-chasquibus

What I have done for now is to clone the Paypal rule for each payment product type, and selected that products SKU as a condition. This is not ideal, because if a user has more than one payment product, we get a duplicate Paypal payment method available for each additional payment product on the order. I guess this makes sense since we have a payment method rule for each one.

My solution would be able to have a condition for product type on the payment method rule, or be able to have the four payment products SKUs in a 'Order contains a particular product' condition.

# Answer
> 10 votes
The product's `type` is a property of the `commerce_product` entity, so you can use the built-in "Data comparison" condition to test it.

Just add a new condition of type "Data comparison", and make the data selector look like this:

When you continue you'll get a screen like this:

As you can see you get a nice drop down list of product types to choose from. I just tested that and it works a treat.

If that isn't working for whatever reason, it's pretty easy to implement your own rules condition in a custom module:

```
function MYMODULE_rules_condition_info() {
  return array(
    'commerce_product_is_type' => array(
      'label' => t('Product is a certain type'),
      'parameter' => array(
        'product' => array(
          'label' => t('Product'),
          'type' => 'commerce_product',
        ),
        'type' => array(
          'label' => t('Product Type (Machine Name)'),
          'type' => 'text'
        )
      ),
      'group' => t('Commerce Product'),
      'callbacks' => array(
        'execute' => 'MYMODULE_commerce_product_is_type',
      )
    ),
  );
}

function MYMODULE_commerce_product_is_type($product, $type) {
  return $product->type == $type;
}

```

---
Tags: commerce
---


title: Creating a sortable field

text:
# Question
Title: Creating a sortable field
I have a custom field declared and I am trying to make it sortable. The field holds date values already formatted ie: 06/10/12. How could I make this sortable? I thought this code would work but the header on the table doesn't become hyper linked even.

```
     function uc_order_views_data() {
      $data['uc_orders']['data'] = array(
        'group' => t('Order') . ':data',
        'title' => t('Ship Date'),
        'help' => t('The date to ship the order.'),
        'field' => array(
        'handler' =>'uc_order_handler_field_ship_date',
          'click sortable' => TRUE,
         ),
         'sort' => array(
           'handler' => 'views_handler_sort',
         ),
         'filter' => array(
           'handler' => 'views_handler_filter_string',
         ),
      );
     }

```

I do have the ability to send through a UNIX epoch timestamp instead if that would help me make this sortable so long as I can sort by the epoch but render it as a formatted date. **The fact that this is an extension of ubercart bears no factor on the result. Treat this question as if it were just a simple implementation of the views module, which in essence it is.**

# Answer
> 10 votes
I finally figured out the answer. Only took me a week.

Under the view settings there is a "Format" option, and beneath that there is a "Settings" link. Upon clicking there are options to make your new fields sort-able or not to the user. Adding `'click sortable' => TRUE` just exposes that radio button!

Good grief that was causing me some headaches! I was beating myself up on the code when it was a UI setting withing Drupal.

Something else to consider is the actual sorting. There are many different handlers for sorting fields. This particular field is a date. In order for this to work, the date needs to be stored as a UNIX time epoch. There are flags that I did not pass that can allow you to choose the granularity of the sort, (seconds, minutes, days, months, years).

This is what my code ended up looking like to make the date sort actually work as expected. When I stored the date as a UNIX time epoch.

```
/**
 * Implements hook_views_data().
 */
function uc_order_views_data() {
  $data['uc_orders']['data'] = array(
    'group' => t('Order:data'),
    'title' => t('Ship Date'),
    'help' => t('The date to ship the order.'),
    'field' => array(
      'handler' =>'uc_order_handler_field_ship_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort_date',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_date',
     ),
  );
}

```

Now, lets take a look at the uc\_order\_handler\_field\_ship\_date handler. You want to be sure that if you are not using the standard sort handler, that you extend the proper handler. If this date was not buried within some serialized data, I wouldn't even need this class and the default views handler would be sufficient.

```
class uc_order_handler_field_ship_date extends views_handler_field_date {
  /**
   * Overrides views_handler_field_date::render().
   */
  function render($values) {
    $data = unserialize($values->uc_orders_data);
    if (isset($data['fedex_calendar_ship_date'])) {
      $date = $data['fedex_calendar_ship_date'];
    }
    else {
      $date = "-";
    }
    return date('n/j/Y',$date);
  }
}

```

For more information on all of the sort handlers available see: http://api.drupal.org/api/views/handlers%21views\_handler\_sort.inc/class/views\_handler\_sort/7

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


# Question
Title: How to bring facebook connect button in login form?
For one of my projects I installed the Facebook O Auth module in my site. Now I would like to display the Connect with facebook in my login form.

# Answer
You have to alter both form using hook\_form\_alter and add a markup field with value `fboauth_action_display('connect')`

```
$form[fb_connect] = array(
   '#markup' => fboauth_action_display('connect'),
);

```
> 4 votes

---
Tags: 7, users, social-network
---


# Question
Title: Customise Drupal 7 Taxonomy View / Template (without module)
How would I go about changing a custom taxonomy view / template without using a module?

i.e. I have a taxonomy named 'tutorials' which has three posts.

How would I modify the HTML output for 'tutorials?

From what I've heard, you can create a file named 'taxonomy--name.tpl.php' to override the default taxonomy template?

Thanks!

# Answer
> 2 votes
As described in Drupal 7 Theme Hook Suggestions, the template files that Drupal looks for a taxonomy term page are the following:

* taxonomy-term--\[tid\].tpl.php
* taxonomy-term--\[vocabulary-machine-name\].tpl.php
* taxonomy-term.tpl.php

Replace *\[tid\]* with the taxonomy term ID, and *\[vocabulary-machine-name\]* with the machine name set for the vocabulary. Supposing that the machine name is programming\_languages, then the template filename that Drupal looks is taxonomy-term--programming-languages.tpl.php. (The underscores are replaced with hyphens.)

The first file that is found is the one that Drupal uses.

# Answer
> 0 votes
Basically, if you don't want to use any module, but are fine to carve in your PHP templates, then this taxonomy.module API is what you need. We could probably come up with more detailed help if you described your goal more precisely.

# Answer
> 0 votes
You can rewrite output in Views, and change Style (the HTML containers and classes) for each.

Did you mean without create a custom module? If so, there are several contrib taxonomy modules out there:

Taxonomy Formatter -- lets you add HTML wrappers around element and container Taxonomy Page Display -- create custom taxonomy page for each term (or certain terms) Display Suite - let you customize dang near any node or form

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


# Question
Title: User fields that are visible, but can't be manually edited
I have a web service that will be automatically populating certain attributes of a user's profile.

I am creating my fields via field api when the module is installed. I want all of the fields to be visible when editing the user profile, and some of these fields will be visible publicly as well.

My current plan is to form\_alter my away around the issue, but I was wondering if someone has an alternate approach they would take.

# Answer
Between the hooks used from the field API, there is hook\_field\_access(), which allows to define which users has access to a field when the entity is being viewed, or when the entity is being edited.

```
function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    return user_access('edit field of interest', $account);
  }

  return TRUE;
}

```

There is also a module that uses that hook: Field Permissions.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> ### Features
>
> * Enable field permissions on any entity, not just nodes
> * Role-based field permissions allowing different viewing patterned based on what access the user has
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed
> * Field permissions overview
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Theme hook suggestions for the breadcrumb block
I'm using the Omega theme with the Delta module. How can I theme the breadcrumb block using block--breadcrumb.tpl.php?
I want to change the output of the block to something similar to the following.

```
<nav id="breadcrumb">
  <ul>
    <li></li>
  </ul>
</nav>

```

# Answer
> 1 votes
You should copy `theme_breadcrumb` to your theme's template.php file:

```
function YOURTHEME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
      $crumbs = '<nav><ul class="breadcrumbs">';
      foreach($breadcrumb as $value) {
           $crumbs .= '<li>'.$value.'</li>';
      }
      $crumbs .= '</ul></nav>';
    }
      return $crumbs;
  }

```

By this function you can set up a `ui li` structure.

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


# Question
Title: Sharing Global Menu Links Menu to subsites
How to present a global menu across multiple subsites

I've been trawling the Drupal site for answers to this and because I'm only 4 days into my Drupal 7 adventure I'm sure half my battle is finding the right words to say to the community to get what I'm asking for.

This question seems to hit the mark http://drupal.org/node/1428516

But the only answer is something about Domain Access http://drupal.org/project/domain but that looks pretty complicated when all I want to do is to splat a small block of html at the top of all my sites.

So I'm thinking the architecture would be something like this.

```
master site
+ - menu-global-menu
+ - global-menu-module (looks in master site db for menu-global-menu
                        and fills variable $global_menu)
+ - corporate theme (requires global-menu-module)
|
+ - > subsite 1
+ - inherits corporate theme
|
+ - > subsite 2
+ - inherits corporate theme

```

Does this make sense? Or should I be achieving this some other way?

# Answer
> 0 votes
So I think I've gone a long way to achieving this.

In the setting.php file of each site I declare a Data Connection called globalmenu that point's to the database belong to the menu's management site.

I make the menu and get the machine name for it; in my case menu-global-menu.

In my page.tpl.php of my theme I have included this

```
  <?php
  if ($global_menu){
  print($global_menu);
  }
  ?>

```

My module

```
function global_header_preprocess_page(&$variables, $hook) {

 $query_options['target'] = 'globalmenu';

 $query = db_select('menu_links', 'p', $query_options)
    ->fields('p')
    ->condition('menu_name', 'menu-global-menu', '=')
    ->execute();

 if($query->rowCount() ==   0) {
    print '<div class="messages error"><em>No Global Header Configured!</em><ul><li>Check the Global Header Module Help for details</li><ul>   </div>';
}

 $links = array();
 $markup = "<div class='global-navigation'><ul class='nav'>";

 foreach ($query as $item) {
    $markup = $markup ."<li><a href='".$item->link_path."' class='global-link'>".$item->link_title."</a></li>";
 }

 $markup = $markup ."</ul></div>";
 $variables['global_menu'] = $markup;
}

```

There's probably a much better way of doing the markup but I'm a noob so I guess someone will correct me.

---
Tags: 7, routes, domain-access, database
---


title: How to update taxonomy field in a node?

text:
# Question
Title: How to update taxonomy field in a node?
```
node_load($nid);
$node->mytaxonomyfield['und'][0]['tid']=$data;
node_save($nid)

```

my corresponding terms : online,offline,pre-online and the corresponding tid : 1,2,3

my question : what the program will be that changing the field data by words instead of tid

# Answer
> 3 votes
You can't (at least not directly). Don't forget that multiple taxonomy terms may have the same name so they need to be identified by their `tid` or you'd get clashes.

You have a couple of options to load a taxonomy term by name, but for each you'll need to know the `vid` of the term's vocabulary.

The first option is to use the deprecated `$conditions` parameter of the `taxonomy_term_load_multiple()` function:

```
$terms = taxonomy_term_load_multiple(array(), array('name' => 'online', 'vid' => $vid));
$first_term = array_shift($terms);
$tid = $first_term->tid;

```

As you can see it's limited to loading just one term at a time.

The second (much better) way is to use an `EntityFieldQuery`:

```
$terms = array(
  'online',
  'offline',
  'pre-online'
);

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $vid)
  ->propertyCondition('name', $terms, 'IN');

$results = $query->execute();

if (isset($results['taxonomy_term'])) {
  // Get an array of tids
  $tids = array_keys($results['taxonomy_term']);
}

```

That way you can load multiple terms in one go, and take advantage of non-SQL field storage solutions if you need to.

If you're worried about speed you could also go directly into the `taxonomy_term` table to get this data; but I don't advise doing this unless you really know what you're doing.

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


# Question
Title: Split the account edit form in multiple pages
I need to split the account edit form that shows up on one page to multiple pages. That means I want to separate change password fields, two custom fields i created - field\_first\_name and field\_last\_name and so on. For moving the password fields to new block I used the solution provided in this link How can I display a change password form on its own? and it works great.

I am trying to use the same code except make some minor changes for modifying the custom fields (first name and last name). The only difference is, I need to pre-populate these fields with the values from the current logged in users information.

```
// Get the currently logged in user object.
$form['#account'] = $GLOBALS['user'];

// Textfield for first name.
$form['field_first_name'] = array(
  '#type' => 'textfield',
  '#title' => t('First Name'),
  '#size' => 60,
  '#default_value' => // What should I enter here?
  '#required' => TRUE,
);

```

When I enter a new value for these fields, it doesn't get updated in the account. I am using the following code.

```
/**
 * Submit handler for change_name_form().
 */
function change_name_form_submit(&$form, &$form_state) {
  // Set up the edit array to names to user_save().
  $edit = array(
    'field_first_name' => $form_state['values']['field_first_name'],
    'field_last_name' => $form_state['values']['field_last_name'],
  );

  // Save the account with the new name.
  user_save($form['#account'], $edit);

  // Inform the user.
  drupal_set_message(t('Your information has been changed.'));
}

```

What changes do I need to make to the code to get the desired output?

# Answer
I haven't done this in code, but I split the user profile into multiple pages on my site with the Field Group module (as the module's page says, it is only client-side).

There is a screencast about how the multipage features work.

Another option is the Profile 2 module, which will create actual separate paths for different settings.
> 1 votes

---
Tags: 7, forms, users
---


title: Creating a custom locked role

text:
# Question
Title: Creating a custom locked role
Within Drupal 7 I am trying to modify the page myserver.com/admin/people/permissions/roles so that a custom role which I have added cannot be edited. In other words, I'd like it to be locked like the anonymous and administrator roles.

I have found one possible solution at http://drupal.org/node/397480 but I think it is a Drupal 6 fix.

I've tried modifying the render array for the content directly, but also can't figure that out quite right.

Here is the closest I've been able to get it. Any suggestions or solutions will be much appreciated.

```
function access_group_preprocess_page(&$variables) {
  //check to see if the current page matches the path specified
  $match_path = explode('/', 'admin/people/permissions/roles');
  $match = TRUE;
  for ($i = 0; $i < count($match_path); $i++) {
    if ($match_path[$i] != arg($i)) {
      $match = FALSE;
      break;
    }
  }

  //if there is a match, modify the page
  if($match){
    //define the locked roles
    $locked_roles = array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID,);
    $access_group_role = user_role_load_by_name(ACCESS_GROUP_ROLE);
    if ($access_group_role) $locked_roles[] = $access_group_role->rid;
    kpr($locked_roles);

    kpr($variables);

    //recreate the render array for the table
    $header = array(
        t('Name'),
        array(
            'data' => t('Operations'),
            'colspan' => 2
        )
    );
    foreach (user_roles() as $rid => $name) {
      $edit_permissions = l(t('edit permissions'), 'admin/user/permissions/'. $rid);
      if (!in_array($rid, $locked_roles)) {
        $rows[] = array($name, l(t('edit role'), 'admin/user/roles/edit/'. $rid), $edit_permissions);
      }else{
        $rows[] = array($name . " <em>(locked)</em>", '', $edit_permissions);
      }
    }

    //$form = user_admin_role(array(), array(), );
    //$rows[] = array(drupal_render($form['name']), array('data' => drupal_render($form['submit']), 'colspan' => 2));
    $form = $variables['page']['content']['system_main'];
    $rows[] = array(
      array(
          'data' => drupal_render($form['name']) . drupal_render($form['add]']),
          'colspan' => 3,
      ),
    );

    $output = drupal_render_children($form);
    $output .= theme('table', array(
        'header' => $header,
        'rows' => $rows,
    ));

    $variables['page']['content'] = $output;
  }
}

```

# Answer
Unfortunately this behaviour is hard coded into the `theme_user_admin_roles()` function, so you'll need to override that theme function to remove the link and add the *locked* label. You'll also need to override the access check for the role edit/deletion page so it can't be visited directly.

This is the theme override you'll need to use (it's exactly the same as `theme_user_admin_roles()` except it has an extra test for your custom role):

```
function MYTHEME_user_admin_roles($variables) {
  $my_role_id = function_to_get_custom_role_id();

  $form = $variables['form'];

  $header = array(t('Name'), t('Weight'), array(
      'data' => t('Operations'),
      'colspan' => 2,
    ));
  foreach (element_children($form['roles']) as $rid) {
    $name = $form['roles'][$rid]['#role']->name;
    $row = array();
    if (in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID, $my_role_id))) {
      $row[] = t('@name <em>(locked)</em>', array('@name' => $name));
      $row[] = drupal_render($form['roles'][$rid]['weight']);
      $row[] = '';
      $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid);
    }
    else {
      $row[] = check_plain($name);
      $row[] = drupal_render($form['roles'][$rid]['weight']);
      $row[] = l(t('edit role'), 'admin/people/permissions/roles/edit/' . $rid);
      $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid);
    }
    $rows[] = array(
      'data' => $row,
      'class' => array('draggable'),
    );
  }
  $rows[] = array(array(
      'data' => drupal_render($form['name']) . drupal_render($form['add']),
      'colspan' => 4,
      'class' => 'edit-name',
    ));

  drupal_add_tabledrag('user-roles', 'order', 'sibling', 'role-weight');

  $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'user-roles')));
  $output .= drupal_render_children($form);

  return $output;
}

```

And this is the code for the access override (needs to go in a custom module)

```
function MYMODULE_menu_alter(&$items) {
  $items['admin/people/permissions/roles/edit/%user_role']['access callback'] = 'MYMODULE_user_roles_edit';
  $items['admin/people/permissions/roles/delete/%user_role']['access callback'] = 'MYMODULE_user_roles_edit';
}

function MYMODULE_user_roles_edit($role) {
  $my_role_id = function_to_get_custom_role_id();

  if ($role->rid == DRUPAL_ANONYMOUS_RID ||
    $role->rid == DRUPAL_AUTHENTICATED_RID ||
    $role->rid == $my_role_id) {
    return FALSE;
  }

  return user_access('administer permissions');
}

```
> 1 votes

---
Tags: users
---


# Question
Title: Import a class via template.php or other ways
I'm using Drupal 7 and have this structure:

```
<div id="node-11" class="node node-ortaklar-cv node-promoted node-teaser node-type-ortaklar_cv node-teaser-ortaklar_cv" typeof="sioc:Item foaf:Document" about="/tr/node/11">
        <h2 datatype="" property="dc:title"><a href="/tr/node/11">Lorem Ipsum</a></h2>
    <div class="field field-name-field-cv-tr field-type-file field-label-hidden d_tr">
...
    </div>

```

I want add a class top of this structure. E.G.

```
**<div class="HEADER">**
   <div id="node-11" class="node node-ortaklar-cv node-promoted node-teaser node-type-ortaklar_cv node-teaser-ortaklar_cv" typeof="sioc:Item foaf:Document" about="/tr/node/11">
            <h2 datatype="" property="dc:title"><a href="/tr/node/11">Lorem Ipsum</a></h2>
        <div class="field field-name-field-cv-tr field-type-file field-label-hidden d_tr">
    ...
        </div>
**</div>**

```

I don't use page.tpl.php files because using Views module. I put this code in template.php but don't working:

```
function mysite_preprocess_image(&$variables) {
if ($variables['style_name'] == 'node-ortaklar-cv') {
$variables['attributes']['class'][] = 'header';
}

```

}

Is is possible put a div in structure via template.php or some way? And how? Thanks.

# Answer
The code needs to go in node.tpl.php, not page.tpl.php or template.php. Just follow these steps:

1. If you haven't already, copy the code from node.tpl.php into a file with the same name inside your theme's folder.
2. Edit the node.tpl.php file and add your markup around the main node div
3. Flush Drupal's caches (or at least the theme reigstry)

Then your nodes will all be wrapped in the markup you need.

If you just need to do this for a specific content type (I'm going to guess at one called `image` here), your template file will need to be called node--image.tpl.php. You'll still need the original node.tpl.php file in your theme though, as node template overrides won't work without it.
> 0 votes

---
Tags: 7, theming
---


title: Custom validate and submit don't works

text:
# Question
Title: Custom validate and submit don't works
I made my custom module, and wanted to do some staff in the validation and submission handlers. My Fields are in two field sets:

* Member profile, with username and password
* Company profile, with company name, URL, location, and logo

I am also using the #states attribute on some fields, but everything works except the validation and submission handlers.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_profile_form':
      // Only pre-render works.
      $form['#pre_render'][] = 'mymodule_user_profile_form_pre_render';
      // I try to empty fields with states attribute, but without success. Disabled work OK.
      $form['field_company_url']['und']['0']['value']['#states'] = array(
       'empty' => array(':input[name="field_company_confidential[und]"]' => array('checked' => TRUE)),
       'disabled' => array(':input[name="field_company_confidential[und]"]' => array('checked' => TRUE)),);

      // These don't work as expected.
      $form['#validate'][] = 'mymodule_user_profile_form_validate';
      $form['#submit'][] = 'mymodule_user_profile_form_submit';

      // I also tried this one.
      // $form['actions']['submit']['#submit'][] = 'mymodule_user_profile_form_submit';
  }
}

function mymodule_user_profile_form_submit($form, &$form_state) {
  // I want to download the image from another website and set as logo.
}

function mymodule_user_profile_form_validate($form, &$form_state) {
  //I need to check if checkbox is checked to empty all other fields.
  if ($form_state['values']['field_company_confidential'] == TRUE) {
    $form_state['values']['field_company_url']['und']['0'] = '';
  }

  return $form;
}

```

When I try to access `$form_state['values']`, I don't get any value.

What I am doing wrong?

# Answer
> 1 votes
The main problem was with devel module. When I disable it and try again all job everything works perfect. So maybe was some bugs with devel module, but I am not sure.

---
Tags: users, forms
---


# Question
Title: Exposed view filtering on a related node's value
I have a view with a list of nodes. Each node has a number of related nodes which I want to display below the parent node. This works fine.

However, when I go to filter the listing on values in one of the related nodes, then an empty set is returned.

I'm guessing it's trying to filter the parent nodes on this value, and not the related nodes. How can I remedy this?

# Answer
> 1 votes
When adding a new relationship, ensure that you select 'Require this relationship'. Also, when adding a filter, ensure that you select the relevant relationship from the list where necessary.

---
Tags: views
---


# Question
Title: How to query entities/nodes that does not have the field "field_parent" with EntityFieldQuery?
I'm using the Entity reference module and want to select all nodes that has no parent defined. I'm trying with:

```
$query = new EntityFieldQuery();
$children = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'page')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_parent', 'target_id', null, 'IS NULL')
    ->execute();

```

.. but that does not give anything as the field "field\_parent" is missing and not set to NULL. If I use IS NOT NULL I get all nodes that has a parent.

How can I select all nodes that has no parent (or is missing the field "field\_parent")?

---

Thanks to Clive I managed to solve this in the following way:

```
$query = new EntityFieldQuery();
$children = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'page')
    ->propertyCondition('status', 1)
    ->addTag('filter_no_parent')
    ->execute();

/**
* Implements hook_query_TAG_alter()
*/
function mymodule_query_filter_no_parent_alter(QueryAlterableInterface $query) {
    $query->leftJoin('field_data_field_parent', 'p', 'node.nid = p.entity_id');
    $query->isNull('p.field_parent_target_id');
}

```

# Answer
> 5 votes
You can't (natively) I'm afraid. An `EntityFieldQuery` doesn't have support for `IS NULL` or `IS NOT NULL`.

There are workarounds, however, essentially by adding a tag to the query and implementing a query alter hook, in which you add the required `LEFT JOIN` and `IS NULL` statement.

See EntityFieldQuery does not support isNull or isNotNull for a code example. I've used that code before with good results.

---
Tags: 7, entities, database
---


# Question
Title: Create an image slideshow with multiple image fields per node
I'd like to create an image slideshow using views slideshow. I see a few ways of doing it, like this one create-an-easy-jquery-slideshow-in-drupal-7, but they all require a single image per node.

I would like to have a content type that accepts multiple images and still retains similar functionality. So there is a list of thumbnails at the bottom, as a pager, and a single image above that is activated by hovering the thumbnails below.

I'm sure there is a way to do this. possibly with a few more modules? I'd love to know.

EDIT: This is drupal 7

# Answer
In drupal 7 for the very basic slideshow you will need views and views slideshow.

You will need to create two imagestyles for the slideshow, a large image, and a small image that will be used for the pager.

next for the view Fields you will need two image fields. One, the first, you will choose the larger imagestyle setting. For the second image filed you will use the smaller imagestyle that will be used for the pager, also on this one you will need to 'exclude from display.'

For the view format choose slideshow. These settings you can use most of the default settings but for the pager type you will be choosing fields and also you will choose the second image type (the pager image.)

For the view contextual filters you'll choose content:nid and choose 'provide default value' with the value being 'content id from url.'

I realise those are very blunt directions but as long as you're looking at your view display you should be able to follow it.
> 1 votes

# Answer
You can achieve this using Views Slide Show.... See this example I've done here `http://www.cnngo.com/hong-kong/visit/hong-kongs-temporary-june-4-memorial-museum-568132` which is using Views Slideshow (ThumbnailHover) + Simply Scroll Jquery Plugin. See images below...
> 2 votes

---
Tags: views, media, javascript
---


# Question
Title: Exposed filters submit with AJAX not working - regular submit instead
I created and customized exposed forms. When I change some values I change exposed filters widgets accordingly. Then I call submit with JavaScript, but my form is send with regular submit not like I checked on Views Advanced Settings form to use AJAX. What could be wrong with that? Pagination also change current URL.

-- edit -- When I click on item connected with exposed filter I execute this code:

```
$('#category-product-finder .frame a').each(function() {
    var $a = $(this);
    var $exposed_filter = $('#views-exposed-form-product-finder-page');
    $a.click(function(e) {
        e.preventDefault();
        $exposed_filter.find('#edit-product-category').val($a.attr('rel'));
        $('#views-exposed-form-product-finder-page').trigger('submit');
    });
});

```

And this make my form to submit without using AJAX.

# Answer
Did you edit the templating of view? As AJAX views use the default ID's to attach itself to the form and view itself. If you've altered / removed these ID's, it would explain why the form submits in a regular way.

A few lines of the selectors in ajax\_views.js to get you on the right path:

```
var selector = '.view-dom-id-' + settings.view_dom_id;

...

// Add the ajax to exposed forms.
this.$exposed_form = $('form#views-exposed-form-'+ settings.view_name.replace(/_/g, '-') + '-' + settings.view_display_id.replace(/_/g, '-'));
this.$exposed_form.once(jQuery.proxy(this.attachExposedFormAjax, this));

```
> 0 votes

# Answer
Found a solution. Ambidex idea is the key. My problem was that I didn't have printer classess within views-view--XXXX.tpl.php. After this everything works OK and there is something like "view-dom-id-82374yrcnuerhnw875yt3o8743y" (first line of Ambidex code) class added, which is probably needed by AJAX calls.
> 1 votes

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