# Question
Title: How to open pop up window in javascript in drupal 6?
I have made a custom module in Drupal 6 and want to implement the following: When I click on my link it should open in a pop up window in javascript. But I don't know it how to implement pop up window in Drupal.

Please help me.

This is my link code.

```
l('open pop up','admin/state_user/stateadmin/state/user/disable/'
  . $result -> uid, array('attributes' => array('title' => t('open pop up'))),TRUE);

```

# Answer
> 1 votes
Use the Colorbox module.

> Colorbox is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal.
>
> Images, iframed or inline content etc. can be displayed in a overlay above the current page.

You need to activate the iframe method and add the custom iframe class to your link.

# Answer
> 0 votes
Though window.open is not considered as good practice but still if you want to open window in D6 using this then you can do like this.

Create a link

```
<?php echo l('product', 'product', array('attributes' => array('id' => 'product-link'))); ?>

```

Add JavaScript file & add it to theme.info or call it in some custom module.

Write javascript code as

```
$(document).ready(
function() {
  $("#product-link").click(
    function(e) {
      openWindow();
      e.preventDefault();
    }
  );
}
);

```

---
Tags: 6
---


# Question
Title: How To Hide the Contact Button and Replace with a Message
I'm building a room letting website. Next to every advert is a send user private message button.

If the room is no longer available. I want to replace the button with the message "Sorry room no longer available" how can I do this please?

Many Thanks for your help Charles

# Answer
> 0 votes
You can use `hook_form_alter`. Find your form name and use the code below (form api doc).

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id=='your_form_id'){
 hide($form['#submit']);
$form['mymessage']= array(
   '#type' => 'markup',
   '#markup' => 'sorry , no one available in room',
   '#weight' => 0,
);
}
}

```

---
Tags: privatemsg
---


# Question
Title: Add values to an existing custom entity bundle
I've created a custom entity with bundle and added 3 fields to the bundle(namely recipient, sender, flag). How can I add values to it programmatically. Any help would be appreciated.

Thanks

# Answer
> 2 votes
One approach is using entity\_metadata\_wrapper:

> The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner.

Example:

```
$entity_wrapper = entity_metadata_wrapper('myentity', $id);
$var = $entity_wrapper->field_flag->value() + 1;
$entity_wrapper->field_flag->set($var);
$entity_wrapper->save();

```

# Answer
> 1 votes
So this is one way to do it. You have to build an object, then assign values to the fields you've created and call the entity\_save: ("Blocking" entity type and an bundle with the same name).

```
$entity = new stdClass();
$entity->type = 'blocking';
$entity->field_recipient[LANGUAGE_NONE][0]['uid'] = $user->uid;
$entity->field_sender[LANGUAGE_NONE][0]['uid'] = $user_to_block;
$entity->field_blocked[LANGUAGE_NONE][0]['value'] = 1;

entity_save('blocking',$entity);

```

---
Tags: entities
---


# Question
Title: Fatal error when altering the user login form
i want to customize login block in a fancy login box.

i used this code in a template.php

```
function bootstrap_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  $form['name']['#size'] = 30;
  $form['pass']['#size'] = 30;
  $markup = l(t('Forgot your password?'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
    $markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => 'register-link')));
  }
  $markup = '<div class="clearfix">' . $markup . '</div>';
  $form['links']['#markup'] = $markup;
  $form['links']['#weight'] = 10000;
}

```

this code working fine, but on clicking singup link it giving error

> Fatal error: \[\] operator not supported for strings in C:\xampp\htdocs\drupal\includes\common.inc on line 2445

How do I resolve it?

# Answer
Looks like the problem is your class definition.

\['attributes'\]\['class'\] should be an array but you are setting it as a string.

Your line:

```
$markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => 'register-link')));

```

Should be:

```
$markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => array('register-link'))));

```
> 2 votes

---
Tags: theming, blocks, users
---


# Question
Title: How can I let anonymous users comment only once?
I'd like anonymous users to be able to comment only once on a node. I thought about checking whether there's already a comment from the user's IP-adress and, if yes, hiding the comment form, but I don't know how to do that.

How can I achieve this?

# Answer
You can do this by means of two functions called flood\_register\_event() and flood\_is\_allowed().

When a anon user views a node, call `flood_is_allowed` in `hook_node_view` that sets `COMMENT_NODE_CLOSED` for the node.

When a anon user comments, register that as a flood event in `hook_comment_presave` for that particular node. By setting the `$threshold` (parameter for `flood_is_allowed`) to 1, the user will be stopped from commenting after the first comment is posted.

This is the bare bones of how to implement hooks that make use of these functions:

```
function MYMODULE_comment_presave($comment) {
  global $user;
  if (!$user->uid) {
    flood_register_event($comment->nid);
  }
}
function MYMODULE_node_view($node, $view_mode, $langcode) {
  global $user;
  if (!$user->uid && !flood_is_allowed($node->nid, 1)) {
    // This bars the anon user from posting a second comment of the node.
    // For a more sophisticated blocking method (e.g. to prevent the comment form from
    // showing up), ask another question about how to do that.
    $node->comment = COMMENT_NODE_CLOSED;
  }
}

```

PS: The module Anonymous Publishing is already using this pair of functions to limit the number of comments an anonymous user can post (but not exactly in the way you specify). However, looking at the source code of that module should give you an idea about how to use this pair of functions for flood control of anonymous comments.
> 5 votes

---
Tags: 7, comments
---


# Question
Title: Custom login form with signin button -- POSTing registration
I have added a "register" button to the login form which is shown as a block on my homepage. I want the button to simply redirect to the registration page but it's POSTing to login and error'ing -- any ideas?

```
  function MYMODULE_form_user_login_alter(&$form, &$form_state) {
    $form['actions']['register'] = array(
      '#type' => 'submit',
      '#value' => t('Sign Up'),
      '#submit' => array('_user_login_register_submit')
    );
  }

  function _user_login_register_submit($form, &$form_state) {
    drupal_goto('user/register');
  }

```

# Answer
It's not working because the login form validate handler is executed, and fails, before the function you call with the #submit attribute.

You can use #validate like a workaround probably, but there's a cleaner way to achieve what you are after.

I wouldn't create a button element at all. Make it a link to user/register instead and style it to look like a button if needed.
> 0 votes

---
Tags: users
---


# Question
Title: Cache flushing doesn't help after manual deletion of entity references
I have a little function that deletes specific entity references directly from database. Because of fact that it bypass the whole entity\_load / entity\_save system it flushes cache of all entities it affects by itself.

The weird thing is that it doesn't work. The references, while not present in the database, still show up on node view / edit pages.

```
  $affected_users = db_select('field_data_fmu_users_firm', 'su')
          ->fields('su', array('entity_id'))
          ->condition('fmu_users_firm_target_id', $user_id, '=')
          ->execute()->fetchCol();

  db_delete('field_data_fmu_users_firm')
      ->condition('fmu_users_firm_target_id', $user_id, '=')
      ->execute();

entity_get_controller('user')->resetCache($affected_users);

```

No special caching module is enabled on the site.

# Answer
Core has caches. Use the API. If you still do not want to use the API this might be helpful
Is it proper to perform a db\_update on an entity table?
> 2 votes

# Answer
As @mikeytown2 suggested the problem was in cache\_field cache. The solution is quite simple:

```
// Clear field cache
cache_clear_all("field:node:$node->nid", 'cache_field');

```
> 0 votes

---
Tags: caching, entities
---


# Question
Title: Charging UserPoints for flagging a node with Rules in PHP
I am trying to charge points for flagging a node with Rules in PHP, an I am using the following code.

```
 //Get variables and load user.
$uid = [userpoints-transaction:user:uid];
$account = user_load($uid);

// Check the user has enough points.
if ($loaded_points > 10) {

  // DON'T KNOW HOW TO TAKE 10 POINTS.

  // Flag a node.
  $flag = flag_get_flag('purchase') or die('no "purchase" flag defined');
  $flag->flag('flag', $node->nid);
  // Search for the newly created flagging entity.
  $flag = flag_get_user_flags('node', $node->nid);

  foreach ($flag as $flagging_object) {
    $flagging_id = $flagging_object->flagging_id;
  }

  // Load the entity found and create or update a field value.
  $flagging = entity_load_single('flagging', $flagging_id);
  $flagging->purchase['und'][0]['value'] = 'DONT KNOW DEFAULT VALUE OF FLAGGING';

  // Save the updated flagging entity object.
  entity_save('flagging', $flagging);
}

drupal_set_message($msg);

```

I don't know how to charge them 10 points and what the default value is when flagging a node.

# Answer
When you simply want to grant 10 userpoints to a user after flagging a node, you're making things way to complicated! This can be done without custom coding at all. Here's what you have to do:

1. Create a new rule.
2. Add an event "A node has been flagged, under YOUR\_FLAG".
3. Add an action "Grant points to a user" and give it an amount of 10.
4. Done!
> 1 votes

---
Tags: 7, rules, userpoints
---


# Question
Title: Can I hide date field if older than a certian time using Rules?
I want to know if I can hide the values of a date field if the values are older than a certain time. The website is built with Drupal 7, and Display Suite.

# Answer
Use the Conditional Fields module.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
> 1 votes

# Answer
The field formatter conditions module allows you to configure your field formatters with various conditions.

One of the included conditions is "Hide date field if from/to has expired", which should cover your requirements.

The module also has rules integration, but that shouldn't be needed for your requirements.

\[EDIT\] Actually it only allows working based on current time, not an arbitrary time.
> 1 votes

---
Tags: entities, rules, datetime, display-suite
---


# Question
Title: How to redirect anonymous users to login page using Rules module?
I'm using rules module with drupal 7 in order to redirect anonymous users to the login page, so I created a rule with react on event "Drupal is initializing", condition "User has role" with anonymous user and "Not site login url", then added an action "Page redirect" to site login url. When I tried to test the rule; drupal kept redirecting to the login page over over and over until apache server stopped working. Any recommendations.

# Answer
The way I solved it as follow:

* **Events:** Drupal is initializing
* **Conditions:**

1. *User has role(s)* \- `Parameter: User: [site:current-user], Roles: anonymous user`
    2. *NOT Text comparison* \- `Parameter: Text: [site:current-page:url], Matching text: user/login`
* **Actions:** *Page redirect* \- `Parameter: URL: user/login`

---

Export rule as follow:

```
{ "rules_login" : {
    "LABEL" : "login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "login" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/login" } }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/login" } } ]
  }
}

```
> 12 votes

# Answer
Go to `/admin/people/permissions` uncheck View published content for anonymous users

now go to `/admin/config/system/site-information` add 'user' in (access denied) page field
> 3 votes

# Answer
I'm sure you can pull this off with rules, but it would be easy to do in your theme's template.php file as well.

Something like this should work:

```
global $user;
if ($user->uid == 0 && arg(0) != 'user' && arg(1) != 'login'){
  drupal_goto('user/login');
}

```

Or, if access to the user/registration & user/password pages is still wanted:

```
global $user;
if ($user->uid == 0 && arg(0) != 'user'){
  drupal_goto('user/login');
}

```
> 1 votes

# Answer
The problem here is the event in question. Instead of `Drupal is initializing`, try `Content is viewed`.
> 0 votes

# Answer
I know this is a post from two years ago. However, the solution for redirecting an anonymous user to the user login page with rules is as follows:

* event: System log entry is created
* condition: User has role(s): anonymous
* action: page redirect value: user

Hope this will help someone.
> 0 votes

---
Tags: rules, users
---


# Question
Title: how can I set #attributes for each item of selectlist
I know I can set style for form items with `#attributes` but I want set background for select list (drop down) items, how can set `#attributes` for each item of select list(dropdown) in form\_alter ?

# Answer
> 3 votes
```
function MYTHEME_select($vars) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '<select' . drupal_attributes($element['#attributes']) . '>' . MYTHEME_form_select_options($element) . '</select>';
}

function MYTHEME_form_select_options($element) {
  // Build up your own version of form_select_options here
  // that takes into account your extra attribute needs.
  // This will probably involve inspecting your custom FAPI property,
  // which we'll call #extra_option_attributes
}

```

And your code in the form would be something like:

```
$form['select'] = array(
  '#type' => 'select',
  '#options' => array(1 => 'One', 2 => 'Two'),
  '#extra_option_attributes' => array(
    1 => array('title' => 'Test title'), // Attributes for option with key "1",
    2 => array('title' => 'Test title'), // Attributes for option with key "2",
  )
);

```

In MYTHEME\_form\_select\_options() you can then inspect the element's #extra\_option\_attributes key (if one exists) to see if you need to physically add any more attributes in the HTML you create.

Credit to @Clive for this post : https://stackoverflow.com/questions/9261224/adding-attribute-to-option-element-using-forms-api-drupal-7/9264589#9264589 .. Cross posting here in Drupal Q & A

---
Tags: forms
---


title: Conditional Field in Content Type

text:
# Question
Title: Conditional Field in Content Type
I am looking for a module or a method in Drupal 7 that can achieve the following:

I have a field in a content type called e.g. "Is the Ladder Attached". It has a select list, YES or NO.

When a user selects YES then I want it to populate another field next to it saying "No Hazard".

When a user selects NO then I want it to populate another field next to it saying "Hazard".

How can this be done? I tried the conditional field module and it doesn't seem to be the right solution.

Thanks

# Answer
You can try the Field Conditional State module: With field conditional state module you can set #state form field attribute based on value selected in other form fields.

Module splits fields into two types:

* Control field - field which set #state attribute based on the value from that field
* controled field - field for which #state attribute is set based on the value from the control field.

Module supports AND/OR functionality for control fields which means:

* AND - all choices must be selected to control the filed (example: field A will be visible when in field B option 1 and option 2 is selected)
* OR - any choice will control field (example: field A will be visible when in field B option 1 or option 2 is selected).
> 3 votes

# Answer
I think **Conditional Fields** best suits your requirement.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

Follow this https://drupal.org/project/conditional\_fields
> 1 votes

---
Tags: entities
---


# Question
Title: Views with logged user contextual filter stop working after adding relationship
I have two content types in a project I am working right now. Content type A has a field that hold the user ID of the user that "reserved" a node from that content type. Once the user has reserved a node from Content type A, he/she can then create a node from Content type B referencing the "reserved" node from Content type A. All that is done and working like a charm.

My issue is that I created a View where I want the user to see all the nodes he/she has reserved (Content type A), but I want to exclude the nodes from Content Type A that he/she has already used to create nodes for Content type B. The solution was fairly simple. I added the reserved by field to the contextual filter and I used the ID of the logged user and I added a relationship to "A bridge to the Content entity that is referencing Content via field\_USED\_FOR\_REFERENCE"

The odd thing is that for user 1, the View work like a charm, but for other users the view display a blank page. I have rebuilt the permission, clear the cache, test the preview SQL query with the other users IDs (it does work), but the view page still show me a blank page for any user that is not user 1.

> **Note:** In my tests I have remove all the views permissions without any luck. If I remove the relationship in the views then everyone can see the views results and not only user 1.

What am I missing?

# Answer
Sounds like a permissions issue. User 1 has access to everything, others do not.

What I would do is: 1) Either backup your site, or note (screenshot) what permissions you have set currently 2) Start adding several permissions at a time, and going back to check if the view has changed, until you've exhausted all permissions
> 0 votes

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


title: Undefined variable: nid

text:
# Question
Title: Undefined variable: nid
I put this code in Rules Action PHP Evaluation. What I want is getting the field\_price's value, changing it for negative and returning it for Rule. With this I will be able to charge points because in Rules (Drupal 7) it is impossible to put "-" before data-selector (in this case, field\_price's value) and make it negative to charge these points instead of adding them.

```
<?php
if (arg(0) == 'node') {
   $nid = arg(1);
}
   $node = node_load($nid);
   $value = $node->field_price['und'][0]['value'];
   return $value;
?>

```

# Answer
> 2 votes
The reason you're getting the error "Undefined variable: nid" in some cases is obvious. You're *only* assigning a value to `$nid` if the following is TRUE: `arg(0) == 'node'`. If `arg(0)` is something else, `$nid` never becomes defined, causing the error.

Since it doesn't make sense to use `$nid` *unless* it is defined, you can get rid of error by moving the construct where you *use* the value of `$nid` inside the if-test, like this:

```
<?php
if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid);
  $value = $node->field_price['und'][0]['value'];
  return $value;
}
else {
  return FALSE;
}
?>

```

Note that this will return the value stored in the field `field_price` if `arg(0)` is equal to the string `'node'`, and return `FALSE` otherwise.

You write:

> What I want is getting the field\_price's value, changing it for negative and returning it for Rule.

Please note that your original code does not do that. Nor does mine. I just told you how to fix the bug. The business logic is still up to you.

Please also note that this has nothing to do with Drupal - it is Programming 101.

# Answer
> -1 votes
**Assumptions**:

1. You have a numeric array named arg where you are storing `node type` in even indexes and `node id` in odd indexes.
2. You want to load the specific node into memory and call the member function `field_price` of node object which is a custom field added using the hook `node_field_extra_fields()`.

Now if my assumptions are correct, then the solution to you problem should be :

```
<?php
function get_node_price{
if ($arg[0] == 'node') {
   $nid = $arg[1];
}
   $node = node_load($nid,NULL,FALSE);
   //Not sure whether the args and the method are correct here as it's custom.
   $value = $node->field_price['und'][0]['value'];
   return $value;
}
?>

```

---
Tags: rules, nodes
---


# Question
Title: how to change node edit path from node/[nid]/edit to node/[nid]/update?
I have Pathauto which changes node/\[nid\] to having a path of \[title\]; I then use subpathauto to change node/\[nid\]/edit to \[title\]/edit.

But now how can I change the edit fragment? I want to change all instances of edit to update. so the URLs would be \[title\]/update instead of \[title\]/edit.

I cannot use arguments or wildcards in Pathauto, so I cannot specify a path like `*/*/edit` to be `*/*/alter`, but that is effectively what I would like to happen.

# Answer
> 2 votes
I think this is a legit request as long as you add an additional alias as opposed to overwriting system paths.

I would implement `hook_node_insert()` and then use `path_save()` to set your custom edit path on node creation. You will also probably need to make sure that this hook runs after the Pathauto module has set its path, so you can use the alias it sets as part of your additional edit alias.

---
Tags: uri
---


title: How to load field value to custom form?

text:
# Question
Title: How to load field value to custom form?
I'm using Drupal 7 for my website. I created custom settings page with custom form in it, but the problem is I don't know proper way to load inserted value from database to my form after saving it, and every time I write something in it, information is written to database, but form is empty. My code looks like this for this:

```
function registration_pdf_form($form, $form_state) {
    $form['registration_body_twoside'] = array(
        '#type' => 'text_format',
        '#title' => t('Two-sided PDF'),
    );
    $form['registration_body_threeside'] = array(
        '#type' => 'text_format',
        '#title' => t('Three-sided PDF'),
    );
    $form['actions'] = array(
        '#type' => 'actions'
    );
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save settings')
    );
    return $form;
}
function registration_pdf_form_submit($form, $form_state){
    $values = array(
        'reg_twoside' => $form_state['values']['registration_body_twoside']['value'],
        'reg_threeside' => $form_state['values']['registration_body_threeside']['value'],
    );
    $insert = db_update('pdf_settings')
        -> fields(array(
            'reg_twoside' => $form_state['values']['registration_body_twoside']['value'],
            'reg_threeside' => $form_state['values']['registration_body_threeside']['value'],
        ))
        ->execute();
    drupal_set_message(t('Settings have been saved'));
}

```

How do I get values to my fields from database?

# Answer
You can try using system\_settings\_form which is simple way of storing settings in Drupal..

```
function registration_pdf_form($form, &$form_state) {
   $form['registration_body_twoside'] = array(
        '#type' => 'text_format',
        '#title' => t('Two-sided PDF'),
        '#default_value' => variable_get('registration_body_twoside', ''),
    );
    $form['registration_body_threeside'] = array(
        '#type' => 'text_format',
        '#title' => t('Three-sided PDF'),
        '#default_value' => variable_get('registration_body_threeside', ''),
    );
  return system_settings_form($form);
}

```

you can read values using

```
$twoside = variable_get('registration_body_twoside', '');
$threeside = variable_get('registration_body_threeside', '');

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Printing the last 6 characters of a field into a confirmation email
I have a booking system set up using Rooms.

The customer enters their phone number on checkout, which is a 5 number area code, followed by 6 other numbers. E.g. 01234 567 890.

The rooms at the hotel have a secure pin pad entry which is set to the last 6 digits of their phone number for their arrival.

As far as I can see there are two ways of doing this.

1. Replace the phone nunber field with two fields, one for area code and one for the 6 digits, then send the 6 digits to the customer in a confirmation email. The only downside to this will be the existing customer phone numbers in the database will not fit the new fields, and also the validation of phone numbers used in the "Phone Number" module will not work for a split field.
2. Create a way to only print the last 6 digits of the data in the phone number field. This seems like the best option, as it doesn't involve me having to edit the data for current bookings.

Can anyone explain to me how I might achieve option 2? Printing the last 6 digits in views etc would be easy enough, but I need to print the last 6 digits into an email template, and then send that email with rules. I have a token for \[commerce-order:commerce-customer-billing:field-phone-number\] that I can put into the confirmation email. Is there a way to trim the output of a token?

# Answer
> 0 votes
You could probably use the rules module with the "Execute custom PHP Code" option to execute a small php substr function.

You might need to enable the php filter module for this.

---
Tags: commerce
---


title: Get value from field in php

text:
# Question
Title: Get value from field in php
I am trying to get fields value in php but I cannot make it work. My code

```
<?php
$value = $node->field_price;
return $value;
?>

```

Can somebody please help me to solve this? I believe it has to be something very simple.

# Answer
You should first load your node with `$node = node_load($nid)`. You can also use the Devel module (`dpm(noad_load($nid))`) to debug the node and make sure you're calling the right path to the value.
> 1 votes

# Answer
The values of fields are stored a bit deeper in $node-\>field\_price, to be more specific they're stored like this:

```
$node->FIELD_NAME['LANGUAGE_CODE'][INDEX]['value']

```

The LANG\_CODE is usually 'und' or undefined (if you run a multi-lang setup they correspond to the fields lang). The index specifies what exact value are you looking for (makes sense just for fields with cardinality higher than 1).

E.g. if you have a field with infinite cardinality that stores 3 taxonomy tags, you'll have three separate values under:

```
$node->FIELD_NAME['LANGUAGE_CODE'][0]['value']
$node->FIELD_NAME['LANGUAGE_CODE'][1]['value']
$node->FIELD_NAME['LANGUAGE_CODE'][2]['value']

```
> 1 votes

# Answer
Try this safer method:

```
  $node = noad_load($nid);
    if (isset($node->field_price[LANGUAGE_NONE][0]['value']))
    {
      $value = $node->field_price[LANGUAGE_NONE][0]['value'];
    }

```
> -1 votes

---
Tags: entities
---


# Question
Title: How to enable Text formats after disabling it in Drupal?
In attempting to get pictures inline with text, I did the following:

`Configuration>> content authoring >> text formats>>` and disabled *Full HTML* and *Filtered HTML* formats.

This clearly did not give me the desired result as now all text is no longer visible on my Drupal website.

How do I re-enable this text on the website?

# Answer
> 5 votes
This looks like a bug in Drupal. Anyway the following method works.

1. Go to your Drupal database (I use phpMyAdmin)
2. Browse table called '`filter_format`'
3. There You can see list of input formats. In '`status`' column change (update) status form **0** to **1**. (Disabled status will have 0. So change to 1 to enable)
4. Clear your cache. (`configuration >> development >> performance`)

That's it. Now all 'Text formats' will be visible under that configuration page.

It works, I tested it :)

# Answer
> 1 votes
Run the following script to update your database:

```
db_update('filter_format')
  ->fields(['status' => 1])
  ->condition('format', 'full_html')
  ->execute();

```

---
Tags: 7, input-formats
---


# Question
Title: How to create groups and assign users to them using Organic Groups?
I have downloaded the Organic Groups module for my Drupal project and am currently trying to create groups and assign users to them.

I don't want anything fancy. I just want to be able to create groups, have the user assigned to them by the main administrator (not allow the user to register themselves) and have the assigned 'leader' of the group be the only one within the group with edit/etc permission.

I am unsure how to start. I found the resource Organic Groups: Enable users to create collaborative groups that looks really good, but I think it is for an older version of Drupal because the OG sections I have found are in a different location than the site says.

How do I do this?

# Answer
> 2 votes
Have you read the readme file in og module folder, it shows basic instruction to create a group, assign content to the group.

Basically, after enabling OG module, you need to create a content type, if you want it to be a 'group', select the "Group Type" option, then each instance of this content type will represents a group.

Below are some links will help you start:

Basic OG Documentation: http://drupal.org/node/483234

Amitai's presentation of OG7: http://www.archive.org/details/GrouptheNewOrganicGroups-BuildingSocialNetworksInDrupal7 **(I recommend you watch this video, very informative. I am sure you will sort it out)**

# Answer
> 2 votes
Organic Groups module doesn't provide any option to create a Group inside 'Add Content' menu. For creating a Group you need to go to:

```
- Content types >> Add content type

```

And fill the details for your group such as name, type, description (just like any other content type) then in the Organic Groups settings area, assign this content type to "Group Node" and then you can save the group.

You can find further advanced details in this Beginner's Guide to Organic Groups.

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


# Question
Title: how to get radio value from radio button by form api drupal
How to get radio value from radio button by using the following code

```
$form['pd']= array(
  '#type' => 'radio',
  '#title' => t('Programme Day'),
  '#options' => array(0 => 'One Day Programme', 1 => 'Two or More Day Programmes'),
  '#required'=>TRUE
);

$form['one_day'] = array(
  '#title' => t('Date'),
  '#type' => 'date',
  '#description' => t('Please select the date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => -15:+1',
  '#states' => array('visible' => array(':input[name="pd"]' => array('value' => 0)))
);

$form['from_day'] = array(
  '#title' => t('From Date'),
  '#type' => 'date',
  '#description' => t('Please select the from date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => '-15:+1',
  '#states'=>array('visible'=>array(':input[name="pd"]'=>array('value'=>1)))
);

$form['two_day'] = array(
  '#title' => t('To Date'),
  '#type' => 'date',
  '#description' => t('Please select the To date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => '-15:+1',
  '#states'=>array('visible'=>array(':input[name="pd"]'=>array('value'=>1)))
);

```

I tried the following code but the value shows as array not value.

```
$prog_day = $form_state['values']['pd'];

$one_date = $form_state['values']['one_day'];
$from_date = $form_state['values']['from_day'];
$two_date = $form_state['values']['two_day'];

```

# Answer
if you are looking for the submitted values you need to look in the `$form_state` and not the `$form array`.

use `$form_state['values']['your field name']`, depending on element type you might have `['und'][0]` or just `[0]` on the end.
> 1 votes

# Answer
Drupal collects the submitted values of form in the $form\_state array by default so you will get the radio button value in following variable:

```
$form_state['values']['pd']

```
> 0 votes

# Answer
you need a default\_value to get the value !

```
$form['pd']= array(
  '#type' => 'radio',
  '#title' => t('Programme Day'),
  '#options' => array(0 => 'One Day Programme', 1 => 'Two or More Day Programmes'),
  '#required'=>TRUE,
  '#default_value' => 0,
);

```
> -1 votes

---
Tags: forms
---


title: Kickstart Price slider in front page

text:
# Question
Title: Kickstart Price slider in front page
Can any one say that how will i show my `kickstart` price slider in front.

I read many reference but still at no where . I use the `multiblock` module but the block produced is only shows in the search page.

Then I also try through view . I create another `facet block` using `facet api` but there is no option for changing the display widget.

is there any way or i am missing something .

Any help is most appreciable . thank you in advance.

# Answer
got it myself i create a facet block with price field and a search block of index type which will show the facet in every where the search page will shown .i restricted it for only front page .Then it works for me.
> 0 votes

---
Tags: commerce, search
---


# Question
Title: Additional Information pop up box next to a variation in drupal commerce
I am creating a commerce site using Drupal Commerce, there are some variations for products that I would like to inform the customers about. Theres the option of having a sticker finish that is a variation and I wanted to have a "What is this?" text field right next to the select list that then launches a colorbox/fancybox/popup that displays additional information about that variation. Something similar to this:

# Answer
> 0 votes
I was surprised that there wasn't a module that did this so I've created one.

It is only a sandbox project at the moment as I'm still waiting to get approved to create full projects.

Sandbox page

It can however be downloaded from here. You will then need to extract the .tar.gz to a .tar, and then extract that to a folder called "2240445-cbcb2b4" and then rename that folder to field\_info\_popup (Phew!).

I've tested it with all the core field types and seems to work fine but if you do find any bugs then they can be posted here.

---
Tags: commerce
---


# Question
Title: How to make drop down field as mandatory field in views exposed filter?
I need to make one of my drop down field in views exposed filter as mandatory field.How can I achieve this?

# Answer
> 1 votes
In the Exposed Filter option check Required checkbox.. See attached screenshot below for select list field..

---
Tags: 7, views
---


# Question
Title: How do I autoload a class with the X Autoload module?
I have X Autoload installed and enabled. I'm trying to get a simple example to work. The below setup throws the error:

> Fatal error: Class 'Pet' not found in MY-SITE/sites/all/modules/foo/foo.module on line 15

Have I got the directory structure correct for pet.php? I'm finding the docs difficult to follow on the placement and naming of the file that contains the class definitions. I'm trying to follow the PSR-0 standard to begin with. Thanks.

**UPDATE: The below has now been corrected as per Clive's answer.**

foo.info

```
name = Foo
core = 7.x
dependencies[] = xautoload (>= 7.x-4.0)

```

foo.module

```
<?php

function foo_menu() {
  return array(
    'foo' => array(
      'title' => 'Foo',
      'page callback' => 'foo_page',
      'access callback' => 'user_access',
      'access arguments' => array('access content'),
    ),
  );
}

function foo_page() {
  $output = \Drupal\foo\Pet::dog();
  return array(
    '#type' => 'markup',
    '#markup' => $output,
  );
}

```

Pet.php (MY-SITE/sites/all/modules/foo/lib/Drupal/foo/Pet.php)

```
<?php

namespace Drupal\foo;

class Pet {
  public static function dog() {
    return 'Buster';
  }
}

```

# Answer
> 2 votes
If your file-system is case-sensitive, so is PSR-0. Try changing your class filename to

> MY-SITE/sites/all/modules/foo/lib/Drupal/foo/Pet.php

And make sure you're namespacing your class correctly, e.g.

```
namespace Drupal\foo;

class Pet {
  ...
}

```

Lastly, make sure you're referencing the class correctly in your module file. Either

```
// Top of file.
use Drupal\foo\Pet;

// In a hook or whatever
$dog = Pet::dog();

or

// In a hook
$dog = \Drupal\foo\Pet::dog();

```

---
Tags: 7
---


# Question
Title: How to change path that username points to
I have basically disabled user accounts from being accessed, because I am using Profile2 module for user profiles. So there is no need to view the users account page. But in posts and forums in my site the username shows up by default and links to the user's account, not their profile. Is there a hook somewhere that I can use to have the user account path `/user/uid`, always point the the profile `/main-profile/uid`?

I know I can change the link in views, but I was looking for a site-wide solution. That will always make the username link to the profile. I'm thinking there has to be some hook I can use to redefine `$user_path`, but I can't figure it out.

# Answer
> 1 votes
You can use hook\_menu\_alter, it's not even too much work to do, just

```
anymodule_menu_alter( &$items)
{
    $items['user/uid'] = $items['main-profile/uid'];
}

```

clear cache and it will turns user/uid into nothing more than an alias of main-profile/uid.

---
Tags: hooks, users
---


# Question
Title: RedHen Registration: where is the display settings?
I'm using the RedHen module for registration to an event.

I created the registration type and a content type Event that has a field "Registration". For what I read, when one visualize a instance of a content Event it should appear the fields of the registration type but it isn't. In the description it says that depends on the "display settings" but when I create registration type I didn't see an option like that.

What can be wrong? Thanks in advance.

# Answer
Well after a break and with my mind a bit clearer. The display settings don't depend of the registration type, they can be found in "manage display" of the content type (in my case "Event"). Only that no matter what display one choose it will always appear a tab for "registration", but I think this can be manage with the css.
> 0 votes

---
Tags: users
---


# Question
Title: jQuery Uncaught TypeError: Object #<Object> has no method 'on'
I downloaded a jQuery Lightbox2 library (not module, just a raw library) and added the following in my custom module:

```
drupal_add_js($libpath . '/js/jquery-ui-1.8.18.custom.min.js');
drupal_add_js($libpath . '/js/jquery.smooth-scroll.min.js');
drupal_add_js($libpath . '/js/lightbox.js');

```

But it causes an error like this (see below debug printscreen):

Could someone tell me, what to do to get rid of the error?

After some googling I installed the JQuery Dollar module but the error is still there. No clue what else to do.

# Answer
`on()` was only added in jQuery v1.7; Drupal 7 ships with jQuery v1.4, and can be updated to 1.5 using the jQuery Update module. The reason you're getting the error is simply that the lightbox library you're using is written for jQuery v1.7 and above.

See How do I update jQuery to the latest version I can download? for some ideas on how to get round this.
> 4 votes

# Answer
In order to improve compatibility with other javascript frameworks, Drupal 7 requires to use a wrapper. Instead of `$(document)` in Drupal 6 it would be `jQuery(document)` in Drupal 7 (there are more options though).

Since you are not using the Lightbox2 module but just an external script it might not play along well. Although, I would rather expect the `$ is not a function` error message.
> 0 votes

# Answer
I think the 'on' function is a cousin of 'delegate', and was implemented in jQuery 1.7. Which version of jQuery are you using with your Drupal?
> 0 votes

# Answer
This is the easiest way to do it. Install this module:

https://drupal.org/project/jquery\_plugin

Then add the following to your template.php:

```
function YOUR_THEME_preprocess_html(&$variables){
  drupal_add_library('jquery_plugin', 'tooltip');
}

```

And then you are free to add whatever javascript you want to your site as far as tooltip is concerned.
> 0 votes

---
Tags: 7, javascript
---


title: User Name and User Email Conflict?

text:
# Question
Title: User Name and User Email Conflict?
I imported 500+ users into Drupal 7 by Feeds module. However, 1 of the user has 2 accounts. I got a error message "This name has already been taken by another user." when chaning their roles. Their username is different, but account A user name is same as account B email address. I think they have user name and user email conflict. Is it possible to fix this without changing username and user email?

User account A:
Username - usernameX
user email - usernameX@gmail.com

User account B:
username - usernameX@gmail.com
user email - usernameB@gmail.com

# Answer
> 3 votes
I am puzzled by your description of the problem. Drupal 7 should *not* complain if A *user name* is the same as account B *email address*.

However, without making a too big deal of that, there is a way you can change an email address to avoid any conflict within Drupal, and still get mail delivered to that user without interruption.

Simply insert the character `+` and some string after the name part of the address, like this:

```
User account A:
Username   - usernameX
user email - usernameX+a@gmail.com

User account B:
username   - usernameX@gmail.com
user email - usernameB@gmail.com

```

Drupal allows email-adresses with a `+` in them.

And for string comparison purposes:

```
usernameX+a@gmail.com ≠ usernameX@gmail.com

```

While for mail delivery purposes:

```
usernameX+a@gmail.com = usernameX@gmail.com

```

This technique, known “plus-addressing” allows users to sign up for different services with different aliases and then easily filter all e-mails from those services (provided their mail server doesn't strip it). Mail servers deals differently with “plus-addresses”. MS Exchange strips it, while Cyrus and GMail retains it - but AFAIK *all* mail servers deliver mail with “plus-addresses” to the intended recipient.

---
Tags: users, emails
---


# Question
Title: CKEditor4: the image disappear when I switch from Rich text View to source view
I am using the CKEditor4 module for Drupal7 (https://drupal.org/project/ckeditor) and I noticed that when I am in the "Rich Text" view and I upload an image using the Image button. Initially the image is there, but when I switch to the "source view" and go back to the "Rich Text" view the image disappears. Also when I save the page in the Admin and I come back to it the image disappears. The code for the image still exists in the source view and the image shows up in the Live post but NOT in the "Rich Text" view.

Any ideas what's the problem?

Thanks.

# Answer
That was a very weird behavior. But after hours of debugging and testing, the fix was by re-installing the latest versions of CKEditor module (at https://drupal.org/project/ckeditor ) along with the CKEditor and CKFinder programs (at http://ckeditor.com/download ). The latest versions available as of today (April 14, 2014).

I am confident that the issue of the image disappearing had nothing to do with anything I did, since I reintroduced the exact same configuration settings as I had in the old version (the old version combo was from about 4 months ago) and I have no problems now.

Boutros.
> 0 votes

# Answer
You need to make it clear that images are allowed content.

You may safely declare that images, only certain image attributes, all image styles, and all image classes are allowed content. You do that with the following line of JavaScript:

```
config.extraAllowedContent = 'img[!src,alt,title,width,height,style](*){*}';

```

To set these variables, navigate to *Configuration → Content authoring → CKEditor* and then press edit for the profile you want to configure. Expand *Advanced options*, and type the JavaScript directly into the textfield Custom JavaScript configuration as shown in the screen shot below (disregard the first line unless you also want to set custom `format_tags`);

**PS**: If you Google this, you'll often see the following JavaScript suggested to "fix" the disappering image problem:

```
config.allowedContent = true;

```

Yes, it will fix the problem of images disappeearing when you toggle between rich text and source. But it will *also* make all sorts of content allowed - which is a gaping security hole in your site if you allow untrusted users to create and edit content. Don't use this quick "fix". Use the solution that uses the `extraAllowedContent` directive to spell out what shall be allowed (and allow only safe content).
> 1 votes

---
Tags: wysiwyg
---


title: Trying return array as page content

text:
# Question
Title: Trying return array as page content
I'm working on a module in Drupal 7. I have three different forms set up with hook\_form. I would like to display the three forms on one page along with some html to organize the forms and apply some css to change the look a little bit. What I have right now is:

```
  function floormap_setup_page() {
    $info[0] = '<div id="floormap_setup">';

    $info[0] .= '<div id="select_floormap">';
    $info[0] .= '<ul>';
    $floormap_options = get_floormap_options();
    $floormap_list = '';
    foreach ($floormap_options['name'] as $key => $value){
        $span_delete = '<span class="delete"><a href="#"> ' . t('Remove Floor Map') . ' </a></span>';
        $span_default = '<span class="default"><a href="#"> ' . t('Make Default') . ' </a></span>';

        $floormap_list .= '<li>' . $value . $span_default . $span_delete . '</li>';
        }
    $info[0] .= $floormap_list;
    $info[0] .= '</ul>';
    $info[0] .= '<div><!--select_floormap-->';

    $info[0] .= '<div id="label_cameras">';
    $info[1] = drupal_get_form('setup_cameras_form');
    $info[2] = '</div><!--label_cameras-->';

    $info[2] .= '<div id="set_expectations">';
    $info[3] = drupal_get_form('set_expectations_form');
    $info[4] = '</div><!--set_expectations-->';

    $info[4] .= '<div id="new_floormap">';
    $info[4] .= '</div><!--new_floormap-->';

    $info[4] .= '</div><!--floormap_setup-->';
  return $info;
}

```

Doing this displays the page how I want it, the only problem is that I get a bunch of errors along with it..

The errors look like this:

> Warning: Illegal string offset '#children' in drupal\_render() (line 5887 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
>
> Warning: Illegal string offset '#children' in drupal\_render() (line 5897 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
>
> Warning: Illegal string offset '#children' in drupal\_render() (line 5935 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
>
> Warning: Illegal string offset '#printed' in drupal\_render() (line 5942 of /var/www/app.local.nucloudglobal.com/includes/common.inc).

The entire set of errors repeats for each item in the $info array.

# Answer
Render arrays look like this:

```
$build = array(
  '#prefix' => '<div id="floormap_setup">',
  '#suffix' => '</div>',
  'select_floormap' => array(
    '#markup' => '<p>Markup for the first bit</p>',
  ),
  // drupal_get_form() returns a render array.
  'setup_cameras_form' => drupal_get_form('setup_cameras_form') + array(
    '#prefix' => '<div id="label_cameras">',
    '#suffix' => '</div>',
  ),
  'expectation_form' => drupal_get_form('set_expectations_form') + array(
    '#prefix' => '<div id="set_expectations">',
    '#suffix' => '</div>',
  ),
  'new_floormap' => array(
    '#markup' => '<div id="new_floormap"></div>',
  ),
);

```

See the render array docs and What are "#" properties? for a bit more explanation.
> 2 votes

# Answer
You can directly render the form yourself before assigning it to the array

$info\[3\] = drupal\_render( drupal\_get\_form('set\_expectations\_form'));

eventually you can just implode the array and return the resulting string, this way you can also avoid to deal with rendering arrays.
> 0 votes

---
Tags: forms, 7, theming
---


# Question
Title: Is there a fast way to see a site without the drupal admin elements?
Once in a while various Drupal elements can be a real pain:

* The context menu covers the search menu & prevents me from clicking into the text field
* A co-worker is worried that the user is seeing things like 'Available Updates' notifications
* View/Edit tabs and action links are present in screenshots

The easy answer is to log out and view the page again, but that's a pain when you just want to do a very quick thing.

What is a quick, easy way to jump in/out of Drupal?

# Answer
> 3 votes
I put together a simple javascriptlet that I can click on to show/hide most admin elements. It is kind of a static solution (I'll need to update it periodically as new admin elements appear that need to be hidden), but it's simple. Works with the Admin-Menu module too.

Just make a new bookmark and paste this into the 'url' field:

```
javascript:(function($){ if( $('html').data('drupal_clutter_hidden') ){ $('html').data('drupal_clutter_hidden', false); $('#block-search-form').css('z-index', ''); if( $('html').data('drupal_has_adv_toolbar') ){$('body').addClass( $('html').data('drupal_has_adv_toolbar') );$('#admin-menu').show();$('html').removeData('drupal_has_adv_toolbar');} else {$('body').css('padding-top', '64px'); $('#toolbar').show(); }$('.alpha-grid-toggle, .alpha-block-toggle,em.placeholder, #messages, .krumo-root, ul.tabs.primary, .region-inner > .tabs, .contextual-links-wrapper').show(); } else { $('html').data('drupal_clutter_hidden', true); $('#block-search-form').css('z-index', '100'); if( $('body').hasClass('admin-menu') ){var classes = $('body').hasClass('admin-menu-with-shortcuts') ? 'admin-menu admin-menu-with-shortcuts' : 'admin-menu';$('html').data('drupal_has_adv_toolbar', classes); $('body').removeClass( $('html').data('drupal_has_adv_toolbar') );$('#admin-menu').hide();} else {$('body').css('padding-top', '0'); $('#toolbar').hide(); }$('.alpha-grid-toggle, .alpha-block-toggle,em.placeholder, #messages, .krumo-root, ul.tabs.primary, .region-inner > .tabs, .contextual-links-wrapper').hide(); } }(jQuery));

```

Before:

After:

---
Tags: 7, users
---


# Question
Title: Where drush make downloading my projects?
I have created a drush make file through drushmake.me

Which is, I've created a file `my.make` in `public_html` folder and run the following command:

```
drush make my.make

```

It shows all the files downloading ok, but when I am checking my `public_html` folder it's showing nothing in my `public_html`.

I don't understand where all the projects are downloaded.

Any idea?

# Answer
Normally drush makes default behaviour is to create the site in the current directory - relative to where you run the command.

But the simplest way to deal with this is just to run drush-make with a parameter explicitly stating where to deploy the site:

```
drush make my.make relative/path/to/my/public_html

```

or

```
drush make my.make /absolute/path/to/my/public_html

```

Obviously replacing the path in question with the appropriate one. Don't understand UNIX file paths? Read up on them on wiki page.

And while I am at it, why don't you take a look at the drush make documentation too.

There are a number of drush configuration files that affect the working directory for drush commands - the most likely candidate being a drushrc file is example.drushrc.php.
> 0 votes

---
Tags: drush
---


title: drush cc all giving me an unlink error

text:
# Question
Title: drush cc all giving me an unlink error
I found a similar issue but it will not help me since I have not changed permissions.

I am running drush cc all and getting this error...

I have logged out and back in and nothing. I have not changed permissions and I have the admin rights to the account. Any ideas on what to do?

# Answer
I've seen this problem when as unprivileged user you call drush cc all and drush tries to delete cache files created by the web server process. Those files are owned by the web server user and they don't have the 'all other users" write permissions enabled (the last three permissions group).

Fixing this is a file permissions issue. One fix is to put web server user and drush user in the same group and assure that files created by the web server process are writable by its group members.
> 2 votes

---
Tags: drush
---


title: Errors displayed during core upgrade

text:
# Question
Title: Errors displayed during core upgrade
When I am updating Drupal core, and uploading files via FTP, how can I prevent mydomain.com/install.php trying to load and displaying WSOD errors like "Fatal error: require\_once() \[function.require\]: Failed opening required..."?

I'd like to display a static page with a BRB message instead.

# Answer
> 1 votes
Just move your entire Drupal root somewhere else, and put something else in its place (with a "Be Right Back"-message) while the upgrade goes on.

For instance, if your Drupal root is `/var/www/html`, prepare a directory named `/var/www/brb` and put a static `index.html`-file in it with your BRB message.

Then execute the following pair of commands:

```
mv /var/www/html /var/www/pending_upgrade
mv /var/www/brb /var/www/html

```

Now, make sure that your ftp job puts the files in below `/var/www/pending_upgrade`.

When done, restore your site with the following pair of commands:

```
mv /var/www/html /var/www/brb
mv /var/www/pending_upgrade /var/www/html

```

The above assumes that you have CLI access. If you don't, most ftp tools have built-in commands to move directories around.

---
Tags: upgrading
---


title: What governs view access?

text:
# Question
Title: What governs view access?
I just built a view to display user information. I can see this view just fine as a root admin but when I log in as a different user, the view is restricted.

What governs view access?

Is it a compost of all the permissions involved in the data that is being viewed? If I want to block a user from looking at a view, do I restrict some or all of the content? Is there a way to set up a permission directly one a view?

# Answer
There are two things which govern access to views and their results.

1. The access settings for the view. These are found on the view page and can be based on `permissions` or `roles`. This is a base rule for who can see this view.
2. The access settings for the content being displayed by the view. This is definitely where things get a bit funky. Essentially, views doesn't collaborate with Drupal permissions or `hook_node_access()`. It will show content users might not have the permission to see or content that has been safeguarded by `hook_node_access()`. That makes these two methods pretty useless for protecting content.

What actually happens is that views queries the `{node}`, `{user}` or other entity table and retrieves nid's, uid's or other entity id's. At no stage does it check permissions or `hook_node_access()`. However, when checking nodes it does join with the `{node_access}` table to determine if that system has any rules about the content. *Note that `hook_node_access()` doesn't really have anything to do with the `node_access` system.*

By default you probably aren't using the `node_access()` system, but if you are using a module like content\_access then you are using this system and it may be restricting views results.

If you have `devel` module installed, you can use the block with the title *Devel node access* and place it on a node page. Now when you visit that page, it will show the roles and their access level. *Note that you need to access that nodes page with a user with that role before it will show in the block*. This is the access record which will determine if the node can show in a views result.
> 3 votes

---
Tags: 7, views, users
---


# Question
Title: Is it a way to get know if more than one user edit the same node?
I'm looking for the way to inform site editors if the other editor is trying to edit the same node. In other words I need functionality that is similar to the Checkout module. But it is no longer maintained and I don't like to lock anything, just show a popup message.

Do you think that it is possible? I didn't find any hooks in Drupal API that could do that.

And the last thing - this is Drupal 6

# Answer
This is already built-in in Drupal 6 (and 7), in the function node\_validate.

The relevant piece of code is reproduced below:

```
if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}

```

It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done.

The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.
> 1 votes

---
Tags: 6
---


title: Upload as Teaser Background

text:
# Question
Title: Upload as Teaser Background
I have created a views page which displays teasers of specific content type.

When creating content I am also uploading an image which we want to display on the background of the relevant teaser.

So every teaser has its image on the background.

Looking forward for professional guidance in this regard.

# Answer
> 1 votes
Try to use Background Images Formatter module, hopefully it will fulfill your requirement.

> Background Images Formatter module provides an image formatter who allows you to set an image in background of a div. The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.

Change selector value to whatever you want in manage display section (explained in attached screen shot)

---
Tags: views, entities, theming, nodes
---


# Question
Title: Add class that surrounds all tables (or any other node,field etc...) using preprocess template?
I have been able to find information on adding classes to tables and other items in my pages, however, I cannot find any information on wrapping the entire table for example in a div through the preprocess function.

I added this for example:

```
function bootstrap_preprocess_views_view_table(&$vars) {
    $vars['classes_array'][] = 'table table-striped';
}

```

My tables are stripped which is what I was after, however, I would like to wrap the entire table itself in `<div class="table-responsive">{TABLE}</div>`, but am not finding where / how to add the class to show before the table?

Adding a picture of where it could be added:

# Answer
> 0 votes
you can override views-view-table.tpl.php template to achieve this.

Like :

```
<div class="table-responsive">
<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
   <?php if (!empty($title) || !empty($caption)) : ?>
     <caption><?php print $caption . $title; ?></caption>
  <?php endif; ?>
  <?php if (!empty($header)) : ?>
    <thead>
      <tr>
        <?php foreach ($header as $field => $label): ?>
          <th <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
            <?php print $label; ?>
          </th>
        <?php endforeach; ?>
      </tr>
    </thead>
  <?php endif; ?>
  <tbody>
    <?php foreach ($rows as $row_count => $row): ?>
      <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
        <?php foreach ($row as $field => $content): ?>
          <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
            <?php print $content; ?>
          </td>
        <?php endforeach; ?>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</div>

```

Get a look for override views template here

For other tables Override theme\_table and change its return statement Like:

```
return '<div class="table-responsive">'.$output.'</div>';

```

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


# Question
Title: During which bootstrap phase hook_exit & hook_boot will be invoked?
Project Documentation says.. Both are invoked even for cached page views. hook\_boot says

> This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request.
>
> Only use this hook if your code must run even for cached page views. This hook is called before the theme, modules, or most include files are loaded into memory. **It happens while Drupal is still in bootstrap mode.**

hook\_exit says...

> Perform cleanup tasks.
>
> This hook is run at the end of most regular page requests. It is often used for page logging and specialized cleanup. This hook MUST NOT print anything because by the time it runs the response is already sent to the browser.
>
> Only use this hook if your code must run even for cached page views. If you have code which must run once on all non-cached pages, use hook\_init() instead. That is the usual case. If you implement this hook and see an error like 'Call to undefined function', it is likely that you are depending on the presence of a module which has not been loaded yet. **It is not loaded because Drupal is still in bootstrap mode.**

Interested to know during which bootstrap phases hook\_boot & hook\_exit getting invoked so that it will be helpful in cases where above hooks can be used....

# Answer
hook\_boot is getting invoked during fifth phase which is DRUPAL\_BOOTSTRAP\_PAGE\_HEADER which set up the page header... This is for non cached pages..

```
/**
 * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
 */
function _drupal_bootstrap_page_header() {
  bootstrap_invoke_all('boot');

  if (!drupal_is_cli()) {
    ob_start();
    drupal_page_header();
  }
}

```

For Cached pages both gets executed at Second Phase of Bootstrap which is DRUPAL\_BOOTSTRAP\_PAGE\_CACHE with little difference...

```
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_boot.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

```

what make difference between these hooks is

```
  drupal_serve_page_from_cache($cache);

```

Which tells hook\_boot and hook\_exit is used before and after page requests for tasks like setup and cleanup respectively..

hook\_exit also called in common.inc what makes difference is, Invoke during DRUPAL\_BOOTSTRAP\_PAGE\_CACHE phase applies where cached page requests are served.. In common.inc hook\_exit is called for non cached pages..

```
function drupal_page_footer() {
  global $user;

  module_invoke_all('exit');

  // Commit the user session, if needed.
  drupal_session_commit();

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
  drupal_cache_system_paths();
  module_implements_write_cache();
  system_run_automated_cron();
}

```

Above confirms even for non cached requests hook\_exit is invoked..
> 1 votes

---
Tags: hooks, bootstrapping
---


title: Blank admin panel | Drupal 7 | XAMPP

text:
# Question
Title: Blank admin panel | Drupal 7 | XAMPP
I am migrating a Drupal 7 project from one PC to another and I did the following steps

> 1) Copy pasted the root folder into `D:\XAMPP\htdocs`
> 2) Imported the database of that project into phpmyadmin (had to increase `max_file_uploads` to 20 in `php.ini`)
> 3) reset admin password by referring https://drupal.org/node/1023428
> 4) updated the password in `settings.php`
> 5) cleared cache in the imported db (by deleting the content of cache and cache\_\* tables)

Now I am able to login but the admin panel is blank, When I click *Dashboard, Content, Structure, Appearance* etc. nothing appears

No error is console.

PS: this is the first time I am using Drupal, so in-depth instructions is much appreciated

**Edit**

After @Randell's suggestion I had set `display_errors` to `on` and `error_reporting` to `E_ALL`. Still no error appears anywhere

**Edit**
From `watchdog` the last two rows;

Second-Last row

> uid : 1
> Message : Session opened for %name.
> location : `http://localhost:81/mysite/user`
> referer : `http://localhost:81/mysite/user`

Last Row

> uid : 0
> Message : Attempting to re-run cron while it is already running.
> location : `http://localhost:81/mysite/users/admin`
> referer : `http://localhost:81/mysite/user`

# Answer
Most of the time it is the `memory_limit` setting in your php.ini. Drupal 7 needs a bit more memory and depending on how many modules you are using, it must be set to a higher value. 64M or 128M should be enough for moderate sites.
> 0 votes

# Answer
Increase PHP memory limit

If you need more than 128M:

Add the line ini\_set('memory\_limit', '512M'); to your \[Drupal 7 root\]/sites/default/settings.php file.

check php\_value memory\_limit in php.ini
> 0 votes

---
Tags: 7
---


# Question
Title: How to disable/turn-off drupal 7 caching permanently, to not to mess with module's operations?
I am using Drupal 7 for a real time web application so I cannot afford any caching at all. I also could not find any such option in performance section of Admin Panel. Kindly suggest a method with involving the command line.

---

## UPDATED:

Let me explain the problem further.

Yes theme isn't problem for me. I am new to drupal ad still exploring.

What problem I face is I have written a module which takes CSV file from user, parses and calls moodle web-services to perform operations. What happens sometimes is it seems like that data or code in module is not managed properly and it generates useless/meaningless errors. When I do 'Clear All Caches' at Home » Administration » Configuration » Development; everything gets fixed.

# Answer
> 5 votes
As per Suppress caching (for development), you can add the following to your settings.php file

```
if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
// Default to throwing away cache data
$conf['cache_default_class'] = 'DrupalFakeCache';
// Rely on the DB cache for form caching - otherwise forms fail.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

I'd recommend you don't just blindly add that, though. Instead, take the time to think what you *do* need to cache, and what you *don't* need to cache, and come up with a proper strategy. For example, it's hardly likely that you need rebuild the cache of hook implementations on every single page load, regardless of how highly available the site is.

# Answer
> 0 votes
Theme functions are handled by the theme registry: rebuilding (or worse, disabling) all your site's caches to pick up a new theme function is unnecessary and overkill.

What you can do is use the Devel module to rebuild your theme's registry on every page reload. Once installed, go to Configuration → Development → Devel settings. There, check "Rebuild the theme registry on every page load" and press the "Save configuration" button. Remember to uncheck it (or better yet, disable Devel entirely) when you're done with development.

---
Tags: caching
---


# Question
Title: How to remove default div of views block?
My html code:

```
<div class="workList col-lg-4">
  <div class="view-back">
    <a href="" target="_blank">→</a>
  </div>
<img class="img-responsive" src="<?php print base_path(). path_to_theme();?>/assets/images/img.jpg" alt="">
</div>

```

In views-view-fields--name--name.tpl I'm using this code:

```
<div class="view-back">
    <a href="" target="_blank">→</a>
</div>
<?php print $fields['field_fieldName']->content;?>

```

The generated output is the following.

```
<div class="col-lg-4  first odd">
      <div class="view-back">
    <a href="" target="_blank">→</a>
</div>
<div>## I have to remove this div
  <img typeof="foaf:Image" src="http://localhost/Drupal/name/sites/default/files/styles/recent_work/public/img.jpg?itok=vVkU2WWt" width="390" height="250" alt="">
</div>
</div>

```

I have to remove the default `<div>` before the `<img>` tag.

# Answer
> 0 votes
Click on field and edit settings Override style settings for field

Customize field HTML Customize field and label HTML

---
Tags: views
---


title: Conditional markup field display

text:
# Question
Title: Conditional markup field display
I have content type with a term reference field. Let's call it 'Color'. I want the content type to display markup depending on which term has been selected in the term reference field. For example, if 'Color' is Red, then the markup field will display 'Red is the color of fire'. If 'Color' is Purple, the markup field will display 'Purple is the color of royalty'.

Any ideas?

Thanks

# Answer
You need to implement hook\_preprocess\_HOOK(&$variables), and add processing there, like this:

```
<?php

function MYTHEME_preprocess_node(&$variables) {
    // Check if field tid (term id) is filled up
    if (isset($variables->field_term_color[LANGUAGE_NONE][0]['tid'])) {
        $color = $variables->field_term_color[LANGUAGE_NONE][0]['tid'];

        $text = '';
        // You need to look up tid of each color
      switch ($color) {
        case 123:
            $text = 'Red is the color of fire.'
            break;
      }

      // Assign value to markup (text) node field
      $variables->field_markup_field[LANGUAGE_NONE][0]['value'] = $text;
    }
}

?>

```

You should place the right field names instead of the ones I use, of course.
> 1 votes

---
Tags: forms, nodes
---


# Question
Title: Media module function overriting, user can see only own media
As title says, I need to override few media module functions and add some extra conditions when selecting media. I wanted to create new module that extends media module and overrides those functions but without success.

I wanted to override function

```
function media_admin_list(&$parent_form)

```

and to add this line so media module will select media from logged in user

```
$query = db_select('file_managed', 'f')->extend('PagerDefault')->extend('TableSort');
$query->join('users', 'u', 'f.uid = u.uid');
$query->fields('f', array('fid'));
$query->fields('u', array('uid'));
$query->condition('f.status', FILE_STATUS_PERMANENT);
$query->condition('u.uid', $user_id, "=");
$query->limit($limit);
$query->orderByHeader($header);

```

As you can see in code above, we have condition for selecting media from specific user.

Please advise how to override this function in my own module.

Thanks.

# Answer
The best suggestion I can come up with is to use `hook_form_alter()` to alter the value of `$form['admin']['#files']` (inspect the form array on the `/admin/content/media` page) by calling your own version of `media_admin_list()` with an altered query.

Something like:

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'media_admin') {
        $form['admin']['#files'] = custom_media_admin_list();
    }
}

```

This is slightly inefficient as the original function has already run but I can't see a way to alter it before the initial form array has been built.
> 0 votes

---
Tags: 7, hooks, media
---


# Question
Title: How to make disqus load avatar picture instead of user picture?
In user profiles I created a field called **Avatar** with a machine name of `field_avatar`.

I was wondering if I could make Disqus load the Avatar picture instead of the default Drupal user picture.

Here is the default Disqus code

```
        // Load the user's avatar.
    $user_picture_default = variable_get('user_picture_default', '');
    if (isset($account->picture) && !empty($account->picture) && is_numeric($account->picture) && $file = file_load($account->picture)) {
      $data['avatar'] = !empty($file->uri) ? $file->uri : NULL;
    }
    elseif (!empty($user_picture_default)) {
      $data['avatar'] = variable_get('user_picture_default', '');
    }
    if (isset($data['avatar'])) {
      $data['avatar'] = file_create_url($data['avatar']);
    }
  }
  drupal_alter('disqus_user_data', $data);

  return $data;
}

```

# Answer
> 2 votes
As seen in above code you can use **disqus\_user\_data\_alter** hook to change disqus data in your custom module...

```
function YOURMODULENAME_disqus_user_data_alter(&$data) {
  global $user;
  $user_picture_default = variable_get('user_picture_default', '');
if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file -- Change field_profile_picture with your field name
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
    $data['avatar'] = !empty($file->uri) ? $file->uri : NULL;
  }
  elseif (!empty($user_picture_default)) {
    $data['avatar'] = variable_get('user_picture_default', '');
  }
  if (isset($data['avatar'])) {
      $data['avatar'] = file_create_url($data['avatar']);
  }
}

```

---
Tags: users, comments
---


title: Media Module Bulk File Upload

text:
# Question
Title: Media Module Bulk File Upload
Is there a way to bulk upload into the Media module? What I'm trying to do is get a huge batch of images into the media Library browser. It seems like you have to first establish the image as an entity in the D7, so most of these bulk methods using something like rsync of scp wont work.

# Answer
> 0 votes
The Plupload integration module allows you to upload multiple files at once.

I've used this module before and I think it works really well. It also allows you to drag and drop files onto the browser window to initiate the upload.

---
Tags: media
---


# Question
Title: Migrating nodes with image- and textfield to file-entity with image and description
What is the approach to convert existing nodes consisting of a multivalue field-collection-field (containing an image-field and a textarea-field as caption) to the file-entity which the media module uses?

# Answer
Load an array of nodes, loop over the array and in this loop loop over the field collection items. For each item create a file-entity.

Something like this:

```
$nids = db_query("SELECT nid FROM node WHERE some condition is true")->fetchCol();
$nodes = node_load_multiple($nids);

foreach($nodes as $node) {

  foreach($node->field_collection_field[LANGUAGE_NONE] as $item) {
    $collection = field_collection_item_load($item);

    $values = array(
      'field keys' => 'field values',
      'field keys' => 'field values',
    );

    entity_create('file', $values);

  }

}

```

Note that is half PHP half pseudo code - copying and pasting it won't work but will guide you on the code structure and functions that you'll need.
> 2 votes

---
Tags: migrations, media, entities
---


title: Access page variables in form template

text:
# Question
Title: Access page variables in form template
I have a customised form template 'user-profile-edit.tpl.php' and i'm trying to add some custom variables so I can get a block of dynamic content (users current friends / requests etc) to display in the middle of the form.

I can use 'MODULE\_form\_user\_profile\_form\_alter()' to add to the form but this is not ideal as they are not form items but arbitrary markup from a custom module. I'm having to hack the form structure as follows:

```
$form['my_custom_stuff'] = array(
    '#markup' = 'some markup',
    '#description = 'some more markup',
    '#title' = 'yet more markup',
);

```

which is not nice.

Ideally i'd like to find a way to pass variables created in 'MODULE\_preprocess\_page()' to the 'user-profile-edit.tpl.php'. Is this possible?

Alternatively - is there a way to add custom elements to the form array without getting 'Fatal error: Unsupported operand type'?

And, no I can't change the order of the fields - the design was signed off a long time before I got involved with this project!

Thanks

# Answer
> 0 votes
Try $variables\[\] in your preprocess function!

```
 function template_preprocess_foo(&$variables) {
  $variables['foo_list'] = array(
    'list item 1',
    'list item 2',
    'list item 3',
  );
}

```

---
Tags: forms, theming, users
---


# Question
Title: How can I theme a form "checkboxes" element?
I've got a checkboxes field displayed on the user profile form. I'm trying to restyle that field to put the description BEFORE the checkboxes. That seems like it should be a simple thing?

So far I've got:

```
function MYTHEME_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['my_field_id'][LANGUAGE_NONE]['#theme'] = 'checkboxes_description_before_element';
}

function MYTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'checkboxes_description_before_element' => array(
            'render element' => 'element',
            'function' => 'theme_checkboxes_description_before_element'
        ),
    );
}

function MYTHEME_checkboxes_description_before_element($variables) {
    return "XYZ";
}

```

The checkboxes field is still stubbornly sitting on the markup generated by theme\_checkboxes instead of "XYZ".

I know that the form element is getting the new '#theme' through checking with `dpm()`.

# Answer
The checkboxes description is not rendered in `theme_checkboxes` or `theme_checkbox`. It comes from `theme_form_element`.

1. If you want every form element on the site (not just checkboxes) to have the description first, then you could just override and modify `theme_form_element`.
2. If you want only specific checkboxes to have this, then you could override and modify `theme_form_element` to position the description based on a variable (similar to what it already does with `#title_display`). You could then set the variable when creating the FAPI array.
3. If you want all checkboxes (but only checkboxes) to follow this behaviour, then you could override `theme_form_element` as above, and use `hook_element_info_alter()` and change `checkboxes` to have the new variable you created appopriately set.

Let me know if you have any questions.
> 4 votes

# Answer
This seems to be pretty similar to How to theme a radio button field on node edit form?, I think this should explain what you're looking for.
> 1 votes

# Answer
I have done this before and I can find the code if this first suggestion doesn't work.

If you just need to put the description before the checkboxes, you can use `hook_form_alter` and add a `#field_prefix` to the field.

I assume you have the knowledge to extract the field description, unset it from below the checkboxes and put it into the `#field_prefix`?
> 0 votes

# Answer
There are 2 functions that are responsible to theme checkboxes: `theme_checkboxes()` and `theme_checkbox()`. Where the former themes the wrapper div around the checkboxes, the latter themes the individual checkboxes.

If you want to override one of them or both you should copy them in `template.php` file under your theme folder and rename like `YOURTHEME_checkboxes` and `YOURTHEME_checkbox`.

Then don't forget to clear the caches.
> 0 votes

---
Tags: theming, forms
---


# Question
Title: I want to show a progress bar during form is submitted and processed until submission is created
I am using Form API to create a form on a page and I ask user to submit CSV File which is then process in \_submit function for that form. Kindly suggest me a way to add progress bar with Drupal's way. I tried this actually but did not work.

```
function userop_form_users($form_state) {

  $form['file'] = array(
    '#type' => 'file',
    '#title' => t("Upload CSV file containing information."),
    '#description' => t('<a href="#">Download sample file</a>.<br>Upload a file, allowed extensions: csv'),
    '#ajax' => array(
        'progress' => array('type' => 'bar', 'message' => t('TestMessage'),'interval' => '1500'),
     ),
    );

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

  $form['#cache'] = FALSE;
  return $form;
}

```

# Answer
The easiest way would be to use the managed\_file field type and set the `#progress_indicator` property to 'bar'.

More details are given in this Drupal Answers answer...
> 1 votes

---
Tags: forms
---


title: How to use Profile 2 with Services?

text:
# Question
Title: How to use Profile 2 with Services?
I want to use Services and Profile 2 together.

Like following json code:

**request:**

```
http://localhost/api/user/1

```

**response:**

```
{
  "uid": "3",
  "name": "test1",
  "theme": "",
  "signature": "",
  "signature_format": "filtered_html",
  "created": "1393554511",
  "access": "1393562420",
  "login": "1393562420",
  "status": "1",
  "timezone": "Asia/Chongqing",
  "language": "",
  "picture": null,
  "data": false,
  "roles": {
    "2": "authenticated user"
  },
  "rdf_mapping": {
    "rdftype": [
      "sioc:UserAccount"
    ],
    "name": {
      "predicates": [
        "foaf:name"
      ]
    },
    "homepage": {
      "predicates": [
        "foaf:page"
      ],
      "type": "rel"
    }
  },

  "profile 2 field": "test",
  "profile 2 field2": "test",
  "profile 2 field3": "test",
  "profile 2 field4": "test",
  "profile 2 field5": "test",
  "profile 2 field6": "test"
}

```

I find some code detail in Services Module :

`modules/services/resources/user_resource.inc`

```
/**
 * Get user details.
 *
 * @param $uid
 *   UID of the user to be loaded.
 *
 * @return
 *   A user object.
 *
 * @see user_load()
 */
function _user_resource_retrieve($uid) {
  $account = user_load($uid);
  if (empty($account)) {
    return services_error(t('There is no user with ID @uid.', array('@uid' => $uid)), 404);
  }

  services_remove_user_data($account);

  // Everything went right.
  return $account;
}

```

It seems services invoke user\_load() method to get user's default information.

**So I think:**

* Can I implement hook\_user\_load() to load Profile 2 fields?

# Answer
> 1 votes
You can use the Services Views module to expose the Profile 2 data you need.

> Views support for the Services module version 3.x and later.
>
> It has currently two features:
> \- Create view based resource creating Services display in a view
> \- Execute any view of the system via views resource call
>
> Demo video http://youtu.be/DZEhJKMeR5w

---
Tags: 7, services, users
---


# Question
Title: How to set the value of a Fixed amount Commerce Coupon using Rules?
It is practically impossible for me to set the fixed amount of a coupon created with rules. The coupon is generated allright with a coupon code but the fixed amount value is always empty, I can only edit the generated coupon and set the fixed amount manually. I am referring to these issues which seemed to have never been resolved:

**Edit:** I know that Commerce GC exists but it is buggy and not production ready (breaks my site during checkout) and the bug issues havent been resolved.

Here is my exported rule:

```
{ "rules_send_a_gift_certificate" : {
"LABEL" : "Send A Gift Certificate",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_coupon", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_order_contains_product" : {
      "commerce_order" : [ "commerce_order" ],
      "product_id" : "BGC-1-8",
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : { "type" : "commerce_coupon" },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:commerce-coupon-code" ],
      "value" : "ord[commerce-order:order-id]ers"
    }
  },
  { "data_set" : { "data" : [ "entity-created:type" ], "value" : "commerce_coupon_fixed" } },
  { "data_set" : { "data" : [ "entity-created:is-active" ], "value" : 1 } },
  { "data_set" : {
      "data" : [ "entity-created:commerce-coupon-number-of-uses" ],
      "value" : "1"
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } },
  { "commerce_coupon_action_create_coupon_line_item" : {
      "USING" : {
        "commerce_coupon" : [ "entity-created" ],
        "commerce_order" : [ "commerce_order" ],
        "amount" : "100.00",
        "component_name" : "commerce_coupon_fixed_ord1ers",
        "currency_code" : "NGN"
      },
      "PROVIDE" : { "commerce_coupon_line_item" : { "commerce_coupon_line_item" : "commerce coupon line item" } }
    }
  },
  { "data_set" : {
      "data" : [ "commerce-coupon-line-item:commerce-total:amount" ],
      "value" : "100"
    }
  },
  { "entity_save" : { "data" : [ "commerce-coupon-line-item" ] } },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "mail" : {
            "to" : "[list-item:field-gift-recipient-email]",
            "subject" : "[list-item:field-gift-sender-name] has sent you a Gift Certificate",
            "message" : "Hello [list-item:field-gift-recipient-name], [list-item:field-gift-sender-name] has sent you a \u20a6 [entity-created:commerce-coupon-fixed-amount] Gift Certificate to celebrate your birthday. Your Gift certificate code is: [entity-created:commerce-coupon-code]. Please note that your Gift certificate may only be used once, please spend the full amount in one purchase, any balance remaining is non-refundable. Happy birthday celebration!",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]
}
}

```

# Answer
After much digging, i was able to resolve this using a rules component. The trick is, after generating your coupon code using rules, that is,

> event: completing the checkout process
>
> condition: your condition (e.g order contains a particular product etc)
>
> action: create new entity =\> commerce coupon action: set data value (do this for the coupon code, max number of uses, coupon type (human readable name), etc) action: save entity =\> (your created entity)
>
> action: create new entity =\> commerce line item =\> commerce coupon (set your values) action: save entity =\> (your newly created coupon line item)
>
> create component:
>
> component plugin: rule name: name your component here (e.g "set gift coupon value") data type: commerce coupon label: (give a label that you can identify it easily with) machine name: (give a machine name that you can identify easily) save component.
>
> Under conditions: entity has field: (identify your coupon fixed amount field here e.g "coupon-fixed-value-component") action: set a data value =\> (here you identify the fixed amount coupon field and then set the value you want) save component
>
> Come back to your earlier created rule,
>
> add loop: (it should automatically capture that you want to loop into the commerce line items e.g "commerce-order:commerce-list-item" save loop inside the loop, add action = \> (here you'll select the component you created, it should automatically detect that you want to fire this component on your created coupon entity initially created within this rule e.g "entity-created" save the action.
>
> perform any other action if you want, like send email to referenced user in the gift card.
>
> That would do. each time you complete the checkout for the product referenced in the rules condition, a gift coupon will be created and the amount would be set based on your rules component action value.
>
> Limitation: You have to do this whole process for every different amount of gift coupon you create.
>
> Possible improvement: Allow a user to specify the amount at product creation time, then use rules to capture this amount and then set the coupon value based on the set amount of the product
>
> More improvements welcome..
> 1 votes

---
Tags: rules, commerce
---


title: Layout custom forms using Panels

text:
# Question
Title: Layout custom forms using Panels
Can I use the Panels module to layout a custom form?

I've created a custom form and I'm loading it in a menu callback using a function like this:

```
function _MODULE_menu_callback_function() {
  return drupal_get_form('_my_custom_form');
}

```

My ultimate goal is to use the Panels UI to rearrange the form fields into different panes so that I can easily mix in other elements.

I tried to use Page Manager: Existing Pages to accomplish this, but it simply brings the form in as a whole. I cannot break the fields apart into different panes using this module.

Is this possible with Panels?

# Answer
You need to create fieldable entity type to make form as you wish and make your custom form by adding fields to it. Than this fields will accessible in page manager UI.
> 0 votes

---
Tags: 7, forms, panels
---


title: Custom Block Content with HTML and PHP

text:
# Question
Title: Custom Block Content with HTML and PHP
I am having a lot of trouble understanding what is wrong with my code. I am trying to create a custom Facebook block, utilizing the Facebook Graph API. My module works to the extent that I see some posts show but the following is taking place:

1) The posts duplicate. This does not happen when recreating the feed outside of a drupal module.

2) Output of Block content is outside of any region and loads at the top of the page.

Here is the code I am using:

```
/**
 * Implementation of hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['facebook_block'] = array(
    'info' => t('Facebook Block'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'facebook_block':
      $block['subject'] = '';
      $block['content'] = facebook_main_contents();
      break;
  }
  return $block;
}

function facebook_main_contents(){
require_once('resources/facebook-php-sdk-master/src/facebook.php');

// connect to app
$config = array();
$config['appId'] = 'MYAPPID';
$config['secret'] = 'MYSECRETID';
$config['fileUpload'] = false; // optional

// instantiate
$facebook = new Facebook($config);

// set page id
$pageid = "MYPAGEID";

// now we can access various parts of the graph, starting with the feed
$pagefeed = $facebook->api("/" . $pageid . "/feed");

echo "<div class=\"fb-feed\">";

// set counter to 0, because we only want to display 10 posts
$i = 0;
foreach($pagefeed['data'] as $post) {

    if ($post['type'] == 'link' || $post['type'] == 'photo') {

        // open up an fb-update div
        echo "<div class=\"fb-update\">";

            // check if post type is a link
            if ($post['type'] == 'link') {
                echo "<p>" . $post['message'] . "</p>";
                echo "<a class=\"container\" href=\"" . $post['link'] . "\" target=\"_blank\"><div class=\"sharedlink\">";
                echo "<div class=\"image\"><img src=\" " . $post['picture'] . "\"/></div>";
                echo "<p>" . $post['name'] . "</p>";
                echo "</div></a>";
                echo "<div class=\"posted\">Posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "</div>";
            }

            // check if post type is a photo
            if ($post['type'] == 'photo') {
                echo "<h2>Photo posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "</h2>";
                if (empty($post['story']) === false) {
                    echo "<p><h2>Story</h2>" . $post['story'] . "</p>";
                } elseif (empty($post['message']) === false) {
                    echo "<p><h2>Message</h2>" . $post['message'] . "</p>";
                }
                echo "<p><a href=\"" . $post['link'] . "\" target=\"_blank\">View photo →</a></p>";
            }

        echo "</div>"; // close fb-update div

        $i++; // add 1 to the counter if our condition for $post['type'] is met
    }

    //  break out of the loop if counter has reached 10
    if ($i == 5) {
        break;
    }
} // end the foreach statement

echo "</div>";
}

```

I have tried placing my content code in a separate php file and including it, but that just breaks everything.

# Answer
The problem is the lack of a return value in `facebook_main_contents();` As you can see in the api documentation `$block['content']` should contain either a Drupal render array or fully rendered html. `facebook_main_contents();` is not actually returning anything but instead echoing output to the page.

You need to collect your rendered html and return it, like so:

```
$content = "<div class=\"fb-feed\">";
// check if post type is a link
if ($post['type'] == 'link') {
  $content .= "<p>" . $post['message'] . "</p>";
  $content .= "<a class=\"container\" href=\"" . $post['link'] . "\" target=\"_blank\"><div class=\"sharedlink\">";
  $content .= "<div class=\"image\"><img src=\" " . $post['picture'] . "\"/></div>";
  $content .= "<p>" . $post['name'] . "</p>";
  $content .= "</div></a>";
  $content .= "<div class=\"posted\">Posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "</div>";
}
...

return $content;

```
> 10 votes

# Answer
Your function facebook\_main\_contents should return the HTML code. Replace all your "echo" by a variable which will contain your HTML.

In fact, in drupal, you should never use an echo or a print in a file other than a template (\*.tpl.php in drupal).
> 0 votes

---
Tags: blocks
---


# Question
Title: Views 3: filter nodes such that an entity reference on the node corresponds to the current user
I'm creating an approval/review workflow with notifications.
The content type we're reviewing is called a "Scholarship", and the first review is being carried out by an Intern (interns are a role in my permissions schema). The Scholarship type has an entity reference to a user, of type "intern", which an admin can assign.

I need to create a view for each Intern such that she sees a list of the Scholarships that are assigned to her, in other words all Scholarships where the entity reference field "Intern reviewer" is the same as the logged-in user.

I've got a page display that correctly returns the title of each of my Scholarship nodes. I've created an relationship with the entity that's referenced in the ER field, so as to connect with the assigned intern. I then created a Contextual Filter on the "Intern Reviewer" field, set it to provide a default value, and selected the UID of the current user as that value.

Unfortunately this isn't returning any results. Methinks this may have to do with the fact that what's stored in the ER field is the Intern's username, whereas the contextual filter is using the UID of the logged-in user. Perhaps I need to find a way to provide the current logged-in user's login name as the fixed filter value? In any case, if anyone has any ideas I'd be grateful to hear them.

# Answer
The steps to create a view that lists all nodes of type scholarship that are referenced to the current logged in user:

1. Add new view, showing content of type scholarship
2. Add a relationship: **Entity Reference: Referenced Entity**
3. Add new filter: **User: Current**
4. Select **Yes** for the option **Is the logged in user**
5. Save.
> 1 votes

# Answer
When you add contextual filter by UID make sure that you select right relationship at the top.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to ONLY display an image in the teaser for Drupal 7
I'm currently using a modified version of the Stark Theme, customized to what I need, on this site tobyNews. However, following some new design inspiration, I've decided that instead of showing text in the teaser I want to ONLY display an image. Each image would be displayed as a grid. What I need help on is getting the teaser to show just an image and not the title, date, or author.

# Answer
> 2 votes
1. Install and Enable Display Suite Module
2. Goto your teasers page, click the gear icon which appears on mouse hover on teaser and select manage display
3. on Manage Display page locate **Select a layout** option and select single column layout from drop down *(on selecting any layout the Title field will also be available to be manipulated by DS module other wise you wont be able to hide title field in manage display page )*
4. You will see to headings Content and Disabled. Disable all the fields you don't want to display on teaser and drag image field in content.
5. Now Save your display
6. Other things can be manipulate through CSS.

# Answer
> 3 votes
The display suite module will give you this feature. It will give you advanced teaser-templates where you will be able to display one or multiple fields (and the option to display title or not) + you will get along quite easily!

---
Tags: 7, nodes
---