title: Password Reset Redirect

text:
# Question
Title: Password Reset Redirect
I've been trying to redirect the password reset page to my custom login page by creating a small custom module; however it's not resolving properly.

Has anyone done this before with success? The code that I'm trying to use is:

```
function m2f_password_reset_form_alter(&$form, &$form_state) {
  if ($form['#action'] == "/user/password"){
    $form['#submit'][] = 'user-pass';
  }
 }
/**
* Redirects user after password reset form is filled
*/
function m2f_password_redirect(&$form, &$form_state){
  $form_state['redirect'] = 'node/20';
}

```

# Answer
There are at least three possible issues that I can see:

* You are probably not prefixing the function with the right string.
If the module/theme name is m2f\_password, then `m2f_password_reset_form_alter()` is not recognized at implementation of `hook_form_alter()`.
* If you are trying to alter the form that is shown at user/password, you should not check `$form['#action']`; you should implement `hook_form_FORM_ID_alter()`, and write a function called `m2f_password_form_user_pass_alter()`. (I assume the short name of the module/theme is m2f\_password; if it is not correct, replace m2f\_password with the short name of the module/theme.)
* `user-pass` is not a valid form submission callback name: PHP functions cannot contains hyphens. You are then defining `m2f_password_redirect()`, and that seems a form submission callback.
The correct code is probably the following one.

```
$form['#submit'][] = 'm2f_password_redirect';

```
> 2 votes

# Answer
The problem is probably here:

```
$form['#submit'][] = 'user-pass';

```

The string that you add to the `$form['#submit']` array must be a the name of a valid, existing PHP function. It's likely you just need to change that line to:

```
$form['#submit'][] = 'm2f_password_redirect';

```

Don't forget that PHP function names can't contain hyphens so `user-pass` would never be a valid name for a submit handler.
> 0 votes

---
Tags: 7, users
---


# Question
Title: PHP evaluated in rule works locally but not on remote server
I have this code. When I run this on my local server, it works fine but when I run it on the remote server it does nothing. Not even the messages appear. I am using the devel module. Any help appreciated.

```
drupal_set_message('test');
dpm($node);
// send msg for skills
$arrayofprojectskills = array();
array_push($arrayofprojectskills, $node->field_project_skills['und']['0']['tid']);

$usersprofidstonotify = array();

foreach ($entity_list as $obj) {
    if ($obj->field_skills) {
        $profile1 = $obj->field_skills['und'];
        foreach ($profile1 as $innerar) {
            foreach ($arrayofprojectskills as $oneskill) {
                if (in_array($oneskill, $innerar)) {
                    array_push($usersprofidstonotify, $obj->pid);
                } else {

                }
            }
        }
    } else {
        //drupal_set_message('field skills has no values');
    }
}

$useridstonotify = array();

foreach ($entity_list as $obj) {

    foreach ($usersprofidstonotify as $user) {
        if (($obj->pid) == ($user)) {

            array_push($useridstonotify, ($obj->uid));
        }
    }
}

$arrayofprojectskillnames = array();
foreach ($node->field_project_skills['und'] as $fieldprojinner) {
    array_push($arrayofprojectskillnames, $fieldprojinner['name']);
}

$usersprofidstonotify = array();

$name = dpm($node->name);
$msg = $name;
$msg .= ' has posted a project called ';
$msg .= ($node->title);
$msg .= 'More details:';
$msg .= ($node->body['und']['0']['value']);
$msg .= ' They need the skills of ';
$msg .= implode(",", $arrayofprojectskillnames);
$msg .= 'Can you help them out YEAH!? ';
$msg .= ' If so, please sign up ';
$msg .= '<a href="' . '/node/' . ($node->vid) . '">' . 'here</a>';

foreach ($useridstonotify as $oneuser) {
    privatemsg_new_thread(array(user_load($oneuser)), 'Someone needs your skills', $msg);
}

```

# Answer
> 0 votes
Please follow below steps to debug.

1. Enable Rules Debug settings.
2. Enable the rule you created.
3. Check the messages given by rules debug messages on rule activation conditions.

Still if you cannot able to find the solution, check the error logs.

You may need to change the format of collecting node values. Using "und" $node-\>field\_project\_skills\['und'\]\['0'\]\['tid'\] is not the right way. You can check below post that explains right way of reading node values.

http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

---
Tags: debugging
---


# Question
Title: Views 3: display "block" doesn't show full node
I would like to show full node including comments in views. Everything is ok if I choose display "page" but in case of "block" all comments disappear from the view only content and link "add comment". What is wrong in my case and how to correct it? I need a block with full node content including comments.

My parameters in views:

Format:
Format: Slideshow
Show: Content; All (I also cheked "show comments" and "show links")

Thanks in advance

# Answer
> 1 votes
When you select teaser view instead of full content you can see comments in your block.

If you see implementation of `comment_node_view()` comments are displayed only in node lading pages.

```
if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

```

If you enable the same block in node landing pages you can see the comments in your view.

If you enable the block other than node landing pages, then you cannot see the comments because of `node_is_page($node)` condition i think.

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


title: Switch theme per user upon login

text:
# Question
Title: Switch theme per user upon login
I'd like to switch theme per user upon user login success in my drupal 6 site. I need to check username of a particular user to change a particular theme for that user.
Is there any module around to accomplish this? Or, do I have to write a hook like

```
function mymodule_init(){
    global $custom_theme;
    global $user;
    // check username here.
    $custom_theme = 'garland';
}

```

But, I'm finding a module which have admin interface so that I can define usernames as much as I can.

# Answer
> 2 votes
Try the Themekey module which allows content, user, or role -specific themes.

# Answer
> 1 votes
Why not use the Role Theme Switcher module?

Considering you have a limited number of themes and you can combine roles for a user, why not creating one specific role per theme that you will assign to your users.

---
Tags: 6, theming, users
---


title: check box with date module

text:
# Question
Title: check box with date module
I need a solution for reservation, for example i have a swimming pool and i want to Reserve it, the visitor will choose the time he want, let me say i will select the start and end date (the reservation time) mmmm in our example from 8 am to 9am, what i need to display the available reservation time like this:

And the visitor can select one hour or more to reserve the swimming pool.
Is there a module can do this?and if not is there a reservation module can do what i nees by another way? thanks

# Answer
As far as i know, there is no module which will display exact User Interface as check-boxes that will integrate with date module.

What i would like to suggest is to create time field to display from and to time of timing slots using date module.

If you need exact User interface what you are asking then follow below steps.

1. Add checkboxes field with different timings.
2. Then create date from and to time fields.
3. Hide date from and to fields using css.
4. On click of check-boxes update the hidden date from & to fields using jquery or javascript, so that you can use Date module features.
> 1 votes

---
Tags: 7
---


# Question
Title: How to auto assign node reference value D7
I have user profile with fields:

1. date field: "date of birth" (format: y-m-d)
2. node reference field "card\_ref" which should automatically reference to content-type "cards" node. (users cannot change it only view it)

and content-type "cards":

1. title field
2. date field (multiple values, format: m-d)

so i'd like to make auto-reference to existing node "cards" which have same date-field value but different format.

For example:

I have "cards" nodes: (title - dates)

1. Card A - 01.23, 03.11, 05.02
2. Card B - 02.14, 07.01
3. Card C - 11.11
4. Card D - 02.10, 03.02, 05.07, 09.14

After new user registers his account with date of birth: 1977.07.01, I need "card\_ref" field to automatically assign him "Card B" or if entered date of birth: 1234.03.02, "card\_ref" should be assigned to "Card D" and so on...

should i use custom module or it is possible to use some existing modules? maybe with views reference field, or rules?

any suggestions please? (for drupal 7)

Thank You..

# Answer
> 1 votes
I found the answer by creating own module.

First I create the View which finds Card nodes by dob field of the user, then inside the `hook_user_presave()` function I call `views_get_view_result()` and finally assign the card\_ref field like this:

```
$edit['field_card_ref']['und'][0]['target_id'] = $card;

```

---
Tags: 7, users, nodes, datetime
---


# Question
Title: How to choose multisite instance inside script running from main Drupal directory?
As in question. I know that I can use drush command, but I have small script and I don't want to create module from it. Now I calling that script inside main Drupal folder (no multisites).

Inside that script I just bootstraping Drupal (I need Access to Drupal API):

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
#db integration

```

(The same PHP header I use for e.g unit tests class)

It is possible to run such script in multisite enviromnent too?

My problem is that every sites config settings.php has db name called 'default'. So I don't know how to use db\_set\_active properly.

I have script that creating data (txt file) for Menu Import module. I need access to Drupal and Joomla db, because I need to migrate menu from Joomla.

Anyway here is a script

# Answer
Since you know the database name, you can dynamically set a database name which you will call with `db_set_active()`.

This is copy/pasted from the link below.

```
  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

```

More about this can be found here.
> 0 votes

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


# Question
Title: Display comments from other nodes with a reference
Here's a doozy.

I have a certain content type where nodes of this ct serve as a sort of portal for other nodes. The other nodes (which are all different content types themselves) have entity reference fields, linked too this portal-node.

I need a view that displays the latest -comments- of the nodes linked too the portal node which the user is currently viewing.

# Answer
> 0 votes
Well, I couldn't get this to work with views, so I wrote a custom module with an sql query. Not very clean, but it does the trick.

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


# Question
Title: Use an exposed filter as contextual filter on another view
The question is a pretty simple one, I've created a page-view with an exposed filter. The page-view itself contains a block-view. I was wondering if the value of the exposed filter (which is in the url) could be used as a contextual filter in the block-view.

So far I've tried 'get content ID from url' and 'get raw value' but neither seem to work as the block-view returns no results.

# Answer
> 5 votes
Please follow below steps to achieve functionality that you are looking for.

1. Disable AJAX feature for view.
2. In the block view add a contextual filter and select type as Provide default value \>\> Type as php code.
3. In the php code read the exposed filter value using $\_GET\[\]
4. Return the value you got from $\_GET to contextual filter.

In that way you can able to pass exposed filter value to the contextual filter.

---
Tags: 7, views
---


# Question
Title: Loading Personal contact form and access denied
Into a user profile page I provide a personal contact to conact the profile woner and that contact form is loaded like this:

```
$recipient = user_load(array('uid' => $fptr->uid));
$output .= drupal_render(drupal_get_form(
    'contact_personal_form', $recipient));

```

The form shows up nicely and all is well so far. While testing this form after sending 5 test messages I get the warning that I cannot send more than 5 messages within 1 hour. That is OK, but it seems the access to the entire user profile page is denied and it screws up the page layout.

Is there any way I can just lock the personal contact form instead of locking the entire profile page?In other words, is there a way to check if an anonymous user can send a personal message, and based on that check to show or hide just the message form?

Thanks for your help, also I hope that is easy to accomplish:-)

# Answer
You need to check for flood before rendering the contact form

```
global $user;
// Check if flood control has been activated for sending e-mails.
$limit = variable_get('contact_threshold_limit', 5);
$window = variable_get('contact_threshold_window', 3600);
if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms')) {
// Don't display forms
}
else {
  $recipient = user_load(array('uid' => $fptr->uid));
  $output .= drupal_render(drupal_get_form(
  'contact_personal_form', $recipient));
}

```
> 2 votes

---
Tags: 7, emails
---


# Question
Title: How to use Views/Contextual Filters with a referenced entity
So, I have a site with two content types:

* Sermon Series
* Sermon

The sermon content type has an entity reference field selecting a sermon series that it relates to.

On the page for a sermon series, I am attaching a view to list all the sermons that have the "Sermon Series" field set to that particular series.

Ideally, I'd like to only create one view that will work for every sermon/sermon series.

I know that I need to use contextual filters to do this, but I'm having an exceptionally difficult time wrapping my mind around what settings I need to use, and spending several hours trying stuff out has been to no avail.

Could someone please explain the process to me?

For bonus points- I'd also like to use a view on the sermon page to display an image from the referenced sermon series. I am also not exactly sure how to set this up.

To help clarify, here's the workflow that I want to end up with:

1. User creates a new "Sermon Series" with a title and an image.
2. User creates a new "Sermon", and they can select which "Sermon Series" it belongs to.
3. The new sermon shows up in a list on the corresponding "Sermon Series" page.
4. The image related to the "Sermon Series" shows up on the "Sermon" page.

# Answer
> 1 votes
Did you try to use module EVA: Entity Views Attachment it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

There is a screencast on how to use that module

hope that helps for you...

---
Tags: views
---


# Question
Title: How to show all content type images in a gallery
I would like to realize a View that shows, randomly, 5 images taken from Image field in y content type. I've tried but i only see the images from a single record, i would need to show ALL of them together. Is it possible?

# Answer
If you have 2 pieces of content. And each piece of content has 5 images against field\_example. And you would like to construct a gallery of the 10 images.

You need to amend the 'format settings' of the view using views ui to 'show' as 'fields', if you have not already.

Add the field. 'field\_example'

Click the field 'field\_example' in the views\_UI to get it's associated settings.

Uncheck "Display all values in the same row" under the fields 'multiple field settings'

NB: it is possible to choose these settings when you add the field in the first place. I am assuming you already have the field.
> 1 votes

# Answer
Follow below steps to resolve your issue.

1. Create a new view of type files.
2. Add Filter File:Mime Type and select the condition as Contains any word.
3. Give all image extensions in the value like jpeg jpg png etc
4. Rewrite the results of the File Path field and add img tag with src as file path.

Using above instructions you can list all images in Drupal independent of any content type or image field.
> 2 votes

---
Tags: 7, views, media
---


title: Ubercart Amazon Payments for drupal 7

text:
# Question
Title: Ubercart Amazon Payments for drupal 7
How we can integrate Ubercart Amazon Payments for Drupal 7?

There is a module for Drupal 6 here.

# Answer
> 2 votes
It seems like AMAZON Payments module is not available for Drupal 7. No discussion about D7 port also happening.

If you are interested in writing D7 port for commerce module below article will help you.

http://www.drupalcommerce.org/developer-guide/utilizing-core-apis/writing-payment-method-module

---
Tags: 7, ubercart
---


# Question
Title: Branched user permissions for editing content types
What is the best way to implement the user permissions (in brackets) in following pattern with Content Types as follows:

* Parent (editable by owner & tagged parent-editors)
    + Name
    + Description
    + ...
    + Tagged Parent-editors (users)
* Child (editable by owner & tagged child-editors & tagged parent-editors
    + Name
    + Description
    + ...
    + Tagged Child-editors (users)
    + Entity reference: Parents
* SubChild (editable by owner & tagged child-editors & tagged parent-editors)
    + Name
    + Description
    + ...
    + Entity reference: Childs

Where "..." are some other fields, dependant on the ContentType.

Parent A editors must not be able to edit Parent B

I've looked into the Module Node Access User Reference which seems like it may do this potentially, but I was wondering if there is a standard way of doing this or whether anybody has some prefered/suggested Modules for doing this or even a completely different solution!

# Answer
> 0 votes
I think you may try Node Privacy by Role module. First create three roles Parent Editors, Child Editors, Subchild Editors Then while creating a node you will be asked about the permission to edit the node. But this might not help you when you want to protect nodes per user.

There is also another module Taxonomy Access Control Lite which governs access to nodes based on the taxonomy terms applided to nodes. In this you can create terms for Parent Editors, Child Editors and Subchild Editors

Apart from that there is also good discussion here:

http://drupal.org/node/24073

http://drupal.org/node/285369

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


# Question
Title: How do I prevent a link on an overlay page from opening in another overlay page in Drupal 7?
I have created a custom module that opens up a page in the admin overlay. Upon going to that page, a PDF is generated and the link to the file is displayed on the page. I created the link using `l()`, and gave the link a target attribute of '\_blank' to open in a new tab/window.

```
l('Click here to download your PDF file.', $f_url, array('attributes' => array('target' => '_blank')))

```

The link looks like it is generated correctly.

```
<a href="http://xxxx.com/sites/default/files/custom-pdf/xxxx_4.pdf" target="_blank">Click here to download your PDF file.</a>

```

When I click on it, it opens in a new window, but somehow the overlay fragment is tacked onto the end of the URL in the new window address bar, which appears as the following: http://xxxx.com/sites/default/files/custom-pdf/xxxx\_4.pdf#overlay-context=test.html.

The browser throws up a dialog box with a title of "Adobe PDF Document" and a message alert of "This operation is not allowed".

If I click this link from a non overlay page, it does exactly what it's supposed to do: Open the PDF in a new window.

I'm not exactly sure what's going on here.

How is the overlay fragment being appended to the URL, and how can I prevent it?

# Answer
> 0 votes
I was having the same issue.

There is a patch here.

---
Tags: modal-dialogs
---


title: Programmatically change logo

text:
# Question
Title: Programmatically change logo
I tried two versions: 1.

```
$form_state = array();
form_load_include($form_state, 'inc', 'system', 'system.admin');
$form_state['values']['var'] = 'theme_settings';
$form_state['values']['logo_upload'] = file_save_upload('/path/to/logo.jpg');

drupal_form_submit('system_theme_settings_submit', $form_state);

```

2.

```
 variable_set('logo_path', '/path/to/my/uploaded/logo.jpg');

```

but none of them worked.

# Answer
That setting is part of the theme settings variable; each setting is put in an array and that array is serialised as the value of the main theme settings variable.

You can set this value programmatically like so:

```
$theme_name = 'garland';
$var_name = 'theme_' . $theme_name . '_settings';

$settings = variable_get($var_name, array());

$settings['logo_path'] = $new_path;

variable_set($var_name, $settings);

```
> 9 votes

---
Tags: 7, media
---


# Question
Title: Displaying multiple referenced nodes' fields through Views, using Views Slideshow
I'm trying to build some image carousel functionality. To accomplish this, I've created two content types: Slideshow, and Slide. The Slide content type is what you would expect--a few fields that hold the content of the slide. The Slideshow content type's only purpose is to hold an ordered collection of slides in an Entity Reference field.

The advantage to this approach is that the use of an Entity Reference field means that the content administrator gets a drag'n'droppable UI for the ordering of slides, which is much nicer than some clunky integer weight fields.

So, having got that part set up, I scoot off to Views to work some magic with Views Slideshow. I create a view which calls up my Slideshow node and uses a relationship based on that Entity Reference field to get to the Slide nodes. With that, I can set up the fields of the slides how I like.

The last step would've been switching to the Slideshow view format and configuring the thing, but it was here that I ran into a problem. After I got things set up the way I thought they should be, I found that only the first slide's node was being displayed.

I did my Googling, and I found another question here on Drupal Answers that was similar to mine, which you'll need to read to understand the rest of my question. Reading through it, I tried out the solution that one kind soul provided, and it worked. But it required that I switch from the Slideshow view format to the Unformatted List view format.

So now it appears that I have a choice: I show all the slides as an unformatted list, which is not a slideshow. Or, I can show one of slides as a slideshow, which is not a slideshow.

This bums me out, because I thought I found an almost perfect setup. A content-manageable slideshow with an easy-to-use UI that didn't require the client to understand weight numbers and struggle through the tedium of setting them up. Can anyone help me jump over this roadblock?

# Answer
I don't know if it's possible to do this with views\_slideshow but I just created a patch for the field\_slideshow module. It will be committed once I have tested it a little more or there is some feedback.

The Field Slideshow module page.

The issue with the patch.

And the documentation page: drupal.org/node/1495622

So once you have installed the dependancies and libraries here is how to download and apply the patch:

```
git clone --recursive --branch 7.x-1.x http://git.drupal.org/project/field_slideshow.git
cd field_slideshow
wget http://drupal.org/files/entity_reference_support-1634412-3.patch
git apply entity_reference_support-1634412-3.patch

```

Then enable the module and go to your content type display setting page ( something like admin/structure/types/manage/article/display ). Here you should be able to define the format of the reference field to be a slideshow.
> 1 votes

---
Tags: views, entities
---


# Question
Title: Get multiple results from entity reference relationship in views
In a view that displays content of a type that uses an Entity Reference (specifically User reference), I add that relationship but even though multiple users may be/are referenced by the content I only get one of them. Am I missing some sort of configuration?

In the relationship description: "A bridge to the User entity that is referenced via field\_users"

EDIT: So after a private discussion with @Anil Sagar it seems that you cannot -using entityreference alone- display multiple results of the referenced entities in one row of the Entity the view displays.

The best you can get is:

Article One
body
image
user1 name
user1 surname

Article One
body
image
user2name
user2surname

(users 1 and 2 are referenced by Article One).

# Answer
> 0 votes
Two possible solutions would be either to use views\_field\_view and have an inner view that fetches all the referenced users by using article nid as a contextual filter,

or, using realname module to display first and last name wherever the username would be shown and remove the reference and add the users as a plain field (but that excludes any other fields that you may wanted to display) .

# Answer
> 0 votes
* Verify Distinct Checkbox in View Query Settings. You should disable it.
* Verify number of items to display is more than one.
* Make sure no filters or contextual filters added that will effect the view results.

I just added a entity reference field to Article Content Type. And then added a relationship to the entity in view using Relationships. It does show multiple values.

I am not sure what other configurations are enabled in your view. See below query generated using views for above scenario.

SELECT node.title AS node\_title, node.nid AS nid, users\_field\_data\_field\_user.name AS users\_field\_data\_field\_user\_name, users\_field\_data\_field\_user.uid AS users\_field\_data\_field\_user\_uid, node.created AS node\_created, 'node' AS field\_data\_body\_node\_entity\_type FROM {node} node LEFT JOIN {field\_data\_field\_user} field\_data\_field\_user ON node.nid = field\_data\_field\_user.entity\_id AND (field\_data\_field\_user.entity\_type = 'node' AND field\_data\_field\_user.deleted = '0') LEFT JOIN {users} users\_field\_data\_field\_user ON field\_data\_field\_user.field\_user\_target\_id = users\_field\_data\_field\_user.uid WHERE (( (node.status = '1') )) ORDER BY node\_created DESC LIMIT 5 OFFSET 0

---
Tags: entities, views
---


# Question
Title: Access to only few fields of a content type for specific user
I am using drupal 6. I have created one content type 'video' in which I have many fields like url,language,locations etc. I have created 1 role, Now I just want to give permissions to that particular role so that he can only add fields like url,locations. He shouldn't be able to use other fields.
Any Suggestion,

# Answer
> 4 votes
Field Permissions will let you assign different permissions to a field based on role.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

---
Tags: entities, nodes
---


# Question
Title: How to show a form in Dialog Modal jquery?
Regards,

I need to display a form within a modal dialog when clicking on a link. In which the user can put data and save the data.

I thought about making a template in which I have my form, but not as display them using the method. Dialog () to show me the Modal.

Does anyone know how I can display the dialog template with the method? or does anyone have any other ideas of how to do that?

Thanks.

# Answer
There's 2 good options I know of currently: iframe (in colorbox for example) and CTools. Which option to use depends of the circumstances. I guess this information I found in the CTools modal.html file brings out the main difference:

> CTools provides a simple modal that can be used as a popup to place forms. It differs from the normal modal frameworks in that it does not do its work via an iframe. This is both an advantage and a disadvantage. The iframe simply renders normal pages in a sub-browser and they can do their thing. That makes it much easier to put arbitrary pages and forms in a modal. However, the iframe is not very good at actually communicating changes to the main page, so you cannot open the modal, have it do some work, and then modify the page.

I have no personal experienced with CTools on this subject so I can't add anything else to that, but I've implemented the iframe method in a couple of projects. In the most recent one I used the Colorbox plugin to show a few forms created with the Webform module in a popup. I'll add some example code here in case there's some interest.

Link to the form:

```
<a class="colorbox_form" href="'.url('node/5').'">'.t('Send message').'</a>

```

Javascript code to open the linked address in a popup:

```
if ($('a.colorbox_form').length > 0) {
  var link = $("a.colorbox_form").attr('href');
  link = link.concat('?colorbox=true');
  // colorbox=true is attached for later use (read below).
  $("a.colorbox_form").attr('href', link);
  $("a.colorbox_form").colorbox({iframe:true, width:500, height:450});
}

```

In the theme template file:

```
function mytheme_preprocess_page(&$variables) {
  // Different template and additional stylsheet for colorbox content.
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    $variables['theme_hook_suggestions'] = array('page__iframe'); // page--iframe.tpl.php
    drupal_add_css(path_to_theme() .'/iframe.css');
    $variables['styles'] = drupal_get_css();
  }
}

```

I attached 'colorbox=true' to the links using javascript so that users with javascript turned off would see the form with the normal template. The iframe template only has messages, title and content printed.

This already works, but I ran into a issue with Webforms: 'colorbox=true' wasn't preserved when the form got submitted. My attempt to fix it:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    // The id-s of the forms that are possibly shown within a popup.
    $form_ids = array('webform_client_form_2', 'webform_client_form_4');
    if (in_array($form_id, $form_ids)) {
      $form['#submit'][] = 'mymodule_webform_submit';
    }
  }
}

function mymodule_webform_submit(&$form, &$form_state) {
  //drupal_set_message('<pre>'.var_export($form_state['redirect'], TRUE).'</pre>');
  if (!isset($form_state['redirect'])) {
    $form_state['redirect'] = array($_GET['q'], array('query' => array('colorbox' => 'true')));
  }
  else {
    $form_state['redirect'][1]['query'] = array('colorbox' => 'true');
  }
}

```
> 1 votes

# Answer
OK! I did this with HOOK\_BLOCK Where the content is my TEMPLATE. Then, only I call this block with the method .dialog of Jquery UI.

My code:

```
function mymodule_init() {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css');
}

function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
    switch ($op) {
        case 'list':
            return array(
                0 => array(
                    'info' => t('PopUp'),
                ),
            );
            break;
        case 'view':
            $subject = '';
            $content = '';
            switch ($delta) {
                case 0:
                    $content = theme('mymodule_styling');
                    $subject = t('Show the popup.');
                    break;
            }
            if ($subject || $content) {
                return array(
                    'subject' => $subject,
                    'content' => $content,
                );
            }
            break;
    }
}

function mymodule_theme() {
    $path = drupal_get_path('module', 'mymodule') . '/templates';
    return array(
        'mymodule_styling' => array(
            'template' => 'popup_template',
            'arguments' => array('message' => NULL),
            'path' => $path
        ),
    );
}

```

Then I activate my block and with the CSS only hidde this block:

```
div#block-popup-0{
    display: none;
}

```

And with my JS show like a popup:

```
function show_popup_now(){ // This method have my link on event onclick
    $("div#block-popup-0").css("display", "inline-block");
    $("div#block-popup-0").dialog({
        autoOpen: true,
        modal:true,
        width: 594,
        height: 350,
        closeText: "Cerrar"
    });
}

```

But only have a issue with this, When i click (for first time) in my link for show the popup, WORK!. But when close and (again) click in the link, doesn't show the popup.

My code have some error? Thanks for all! :D
> 1 votes

---
Tags: 6, theming, forms
---


# Question
Title: Undefined variable block...when trying to integrate a form into a block
i was just beginning to build my first module which should display a checkbox in a block.

With this code (see below) I get an Error: Notice: Undefined variable: block in ios\_lang\_checkbox\_block\_view()

```
<?php
function ios_lang_checkbox_menu() {
    $items['ios'] = array(
        'title' => 'View the sample form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('ios_lang_checkbox_nameform'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM
    );
    return $items;
}

/**
 * Define a form.
 */
function ios_lang_checkbox_nameform() {
    $options = array(
        'de' => t('de'),
        );
    $form['ios'] = array(
        '#title' => t('Your Name'),
        '#type' => 'checkboxes',
        '#description' => t('Choose language'),
        '#options' => $options,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit')
    );
    return $form;
}
function ios_lang_checkbox_block_view($delta='')
{
  switch($delta) {
    case 'ios_lang_checkbox':
      $block['subject'] = null; // Most forms don't have a subject
      $block['content'] = drupal_get_form('ios_lang_checkbox_form_function');
      break;
   }
   return $block;
 }

?>

```

Any help with that?

# Answer
> 1 votes
In order for `hook_block_view()` to work properly you also need to implement `hook_block_info()`, which in your case would look something like this:

```
function ios_lang_checkbox_block_info() {
  return array(
    'ios_lang_checkbox' => array(
      'info' => t('Block Name'),
      'description' => t('Block description')
    )
  );
}

```

That will register a block called `ios_lang_checkbox`, which will become the `$delta` var when your implementation of `hook_block_view()` is invoked.

At the moment, when that function executes there's no `$delta` available (since one hasn't been defined), and hence `$block` is undefined when you return it. Usually one would write `$block = array()` at the start of the function to avoid this, but in your case that would actually just have masked the problem.

The signature for your form function is slightly wrong, that needs to be:

```
function ios_lang_checkbox_nameform($form, &$form_state) {

```

It won't actually affect anything on a form that simple, but it's a good practice to get into...eventually it will come back to bite you if you don't!

The other small issue is the name of the form function you're calling inside `hook_block_view()`...I suspect you mean it to be the same form that's available from the path defined in `hook_menu()`, in which case that line should be:

```
$block['content'] = drupal_get_form('ios_lang_checkbox_nameform');

```

Once you've made the changes, make sure to clear Drupal's caches...otherwise your new hook implementation won't get picked up.

---
Tags: forms
---


# Question
Title: Saving a field of type 'text_format' as a system setting variable
I'm attempting to give my content editors the ability to change a variable for a custom module. This variable can have html. I don't want to require them to have any knowledge of HTML, so I want to give them the ability to have our wysiwyg (CKEditor provided by the CKEditor module) at their disposal. However, as of now, the data does not save as a variable. I've read in a few places (D.o, stackexchange) that I needed to do something like this:

```
  $form['foo']['bar'] = array(
    '#type'     => 'text_format',
    '#title'    => 'Bar',
    '#definition' => 'Foo Bar',
    '#default_value' => variable_get('bar', ''),
    '#weight'   => 1,
    '#format' => 'filtered_html',
    '#required' => FALSE,
  );

```

This does not work out-of-the-box with a system\_settings\_form($form). A var\_dump shows this after a save:

```
array (size=7)
  '#type' => string 'text_format' (length=11)
  '#title' => string 'Bar' (length=7)
  '#definition' => string 'Foo Bar' (length=74)
  '#default_value' =>
    array (size=2)
      'value' => string '' (length=0)
      'format' => string 'filtered_html' (length=9)
  '#weight' => int 1
  '#format' => string 'filtered_html' (length=9)
  '#required' => boolean false

```

From this, you can see that 'format' saves correctly, but 'value' does not. What am I missing?

Also, if there is a better way to do this, please do tell.

# Answer
The following worked for me; the #default\_value is expecting a string but the text\_format form element is stored as an array.

```
$barvalue = variable_get('bar', array('value' => '', 'format' => NULL));

$form['foo']['bar'] = array(
'#type'     => 'text_format',
'#title'    => 'Bar',
'#definition' => 'Foo Bar',
'#default_value' => $barvalue['value'],
'#weight'   => 1,
'#format' => $barvalue['format'],
'#required' => FALSE,
);

```
> 30 votes

---
Tags: 7, forms, wysiwyg
---


# Question
Title: Problems to integrate a form into a block
So far, the form is rendered in the block, but the following errors are displayed:

> Notice: Undefined index: ios\_lang\_checkbox\_nameform\_function in drupal\_retrieve\_form()
>
> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'ios\_lang\_checkbox\_nameform\_function' not found or invalid function name in drupal\_retrieve\_form()

```
<?php

function ios_lang_checkbox_block_info() {
  return array(
    'ios_lang_checkbox' => array(
      'info' => t('Ios Like language switcher'),
      'description' => t('Ios Like language switcher')
    )
  );
}
function ios_lang_checkbox_block_view($delta='')
{
    $block['content'] = drupal_get_form('ios_lang_checkbox_nameform');

  switch($delta) {
    case 'ios_lang_checkbox':
      $block['subject'] = null; // Most forms don't have a subject
      $block['content'] = drupal_get_form('ios_lang_checkbox_nameform_function');
      break;
   }
   return $block;
 }

function ios_lang_checkbox_menu() {
    $items['ios_lang_checkbox'] = array(
        'title' => 'View the sample form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('ios_lang_checkbox_nameform'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM
    );
    return $items;
}

/**
 * Define a form.
 */
function ios_lang_checkbox_nameform($form, &$form_state) {

    $options = array(
        'de' => t('de'),
        );
    $form['ios'] = array(
        '#title' => t('Your Name'),
        '#type' => 'checkboxes',
        '#description' => t('Choose language'),
        '#options' => $options,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit')
    );
    return $form;
}

?>

```

Thanks a lot!

# Answer
> 2 votes
You've got `_function` on the end of `ios_lang_checkbox_nameform_function`...just change that line to:

```
$block['content'] = drupal_get_form('ios_lang_checkbox_nameform');.

```

The string passed to `drupal_get_form()` needs to be exactly the same as the function name itself, no need to put `_function` on the end :)

---
Tags: forms, blocks
---


# Question
Title: Insert user password into e-mail body sent by Rules for Ubercart's order completion
I have a Rules for Ubercart

```
Event: Order Checkout Complete
Do :  Send a mail to a user

```

I need to insert the password of the user the mail is sent to but there is no token for it.

How can I insert the user password into the mail body set by Rules modules?

# Answer
> 1 votes
This is impossible because Drupal saves hash of passwords in the database, so you can't access the original password.

---
Tags: 6, ubercart, rules, tokens, users
---


# Question
Title: Node Reference to include an "Apply Now " link
I'm looking for answers to the best approach to dynamically including an "Apply Now"/"Apply For" link/button within node content. For example. the content node has been custom created and visitors (registered users only) can click the "Apply Now" once viewing any said published node. For example, this maybe a "Join Band" on a music band collaborative site, a "Apply Now" on a Jobsite, a "Date Me" on a dating site, "Tender Now" on a contract site etc.

I've also schematicised in LibreOffice Draw for basic work-flow and using the Panels/Ctools/Rules combination along with Relation to ensure that posted content appears in a Users dashboard (based on their profile2/HomeBox type) whereby application Receivers can manage/reply/on-hold/delete such application notices. Or maybe I'm barking up the wrong tree in my approach!?

My Main issues is primarily the inclusion on an "Apply Now" link in any said node and the most effective and futureproof so looking for for clarification on best D7 tools/Modules to use for such a back-end integrated task.

The entry here relates further to my question: Re: Relation Module which relates to a previous module I had started to utilise, but have now made redundant due to it's original author's Module depreciation, but in essense looking for an answer a generalistic approach to building such frameworks of this nature using common D7 modules (no custom coding at present), which I'm sure are very common.

Current overview found: http://www.lullabot.com/articles/photo-galleries-views-attach identities a similar issue, but I'm not too sure if this would be the correct/come best effective approach.

I am a newbie and any help is much appreciated. Anything I learn, I'll gladly pass it on here. Thanks in advance.

# Answer
> 1 votes
I opened a discussion on this here http://drupal.org/node/1204554. There are a couple of approaches/solution that you may find helpful.

iRex

# Answer
> 1 votes
Consider this as a comment but I can't write this in a tiny comment box.

Even though you explain what you want to display,you didn't say what should be the rest. So my answer here is based on your job site example's "Apply Now" functionality.

One approach you have is to, use a new node type as the application. So employers can create a "job" node and workers can create "application" node type. You can bind these 2 nodes with a Node References (from References or Entity Reference module for Drupal 7).

If the job node is at node/12345 , a worker can apply for the job by clicking on a button. That button should send the user to node form to create a "application" node with some sort of a link to the original "job" node. That's what Node Reference URL Widget can do. it can populate the "job" node reference automatically from the given node ID.

ex: job node: node/12345 Apply now button's location: node/add/application/12345 Application node would be node/12390.

Both are nodes but in 2 different types. Now you can use Views to list applications of the job and for worker dashboard, a list of jobs they have applied.

If you want to have "hire" button or something, you can make use of Flag + Rules module to populate a node reference field in the parent job node to the application. (Trigger Rules on even user flags an application node).

---
Tags: nodes
---


title: How to use panels for embeded nodes?

text:
# Question
Title: How to use panels for embeded nodes?
I use Inline Entity Form to embed nodes within nodes.\*

When editing these nodes, the embedded nodes appear as one block within Panels, so I cannot re-arrange the fields inside the embedded nodes:

I would like to split out the nodes into separate panes. I would also like to be able to re-arrange the fields in each embedded node using Panels drag-and-drop interface, as in this mock up:

How can I achieve this?

Mini Panels lets you get the first child node only. Views Context gets all the embedded nodes. However, it will lump similar fields together. (e.g. all the image fields will be displayed in one pane).

\*(Embedding nodes within nodes is useful as each separate node can hold a group of fields. The effect is similar to Field Collection, but there are extra advantages such as being able to share content between nodes).

# Answer
> 1 votes
First, just checking I've understood the problem correctly (please correct me if wrong):

* You have a page set up using panels, on which you want to display a node and that node's child nodes.
* You want a list of child nodes that is configurable. Mini panels don't work well for as the number of child nodes can vary.
* Panels is essential, Inline Entity Form is not necessarily essential but is the best option you've found so far for giving nodes child nodes

---

If this is right, I wonder if you couldn't get what you want using Context Views in panels that use relationships from Relation module (or Entity Reference might do the job more simply - Inline Entity Form might work the same way too but I don't know how well it integrates with Views). After all, lists of any number of items from one relationship with configurable fields is something Views is designed for, and using a context view allows you to chop the view up in Panels and place each part of the view in a way that suits your layout:

* Create a directional relation type between the appropriate node types - let's call it 'Is child of' (or, add an entity reference field to the parent node content type)
* Create a view block showing content and give it a Context display ( context displays are a display type along the top like Page, Block...)
* Give it a contextual filter for the Nid of the parent node, and a required relationship using the entity reference or relation to get the referred child node (if it doesn't work first time, the last time I used relation with views you had to chain node\>relation and relation\>node relationships to get the other node. Direct node\>node relationships didn't work. Might be fixed by now)
* Add and configure your fields however you want them in Views, using the 'Is child of' relationship for each of them
* In Panels, load the view as context on the Panels Context page (make sure the view's contextual filter gets the nid somehow)
* In Panels Content page, you'll find the elements of your view under View Context. You can place all rows (each row being one child node), individual rows or row ranges, and header, footer, exposed filters etc whereever you like in your panels layout.

The individual fields within each 'embedded' child node are controlled in Views - which has all the flexibility of Panels plus extra features for rewriting, tailoring and combining individual fields - and the display between the child nodes and each other and other page elements is controlled in Panels.

If you choose Relation, you can also add fields to the linking relation itself, which can be included in each row of the view. I believe you could also have one multiple endpoint relation where one parent has several children on the same relation entity sharing the same relation fields. Not sure if they've got those cases working with Views yet, though. Entity Reference is less powerful, but simpler.

# Answer
> 2 votes
Try using user568458's solution, but instead of displaying fields in the view, display a "fully rendered node" and set the view mode to a custom view mode.

To customize a view mode, and then configure the layout of a custom view mode, use Display Suite module.

See this about view modes.

If you activate Display Suite's sub module *Panel View modes*, you can then use the Panels module interface, instead of Display Suite for layouts.

**EDIT** I just went to do this myself and discovered that this feature has disappeared in the latest version of Display Suite!

Bummer :(

However, you can still utilize Display Suite to a lesser degree... Sorry

---
Tags: panels
---


# Question
Title: How can I display information about a referenced node within a content creation page?
I have a content/entity type called `venue`. On these `venue` nodes, there is a link to review the venue. When users click on this link, they are taken to a content creation page for a `review` content type. The content creation form has an entity reference field, populated automatically with Entityreference Prepopulate, so that the `review` is associated with the correct `venue`.

I would like to display information about the `venue` being reviewed (including name, address, etc.) on the `review` content creation form, for the purposes of clarification for the user. I'm assuming that there is some way to fetch this information since both the url (/node/add/review?field\_venue\_reference\_review=9) and the reference field contain the NID for the `venue`.

What would be the best way to pull information from the venue node and display it in/above/near the review form? I've tried to do it using a views block with a contextual filter, but it seems that since the NID neither has its own place in the url, or is in the standard place that an NID would be placed on the url of a node page, views cannot detect it. There may be another way to do this that I'm not realizing.

Any help would be greatly appreciated, as I've being searching for an answer for quite some time. Thanks in advance for any help.

# Answer
> 0 votes
At the moment, there doesn't seem to be a way to do this. If I do find a way, I will update this.

# Answer
> 0 votes
If I was faced with this problem I would look to views to help me solve it.

1. Create a view for the `review` content type containing the fields you want to display.
2. Add the entity reference relationship to that view.
3. Pass the correct node id as the argument using that reference.

# Answer
> 0 votes
Stumbled on this question whilst looking for something totally different. I think a good solution to this problem is actually http://drupal.org/project/field\_collection as an embedded review solution. This means your users wont even have to leave the venue page in the first place to create a review. Together with some field permissions you can have so that only specific roles can create/edit the field collections.

---
Tags: entities
---


title: How to partially upgrade a site?

text:
# Question
Title: How to partially upgrade a site?
I'd like to redevelop a site on my local machine (which takes a few days to accomplish) and then import to it only the nodes which are created on the production site during this period, so that importing new nodes does not undo changes made on the local version and then I can migrate the redeveloped version to production without loosing recent activities.

I am wondering whether it is possible, and how? I appreciate your hints.

# Answer
> 1 votes
Depending on the complexity of your nodes (if using custom fields or references) you might be able to use the node export module to export the nodes as CSV files and on the new upgraded site use Feeds to import them. Keep in mind that if the nodes NID are needed for an specific menu the NID might not match.

**Note:** you might also want to check the migrate module as well as the deploy module.

---
Tags: nodes, importing-exporting
---


# Question
Title: Does Entity Translation hijack i18n's operations?
I'd ideally like to use i18n to handle backend translation but use entity translation to maintain multiple language versions for each content node.

Does this require a lot of extra work or lead to caveats? I'm hoping they just handle different sides of the translation puzzle.

# Answer
It's not that difficult or complicated, you just need to know what to do, where and using what. Have a look at Drupal 7 Multilingual Sites book, it has pretty good explanation of the whole process. Essentially, yes, Entity Translation plus i18n modules would take care of most of the things for you.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How do I troubleshoot 'Theme key "" not found'?
How do I troubleshoot the error `Theme key "" not found`?

I found dozens of search results regarding specific keys, but nothing useful for debugging an empty key ("").

Here is the full entry from syslog:

```
Sep 12 09:45:47 core drupal: http://www.example.com|1347457547|theme|192.168.1.10|http://www.example.com/|http://www.example.com/admin/config/development/logging|1||Theme key "" not found.

```

What exactly triggers this error and how should I go about debugging it?

# Answer
This warning message comes from `theme()` function in `includes/theme.inc`. For temporary debug you could just add `ddebug_backtrace()` there (if you're using Devel module) to see where the call comes from (and see what are the params). If not using Devel, just check output of `debug_backrace()`. And then it all depends what you are going to find out...
> 1 votes

---
Tags: debugging
---


title: Multiple users on one profile?

text:
# Question
Title: Multiple users on one profile?
Does anyone have any solutions for multiple users using one profile? Looking for something like profile2 but with the option open for more than one person to use a single profile. Say for instance a company name or organization.

# Answer
> 3 votes
Using Views sounds like a way to go. You could have separate *employee* and *company* profiles (where *employee* profile references *company*), and then add a view to each company profile listing all its employees.

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


# Question
Title: Selecting image for embedded youtube video
Would like to know how to select the image that is shown on the web page for an embedded youtube video. Currently an image from the video seems to be randomly pulled out and used.

# Answer
> 0 votes
Sadly you cant if its not your video. This is chosen either by youtube or if your a youtube partner you can upload your own image (I think they have a tool nowadays which lets regular youtube users choose their thumbnail for their video).

If you visit this page:

https://developers.google.com/youtube/2.0/developers\_guide\_jsonc

You will see down the page there is a default/hqdefault thumbnail that comes with every video feed.

---
Tags: media
---


title: Combine two views on one page

text:
# Question
Title: Combine two views on one page
I have 2 custom views(block types) 'view\_A' and 'view\_B', one shows content the other shows orders. I need to cobmine them in a single page displaying in 2 different tables. Really dosen't make sense to bundle events and orders in one table.

I tried creating a page, but I can't select 'block' for the context type. I can only select nodes. What's the best way using the UI in Drupal 7 to do this?

# Answer
> 8 votes
A simpler way can be:

**Current Setup:**

1. View A (show content)
2. View B (show orders)

**Steps:**

1. Create a new "page display" of the View A and set the path and menu if you have to.

2 a. Then on the view header or footer (*depending if you want the View B before or after View A*) add a global view area that will show the View B when viewing View A page.

2 b. Select from your existing views the View B

2 c. Apply the change to the current display and you are done.

# Answer
> 3 votes
You could just make a blank page with a custom path (i.e. /my-empty-page) and no content.

Then in the structure\>blocks menu assign the blocks to the content region and set them to only show up on the URL for the page you just made?

# Answer
> 2 votes
You can use the Views Field View as well. So you create 2 separate views and then decide which one do you want to place in which region i.e header or footer and based on that add the Global: View (Views field view) from the global section.

The only difference which I know from the above method is this module allows you to pass arguments as well from the parent view and has token integration as well.

---
Tags: 7, views
---


# Question
Title: How do I use entity_metadata_wrapper to create a node and at the same time multiple node references?
I have an XML response from a REST api call that returns an object with an array of sub-objects contained in it.

I need to create a node with all the properties of the top level object and node references to nodes created from the sub-objects. I probably will make them nodes but I would prefer to use the Entity API instead of the Node API even if they are nodes.

```
<toplevel>
  <prop1></prop1>
  <prop2></prop2>
  <array_of_sub_objects>
    <sub1>
      <sub_prop1></sub_prop1>
      <sub_prop2></sub_prop2>
      <sub_prop3></sub_prop3>
    </sub1>
    <sub2>
      <sub_prop1></sub_prop1>
      <sub_prop2></sub_prop2>
      <sub_prop3></sub_prop3>
    </sub2>
  <array_of_sub_objects>
</toplevel>

```

Here is an example of 3 objects with 2 contained inside the 1. I need to create 3 nodes or entities with an entity reference of the 2 sub-objects to the toplevel object. How do I use the Entity API to programmatically do this?

# Answer
> 1 votes
You should probably look at Migrate module. IT has support to import xml data into nodes.

---
Tags: entities
---


title: Error with validate

text:
# Question
Title: Error with validate
```
 function mymodule_form_alter(&$form, &$form_state) {

            if ($form['#form_id'] == 'article_node_form') {
              $form['#validate'][] = '_mymodule_test_validation';
                }
    }

    function mymodule_test_validation($form, &$form_state) {
        dsm("hello");
    }

```

Why is not printed the word "hello"?? What is my error in this code.

# Answer
Please see right way of doing form alter below

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    $form['#validate'][] = 'mymodule_test_validation';
  }
}

function mymodule_test_validation($form, &$form_state) {
  if(($form_state['values']['test_field']) == ''){
    form_set_error('test_field', t('You must select a name for this group of  settings.'));
  }
}

```

FYI, `hook_form_alter()`, Form API reference #validate and `form_set_error()`
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: Replace default submit handler when using drupal_get_form() in D7
I'm having issues calling an existing form from the commerce\_coupon module which runs a default submit handler callback (commerce\_coupon\_form\_submit).

My form builds off of that form and simply tries to replace the default '#submit' value to call my own submit function instead of the default commerce\_coupon one. I'm using drupal\_get\_form so my code looks like the following:

```
$form = drupal_get_form('commerce_coupon_form', $coupon);
$form['#submit'] = array('mymodule_coupon_submit');
return drupal_render($form);

```

That is the code from inside a function that is supposed to return the rendered form. The problem is the default commerce\_coupon\_form\_submit submit handler is still running and my own function doesn't get called. I think this has something to do with the form\_id or form\_state still being commerce\_coupon\_form.

I've found related problems on stackexchange but responses were directed for other versions of Drupal. I'm using D7 so please bear that in mind.

I'm adding a little more detail that may help get a better answer for this. The original commerce\_coupon\_form seems to try to use a button-level #submit handler as there is the following before the form is returned:

```
$form['actions'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('form-actions')),
    '#weight' => 400,
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save coupon'),
    '#weight' => 40,
  );

```

but the actual #submit handler isn't assigned so the default drupal handler is being set at the root of the form. I've tried assigning a button-level submit and overriding the root drupal assigned submit to a blank array but that doesn't seem to work. I'm trying to track down documentation for drupal or the function that sets the default #submit so I can figure this out. If you can point me in the right direction I would appreciate it.

# Answer
> 0 votes
On suggestion of @Clive I dug through some of the functions that the Drupal form builder works off of. The easy way to get this done was to build a wrapperform so essentially my own form. To load the original commerce\_coupon\_form's elements I used drupal\_retrieve\_form so my end result looks something like this

```
function mymodule_custom_wrapper_form($form, &$form_state, $coupon) {
  $form = drupal_retrieve_form('commerce_coupon_form', $form_state);
  return $form;
}

```

I end up calling drupal\_get\_form with my own mymodule\_custom\_wrapper\_form as the form\_id argument. Now drupal adds default submit callbacks based on my forms id. That works for now for pulling in form elements from an existing form but I'm still looking for a way to have the original form's hooks remain intact. I'm guessing that will be a greater feat since I just got rid of the core of the original form's functionality by not using drupal\_get\_form directly on the original form. For anyone else trying to implement a type of form within a form this is a good start but there is a module I stumbled into. http://drupal.org/project/subform might be an easier approach to accomplish something similar.

# Answer
> 1 votes
The problem is when the form builder builds the form up again when it's submitted, your function won't be called so it doesn't know about the changes you've made.

`hook_form_alter()` (and `hook_form_FORM_ID_alter()`) were written for exactly this purpose, I'd advise using one of those, e.g.

```
function MYMODULE_form_commerce_coupon_form_alter(&$form, &form_state, $form_id) {
  $form['#submit'] = array('mymodule_coupon_submit');
}

```

It's worth bearing in mind that other modules' hooks might run after yours and change that array again. To avoid that have a look at How to update a module's weight.

# Answer
> 0 votes
You need first unset defaut `#submit` array

```
 $form = drupal_get_form('commerce_coupon_form', $coupon);

unset( $form['actions']['submit']['#submit']);
// or empty it
$form['actions']['submit']['#submit']='';

$form['#submit'] = array('mymodule_coupon_submit');
return drupal_render($form);

```

---
Tags: forms
---


# Question
Title: Display certain content based on whether a date is in the past or future
I have a content type called 'DVD Review' with a field called 'Release Date' which is input using the date module.

On the node page, if the release date is in the future I'd like it to say "Coming Soon", or otherwise, if the release date is in the past say "Out Now".

I'm using Display Suite to arrange the fields, so I'm thinking I could add a code field with a php if statement to handle this.

# Answer
Please follow below instructions to add new custom code field.

1. Go to admin/structure/types/manage/**your\_content\_type**/display
2. Click on Add Custom Fields Vertical Tab @ Bottom of Screen.
3. Click on Add a Code Field.
4. Use $entity object to get Release Date based on that display the message.
5. Enable the Code Field in right place.

Post comments if you have any Questions.
> 1 votes

---
Tags: datetime, display-suite
---


# Question
Title: How to add order number to multivalue fields classes?
A node with a multivalue image field looks something like this in html (the part which displays images):

```
<figure class="clearfix field-item even"><a><img src=....></a></figure>
<figure class="clearfix field-item odd"><a><img src=....></a></figure>
....
<figure class="clearfix field-item even"><a><img src=....></a></figure>
<figure class="clearfix field-item odd"><a><img src=....></a></figure>

```

I would like it to look like this:

```
<figure class="clearfix field-item even image01"><a><img src=....></a></figure>
<figure class="clearfix field-item odd image02"><a><img src=....></a></figure>
....

```

One way is to write a node--contenttype.tpl.php and inside, instead of `print render($content);` make a big loop which will render the fields one by one, adding the necessary class with number to images.

Is there a simpler way to achieve this?

# Answer
> 2 votes
template\_preprocess\_field(&$variables, $hook) gives you the ability to manipulate fields before they are printed. Just like with `template_preprocess_page()` and `template_preprocess_node()`. Not sure what the `$hook` parameter is for and I have never needed it myself.

Since this is a preprocess function that will be executed for each field, you should add a condition for your field name. Something like this will do:

```
function THEME_OR_MODULE_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'FIELD_NAME') {
    // Manipulate the data. use dsm() or print_r() to see the array structure.
  }
}

```

**Edit:** It would seem as if `$hook` is always passed as the string 'field', which would be quite useless. Can anyone confirm this?

**Edit 2:** Okey, so you actually don't need `template_preprocess_field()` at all if you can override theme\_field.

Below is a working example of a extended theme\_field($variables) function based of the original version. There is also a good tutorial/example here, which @camcam shared in a comment.:

```
function THEME_NAME_field($vars) {
  $output = '';
  $i = 0;

  // Render the label, if it's not hidden.
  if (!$vars['label_hidden']) {
    $output .= '<div class="field-label"' . $vars['title_attributes'] . '>' . $vars['label'] . ': </div>';
  }

  // Render the items.
  $output .= '<div class="field-items"' . $vars['content_attributes'] . '>';
  foreach ($vars['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');

    // Add Row index to classes and iteriate row index variable.
    if ($vars['element']['#field_name'] == 'FIELD_NAME') {
      $classes .= ' row-' . $i;
      $i++;
    }

    $output .= '<div class="' . $classes . '"' . $vars['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $vars['classes'] . '"' . $vars['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

# Answer
> 0 votes
You can use jQuery to do this.

```
$('figure.field-item').each(function(index) {
   $(this).addClass("image" + index);
});

```

---
Tags: 7, theming
---


title: Tagging for blogs?

text:
# Question
Title: Tagging for blogs?
Is there a simple way to add the ability to add 'tags' to blog entries in Drupal?

Maybe I need to add a module for this functionality?

# Answer
> 4 votes
Follow below instruction to enable tags on blogs.

1. Login using admin credentials.
2. Go to admin/structure/types/manage/blog/fields
3. Add Tags field by selecting "Select a Type Fields" as "Term Reference" and widget type as "Autocomplete term widget (tagging)"
4. Click on Save.
5. Select Vocabulary as Tags which comes with Drupal Core in next screen.
6. Click on Save Field Settings.
7. Click on Save Settings in next screen.

That's it !

---
Tags: 7, nodes
---


# Question
Title: How to show a variable of node in page template
I have created a content type with some fields in Drupal 7. It output in node.tpl.php of course. But I wonder if I want to display some fields somewhere within the page.tpl.php, how to go about it. e.g. output a content types' field in the header/footer in page.tpl.php or anywhere.

# Answer
*This question is more or less a duplicate of https://stackoverflow.com/questions/8074485/drupal-7-how-to-render-custom-field. But I'd rather see the answer and question here on Drupal.stackexchange.com.*

This goes into your `template.php` or in a module included file.

```
function THEME_OR_MODULE_preprocess_page(&$vars) {
  $vars['VAR_NAME'] = '';
  // Get the object and do some other checks based on what you need.
  if (($node = menu_get_object()) && $node->type) {
    // Generate a render array for the node.
    $view = node_view($node);
    // "Create" a new variable for the page.tpl.php.
    // This will expose $VAR_NAME in the page template.
    // You will most likely have to clear your cache.
    $vars['VAR_NAME'] = drupal_render($view['FIELD_NAME']);
  }
}

```

And then in your page.tpl.php:

```
HTML
<?php print $VAR_NAME; ?>
HTML

```

You might also have to hide the field in your node template, if you don't want to print the field twice. Check at hide() for that.
> 7 votes

---
Tags: nodes
---


# Question
Title: How can to make required the fields keywords and description of the metatags module?
I have a content type and I am interested in make required the field keyword and field description of the metatags module? anyone knows how can I do it?

The field title is not required. The field keywords is required The field metatags is required.

I am working on drupal 7.

Thanks a lot!!

I was trying this code:

```
function mymodule_form_alter(&$form, &$form_state) {
    if ($form['#form_id'] = 'article_node_form') {
        $form['#validate'][] = 'mymodule_form_validate_fields_metatags';
    }
}

function mymodule_validate_fields_metatags ($form, &$form_state) {
     if (($form['#metatags']['metatags']['description']['value']) == '') {
        form_set_error('Description', t('The field Description is required'));
      }
      if (($form['#metatags']['metatags']['keywords']['value']) == '') {
        form_set_error('', t('The field Keywords is required'));
      }

 }

```

this code generate an error : NOtice: undefined index.

I have tried this code and not print dsm:

```
mymodule_form_alter(&$form, &$form_state) {
    if ($form['#form_id'] = 'article_node_form') {
        $form['#validate'][] = 'mymodule_form_validate_fields_metatags';
    }
}

function mymodule_form_validate_fields_metatags ($form, &$form_state) {
dsm("hello");

 }

```

if no print hello how can test the form\_state? I don't understand what is my error. Thanks for your help in advance.

# Answer
> 1 votes
You can use code similar to the following in a custom module/theme:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['metatags'])) {
    if (isset($form['metatags']['description']['value'])) {
      $form['metatags']['description']['value']['#required'] = TRUE;
    }
    if (isset($form['metatags']['keywords']['value'])) {
      $form['metatags']['keywords']['value']['#required'] = TRUE;
    }
  }
}

```

# Answer
> 1 votes
Maybe not a nice solution, but it's possible without any custom code:

1. add a "normal" field for keywords and a "normal" field for description, set both to required
2. hide both fields in 'Manage display'
3. edit the 'Meta tags' settings to give a default value for Meta keywords and Meta description
4. set the tokens of the two normal fields as default values

To the editing user you only show the two normal fields. So don't give them right permission to change the Meta tags fields directly, they should only be able to use the two surrogate fields.

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


title: Drupal 7 Link CCK text field to Node ID

text:
# Question
Title: Drupal 7 Link CCK text field to Node ID
I am creating a view and the Filter Criteria cck text field needs to equal the Node Id. Any ideas on how to accomplish this?

Thanks

# Answer
Include cck text field and node id in your view's field list and then you can make your text field as link to node id.

Also for the filtration you can use contextual filters if required one is not available you can use relations.
> 2 votes

# Answer
Have a look at the "Contextual Filters" on your view. There you have the possibility to use the current node ID as a filter for the view.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Programmatically change view path without views_alter
I have a PHP script in which I want to set the path to a view. For example on site1 I want the news to be at /news/index.html and on site2 I want the news to be at /blog/news/page/1. The sites are sharing the modules folder so I cannot do this from the modules files. So I have a script in which I'm doing my initial setup for each website. Everything works perfect but the view path is not saved.

```
1. $view = views_get_view('news');
2. $view->display['page']->handler->options['options']['path'] = $my_path;
3. $view->save();

```

I also tried to use $view-\>override\_path instead of line 2 but it's still not working.

# Answer
I managed to find the right way. The following code works great for me.

```
$view = views_get_view($view_name, TRUE);
$view->display['page']->display_options['path'] = $new_path;
views_save_view($view);

```
> 2 votes

---
Tags: 7, views
---


title: Modify HTML Output of A View?

text:
# Question
Title: Modify HTML Output of A View?
So I have setup a View as a Block that echoes out three products from Commerce. However I want each of the items to be formatted in this way:

```
<a class="dhover" href="#">
<div class="col33">
<p class="amount">PRODUCT PRICE</p>
<p class="desc">PRODUCT DESCRIPTION<br><br>Donate Now ></p>
</div>
</a>

```

Is it possible to edit the formatting specifically in this way?

Thanks for your time!

# Answer
You can make the same with semantic views, it let you to choose what hmtl tag wants for every field, and also what class/id you want to use.

also, without programing,

I leave enable the link.

I dont't output the amount.

But in the 3º element, I will rewrite the ouput and add the \[amount-token\] So you can build the div you need also.

all this without use tpl.

anyway the best option always will be to make make as say the first comment.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Print out the contents of node object in a node template
How do I print out the contents of the $node object in a node template in a way that is easily readable. I thought that `<?php dpr($node);?>` would do it but that doesn't seem to work in my template.

# Answer
> 0 votes
Devel module have a tab that let you see all the options and elements in that node.

It helps you a lot.

# Answer
> 2 votes
Try below code

```
<?php
   print "<pre>";
   print_r($node);
   print "</pre>";
?>

```

Alternatively you can use below code too...

```
<?php
  drupal_set_message("<pre>" . print_r($node, 1) . "</pre>");
?>

```

# Answer
> 2 votes
To print specific fields in the template you can also try following code:

```
<?php print $node->field_name['und'][0]['value']; ?>

```

To get the value of the body field of node try following code:

```
<?php print $node->body['und'][0]['value']; ?>

```

For more clear understanding: `$node->field_name['und']` will be the Array of all the values of particular fields. So you can try and retrieve any field.

You can also use

```
<?php
  print '<pre>;
  var_dump($node);
  print '</pre>';
?>

```

to see the detailed structure of node, as per suggestion of Anil Sagar.

---
Tags: nodes, debugging
---


title: Displaying Grouped List Items Inline

text:
# Question
Title: Displaying Grouped List Items Inline
Hello i was hoping to create a list view that would look something like this-

FOOTBALL TEAM A football team a link one - football team a link two - football team a link three

FOOTBALL TEAM B football team b link one - football team b link two - football team b link three

etc etc

I have created a view and have it grouped by team. Everything works well. Its just the links below it are also vertical and not horizontal. You can view it here- http://onlinebanter.com/football/links

Ive tried various bits of display:inline aound the view but i just cant seem to find the place that works. Could anyone advise me please?

Thanks

# Answer
You need to add css to your theme css file and clear cache to see the effect...

I am not a css guy, but below css code should work...

```
.view-footballlinks .item-list ul li {
  float:right;
}

```

Try, and let us know...
> 1 votes

# Answer
Can you not use the *Multiple Field Settings* in Views? Or is it necessary for the items to be in an actual html list?

With that you can specify a '–' as a separator between your links.
> 0 votes

---
Tags: views, theming
---


# Question
Title: What it's the easiest way to add a flash frontpage without alter Views node page?
I'm using Views to render content in frontpage, but now, I want create a single flash presentation page as frontpage that links to the current frontpage.

# Answer
> 1 votes
Try using Themekey if its a different look and feel altogether... or Frontpage. Although you can create a node and have that node set as the frontpage in the sites configuration page. You have to use jQuery to have the page render the flash in drupal. As for redirection, what you will have to do is create a jQuery or actionscript that gets redirected at the end of the presentation or use the rule module that gets the page redirected after your particular condition is met. That is what I used on a previous project.

# Answer
> 1 votes
Why not just embed the flash in a normal html page and when the animation finishes have a link at the end that links to your drupal site. I know splash pages are a bit dated now but then again so is having a flash intro.

# Answer
> 0 votes
Create a block and enable the block on Front Page...

---
Tags: 6
---


title: Put class error when I use validate

text:
# Question
Title:  Put class error when I use validate
I am working with the Metatags module, and I have these fields.

I need that looks like as in the following screenshot, when the fields meta description and meta keywords are validated.

This is my code, I don't know how can include the class error and put the * symbol. My question is related with styles. I want the field keywords and description looks as fields required for the user.

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    $form['#validate'][] = 'mymodule_test_validation';
  }
}

function mymodule_test_validation($form, &$form_state) {
   if (($form_state['values']['metatags']['description']['value'] == '')) {
        form_set_error('Description', t('field is required'));
      }
      if (($form_state['values']['metatags']['keywords']['value'] == '')) {
        form_set_error('Keywords', t('field is required'));
      }
}

```

# Answer
If the only validation you are looking for is to make sure the fields are required, then you don't need to call to a validation function. The solution in that case will be to set the "required" attribute to TRUE for the fields description and keywords in the "form\_alter" function. This solution will give you the style you are looking for in the required fields.

Something like this (this is a proof of concept):

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    // Make META DESCRIPTION required
    $form['metatags']['description'] = array('#require' => TRUE,);

    // Make META KEYWORDS required
    $form['metatags']['keywords'] = array('#require' => TRUE,);
  }
}

```

To get the right field names do the following:

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {

   print_r($form);

  }
}

```
> -1 votes

---
Tags: 7
---


# Question
Title: Confusion as to the meaning of `cid` in webform.module
I'm working on a custom module that will return a single question at a time from an existing webform. For example, from the path `mymodule/(webform_nid)/(question)`.

This is my first encounter with `cid`.

From the documentation on webform\_components\_form(), it appears that `cid` represents a *component id*. (Elsewhere in the Drupal API documentation and on forums, I have seen it referred to as *comment id*).

Quickly analyzing some test data, it appears that, as a child element of a webform `nid`, **I can reliably use it to sequentially retrieve single questions from a given webform `nid`.**

Am I correct that `cid`s are unique and sequential *per `nid`*? I assume the implementation of `cid` was done to maintain variable name convention.

Or is a `cid` a unique value assigned to each 'component' across the entire site, as its implementation as *comment id* would suggest (because you can load an existing comment without loading its node, it would need to be a globally-unique value like `nid`)?

# Answer
> 3 votes
A quick look at the `webform_component` table in the database, the description for that field is: "The identifier for this component within this node, starts at 0 for each node."

In my test, however, the first component has a `cid` of 1. AND - keep in mind that if you delete a component, the next `cid` is incremental - so you can't assume 1 - 6 or whatever.

---
Tags: nodes, webforms
---


# Question
Title: Problem with theming form for my module setting page
I am trying to theming my module setting page.

My environment
**version Drupal** 7
**module name:** actionadscatalog
**filesystem:**
actionadscatalog
\- actionadscatalog.info
\- actionadscatalog.module
\- actionadscatalog.admin.inc
\- templates
\- admin
\- actionadscatalog-admin\_run\_import.tpl.php

**actionadscatalog.admin.inc**

```
function actionadscatalog_admin_settings_runImport() {
$form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
);

$form['#theme'] = 'form_style';
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
);
return $form;

```

}

**actionadscatalog.module**

```
function actionadscatalog_theme() {
$path = drupal_get_path('module', 'actionadscatalog') . '/templates/admin';
return array(
    'actionadscatalog_admin_settings_runImport' => array(
        'render element' => 'form',
        'template' => 'actionadscatalog-admin_run_import',
        'path' => $path,
    ),
);

```

}

```
function theme_form_style(&$variables){
$variables['adsru_action_in_load'] = 'hello theme';

```

}

**actionadscatalog-admin\_run\_import.tpl.php**

```
echo $variables['adsru_action_in_load'];

```

But I only see the form with user\_name field. The file actionadscatalog-admin\_run\_import.tpl.php is not run. What have i missed?

Thanks for any help.

# Answer
> 1 votes
It's because you haven't defined a theme registry entry called `form_style`, but you're setting the form's theme handler to a function with that name.

You just need to change your implementation of `hook_theme()` to match the function name and form theme setting you've actually defined:

```
function actionadscatalog_theme() {
  $path = drupal_get_path('module', 'actionadscatalog') . '/templates/admin';
  return array(
    'form_style' => array(
      'render element' => 'form',
      'template' => 'actionadscatalog-admin_run_import',
      'path' => $path,
    ),
  );
}

```

---
Tags: theming, forms
---


# Question
Title: Ubercart entries in menu_links table causing performance issues
Drupal 6: I have found around 130 entries in the menu\_links table such as:

* user/123/order
* user/5a9689f90da4d0d012de104d7da67a8b/order/
* user/123/order//invoice

These entries cause a user\_load to happen which seems to be irrespective of which user is logged in.

Deleting these entries results in around 1000 less queries being run on a page load.

My question is, is it safe to delete these entries and how would they have ended up in the menu\_links table in the first place?

# Answer
Can you give this patch a try? I can't answer you're question directly but I think this might help with all the user loads http://drupal.org/node/1710656#comment-6474030
> 0 votes

---
Tags: ubercart, performance
---


# Question
Title: Blacklisting specific tags from an input format instead of whitelisting
I need a filter for the "Full HTML" input format that allows me to strip specific tags. I want to allow all HTML tags, except the ones specified in the input format options.

I am using Drupal 7.

# Answer
> 6 votes
You can get that functionality out of the box with the HTML Purifier module.

Once you've installed the module, go to the `admin/config/content/formats` page, choose the text format you want to edit, and select the "HTMLPurifier" checkbox. In the settings below, quite a bit further down the page, you'll find the `ForbiddenElements` textarea:

That's where you need to put your disallowed tags. It's probably worth looking at the rest of the settings to make sure they match up with your expectations (there are a lot of them though, HTMLPurifier is pretty configurable).

---
Tags: input-formats
---


# Question
Title: global $language not working in custom module
I have a custom module which I want to check the language code of the current interface language, So I added a helper function to the mymodule.module file.

It didn't work in mymodule when I call it, It returned nothing. But If I added this function to my template.php in the mytheme directory it works like a charm and return the language code for the current interface.

I am guesting that its related to the current weight of the module in the system table, What do you think?

```
function language_code(){
  global $language;
  return $language->language;
}

```

For additional debugging I used `dpm($language);` after defining `global $language;` in mymodule it didn't return the language array.

# Answer
drupal has a function that return default language `language_default` with the below code

```
    function language_default($property = NULL) {
  $language = variable_get('language_default', (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''));
  return $property ? $language->$property : $language;
}

```

I suggest you in `hook_init`(maybe your fuction not called or problem realated to your fuction) call this function

```
function yourmodulename_init() {
  dsm(language_default());
  global $language;
  dsm($language);
}

```

According drupal documentation , `$language` is global variable , you problem is some strange .

I thnik problem is in your function and method of calling function. by default if you put a function in module and your module enabled(after clear cache) ,the function globaly exist and you can use it everywhere (even in views on anywhere you think).

If `dsm` in `hook_init` return `$language` value I suggest you test your function

```
function my_language_code(){
  global $language;
  return $language->language;

```

}

in very where you want

```
$lang=my_language_code();
dsm($lang);

```

test this please
> 1 votes

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


# Question
Title: How to use custom modal with ctools and triggered by a button form
I'm using ctools to render my node form. And my quesiton is how to insert the custom style for the popup window. I know how to use the custom style in the text button. but I don't know how to use it in the button form

the code for my button form

```
function hs_ajax_button_form($cmp_id=NULL)
{
    $form = array();
    $slogan_url='hs_ajax/nojs/slogan/'.$cmp_id;
    $form['url'] = array(
    '#type' => 'hidden',
    // The name of the class is the #id of $form['ajax_button'] with "-url"
    // suffix.
    '#attributes' => array('class' => array('hs-ajax-button-url')),
    '#value' => url($slogan_url),
    );

    $form['ajax_button'] = array(
    '#type' => 'button',
    '#value' => t('New Post'),
    '#attributes' => array('class' => array('ctools-use-modal')),
    '#id' => 'hs-ajax-button',
    );

  return $form;
}

```

and my trigger code is below

```
 $button_form=hs_ajax_button_form($campaign_id);

                    $form['PlayerAttendInformation'][$key]['ctools']=array(
                    '#type'=>'markup',
                    '#markup'=>drupal_render($button_form),
                    );

```

my style is as below

```
    $sample_style = array(
        'slogan-style' => array(
          'modalSize' => array(
            'type' => 'fixed',
            'width' => 800,
            'height' =>700,
            'addWidth' => 20,
            'addHeight' => 15,
          ),
          'modalOptions' => array(
            'opacity' => .5,
            'background-color' => '#000',
          ),
          'animation' => 'fadeIn',
          'modalTheme' => 'CToolsSampleModal',
          'throbber' => theme('image', array('path' => ctools_image_path('ajax-loader.gif', 'hs_ajax'), 'alt' => t('Loading...'), 'title' => t('Loading'))),
        ),
        );

```

how can i do that?

# Answer
> 3 votes
Try this:

```
  $form['ajax_button'] = array(
    '#type' => 'button',
    '#value' => t('New Post'),
    '#attributes' => array('class' => array('ctools-use-modal','ctools-modal-slogan-style')),
    '#id' => 'hs-ajax-button',
    );

```

Vincent

---
Tags: chaos-tool-suite, javascript, theming
---


# Question
Title: Block a single basic page from authenticated users
I have a website with a couple of pages and organic group pages. I'm trying to deny access to one "basic page" for authenticated users. (I only want anonymous users to see the page). Every module I've downloaded seems to mess up my permissions and stuff set up for my other pages and views. Is there any simple way to do this?

I've tried content access and node privacy by role.

# Answer
If you don't mind hard coding the node ID you could do this fairly easily in a custom module using `hook_node_access()`:

```
function MYMODULE_node_access($node, $op, $account) {
  if ($node->nid == $node_id && $op == 'view' && $account->uid > 0) {
    return NODE_ACCESS_DENY;
  }
  return NODE_ACCESS_IGNORE;
}

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to views-filter attached field value by calculated values?
I just want to create a simple "IN" filter for my taxonomy field with values that I calculate in the views\_handler\_filter subclass.

My subclass of views\_handler\_filter implements the function views\_handler\_filter-\>query(). I need to require that the tid of a taxonomy\_term\_reference field is in an array that I build there. How can I build the query to filter by field value?

```
views_plugin_query_default::add_where($group, $field, $value = NULL, $operator = NULL)

```

When calling $query-\>add\_where(), the $field argument is simply described as "The name of the field to check." How can I join the filter query to the field data table and build my $field argument correctly for the taxonomy\_term\_reference field I need to filter by?

# Answer
I solved my current problem in a similar way to the solution here: http://drupal.org/node/1259914

1. Added a filter to the view with my taxonomy field as "not empty"
2. Implemented hook\_views\_query\_alter() to call $query-\>add\_where with my field\_table\_name.field\_data\_column and the values I wanted to accept with the 'IN' operator.

That said, I'm still interested in the views\_handler\_filter-\>query() solution(s).
> 1 votes

---
Tags: 7, views
---


# Question
Title: If I use Panels and Views, do I need to use Blocks at all?
My understanding is that if I go the full panels route (i.e. every node is a panel) then I only need to worry about prepping views to populate the panels. Is this the right way to think about it? Or am I missing something in regards to where blocks are still relevant for site building under an all-panels site?

# Answer
> 3 votes
Well, it depends on what your needs are. Panels and Views is a very powerful combination that can handle almost anything. That said, there may still be times when you need or want a block. For example, the Heartbeat and Revisioning modules both supply useful blocks that I use on my (mostly Panels and Views) site. Yes, these two modules have Views integration, but their built-in blocks are already configured and easier to use than customizing views to meet my needs.

If you need a custom block and are trying to keep things in Panels, you can add a custom content pane. As a bonus, such panes can be exported with the Features module if you have a complicated deployment.

# Answer
> 1 votes
I'd say blocks can be very useful when combined with panels, for instance earlier today I had to place a graphic that linked to a newsletter sign up page in a right column of a page that is controlled by panels. I simply created a new block, uploaded an image using IMCE and CKEditor then pulled that block in using panels, much easier than creating a new region in a template.

# Answer
> 1 votes
I'm new to Drupal but I'm finding I use all three. Four really, if you count Mini Panels. Using all four types of content/display manipulation has let me build a really well layed out site.

---
Tags: views, blocks, panels
---