title: Where to query database in a module

text:
# Question
Title: Where to query database in a module
I'm creating a module that is basically a form but needs to use information from a table in the database to react the some of the button presses. Rather than executing the database query each time the button is pressed in the `callback` function, is there a way to retrieve all of the information from the database when the module loads and store it in a variable so that other functions in the module can use/access it?

Thanks in advance

**Code**: An example module that is similar to my current one. I need to use results from the database query in the `copy_text` function, and as I build the form up the same results in the callbacks for the other functions, so I don't see a point in putting the same `db_query` in each callback - surely that's just unnecessary querying of the database:

```
<?php

function playground_menu() {
  $items['playground/form'] = array(
    'title' => 'Form',
    'description' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('playground_demo_form'),
    'access arguments' => array('access content'),
  );
  return $items;
}

function playground_demo_form($form, $form_state) {

  $form['input'] = array(
    '#type' => 'textarea',
    '#title' => t('Input text'),
    '#prefix' => '<div id="in-text">',
    '#attributes' => array(
      'placeholder' => t('Enter some text here... '),
    ),
    '#suffix' => '</div>',
  );

  $form['buttons'] = array(
    '#type' => 'fieldset',
    '#title_display' => 'invisible',
    '#attributes' => array(
      'style' => 'border: 0px; text-align: right',
      'class' => array('container-inline'),
    ),
  );

  $form['buttons']['copy'] = array(
    '#type' => 'button',
    '#value' => 'Copy text',
    '#ajax' => array(
      'callback' => 'copy_text',
      'wrapper' => 'out-text',
//          'method' => 'replace',
//          'effect' => 'fade',
    ),
  );

  $form['buttons']['reverse'] = array(
    '#type' => 'button',
    '#value' => t('Reverse text'),
  );

  $form['buttons']['clear'] = array(
    '#type' => 'button',
    '#value' => t('Clear text'),
  );

  $form['output'] = array(
    '#type' => 'textarea',
    '#title' => t('Output text:'),
    '#prefix' => '<div id="out-text">',
    '#value' => '',
    '#attributes' => array(
      'placeholder' => t('Your text will appear here...'),
    ),
    '#suffix' => '</div>',
  );

  return $form;
}

function copy_text($form, $form_state){
  $form['output']['#value'] = $form_state['values']['input'];
  return $form['output'];
}

```

# Answer
You could just wrap your query in cache test, like this:

```
function steam_get_username2($steam64)  {
  if($cached = cache_get('steam'.$steam64, 'cache'))  {
    $username = $cached->data;
  }
  if(empty($username)) {
    $username = 'blank'; // Expensive code here
    cache_set('steam'.$steam64, $username, 'cache', 60*60); //1 hour
  }
  return $username;
}

```

Example by alandarev on Drupal.org, tweaked a bit by me.

Please remember that HTTP is stateless protocol, so each time callback is called, it's a new execution, with new variables. That's why Drupal can't cache to RAM on it's own. So Drupal caches in database. Unless your query is really complicated, caching it makes little sense - it only substitutes one query with another. You have to use APC or Memcached to really feel the difference, as these allows fast cache in RAM.

---

If you need the same data in few places during one call, like form building function, validators and callback function, then use static cache. `&drupal_static($name, $default_value = NULL, $reset = FALSE)` is what you need in such situations. Traditional way is to use it as

```
$function_static_data = &drupal_static(__FUNCTION__);

```

This will make sure static data is properly associated with function that uses it, freeing you from the burden of collision prevention (as function names are unique in PHP already).
> 2 votes

# Answer
You've got two options, depending on your needs

1. Static cache - data is built once during a single request and re-used where needed. Your query will run once but once only on every related request. See `drupal_static()` for example usages.
2. Backend cache - the results of your database query are cached, and you query the cache bins for the data instead of your database table. Your query will be run once only, until the cache is invalidated, when it'll obviously need to be run again. You'll still incur the overhead of querying the cache, so if your cache is database-based, this may or may not be worth it, depending on the size and complexity of your data. With this method you'll also need to think about how/when/if you invalidate the cache to get fresh data. See the `Cache API docs` for examples.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Drupal commerce - purchase a product at registration
I'm trying to use Drupal Commerce for a subscription site that will have only one product to purchase - a subscription to a service.

I'd prefer if a user could either do product subscription as a part of user registration, or immediately be redirected. Currently I'm trying the redirection with a rule to a custom order page (which I'm creating with rules), however rules doesn't seem to know what the order id is of the created entity.

So I'm either looking for a way to fix that, or another solution that I may have missed. Basically I want registration to be the easiest thing possible.

# Answer
> 0 votes
Figured this out - apparently you have to add the action, "save entity" after you create it, and also force it to save immediately.

# Answer
> 0 votes
You can do it easily by pro-grammatically to implement this functionality. As i already used this earlier.

You just need to use the `hook_form_alter()` drupal function to alter the registration form

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

if ($form_id == 'Your_FORM_ID') {
$form['#submit'][]='registration_formalter_submit';

}

}
function registration_formalter_submit($form, &$form_state){
 global $user;
 $PID = 2; // say any
  $uid = ($user->uid) ? $user->uid : 0;
    $order = commerce_order_new($uid, 'checkout_checkout');

// Save the order to get its ID.
    commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
// here you need to pass product ID
    $product = commerce_product_load($PID);

    $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
// Save the line item to get its ID.
    commerce_line_item_save($line_item);
// Add the line item to the order using fago's rockin' wrapper.
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
    commerce_order_save($order);
    drupal_goto('checkout');

}

```

Also, add a rule to clear cart before adding a product to a cart.

Hope it works for you!

---
Tags: commerce, rules, entities
---


# Question
Title: Is it wrong to programatically create an entity without its required fields?
This is a general question, but based on a specific situation. In Commerce the standard way of customising a product AFAIK is to use Commerce Customizable Products. It allows you to create different bundles of the line\_item entity and configure certain fields to be used on the add-to-cart form. A typical example would be a customisable message being implemented as a text field. When you add the product to your cart, a new line item is created and that's what's actually associated with your order.

While considering another Q I thought it made sense to have the option to fill out the form at checkout time. It would be useful to have required fields, but that would mean that when the line item is created these required fields are empty. AFAICT core doesn't enforce required fields when saving entities programatically. `field_default_validate()` just checks cardinality. (And a quick test creating a node without required fields populated seems to bear this out.) It *seems* like the required attribute is only for the UI.

One potential problem occurs if users have access to the entity edit form. Imagine you want to change the title of a node, you edit it, and then you have to fill in all the required fields as well before you can save. But in some cases (like line\_item) users typically don't have general access to an entity edit form. So in this situation is it icky to create an entity without its required fields? Is there any precedent? Can anyone see any other pitfalls?

# Answer
Yes, it is wrong. If you will mark some fields as required, other modules will be free to assume they are / need to be filled. So migration of your entities may fail, and it will be your fault.

---

More philosophically, remember robustness principle:

> Be conservative in what you send, be liberal in what you accept

That's what Drupal does, accepting your incomplete entities. But you shouldn't send them to Drupal incomplete.

RFC 1122 and RFC 3117 are telling you basically the same thing if you want to transmit your entities over the Internet. They don't tell you what to do internally, of course, but I believe it is a good practice to store internal data in a robust, standard-compatible, ready to be transmitted shape.
> 2 votes

---
Tags: commerce, entities
---


title: Multiple form on module page

text:
# Question
Title: Multiple form on module page
i created a module. I created a form and implemented it on the page:

```
function tudakozo_menu() {

  $items['tudakozo'] = array(
    'title' => t('Tudakozo'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tudakozo_nevszerint_form'),
    'access callback' => TRUE,
  );

  return $items;
}

```

I would like to have an another form on this

# Answer
Instead of using drupal\_get\_form as the page callback, you can specify a custom callback and build the forms there. An implementation in Drupal 6 would look similar to the following:

```
function tudakozo_menu() {

  $items['tudakozo'] = array(
    'title' => t('Tudakozo'),
    'page callback' => 'tudakozo_page_callback',
    'access callback' => TRUE,
  );

  return $items;
}

function tudakozo_page_callback() {
  $output = '';

  // Render your two forms here.
  $output .= drupal_get_form('tudakozo_nevszerint_form');
  $output .= drupal_get_form('tudakozo_second_form');

  return $output;
}

```

The only difference in Drupal 7 would be working with a render array as opposed to a string in the custom page callback similar to the code below:

```
function tudakozo_page_callback() {
  $build = array();

  // Render your two forms here.
  $build['form_one'] = drupal_get_form('tudakozo_nevszerint_form');
  $build['form_two'] = drupal_get_form('tudakozo_second_form');

  return $build;
}

```
> 17 votes

# Answer
Check here

```
4. Next step is to create a hook_theme() function to theame these forms.
function custom_salesforce_theme() {
  return array(
 // this template is containing theme style for update form
    'custom_salesforce_update_form' => array(
      'template' => 'theme/custom_salesforce_update_form',
      'render element' => 'form',
    ),
 // this template is containing theme style for login form
    'custom_salesforce_login_form' => array(
      'template' => 'theme/custom_salesforce_login_form',
      'render element' => 'form',
    ),
 // this template is containing theme style for both forms
    'custom_salesforce_login_and_update' => array(
      'template' => 'theme/custom_salesforce_login_and_update',
      'arguments' => array('combine_form' => NULL),
    ),
  );
}

Note- Don't forget to create three template files inside theme folder inside your module.
5. Next step to write template preprocessor functions to display individual fields in separate template files.
/**
 * Implements Template Preprocessor For User Login().
 */
function template_preprocess_custom_salesforce_login_form(&$variables) {
  $variables['rtc_registered_email'] = drupal_render($variables['form']['rtc_registered_email']);
  $variables['rtc_password'] = drupal_render($variables['form']['rtc_password']);
  $variables['rtc_submit_form'] = drupal_render_children($variables['form']);
}

```

Above code describes how you can add two forms.

Below here This is how you add it to tpl file

```
<?php
$form = drupal_get_form('user_register_form');
print drupal_render($form);
?>

```

Hope it helps :)
> 0 votes

---
Tags: forms
---


# Question
Title: Unable to set date field programmatically
Somehow my custom fields ('datum' and 'high') are not set in the following script. Could someone tell me what I am doing wrong?

```
    function erstelle_kursenodes() {

$content = file_get_contents('http://www.xmlcharts.com/cache/precious-metals.php?format=json');

if(empty($content)){
    echo 'KEINE API-VERBINDUNG';
} else {
$cuobj = json_decode($content);
  // add node properties
  $newNode = (object) NULL;
  $newNode->type = 'kurs';
  $newNode->title = 'XAUUSD';
  $newNode->uid = 0;
  $newNode->created = strtotime("now");
  $newNode->changed = strtotime("now");
  $newNode->status = 1;
  $newNode->comment = 0;
  $newNode->promote = 0;
  $newNode->moderate = 0;
  $newNode->sticky = 0;
  // add fields
  $newNode->field_datum[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime("now"));
  $newNode->field_high[$node->language][0]['value'] = number_format($cuobj->usd->gold * 31.1034768, 2, '.', '');
  // save node
  node_save($newNode);
}}

```

'datum' is a regular date field

'high' is decimal integer with two digits after a point

# Answer
> 0 votes
It is a format issue that you are choosing to save.

```
    $newNode->field_datum['und'][0]['value'] = date('Y-m-d h:i:s', strtotime("now"));
//Here in place $node->language pass 'und' and then try.
//Just save a node directly from backend, let say it is saved with node id 10.

$nid = 10;
echo "<pre>";
print_r(node_load($nid)) ;
echo "</pre>";

```

Now check which format it is using to save. Pass same format once statically and then make it dynamic. Hopefully it will resolve your issue.

# Answer
> 0 votes
`$node` isn't defined anywhere in your function, so `$node->language` will be `NULL`.

You probably meant:

```
$newNode->field_datum[LANGUAGE_NONE][0]['value'] = date('Y-m-d h:i:s', strtotime("now"));
$newNode->field_high[LANGUAGE_NONE][0]['value'] = number_format($cuobj->usd->gold * 31.1034768, 2, '.', '');

```

Or to use a specific language code instead.

---
Tags: entities, datetime
---


title: Unable to create Menu Item

text:
# Question
Title: Unable to create Menu Item
I am creating a menu item using the following code.

```
$item = array(
'link_path' => 'node/custom',
'link_title' => 'Custom Title 001',
'menu_name' => 'menu-custom-menu', // Menu machine name, for example: main-menu
'weight' => 0,
'plid' => 0, // Parent menu item, 0 if menu item is on top level
'module' => 'menu',
);
menu_link_save($item);

```

I can see the entries is menu\_links table, but can not see this menu item under the menu at 'admin/structure/menu/manage/menu-custom-menu'. What is wrong with my code?

Please note this path('node/custom' actually doesn't exist in Drupal System.

# Answer
**Please note this path('node/custom') actually doesn't exist in Drupal System.**

Whenever we create using admin a menu it asks for a valid path otherwise it shows error of *Url doesn't exist*. So probably it enters the data in database directly but will not be listed in the admin unless it has a valid path assigned.

Please try by adding a page, e.g node/1 to the path and then try.

```
$item = array(
'link_path' => 'node/1',
'link_title' => 'Custom Title 001',
'menu_name' => 'menu-custom-menu', // Menu machine name, for example: main-menu
'weight' => 0,
'plid' => 0, // Parent menu item, 0 if menu item is on top level
'module' => 'menu',
);
menu_link_save($item);

```

and make sure **node/1** exists in the system.

Hope it will help you.
> 0 votes

---
Tags: 7, routes
---


title: Dynamically assign user roles

text:
# Question
Title: Dynamically assign user roles
I have an application using domain access and am looking to reuse a set of subscriber roles across domains, assigning them on login.

I was hoping to use hook\_user\_load to add the additional roles.

I have some code like this:

```
/**
 * Implements hook_user_load()
 *
 * Dynamically assign configured roles based on active domain and subscription
 */
function EXAMPLE_user_load($users) {

  // Process each account once per request
  $processed_uids = &drupal_static(__FUNCTION__, array());
  // Get defined roles
  $roles = user_roles(TRUE);

  // Process accounts
  foreach ($users as $uid => $account) {
    $grant_rids = array();
    if(!in_array($uid, $processed_uids)){
      // Code to get grant role ids here...
      // ...
      // ...
      // Grant subscriber roles
      if(!empty($grant_rids)){
        foreach($grant_rids as $rid){
          // Matching role exists and not already assigned
          if(!empty($roles[$rid]) && !array_key_exists($rid, $users[$uid]->roles)){
            $users[$uid]->roles[$rid] = $roles[$rid];
          }
        }
      }
      $processed_uids[] = $uid;
    }
  }
}

```

Using this approach, the roles do get added, and I can see them in the `$users` array after processing.

However the user logging in, despite running through `hook_user_load` doesn't appear to have those roles "set" ( i.e aren't authenticated as having that role )

Maybe some kind of cache issue?

Does anyone have any ideas about what needs changing above or how to assign user roles dynamically as the user logs in, or as the user is loaded?

**UPDATE:**

Well, it turns out, you *can* actually alter user roles in `hook_user_load`.

My issue was caused by a ctools bug I discovered in my debug travels whereby the current logged in user context didn't fully load the user entity, and thus the access checks for the Panel page access were failing. It also needed a `drupal_static_reset('user_access')` to reset the static `user_access` permission check cache. Patch posted here http://drupal.org/node/2010124

After that, the dynamic role assignment appears to be working fine.

**UPDATE 2**

I wrote too soon, still having problems...

Will update when resolved.

**UPDATE 3**

OK, the remaining issues were related to ctools context caching. I ended up writing my own ctools access plugin to ensure the logged in user context is checked uncached on each access request. After that, all appears well again.

# Answer
You can try user\_multiple\_role\_edit, something like this might help.

```
  $user_id = $user->uid;
  // user the role human name
  $role_name = 'My Awesome Role';
  if (user_role_load_by_name($role_name)) {
    // No need to check if the role is already granted
    user_multiple_role_edit(array($user_id), 'add_role', $role->rid);
  }

```
> 1 votes

# Answer
The documentation for hook\_user\_load() contains a warning about overriding the user properties that are loaded from the {users} table, but apparently that is valid for properties loaded from the {users\_roles} table read from UserController::attachLoad().

The only workaround I found is to alter the global `$user` variable, or change what shown in the user edit form when shown. The other possibility is changing the user roles when the user object is saved.
In a module I developed, I took the first approach.
> 0 votes

# Answer
I am fairly certain that modifying hook\_user\_load as suggested above will not actually allow you to assign a role dynamically to a user. Even though doing this will show that role during the hook\_user\_login hook; the user does not actually get logged in authenticated with that new role.
> 0 votes

---
Tags: 7, users
---


title: Drush for Drupal 4.7

text:
# Question
Title: Drush for Drupal 4.7
I'm trying to find a version of Drush that is compatible with Drupal 4.7. I know it's old and lame and long time ago deprecated but I really need it for a project I'm currently involved in. I've tried to search it but without any luck.

Thanks, Alex

# Answer
You can find it in the last page of the releases for drush on drupal.org (right at the bottom, unsurprisingly).

As Greg mentions in the comments, Drush 1.x is a module so it needs to be put in the modules folder and enabled.
> 2 votes

# Answer
You can find the dev version here..

## "REQUIREMENTS

This version of drush is designed for Drupal 4.7.x running on a Unix platform."
> 0 votes

---
Tags: drush
---


title: views results differ from preview

text:
# Question
Title: views results differ from preview
Working on my first Drupal project, I meet this problem for the second time. I can't figure why this happens and couldn't find any leed on the web.

1) A view with contextual filter *Content: Has taxonomy term ID (with depth)*

* *depth* = 1
* *When argument not in the URL* = *Show all results*
* *Vocabulary* : the proper (hierarchical) taxonomy is selected

The view has path *taxonomy/term/%*

The preview is correct, both when entering as an argument a child term ou a parent term.

The view results are correct for any *taxonomy/term/\[child\_term\]* path.

But for a *taxonomy/term/\[parent\_term\]* path, I get a message "No content tagged with this term". The sentence is true, but it should return all content tagged with any of the child terms. So, it behaves as if there was no *(with depth)*.

2) Adding to the same view a basic *Filter criteria = Content: Type(=\[TheRightContentType\])*.

The preview is ok. But again, the results are not filtered. Even when the argument is a child term, I get all results tagged with that term, but whatever their content type is.

I flushed the browser cache. Then I flushed Drupal's caches. In vain.

Any suggestions appreciated. Thanks.

# Answer
Finally, the view has

• a path *taxonomy/term/%/%*

• a second contextual filter *Content: Has taxonomy term ID depth modifier*

and this solves problem 1 : with a parent tid as an argument the view produces every content that is tagged with one of its child terms.

But problem 2 remains.
> 0 votes

---
Tags: views
---


# Question
Title: how to call a webservices on hook_form_FORM_ID_alter but not when the form is submitted and validation raise no error?
I have to call a webservice than dynamically modify the form. I used hook\_form\_FORM\_ID\_alter to do that. The problem is hook\_form\_FORM\_ID\_alter is also called on submit event when the form is not going to be displayed again to the user.

How can I avoid calling the webservices two times? The information gathered with the webservice are not important for the validation...

This is also linked to this question hook\_form\_FORM\_ID\_alter called twice after submit

# Answer
The reason why your alter is called twice is because Drupal needs to build the form at least two times: one for the first time is delivered to the user and a second time when the submit is done. The second build is needed because Drupal needs to know the complete form that was delivered to the user (for validation and security reasons).

You have two approaches to solve this:

**Form API**

As other have answered modify the form API behavior to avoid that second call:

* Detect the second call and do not call the webservice (checking $form\_state\['triggered\_element'\]\['#name'\] as told): it's ok but take into account that if the form built in the second call is different form the first one you may have problems with Form API complaining about invalid user input,
* Enable form cache ($form\_state\['cache'\] = TRUE). This way Drupal saves the form when is built for the first time, so the second time during submit, form is fetched form DB.

**Cache webservice results**

A second call to the webservice is not a problem if you cache webservice data because you retrieve the results from the cache instead of call it again. I think this is the best option if the nature of the webservice data allows to cache it.

This way the problem is solved in the webservice area while the other solutions involves that other components solve the issue (your form API code *solves* the webservice problem). If there's another similar use case you will have to solve again the proble, but if you solve it using webservice caching the problem is solved for all use cases.
> 5 votes

# Answer
You could check it the $form\_state\['triggered\_element'\]\['#name'\] value matches your submit button #name.

Example:

```
function mycustom_form($form, &$form_state) {
  ...

  if (!empty($form_state['triggering_element']['#name'])
    && $form_state['triggering_element']['#name'] == 'submitname') {
    // DO STUFF
  }

  $form['submit'] = array(
    'type' => 'submit',
    'name' => 'submitname',
    'value' => 'Save',
  );

}

```

You can also check other triggering\_element properties as #value but #name is more accurate.

Note: ajax callbacks are also defined on the triggering\_element form property this is the reason you should check the #name.
> 1 votes

# Answer
The reason you're seeing this behaviour is that the FAPI needs the form array for two different page requests: the form view, and the form submit. By default it recreates the form on submission for this, but you can tell it to cache the form instead and just reload it:

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

This will still mean that every time the user loads the initial form a new web service request will be made, so you might want to implement caching for the service itself. (Especially if this form is open to the public, you probably don't want to have a direct link between a page view and a web service request, but I don't know the specifics of your situation.)
> 1 votes

# Answer
If you set a value in your form with the form alter, either the result of the webservice or an arbitrary value you can then test if this value is set and if it is not set call the webservice.
> 0 votes

# Answer
I'd recommend exploring the $form\_state array in your alter hook. You'll notice a couple of elements that you can key off of. I believe you'll want to look at $form\_state\['submitted'\]. This should be FALSE when the form is first loaded and TRUE when the form is submitting.

So your webservice call can be made when $form\_state\['submitted'\] == FALSE.

The drupal\_build\_form gives a good description of the various $form\_state elements.
> 0 votes

# Answer
For your particular situation, I would recommend you cache the results of the webservice call in `$form_state` and set `$form_state['cache'] = TRUE`. As others have said, this will cause Drupal to retrieve the form (and form state) from the database (or other cache system); otherwise the form will need to be built again *before* the form processing recognizes the form is being submitted. So your alter hook should look like this:

```
function hook_form_FORM_ID_alter(&$form, &$form_state) {
    $form_state['cache'] = TRUE;
    if (!isset($form_state['storage']['mine'])) {
        // Call the web service and store the data in $form_state['storage']['mine'].
    }
    // Now use $form_state['storage']['mine'] to alter the form.
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Always expanded menu items not showing up expanded in custom menu
I have a custom menu `profile-menu` and have configured a block to display that menu. It has four menu items with `'expanded' => TRUE`. However, during test runs these expanded menu items do not show as expanded. I've dug through the Drupal menu code and it looks like Drupal won't handle `'expanded'` unless the variable `'menu_expanded'` includes the menu name, which is odd because I've never had this problem outside of the test environment. I tried adding `variable_set('menu_expanded', array('profile-menu'))` to `hook_install` but for whatever reason when I call `variable_get('menu_expanded')` inside the test case that variable is an empty array.

If during the test case I call `menu_cache_clear_all(); variable_set('menu_expanded', array('profile-menu'))`, everything does work as expected. The code that seems to be gated by this variable is in `menu_tree_page_data`.

What's the right way to make sure certain menu items (which I have defined myself in `hook_menu`) are always expanded? Because setting `expanded => TRUE` in `hook_menu` apparently doesn't cut it during test cases. Also, why am I only seeing this issue when running test cases?

# Answer
> 0 votes
I have investigated this a bit more and made a bug report on Drupal.org. It turns out the `'menu_expanded'` variable is basically a redundant layer of caching which must be set by `_menu_set_expanded_menus` whenever the cache is cleared. However, if Drupal tries to call that function more than once in a single request, it will be registered as a shutdown callback instead of called immediately. This would work fine most of the time in normal use, but during test cases the shutdown function won't get called until after the tests are over.

Knowing that most of the time this operation will handle itself correctly, and that even if it doesn't it's just a cache clear away from being fixed, I've decided it is acceptable to add a direct call to `_menu_set_expanded_menus` in the `setUp` function like so:

```
function setUp() {
  parent::setUp('custom');
  // Call this function now to set up expanded menu item processing. Normally
  // we could wait for it to be called in a shutdown function added during
  // the menu rebuild in parent::setUp() above, but in this case it must be
  // handled before the tests are run.
  _menu_set_expanded_menus();
}

```

---
Tags: routes, testing
---


# Question
Title: How to use variables in a PHP evaluation in a rule?
I created a rule with the actions "Provide a variable: mynumber" and "Grant points to a user". I'd like to evaluate the points with PHP, using "mynumber". For some reason, I can't use `$mynumber`, although that is possible in the PHP evalution of the sections 'Operation' and 'Description'. As the replacement pattern `[mynumber]` is available, I tried to use it in my code with and without the square brackets, but in both cases, I get the error:

> Notice: Use of undefined constant mynumber - assumed 'mynumber' in eval() (line 1 of C:\wamp\www\mysite\sites\all\modules\rules\modules\php.eval.inc(146) : eval()'d code).

Is this a missing feature, a bug in the Rules module or did I do something wrong?

# Answer
It turned out that the problem is caused by the way Rules handles integers and numbers in general. Instead of trying to calculate the Userpoints in the action "Grant points to a user", one should provide a new variable earlier.

1. Provide a new variable (**text type!**), called "Number", with the necessary PHP code (wrapped with `<?php ... ?>`). One can then use earlier calculated results like `$mynumber`.
2. Convert "Number" to an integer, called "Points".
3. Grant "Points" to the user.

Hopefully, Rules will cope a little bit better with numbers in the future, but until then, I hope this trick helps a lot of people.
> 0 votes

# Answer
You can achieve this, use variable module and define variable which you want use in rule.

To define a variable you need to write custom module , which will contain following function

```
function My_module_variable_info() {
  $variables['rainbow_count'] = array(
  // 'name' isn't really necessary, as it will get populated from the key of this array above.
 'name' => 'rainbow_count',
 'title' => t('Number of Rainbows'),
 'type' => 'number',
 'group' => 'UserPoints Config',
 'token' => TRUE,
'default' => 0,
'description' => t('Specify the number of rainbows.')
);

}

```

Set value for variable which you want use in rule through :

`configuration>>variables>>modules>>My_module_...`

Now go to rules \>action\> grant points to a user \> Points:

Set `data type =current-user:uid` and put `return variable_get('rainbow_count');` code in PHP evaluation.

This solution worked for me,hope will help you also.
> 1 votes

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


# Question
Title: Why can't my user see the private groups they are members in?
I just installed Drupal Commons 7.x-3.x. I configured two private groups, and added a normal user to them. That user can see content posted to those groups, but it cannot see the group itself, or post content to the group.

Why?

I've added the user as an administrator in the group.

I've cleared all the Drupal Caches on the performance page.

I've cleared my browsers cache.

I've logged the user in and out.

I've rebuilt node permissions.

I've run cron manually.

I've double checked the people/permissions to make sure the user had permission to create groups, just in case that mattered.

No matter what I do, if I try to go to commons/groups/privategroupname with my non-user1 user I get an "Access Denied" page.

If the user wasn't a member, it would not be able to see the content in the list on the /home page.

Public groups work fine.

When creating the private groups, I selected: "Joining requires an invitation. The group and content is hidden from non-members." in the Privacy Settings.

So, I'm at a loss. Help!

# Answer
> 0 votes
I think this has to do with publishing the content.

If I published a group that was marked as invite only, it would then show up in the list of groups as invite only, and content would only be viewable by members. Seems like an imperfect solution though, as to me, an invite only group should be hidden. But if you do use this solution, be sure to mark the content type to default to published.

There's problems with Drupal and unpublished content sometimes. In this case, the usual solution (Views won't display unpublished nodes when explicitly told to) didn't seem to fix it.

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


# Question
Title: Dymanimcally add links in main menu (e.g. last 4 nodes)
I have main navigation menu with root menu items. A request is that one of those have links to latest 4 nodes of a certain content type. So for example if I have a structure similar to this:

-Parent item:

* child item 4
* child item 3
* child item 2
* child item 1

(All child items are all of the same content type, for example Article)

When a user adds a new node of the content type Article, the structure should be the following:

-Parent item:

* child item 5
* child item 4
* child item 3
* child item 2

All I can think of is to use Views to make a list of linked titles in a block and then to attach the block to the menu (i'm using TB Mega Menu which allows this). The solely problem with this approach is that I then don't have trail of active menu items in menu.

Any ideas?

Thanks.

# Answer
> 0 votes
**Make the URLs static; have the content of those URLs change**

You were on the right track with views. But don't use it to create a block with the links, use it to create a page that displays the full rendered entity of the last node of your content type. You can give it a URL like `/latest-article`.

You could get fancy and use contextual arguments to display the 2nd, 3rd, ... offsets (e.g. `/latest-article/%`) or you could just add four more displays to the view, each with the offset bumped up by one.

# Answer
> 0 votes
First, in the you can choose what menu and what parent should those links go . That way, all the new links should appear where you wish.

Then, using Rules and Menu Rules you can make disappear the oldest menu link when you add a new one.

---
Tags: views, routes, blocks
---


# Question
Title: Apply CSS and Javascript affect to images
**Updated**

I am trying to add CSS and Javascript hover affect to some images in drupal 7 .. something like in this tutorial.

http://callmenick.com/2014/03/06/image-overlay-hover-effects-with-css3-t ... Hover on some touch devices is sticky like iphone .. in this example it gives the user a (X) which close the sticky hover when it is touched

i have jQuery Update already installed ... and when i applied the code like in this tutorial in custom CSS and Javascript files .. its not working ... i really do not know what am i doing wrong or if i have to install another library to drupal or what am i missing to add to drupal ... even when i try to test it here http://codepen.io/anon/pen/onsyH ... still not working ..

any help will be appreciated

# Answer
> 3 votes
I have done a CSS only alternative for you.

http://jsfiddle.net/bk5h7/

**EDIT:** In answer to the JS not working in Drupal, you may need to wrap any document ready JS in behaviour tabs, and/or declare jQuery.

This will also help if you use it in a view that uses AJAX. Putting it in a behaviour instead of document ready, means the JS will load again even on every AJAX request.

```
(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

        // Put your jQuery Code Here

  }
};
})(jQuery);

```

**EDIT 2:** The demo uses jQuery 1.9.1, whereas Drupal 7 is shipped with 1.4.4. Maybe try using the jQuery Update module to update your version.

**EDIT 3:** What are you using to load the Modernizr.js script? That touch function you are talking about relies on device detection using Modernizr.js.

Copy the modernizr.js file to your themes JS folder, and in your themes template.php file, try adding...

```
drupal_add_js(drupal_get_path('theme', 'YOUR_THEME') . '/js/modernizr.js');

```

---
Tags: javascript, theming, media
---


# Question
Title: Create view gallery, with page for every image
I have a node "Event Gallery" that has a multiple unlimited image field that I load up to 50 images into for each event.

In manage display, I set the image field as hidden, and instead, I use a views block with a content by ID filter, and the block visibility set to all node type \> Event Gallery.

In the past I have used something like colorbox to let users scroll through the gallery, which looks nice, but does not function well when you want visitors to be able to "share" or "like" an individual photo, and for that individual photo to have its own url.

In the image field settings, you can make each image in the gallery link to its file, but I want the file to be shown in the theme, and have its own url.

How do I attach a page to my block view, to show every image of the gallery on its own page, with previous & next links (pager), and for every image to have its own url?

# Answer
> 0 votes
If I understand the question properly, something like this should work...

if the url is user defined, create a field using URL. If not, the answer depends on the requirements of the URL.

1 per page: set the pager to limit 1 per page

Link:

* add the link field, set to exclude from display
* add the image field as normal, exclude from display
* create a Global Text, with tag, using the image field and link field as replacement patterns

---
Tags: views
---


# Question
Title: Flexslider not working on Acquia Drupal cloud
I've been able to get the Flexslider module \+ library to work on local dev instances of core Drupal in the past, but when I try to enable/configure for Acquia cloud, it inserts the images as li's but does not animate them.

These are the steps I've taken:

* Installed/enabled the flexslider module on my local dev environment.
* Downloaded and installed the latest Flexslider library from github into `docroot/sites/all/libraries/flexslider`.
* git added/committed/pushed the changes to Acquia cloud.
* Enabled the module in the Acquia cloud dev environment.
* Edited the 'basic page' content type to use a flexslider field.
* Created a basic page with a few images in that field.

As stated above, the images get inserted as list items, but do not get animated. It seems like the module is being invoked, but the flexslider js files are not being included in the `<head>`.

The page in question: http://acquiacloudwwedev.devcloud.acquia-sites.com.

# Answer
> 0 votes
Boneheaded mistake on my part - In the default option set for FlexSlider, I had the "Move" field set to 0. This apparently makes it not animate. Changing it to "1" resolved it.

---
Tags: javascript, acquia-cloud
---


title: Is weather.com still running Drupal?

text:
# Question
Title: Is weather.com still running Drupal?
There have been news items in 2013 about weather.com moving to Drupal. I have been reading How to tell if a site is using Drupal 7 and I have been unable to find out if the site is still running on Drupal.

How can I find out if weather.com is still running Drupal?

# Answer
I use buildwith chrome plugin and Appspector, it does not looks like they use drupal CMS.
> 0 votes

# Answer
There is usually some CDATA starting with

```
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings

```

Or the files and folders are in a /sites/all/.. directory that are the major drupal give aways.

It does not look like weather.com uses drupal.
> 0 votes

# Answer
Is not Drupal. IMHO is a custom php framework based on YUI library.
> -1 votes

---
Tags: 7
---


title: How do I preprocess "extra fields"?

text:
# Question
Title: How do I preprocess "extra fields"?
Drupal allows you to create "*extra fields*" through hook\_field\_extra-fields.

I'd like to be able to load javascript (among other things) in my module, based on the presence of one of these fields, but I can't seem to find a hook that will fire before it renders.

I've tried *hook\_preprocess\_HOOK* (for mymodule\_preprocess\_field), but that didn't work. You can detect for it on *hook\_preprocess\_node*, but that doesn't work if the field is being rendered individually, or a in a view. Any ideas?

# Answer
> 1 votes
It depends on what fields you are dealing with.

hook\_field\_extra\_fields() allows you to define extra fields for any entity, then the field itself is added in a hook that runs when the entity's content is being generated.

That is the place where you need to add the js.

In that hook you can modify the fields you care about and add your js using drupal\_add\_js() or #attached.

#attached is generally more resilient to caching as it lives with the field render array.

Use #attached like this:

```
$form['YOURELEMENT']['#attached']['js'][] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';

```

For example, if the field you want is being added to nodes, you would implement hook\_node\_view() or hook\_node\_view\_alter() something like this:

```
function MODULENAME_node_view($node, $view_mode, $langcode) {
  if (isset($node->content['EXTRAFIELD'])) {
    $node->content['EXTRAFIELD']['#attached']['js'] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';
  }
}

```

or in hook\_node\_view\_alter() it would be like this:

```
function MODULENAME_node_view_alter(&$build) {
  if (isset($build['EXTRAFIELD'])) {
    // Change its weight.
    $build['EXTRAFIELD']['#attached']['js'] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';
  }
}

```

The same principle can be applied to other entity types, like users, which would use hook\_user\_view() or hook\_user\_view\_alter().

If your field is on multiple entity types you might have to use multiple of these implementations, or even better, you could use hook\_entity\_view() or hook\_entity\_view\_alter(), which allow you to target all entity types in the one place.

If you need to make sure your hook runs after all other modules' implementations of that same hook then you can either set the weight of your module higher than others or use hook\_module\_implements\_alter() to make sure your module runs last.

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


title: Clickable image contents with checkbox

text:
# Question
Title: Clickable image contents with checkbox
I have created a site consisting of image galleries, gallery consists of image and a description for it. I want that the user should be able to select multiple image contents as checkbox so that he can add them to cart. After selecting the images I want to compare the details of the selected images. How can I achieve this?

# Answer
> 0 votes
Try the Commerce product comparison module

> This module allows you to compare products. This is a familiar feature on commerce website.

There is another module called Dynamic properties

> Provides a dynamic properties field that allows to store product properties or similarly structured information. A property consists of an attribute, the name of the property and a value. It belongs to a category.

---
Tags: commerce
---


# Question
Title: Variable containing HTML is not rendering when sent by message notify
I am trying to send e-mails with message notify and rules, everything is running pretty well, but there's one variable which contains a "HTML code", It describes a table of items that were bought for someone. I NEED to pass it as a HTML table, but it renders like these on the users E-mail Inbox:

```
<tr>
<td>Peep Toe Colorido (34, Marrom) (415-01612--11163-11184)</td>
<td>1</td>
<td>10990</td></tr>
<tr>
<td>Sandália Clássica (34, Nude) (577-02357--11163-11186)</td>
<td>2</td>
<td>19980</td></tr>

```

and the tags which were entered in the message type and are rendered right, showing not the markup tags but the table itself.

How can i make the HTML generated by a variable render properly when sent by message notify?

# Answer
Try using the HTML Mail module, Which will help you to render HTML in your email notification

> Lets you theme your messages the same way you theme the rest of your website.
> 0 votes

---
Tags: rules, emails, theming
---


title: Move DB from Apache to IIS

text:
# Question
Title: Move DB from Apache to IIS
I've been working on a Drupal site under a LAMP configuration. My client uses SQL Server, so after I'm done with development I need to move the site over to their configuration. I work on Linux, so I have no way to test the site live (I can remotely connect to my client's server but if I want anything changed I have to go through their IT department, which is painful and slow at best).

I found this module, driver for SQL Server, but from the instructions I gather this is for a fresh Drupal install. Could it work, if I already have some work done, to move my current DB over to their server? If not, is there another option to keep working on MySQL and later migrate to SQL 2008?

I'm not familiar with SQL Server, so any help is appreciated.

# Answer
> 0 votes
Here is the way I would approach your issue:

1. Prepare two IIS+MSSQL servers, Staging and Production
2. Do a fresh install on Staging
3. Use tool like Features, UUID, and data migration module of your choice to move configuration and data from Development to Staging
4. Tie loose ends on Staging
5. Copy Staging to Production
6. Replace my dev with something less unlike production

---
Tags: 7, migrations, database
---


# Question
Title: ImageStyles does not create thumbnail image while uploading large images
I try to create a website using Drupal on a shared host, everything goes fine except ImageStyles.

When I try to upload large images (more than 1MB) thumbnails does not created , but works fine with smaller one.

I searched it and found these two:

Failing to create thumbnail, medium and large images

Image styles: Does not work with large images

but I can't use these solutions because I'm using a shared host.

Any suggestion will be appreciatived ;)

# Answer
If Drupal can't resize images due to not enough RAM or due to timeouts, and you can't change RAM and timeout settings, and can't change library, then you have only three options:

1. Limit image size to something your installation can handle.
2. Provide additional field for thumbnails and make your users prepare them.
3. Change hosting.

Personally I would go with 3.
> 0 votes

# Answer
You can restrict the **image upload size** using field settings in the admin to less than 1 MB and show a help text that max upload size is 1 MB.

Other option already given by Molot.

Hope it will help you.
> 1 votes

---
Tags: 7, files, media
---


# Question
Title: Views Filter with Checkbox and Searchfield
I am searching for a solution to generate a custom filter consiting out of two fields. I want to have one Dropdown which holds the fields of my view, and then a second field "textfield" which will hold the search variable.
Here's an example. I do have a view with ID, name, email. My two filters would be a dropdown containing ID, name and email. And when I type something into the textfield, the field selected in the dropdown will be the filtered one. Does anyone know a module that does that? If not, I will write one.
I've checked Global combined filters so far, but they don't do what I want.

EDIT: just in case my question wasn't clear enough, this is what I want to achieve. And still got no idea how to.

# Answer
> 0 votes
What I've found so far is the Module Composite Views Filter, which does quite the thing. You can display a filter on selection of dropdown. But not programatically. You have to fill your dropdown yourself.
Not quite what I was looking for, but better than nothing.

---
Tags: views
---


title: Regions and Page Layouts

text:
# Question
Title: Regions and Page Layouts
How do you work with regions if your website has different page layouts? For instance, the home page is a header-content-footer page, while the article page is header-sidebar-content-footer, etc.

Learning themeing :)

Thanks!

# Answer
You can do it by creating **templates** for different types of **pages**.

**e.g.** If you have different layouts for front page, you can create **page--front.tpl.php**. It will work for front page only, for rest of the pages **page.tpl.php** will work.

If further you have different layouts for page types, e.g a *normal layout for pages* and *different layouts for article type of pages* then you can create two types of tpl.

1. node--article.php, if you have the same header and footer content and just content part design is different.
2. page--article.php (page–\[node-type\].tpl.php), Here you can customize the content part as well as different layout for header and footer part.

Also there will a customization option in the manage display part of the content type.

Hope it will help you.
> 0 votes

# Answer
Different page layouts are usually created by themeing the main page.tpl.

So if your front page is different, it is likely your theme is using a page--front.tpl.php to override the look of the front page.

You can also hide regions if they are on the front page by checking if $is\_front...

This checks if it is the front page, and then makes sure there is content in the front\_welcome region, before printing that region.

```
  <?php if ($is_front): ?>
    <div class="container">
      <?php if ($page['front_welcome']): ?>
        <div id="front-welcome"> <?php print render($page['front_welcome']); ?></div>
      <?php endif; ?>
    </div>
  <?php endif; ?>

```

You can also check if other regions have content, before printing regions on other parts of the page, and assigning classes to other regions...

In this example in one of my themes, I work out if one, or two sidebars are being used, and print a class for the main content to determine the contents width with CSS...

```
<?php if($page['sidebar_first'] && $page['sidebar_second']) {
      $contentwid= "seventeen";
 } elseif($page['sidebar_first'] || $page['sidebar_second']) {
      $contentwid= "eleven";
 } else {
      $contentwid= "sixteen";
 } ?>

<div id="content" class="<?php print $contentwid; ?> columns">
</div>

```

Does that help at all?
> 0 votes

---
Tags: theming
---


# Question
Title: Delete selected comments of a particular node?
Is there any module in Drupal 7 for deleting *selected comments* at one go for a particular node?

# Answer
You can do this with Views Bulk Operation module. Follow the steps:

1. Install Views and Views Bulk Operation modules and enable these modules.
2. Create a View of Type **"Comment"**.
3. Change the Views Format *show* from **'Comment'** to **'Fields'** under Format section.
4. Change the Views *Format* from **'Unformatted list'** to **'Table'**.
5. Add **Bulk Operation:Comment, Comment:Title and Content:title** fields under Fields section.
6. In step 5 When you chose **Bulk Operation: Comment** select **Delete Item** under *SELECTED BULK OPERATIONS* setting.
7. Add **Content: Title** filter criteria and expose this filter So that you can filter comments of a particular node.
> 1 votes

---
Tags: 7
---


title: using $GLOBALS['base_path']

text:
# Question
Title: using $GLOBALS['base_path']
A quick one - is it ok to use this? I can't seem to get access to $base\_url in my node which is set in my settings.php file.

# Answer
No, it's not OK to use it directly. Always use `base_path()` function instead. There are two benefits:

1. You will not risk accidental change in the original variable, so you will not cause other modules to fail if you'll make a mistake.
2. If, for whatever reason, Drupal will change way it stores base path, your module will continue to work properly.
> 2 votes

---
Tags: uri
---


# Question
Title: theme superfish menu item link add query string
I need to add the destination to user/logout links in the THEME\_superfish\_menu\_item\_link preprocess function, but I am having no luck.

In template.php I have:

```
function THEME_superfish_menu_item_link(array $variables) {
  if ($variables['menu_item']['link']['link_path'] == "user/logout") {
    $dest = drupal_get_destination();
    $link_path = $variables['menu_item']['link']['link_path'] . '?destination=' . $dest['destination'];
    $menu_link = l($variables['menu_item']['link']['title'], $link_path, $variables['link_options']);

    return $menu_link;
  }
}

```

My links end up encoded: /user/logout%3Fdestination%3Dhome

I assume query strings can be added as parameters to the $variables\['menu\_item'\] but am unsure how.

# Answer
I think your problem is in how you add the query string. Check this article: Webemania | How and why to use l() function to create links in Drupal and specifically example 6.

```
<?php
// adding query string on example:5
print l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf'), 'query'=>array('id'=>'5','status'=>'ok') ));
?>

```
> 0 votes

---
Tags: 7, routes, theming, navigation
---


# Question
Title: Do I have to activate a parent theme when I activate its sub theme?
A sub theme relies on its parent. Does that mean I always have to activate both of them?

# Answer
> 6 votes
No it doesn't. As long as the base theme is present, that's OK.

As an example, if you test the Sky theme on Simplytest.me and go to the *admin/appearance* page, you'll see that Sky is enabled, but the base theme (AdaptiveTheme) is not.

# Answer
> 1 votes
In Drupal 8, the base theme is automatically enabled.

https://www.drupal.org/node/2232651

> When a sub-theme is installed, then its base theme(s) are installed, too.

---
Tags: 7, theming
---


# Question
Title: Where to find the html.tpl.php $head variable content generation
I'm looking for a way to edit the $head variable of the html.tpl.php. Where exactly is this variable composed and set?

# Answer
> 4 votes
The most common way to add information to the `<head>` is using `drupal_add_html_head()`.

If the data you want to alter was added using that function, you can alter it by implementing `hook_html_head_alter()` within a custom module. Using the alter hook requires that you know the `$key` of the data that was added during `drupal_add_html_head()`.

If you want to alter CSS or JS, use `hook_css_alter()` and `hook_js_alter()` respectively.

---
Tags: theming
---


# Question
Title: Create a field instance programmatically on a taxonomy vocabulary
I'm trying to create a module which creates a taxonomy vocabulary on installation of the module, and creates one text field on the taxonomy vocabulary/term. But I'm getting the following error when I enable my module:

> \[error\] FieldException: Attempt to create an instance of field field\_flickr\_photoset on forbidden entity type taxonomy\_term. in field\_create\_instance() (line 468 of /var/www/www.example.com/htdocs/modules/field/field.crud.inc).

First of al, why a Forbidden entity type? Is it not possible to create a field on a taxonomy vocabulary through code? Or am I missing some parameters?

I used very similar code to create a node type and attach fields to it, which currently works without any problems. I didn't think that changing the entity type would cause such problems.

I tried searching on google and here on how to do this, but all I get is people who are asking how to attach a taxonomy term reference field to a node type, which is not what I'm asking. It's attaching a text field to a taxonomy term/vocabulary.

# Answer
> 3 votes
If you look in `taxonomy_entity_info()` you'll see this code that defines the `taxonomy_vocabulary` entity type:

```
$return['taxonomy_vocabulary'] = array(
  'label' => t('Taxonomy vocabulary'),
  'controller class' => 'TaxonomyVocabularyController',
  'base table' => 'taxonomy_vocabulary',
  'entity keys' => array(
    'id' => 'vid',
    'label' => 'name',
  ),
  'fieldable' => FALSE,
);

```

The important bit to note is `'fieldable' => FALSE`...that's why it's 'forbidden' to add fields to that type.

The `taxonomy_term` entity type *is* fieldable so you won't have any problem adding field instances to one of those.

If you really want to add a field to the vocabulary, you'll need to implement `hook_entity_info_alter()` to change the vocabulary entity to `'fieldable' => TRUE` (I've done it before, it's perfectly safe):

```
function MYMODULE_entity_info_alter(&$info) {
  $info['taxonomy_vocabulary']['fieldable'] = TRUE;
}

```

# Answer
> 1 votes
**Drupal 7**

If you check the code which causing that Exception, you'll see the following condition:

```
  // Check that the field can be attached to this entity type.
  if (!empty($field['entity_types']) && !in_array($instance['entity_type'], $field['entity_types'])) {
    throw new FieldException(t('Attempt to create an instance of field @field_name on forbidden entity type @entity_type.', array('@field_name' => $instance['field_name'], '@entity_type' => $instance['entity_type'])));
  }

```

That means the field which you're trying to define has restricted `entity_types` attribute which has list of entities to which the field can be attached.

So either you need to define your entity via the following property of your field:

```
  'entity_types' => array(0 => 'allowed_entity_type'),

```

leave it empty, or just try to remove `entity_types` attribute from the field definition at all.

---

Don't forget to clear the caches in Performance.

If the problem persist, you may try to remove the field to be able to recreate it again (e.g. `drush eval "field_delete_field('field_which_is_broken');"`).

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


# Question
Title: Accessing all taxonomy terms from one specific vocabulary through url
I want do display all my terms from one vocabulary over drupals pathauto url scheme. So f.e. I have example.com/taxonomy/term/314 or after pathauto: example.com/screwdriver/slot or example.com/screwdriver/torx. This works good.

But if I visit example.com/screwdriver, this page doesn't exist.

Actually I'm kind of puzzled, that this is not working out of the box. Do I really have to implement a custom module for this?

# Answer
> 1 votes
Is there a functionality made for that particular page? Is that a term namde, a node or a view? Any kind of entity? Because if it is not, nothing will show up, obviously. Create a view page showing all taxonomy terms within that vocabulary. Taxonomy pages are for taxonomy terms only, not for taxonomy vocabulary based on some url scheme.

---
Tags: taxonomy-terms, path-aliases, uri
---


# Question
Title: Showing all Sibling nodes that share the same Taxonomy term in Drupal 7
I made a Taxonomy named `Category` which has terms as following:-

* Term 1
* Term 2
* Term 3
* Term 4

As a requirement, any node that I create has to select one term mentioned above.

Now, what I wanna do is; that when I visit any node page, it should show me all the node titles that share the common term.

As an example, if I selected `Term 2` as a category when creating following nodes:-

* Node 1
* Node 2
* Node 3
* Node 4
* Node 5
* Node 6

I want the list of all these nodes when I visit any of these nodes.

My URL, when I visit any of these nodes is:-

```
http://www.mysite.com/term_name/node_name

```

Thanks.

## P.S.

I tried `Views arg parent term` within a view and followed instructions here (https://www.drupal.org/project/views\_arg\_parent\_term), but it seems it works with a Taxonomy Term ID and I guess my URL has Taxonomy Name in it.

Any help would be highly appreciated.

Best.

# Answer
Try to add validator when filter value is AVAILABLE or Default is provided:
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Services 3: Setting taxonomy terms on node creation/update
For a custom node type, I have defined a field that is to hold an unlimited number of values from a taxonomy vocabulary that I defined.

This is what it looks like:

```
[field_taxonomy] => Array
  ( [und] => Array
      [0] => Array
        ( [tid] => 13 )
      [1] => Array
        ( [tid] => 14 )
      [2] => Array
        ( [tid] => 15 )
  )

```

This is the JSON I pass to the server during node creation (as per \[1\]):

```
'field_taxonomy':
  { '11':
    { 'tid': '11'} }

```

This format is accepted (i.e. no 406, which I get if I try to mirror the above structure), but when I look at the node on the server, the field does not contain any terms.

What does my request have to look like so I can succesfully set taxonomy terms on a node?

\[1\] What will be the post parameter when specifying vocabulary term?

# Answer
> 3 votes
Your request should use the following:

```
"field_taxonomy":{ "und": { "values": "14" }  }

```

# Answer
> 0 votes
As i understood from Services Documentation you doesn't need to create ершы sequence in the array \[0\],\[2\] etc. The Services module numbers it itself.

Also, if you are using auto complete for taxonomy you should use the term id, tid, 3 times

```
"field_taxonomy":  [{
  "tid":{
    "tid":"[tid:11]",
    "tid":"[tid:12]",
    "tid":"[tid:13]"
        }
}]

```

# Answer
> 0 votes
One thing that tripped me up:

If you've created an autocomplete field for your term reference using a view, instead of passing in the term name like:

```
"field_vocab_tags": {
      "und": [
          {
             "target_id": "40"
          }
      ]
  }

```

You need to pass in the complete term title *according to the view*. In my case, I have the title set as:

```
Term Title - my_unique_id_field (tid)

```

so I actually have to set:

```
"field_vocab_tags": {
      "und": [
          {
             "target_id": "My Term Title - UNIQUE_ID_23 (40)"
          }
      ]
  }

```

This is specifically in the case where you have an autocomplete using views, and the view formats the title as I did above.

If you want multiple references, simply add additional arrays in your field\[und\] array, like so:

```
"field_vocab_tags": {
      "und": [
          {
             "target_id": "My Term Title - UNIQUE_ID_23 (40)"
          },
          {
             "target_id": "My Next Term Title - UNIQUE_ID_24 (41)"
          },
          {
             "target_id": "Your Term Title - UNIQUE_ID_C (42)"
          }
      ]
  }

```

Hope this helps someone.

# Answer
> -1 votes
I used a string as tag values:

```
"field_tags": {
   "und": "term 1, term 2"
 }

```

---
Tags: taxonomy-terms, services, 8
---


# Question
Title: How to translate a database query with a subquery to a db_select statement?
Assume any variable that doesn't have a definition in the sample code is defined elsewhere. I need to get the results of the following query:

```
select type, eid, vid, language, keyword, custom_value from (select * from custom_keywords_entity_values where language = 'en' order by eid asc, vid desc) as ckev group by keyword;

```

However, I'm not entirely sure how to translate this into a query that leverages the Database API.

Fatal error: Unsupported operand types in /Users/lpeabody/Sites/jandj/docroot/includes/database/query.inc on line 1809

This is my working structure right now:

```
$subquery = db_select('custom_keywords_entity_values', 'a');
$subquery->fields('a')
  ->where('language', $language)
  ->orderBy('eid')
  ->orderBy('vid', 'DESC');

$query = db_select($subquery, 'ev');
$query->fields('ev')
  ->groupBy('keyword')
  ->execute();

$keywords = $query->fetchAllAssoc('keyword', PDO::FETCH_ASSOC);

```

I feel like that's the most literal translation, but I'm probably missing something since I'm getting this sweet error:

```
Fatal error: Unsupported operand types in /Users/lpeabody/Sites/jandj/docroot/includes/database/query.inc on line 1809

```

Let me know if there's any other information you need me to provide you.

# Answer
> 2 votes
`SelectQuery::where()` takes a string (not an object).

You probably meant to use `SelectQuery::condition()`:

```
$subquery->fields('a')
  ->condition('language', $language)
  ->orderBy('eid')
  ->orderBy('vid', 'DESC');

```

Your execution is slightly off too; at the moment you're discarding the results of the execution, and instead invoking `fetchAllAssoc()` on the wrong type of object.

What you need is

```
$keywords = $query->fields('ev')
  ->groupBy('keyword')
  ->execute()
  ->fetchAllAssoc('keyword', PDO::FETCH_ASSOC);

```

or

```
$result = $query->fields('ev')->groupBy('keyword')->execute();
$keywords = $result->fetchAllAssoc('keyword', PDO::FETCH_ASSOC);

```

Or some other derivative of the same logic.

After those changes you should wind up with

```
SELECT  ev.*
FROM
(SELECT  a.*
FROM
{custom_keywords_entity_values} a
WHERE  (language = 'en')
ORDER BY eid ASC, vid DESC) ev
GROUP BY keyword

```

Pretty close to your original, and functionality identical.

---
Tags: 7, database
---


# Question
Title: Check for double escaped string - Simpletest
I am trying to create a test case against a patch which will be used for automated testing in D8 release.

However, I am trying to do it to check if the page I am on it, has any multiple escaped HTML element. The page where I am trying is following,

```
<table class="responsive-enabled">
  <thead>
    <tr>
      <th>Uninstall</th>
      <th>Name</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr class="odd">
      <td align="center">
        <div class="form-item form-type-checkbox form-item-uninstall-block form-disabled form-no-label">
          <label class="visually-hidden" for="edit-uninstall-block">Uninstall Block module</label>
          <input disabled="disabled" type="checkbox" id="edit-uninstall-block" name="uninstall[block]" value="1" class="form-checkbox" />
        </div>
      </td>
      <td><label for="edit-uninstall-block" class="module-name table-filter-text-source">Block</label></td>
      <td class="description">Controls the visual building blocks a page is constructed with. Blocks are boxes of content rendered into an area, or region, of a web page.<div class="admin-requirements">To uninstall Block, the following module must be uninstalled first: Custom Block</div></td>
    </tr>
    <tr class="even">
      <td align="center">
        <div class="form-item form-type-checkbox form-item-uninstall-breakpoint form-disabled form-no-label">
          <label class="visually-hidden" for="edit-uninstall-breakpoint">Uninstall Breakpoint module</label>
          <input disabled="disabled" type="checkbox" id="edit-uninstall-breakpoint" name="uninstall[breakpoint]" value="1" class="form-checkbox" />
        </div>
      </td>
      <td><label for="edit-uninstall-breakpoint" class="module-name table-filter-text-source">Breakpoint</label></td>
      <td class="description">Manage breakpoints and breakpoint groups for responsive designs.<div class="admin-requirements">To uninstall Breakpoint, the following module must be uninstalled first: Toolbar</div></td>
    </tr>
    <tr class="odd">
      <td align="center">
        <div class="form-item form-type-checkbox form-item-uninstall-ckeditor form-no-label">
          <label class="visually-hidden" for="edit-uninstall-ckeditor">Uninstall CKEditor module</label>
          <input type="checkbox" id="edit-uninstall-ckeditor" name="uninstall[ckeditor]" value="1" class="form-checkbox" />
        </div>
      </td>
      <td><label for="edit-uninstall-ckeditor" class="module-name table-filter-text-source">CKEditor</label></td>
      <td class="description">WYSIWYG editing for rich text fields using CKEditor.</td>
    </tr>
    <tr class="even">
      <td align="center">
        <div class="form-item form-type-checkbox form-item-uninstall-color form-no-label">
          <label class="visually-hidden" for="edit-uninstall-color">Uninstall Color module</label>
          <input type="checkbox" id="edit-uninstall-color" name="uninstall[color]" value="1" class="form-checkbox" />
        </div>
      </td>
      <td><label for="edit-uninstall-color" class="module-name table-filter-text-source">Color</label></td>
      <td class="description">Allows administrators to change the color scheme of compatible themes.</td>
    </tr>
  </tbody>
</table>

```

From the code you can understand that it's the module's uninstall page. So in the **RAW** HTML we can see it has the double escaped HTML elements. Like `<` became `<`.

The test file I am writing is the following,

```
<?php

/**
 * @file
 * Definition of Drupal\system\Tests\Module\UninstallPageLoad.
 */

namespace Drupal\system\Tests\Module;

use Drupal\Component\Utility\String;
use Drupal\simpletest\WebTestBase;

/**
 * Tests the module uninstall page load for multiple HTML escaping.
 *
 * @group Module
 */
class UninstallPageLoad extends WebTestBase {

  /**
   * Loads module uninstall page and checks HTML escaping
   */
  function testUninstallPageHtmlEscape() {
    // Create new admin user and test page load.

    $account = $this->drupalCreateUser(array('administer modules'));
    $this->drupalLogin($account);
    $this->drupalGet('admin/modules/uninstall');
    $this->assertResponse(200, 'Module Uninstall page loaded.');

    // Test the page if it has multiple HTML sanitizations.
    $this->assertNoRaw('<label', 'Page should not have htmlentities');
  }
}

```

While executing the file I think I should get a **failed** result as the page do have many double escaped HTML characters. But I am getting a success.

**EDIT: After Core debug**

I think now I know the reason why this fails, When I added a debug code in `core/modules/simpletest/src/AssertContentTrait.php` in the method `assertNoRaw` it gave me the following RAW HTML.

```
<table class="responsive-enabled">
  <thead>
    <tr>
      <th>Uninstall</th>
      <th>Name</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr class="odd">
      <td colspan="3" class="empty message">No modules are available to uninstall.</td>
    </tr>
  </tbody>
</table>

```

So no modules are loading in this page. So now the question is how to replicate the page output same as `theme_system_modules_uninstall` from `core/modules/system/system.admin.inc, line 290` page.

Can any one help me with this?

# Answer
> 2 votes
To get output on the page, you first need to install some non-required modules.

A test uses the testing profile, which installs no modules except those that are required (system, user, field, entity), and you can't uninstall them.

So all you need to do is add a `public static $modules = array('node')` or any other non-required module to have some output show up there.

Note: Simpletest by default stores out the output of every page request you make as a static page, with a "Verbose output" link (only shown in the UI). Looking at that is a lot easier than debugging some code somewhere.

---
Tags: 8, testing, version-control
---


# Question
Title: Removing "node" path from "node/add/*" URLs
How can I remove the "node" part from "node/add" URLs? I have clean URLs on, and I have successfully used Pathauto to remove "node" from other paths.

# Answer
If you go to `admin/config/search/path/add` then you can easily alias `node/add/type` to whatever you want. For example, if you're using a node type called contact-form for a contact page, then just add `contact-form` as an alias for `node/add/contact-form`.
> 5 votes

# Answer
Enable the Path module (in core), and add a new alias.
> 2 votes

# Answer
If you wanted to create a different path from which you can add nodes, you could also do something along the lines of...

```
function mymodule_menu() {

  $items['add/%'] = array(
    'title' => 'mymodule add',
    'page callback' => 'mymodule_add',
    'page arguments' => array(1),
    'access callback' => TRUE, // or set to your specifications of your site
    'type' => MENU_CALLBACK,
  );

  return $items;

}

function mymodule_add($type) {
  global $user;

  module_load_include('inc','node','node.pages');
  $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $type, 'language' => '');

  return drupal_get_form($type .'_node_form', $node);
}

```

...in a module. I say along the lines of because a) that's a drupal 6 example and I know you said drupal 7, and b) no security is included in the above either. But at least I hope it's showing how easy it is to extend things. Also, you just have to make sure there are no namespace collisions, because, unless your "mymodule" is named "add," it is being somewhat rude by claiming "add" as its own.
> 2 votes

# Answer
You can get the aliases you want created automatically with the Sub-pathauto module

(Sorry it's a rather late answer, but hopefully a more useful one for some readers.)
> 0 votes

---
Tags: 7, uri
---


title: Views, Blocks, and Content Types

text:
# Question
Title: Views, Blocks, and Content Types
I made a content type where I have used views to make my content into a block. But the content type's page shows two copies of the data. One from the content type, and another from the block made through views. I want the data that is shown through views, but I also want to keep the edit content tab for easy editing. I am not sure what other information I need to give to make the problem clearer.

# Answer
> 1 votes
From what i understand, you are most probably doing it wrong :).

If you want to change the node display, have a look at the Display Suite.

If you insist on changing it with views, you might want to switch to a page display, set the path to node/nid to override the default node view and do what you need there.

---
Tags: views, blocks, nodes
---


title: Use "view" inside a loop / clone a view

text:
# Question
Title: Use "view" inside a loop / clone a view
I'm trying to use a view inside a loop but it's not working, I'm using "views\_get\_view($name)" but "clone\_view()" / "copy()" is not working, I can't create another reference.

I have a view with a contextual filter and by settings different arguments on each loop with "set\_arguments" the result should be different. I get the result for the first loop but all the others are empty.

I'm trying to use something like this:

```
for($i=2; $i<=4; $i++){

    $view = views_get_view('view_name');
    $view->set_display($i);
    $view->set_arguments(array($i));
    $view->execute();

    dpm($view->result);
}

```

and the result is:

```
... (Array, 4 elements)

... (Array, 0 elements)

... (Array, 0 elements)

```

The first result is working great (4 elements inside the array) but the others are empty.

I know the above code is not correct as this is not the way to handle objects but at least you will know what I want, a different result for each set of arguments, arguments which are connected to a contextual filter inside view.

Can someone help me with a method to use the view inside a loop ? I only managed to generate the result once no mather what.

Thanks.

# Answer
The $view-\>set\_display($i); will not work unless you have an integer as the display name of your view (which is something I'm not sure if possible or if you need it).

try changing the $i in $view-\>set\_display($i); to the display name of your view:

```
for($i=2; $i<=4; $i++){

    $view = views_get_view('view_name');
    $view->set_display('display_name'); //Example: page, page_1, block_1, custom_display_name ..etc
    $view->set_arguments(array($i));
    $view->execute();

    dpm($view->result);
}

```
> 0 votes

# Answer
The problem was/is "$view-\>execute", it seems that I can run this method only once no matter what I do, so I had to approach the issue different. I've found another solution:

```
for($i=7; $i<=10; $i++){

        $view = views_get_view('edc_menu', TRUE);
        $view->set_arguments(array(2, $i));
        $view->use_pager();
        $view->set_items_per_page(0);
        $view->build();

        $q = edcmenu_qc($view->build_info['query'], TRUE);
        $q = db_query($q);

        foreach($q AS $key => $item){
            // Generate array with results.
        }
    }

```

I extracted the view query from each iteration then I used db\_query() to run it.

edcmenu\_qc() is a method based on "devel" method dpq() to convert the object query into a string so I can pass it further to db\_query()

```
function edcmenu_qc($query, $return = FALSE) {

    if (method_exists($query, 'preExecute')) {
        $query->preExecute();
    }
    $sql = (string) $query;
    $quoted = array();
    $connection = Database::getConnection();
    foreach ((array) $query->arguments() as $key => $val) {
        $quoted[$key] = $connection->quote($val);
    }
    $sql = strtr($sql, $quoted);
    if ($return) {
        return $sql;
    }

    return ($return ? NULL : $query);
}

```

Problem solved and eveyrthing is working perfect.
> 0 votes

---
Tags: views
---


# Question
Title: How can I get header part from my drupal 7 site?
Hotelscombined(hotel information site) asked me "the header part" of my website so they can combine my website's header and their hotel list. My header part will be placed in their site.

Then it looks that my website services hotel information. My site is developed using Drupal 7. How can I get header part only? It shouldn't be just copying and pasting. It should be something like link. With that, it will be affected in Hotelscombined, even if I changed header part of my website like main menu.

Please help me.

# Answer
> 1 votes
Usually header part is included in drupal in page.tpl.php.

Still you can do it by creating a function in your template.php

e.g. **myheader()** and calling it in **page.tpl.php**.

```
function myheader(){
$html = "<div class='header'>
 Insert header html
</div>";
return $html;

}

```

Other way you create a template using hook\_theme in your custom module and call it in page.tpl.php.

e.g. it will be called in page.tpl.php by below code

```
print theme('myheader');

//It will defined in custom module

function mymodule_theme($existing, $type, $theme, $path)
{
  if($type == 'module')
  {
    return array(
      'myheader' => array(
        'variables' => array('var_name'=>NULL),
        'template' => 'myheader'
      ),
    );
  }
  return array(); //will raise fatal error if void
}

```

and put a template in theme directory with name myheader.tpl.php

Hope it will help!

---
Tags: theming, javascript
---


title: Invoke colorbox from a URL (not a link)

text:
# Question
Title: Invoke colorbox from a URL (not a link)
All of the documentation assumes the content content load into colorbox will happen as a result of click... (e.g., the parameters calling colorbox are built into the link)

> My Example

I want to issue a redirect to a URL that then opens in colobox...

Any suggestions or experience solving this?

# Answer
> 1 votes
You should use java-script and the iframe support in color-box.

```
<script type="text/javascript">
  $(document).ready(function() {
    $("a", ".the-class-added-to-links-clicking-which-will-open-theurl-in-coloyxbox").click(
      function(event) {
        event.preventDefault();
        var elementURL = $(this).attr("href");
        $.colorbox({iframe: true, href: elementURL, innerWidth: 645, innerHeight: 509});
      });
  });
</script>

```

Code Source : https://stackoverflow.com/a/8933655/493742

# Answer
> 1 votes
If you have installed colorbox module that you don't need to add any library files just use the below code to open lightbox in you custom code

```
<a href="http://hdwallsource.com/img/2014/7/desktop-images-15066-15533-hd-wallpapers.jpg" class="customclass"> Open colorbox </a>

  <script>
    jQuery(document).ready(function() {
        jQuery("a.customclass").click(
          function(ev) {
            ev.preventDefault(); //To prevent redirection
            var hr = jQuery(this).attr("href");
            jQuery.colorbox({iframe: true, href: hr , innerWidth: 500, innerHeight: 400});
          });
      });
 </script>

```

Here href will be link of the page that you want to open in colorbox.

Hope it will help you.

# Answer
> 0 votes
When you load the new URL, you'll need to have javascript on the page to fire the colorbox load event.

---
Tags: javascript
---


# Question
Title: How can I split up a massive feature module into multiple smaller modules?
I have one massive unmaintainable features module that I want to split up into smaller, manageable features. Can I disable the massive module without it removing or disabling content types and dependencies, as well as strongarm variables?

# Answer
I came across this solution which suggests using CTools Bulk Exporter to get the features back into the database so they can be re-exported as smaller features.

> Think I've found an alternative solution to get your exported objects back into the database so you can safely disable/remove your features.
>
> 1) Export everything you want in the database using CTools Bulk Exporter (admin/structure/bulk-export). Put the module it generates into your modules folder (eg. my\_exports\_module) 2) Disable the features containing the objects you just exported 3) Enable the module CTools Bulk Exporter created for you 4) Download Drush CTools Export Bonus & enable it 5) Run the following drush command: drush cbsa my\_exports\_module 6) Disable my\_exports\_module
>
> Tested this with view modes/fields/... created in Display Suite - everything went better than expected :)
> 1 votes

# Answer
Another way would be to create new features while your original feature is enabled.

Create a new feature and under "Advanced options" tick "Allow conflicts to be added". Now all your components, even those added to other features before will be available.
> 0 votes

---
Tags: features
---


# Question
Title: form_set_error not showing error message on webform
I have created my own module and when i try to use form\_set\_error all im getting is the red border around the form input but no error message.

here is my code

```
function dd_alert_register_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id === 'webform_client_form_123'){
        $form['#validate'][]='dd_alert_register_form_validate';
    }
}

function dd_alert_register_form_validate($form,&$form_state)
{
    //where "phone" is field name of webform phone field
    $email = $form_state['values']['submitted']['email_address'];

    if ((bool) db_select('users')->fields('users', array('uid'))->condition('mail', db_like($email), 'LIKE')->range(0, 1)->execute()->fetchField()) {
        form_set_error('submitted][email_address',t('The e-mail address is already registered'));
        return $form;
    }
    // Then use regular expression to validate it.
    // In above example i have check if phonefield is empty or not.
}

```

# Answer
> 2 votes
I think it could also happen if `$messages` haven't printed in the `page.tpl.php` in your theme.

Is the `<?php print $messages; ?>` included in your `page.tpl.php` file?

Check this line in your page template. You might have missed it.

Hope it will help you!

---
Tags: forms, webforms
---


title: Alternative to panels

text:
# Question
Title: Alternative to panels
Is there any alternative to Panels that can be used for smaller websites where Panels may be a overkill?

I recently took up DP development again, haven't worked with DP7 for approx a year now, did lots of work on DP7 earlier.

When settings up a new site I always feel blocks are sufficient, if only the configuration had been made "correct" from the beginning - sorry for being biased.

But is the only alternative to blocks full blown Panels and mini panels if you want to be able to configure blocks differently depending on the the context in which they appear?

# Update

after having tested Context and Display Suite I have to admit they fit perfectly! As stated by @j-reynolds in his comment, the Display Suite makes it possible to create column based layouts in which you can determine what data you want to see eg. splitting your node into a 2 column stacked view where body is in the left region and tags in the right, title goes into the header region.

Using the Context module you can control which blocks or regions are being shown based on eg. term view or node view.

Combining the 2 and you have something easy to work with and manageable without going full blown Panels.

Both modules can do a lot more, I am just mentioning a few of the options.

# Answer
Check out Context.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.
> 2 votes

# Answer
If your site is really simple and you have very few contexts the basic drupal core block system is still a valid option.

It saves on server resources compared to things like panels & context so if you don't really need the features of those you're better off without them.

I agree it is not really viable for more complex setups but on simpler sites it can be perfectly acceptable, especially if you aren't changing blocks and block content regularly.
> 0 votes

---
Tags: 7, blocks, panels
---


# Question
Title: Views displaying only one record on pagination
Created a view which displays all user on the website, I have added pagination which displays 10 records on the page.

I am not sure but its displaying only one records but correct pagination link.

# Answer
> 1 votes
Go to your view and Click on Pager settings. and change the items per page

# Answer
> 0 votes
Check if the Filter Criteria of your view meet the requirements/conditions. For example, check if you are listing only the blocked users.

---
Tags: views, paging
---


# Question
Title: CKEDitor removes class names, even with the exception in config
CKEditor seems to be stripping out class names when I toggle between HTML view and Rich Text view.

As per many suggestions across the web I have added the following to the config.js file:

```
config.allowedContent = true;

```

Uploaded, cleared cache and even gone to the JS file directly to check it is not caching on my machine, but it's still removing classes.

Is there another solution?

# Answer
Go to "Admin \>\> Configuration \>\> CKEditor"; under *Profiles*, choose your profile (e.g. *Full*).

Edit that profile, and on "Advanced Options \>\> Custom JavaScript configuration" add `config.allowedContent = true;`.

Don't forget to flush the cache under "Performance tab."
> 18 votes

# Answer
Edit the full profile in Configuration \> CKEditor

Open the Advanced Content Filter section and select Disabled

No need to add anything in the Extra Allowed Content field. No need to change the config.js. \[...like this hasn't taken me hours and hours to figure out\]
> 6 votes

# Answer
This issue has been solved in dev (7.x-2.3 when published) as part of CKeditor 4.1 ACF. You may try either to upgrade your WYSIWYG or try the below workarounds.

---

In Drupal 7 you can try the following hook:

```
<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
    $settings['allowedContent'] = TRUE;
  }
}
?>

```

or by using some other idea:

```
<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
      $settings['extraAllowedContent'] = array(
        'img[src,title,alt,style,width,height,class,hspace,vspace,view_mode,format,fid]',
      );
  }
}
?>

```

or with the following jQuery code:

```
CKEDITOR.replace( textarea_id, {
    allowedContent: true
} );

```

Related:
> 1 votes

# Answer
Go commando and disable the wysiwyg altogether.

If you know how to write basic HTML and CSS, i.e. you're not the client, then turn off the plugin. It'll also improve your HTML/CSS skills

I spent days figuring out how to prevent the wysiwyg butchering my classes and pre/code tags everytime I reloaded the editor. I realised that all I was doing was trying to disable all the wysiwyg plugin functionality. So I turned it off.

Yep, this is contrary to my answer above.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Are there any Drupal modules that allow you to select a template to use for output or are there any modular content editing interfaces?
I'm doing some work for a design agency and I'm looking into how I can achieve their fanciful designs using Drupal. In particular I'm worried about the formate of their blog posts, it's quite clear that what they want is not going to be satisfied by any kind of WYSIWYG editor. So I'm left with two options:

1. Allow them to enter HTML and code up each of the blog posts myself (obviously not desirable).
2. Limit them to a few different templates that they can use for the future.

# Answer
I think your best bet is to add an additional field to the blog post content type, which can be used in the theme layer to select the proper template. You will provide the templates in advance, which will result in an easy UI for the editor, but will not sacrifice your ability to customize and tightly control the template.

## Step 1: make your new field

This new field should provide them with options for the layouts. For the purposes of this example I'll use a field called `field_blog_layout` that provides two options: **Single Column** and **Staggered**. Make sure you provide machine values in a format that is accepted by the theme hook system, just to make it a tad simpler for yourself in the next step. Here would be the values in your field settings:

```
single_column|Single Column
staggered|Staggered

```

## Step 2: Add dynamic theme hook suggestions

Now that you have your field, add a new hook inside template.php (or a custom module, e.g. if you have a Blog Feature). My example would live inside a module file called `my_feature.module`:

```
/**
 * Implements hook_preprocess_node().
 *
 * Provides theme hook suggestions to complement the custom layout.
 */
function my_feature_preprocess_node(&$vars) {
  // Only run this code on Blog nodes.
  if ($vars['node']->type == 'blog') {
    // First, grab the value of the Layout field.
    $my_layout = field_get_items('node', $vars['node'], 'field_blog_layout');
    // Add the theme hook suggestion using the field's value
    $vars['theme_hook_suggestions'][] = 'node__blog__' . $my_layout[0]['value'];
  }
}

```

If you were careful about using the expected format for theme hooks within your custom field's machine values, there should be no other processing needed.

## Step 3: Implement the theme hook by adding templates

With the theme hooks ready to go, you can now create templates. It's simple, just create a template using the exact format of the theme hook, except replace all underscores (`_`) with dashes (`-`):

```
node--blog--single-column.tpl.php
node--blog--staggered.tpl.php

```

For the content of these templates, just make a copy of node.tpl.php and customize it to your heart's content.

*Note: you **must** have a file called `node.tpl.php` in your theme for the special templates to work. This is a known behavior of the Drupal 7 theming system.*

## Step 4: Clear the cache and marvel at your work

New hooks and templates both require a cache clear. Don't forget or you'll wonder why nothing is changing!
> 4 votes

---
Tags: nodes, wysiwyg
---


# Question
Title: Profile2 regpath move account email field, into profile2 form and handle submit
I have a profile2 regpath displaying my profile2 form, and the system default account registration form below it. I need to move the account email field up into the container with the profile2 fields.

I have altered the form and moved the account mail field from the account form, into the profile form, and I have created an additional validation handler to try insert the mail value into the $form\_state value so the user\_account\_form\_validate() doesn't choke on a missing \['mail'\] index:

```
function si_student_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  // remove fieldgroups and tabs for anonymous users, e.g. /student/register
  if($user->uid == 0) {
    // move email field from account to below profile2 name fields
    $email = $form['account']['mail'];
    unset($form['account']['mail']);
    // add email to profile
    $form['profile_student']['mail'] = $email;
    // change weights
    $form['profile_student']['mail']['#weight'] = 3;

    // custom validation handler to inject mail value into
    // correct place in $form_state['values'] array
    $form['#validate'][] = '_si_student_register_anonymous_validate';
    //dpm($form);
  }
}

function _si_student_register_anonymous_validate($form, &$form_state) {
  $form_state['values']['mail'] = $form_state['values']['profile_student']['mail'];
}

```

However this isn't working, and I get the following:

Any ideas? I'm not sure I'm taking the right approach here. Thanks

# Answer
> 0 votes
Found solution here: move fields in the user profile form in fieldsets

But I also needed to add the submitted $form\_state mail value, back to the location it would have originally existed.

```
function si_student_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  // remove fieldgroups and tabs for anonymous users, e.g. /student/register
  if($user->uid == 0) {

    // move email field from account to below profile2 name fields
    $email = $form['account']['mail'];
    unset($form['account']['mail']);
    // add email to profile
    $form['profile_student']['mail'] = $email;
    // change weights
    $form['profile_student']['mail']['#weight'] = 3;

    // replace original validation handler
    $form['#validate'][0] = '_si_student_register_anonymous_validate';
  }
}

function _si_student_register_anonymous_validate(&$form, &$form_state) {

  // add field back to account
  $form['account']['mail'] = $form['profile_student']['mail'];
  // add submitted value from profile2 submission handler into default mail value location
  $form_state['values']['mail'] = $form_state['values']['profile_student']['mail'];
  // call validation function with update field
  user_account_form_validate($form, $form_state);

}

```

---
Tags: forms, users
---


# Question
Title: Can I show email Id entered by user to the visitors?
Suppose When a user doing the registration, site will ask that **"Do you like to show your email ID?"** If the user selects YES then the site will show his email ID and if it selecet no the site will not, I am new to the drupal, so please help me.

# Answer
Check out the following modules

User Field Privacy

> A successor of Profile Privacy for Drupal 7 that works with standard Field API (ie. non-profile) user fields.
>
> In easier-to-understand terms:
>
> * All the user fields should have an "alterable privacy" checkbox.
> * If this checkbox is ticked, the user should be presented with an additional checkbox for the privacy-enabled fields on user edit forms to be able to make that fields' values private.
> * If this second checkbox is ticked for a field of a user, only the site administrators (members of roles with the "Access private fields" permission) and the user herself should be able to view that field's value.

Profile Privacy

> This module allows users to set privacy options for their profile fields when using the core profile.module. It does not create any settings pages or configuration screens, and it integrates seamlessly with the existing profile module.
> 1 votes

# Answer
Check this out: Override user pages with a view

You should as well build up a view for the user page to control if the email address is displayed or not.
> 0 votes

---
Tags: emails, views, users
---


# Question
Title: CKEditor for Drupal 7 does not show the page contents
This page http://sunsethill-ubud.com/bistro contents some text. When I look at it as admin, I can use the Edit tab. But if I click this tab, I get an empty page in CKEditor:

I tried playing with or without additional modules, with the version of jQuery, with uninstalling and installing again CKEditor, and so on. Probably the problem is very simple, but I don't see any solution.

Thanks in advance for any help!

# Answer
> 1 votes
I solved my problem. In my numerous attempts, I had checked the wysiwyg filter in the configuration page of CKEditor. I unchecked it, and everything is OK now.

---
Tags: wysiwyg
---