# Question
Title: How to set up a view containing a list of events ordered by date
I want to have a list of Events on the front-end like this:

```
Upcoming (Newest on top)
<Event1 title> @ <Event 1 Date>
<Event2 title> @ <Event 2 Date>
.
.
Past (in reversed order)
<Event3 title> @ <Event 3 Date>
<Event4 title> @ <Event 4 Date>

```

So I created a `content type`: `event`:

```
Title
Description
Start_Date

```

And a `view`: `events` with the filter criteria `Type = event`.

This gives me a list of all events created. But where to go from here? I created a new views-view--events.html.twig but I don’t know how to retrieve the Start\_Date value. Also I think this should/can be done somewhere else?

Thanks!

# Answer
> 0 votes
In the view, you may configure the fields you want to show (assuming you want a list of unformatted fields, for easier theming).

You just pick fields as `title` or `date start`/`date end`, so you have them available when the view is processed.

Having them available, the rest is up to you, your project requirements, and twig :)

# Answer
> 0 votes
It sounds like you want a sort order for past events different to the one you want for future events?

Perhaps you'll have to have to create 2 views and attach one to the other. I think something like that is possible.

---
Tags: views, 8
---


# Question
Title: Add product variations to product display with rules
Using RULES, can anyone point me in the right direction to add lots of product variations to existing product displays?

Everything I've researched seems to be centered around creating the display when the variation is created or vice versa.

In a nutshell, my customer has created the product displays and I've setup VBO to create all the product variations. However I can't find a way to add all my particular variations to a particular display unless I either use the "Product Display Manager" module (which doesn't appear to support Bulk Operations), or add the variations one by one via the "Inline Entity Form". We'll be talking about 1000's of variations in the end.

I am a novice at RULES but it's cool to use, so ideally I would like to be able to create a RULE called, "Add variations to display". which would be available on the this page:

admin/commerce/products/variations

where I can:

1/ Select the variation checkboxes 2/ Choose the rule 3/ Click APPLY 4/ Have the rule ask me which product display the selected variations should be applied to (Ideally a list of display TITLES) 5/ Then save that product display once complete (I should be able to do that bit in the rule from what I have read)

Love to hear if someone has been able to do this or at least point me to where I can follow instructions specific to my issue. But I have a sneaky suspicion that it can't be done like this, otherwise I would have found a solution already.

Cheers

# Answer
> 1 votes
Even though I've quite a bit of experience with the Rules module, I don't know (yet) of how to do exactly as you described in your question (also because your question does not exactly include the details about which ***Event(s)***, which ***Condition(s)*** and which ***Actions*** you are looking for (try to be more specific on that (by editing your question accordingly).

I might enhance my answer (soon), but while waiting you may want to look/investige if either of the approaches below can be of any help ...

# Commerce Bulk Product Creation

Consider using the Commerce Bulk Product Creation module. Excerpt from its project page:

> ... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

**Attention**: this module doesn't have an official release yet (only an RC6), though with over 1.600 reported installs, it seems it is pretty stable / trustworthy.

# Commerce Backoffice

Another option to consider is using the Commerce Backoffice module, e.g. because of the ***auto creation of product display nodes***. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

* Commerce Backoffice **Product** (commerce\_backoffice\_product).
* Commerce Backoffice **Order** (commerce\_backoffice\_order).
* Commerce Backoffice **Content** (commerce\_backoffice\_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

**Note**: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).

# Answer
> 0 votes
Thanks Pierre.

I'm already using BPC and have installed Backoffice. All that works fine. I just can't understand why it's so hard to add *many* product variations to existing product displays using a Rule?

Maybe this will help make it a bit clearer ...

Imagine you had 3 product displays (I've actually got 60+ with this project already created):

* Tall Boots
* Short Boots
* Kids Boots

and each product display is going to have 20 variations comprising of different colours and sizes. So that's 60 product variations that I need to get into the "Product Reference" field of each display. BPC works great creating all the variations, so no worries there.

Backoffice gives us a page at:

/admin/commerce/products/variations

which nicely lists all the variations and I can filter it accordingly.

With BPC installed, I get the option to select the variations I want and then run a "Rule/Component" on those variations. Such as the default "Delete product" rule to bulk delete variations.

So as per my post, I need to somehow get a rule working to do what I need, if in fact BPC & Product Reference field will allow this to happen. Maybe there is some mystery to all this, that's why no one has come up with a solution.

Does that help explain it better Pierre?

Cheers

---
Tags: commerce, rules, views
---


title: Pager not displaying

text:
# Question
Title: Pager not displaying
I am having problems getting a pager to display after a table in the block\_view hook of a module

The code for the query is the following one.

```
$query = db_select('registry', 'r');
$query = $query->extend('PagerDefault')->extend('TableSort');

$query->limit(10)
    ->fields('r', array('name', 'type', 'filename','module','weight'));
$result = $query->execute();

```

I build and the table with no problem adding it to the content

Then I add the pager or rather I don't with the following code

```
$block['content'] .= theme('pager').'<br>mmm<br>';

```

the mmm bit was just there as a quick check to see what was happening.

I know that the extend needs to be assigned to a new variable and I believe that I am doing this.

Is there anything wrong I am doing?

This is the complete code of the module.

```
/**
 * @file
 * A block module that displays registry info.
 */

/**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function current_posts_help($path, $arg) {
  switch ($path) {
    case "admin/help#current_posts":
    return '<p>' . t("Displays registry info for testing tables and pager") . '</p>';
    break;
  }
}

/**
 * Implements hook_block_info().
 */
function current_posts_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current posts'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}

function current_posts_block_view($delta = '') {
  switch($delta) {
    case 'current_posts':
      $block['subject'] = t('Modules list');
      if(user_access('access content')) {
        $query = db_select('registry', 'r');
        $query = $query->extend('PagerDefault');
        //$result = $query->limit(50)
        $query->limit(10)
          ->fields('r', array('name', 'type', 'filename','module','weight'));
        $result = $query->execute();

        // Array to contain items for the block to render.

        $rows = array();

        // Iterate over the resultset.
        foreach ($result as $node) {
          $rows[] = array(
            'name' => t($node->name),
            'type' => t($node->type),
            'filename' => t($node->filename),
            'module' => t($node->filename),
          );
        }

        // Table header.
        $header = array(
          'name' => t('Name'),
          'type'     => t('Type'),
          'filename'    => t('Filename'),
          'module'    => t('Module'),
        );

        $block['content'] = theme('table', array(
          'header'  => $header,
          'rows'    => $rows,
          'id'      => 'table-articles',
          'class'   => 'articles',)
        );

        $block['content'] .= theme('pager').'<br>mmm<br>';
      }

      return $block;
  }
}

/**
 * Implements hook_menu().
 */
function current_posts_menu() {
  $items = array();

  $items['admin/config/content/current_posts'] = array(
    'title' => 'Current Registry',
    'description' => 'Configuration for Current posts module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('current_posts_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: Current posts settings
 *
 * @see current_posts_menu()
 */
function current_posts_form($form, &$form_state) {
  $form['current_posts_max'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum number of posts'),
    '#default_value' => variable_get('current_posts_max', 3),
    '#size' => 2,
    '#maxlength' => 2,
    '#description' => t('The maximum number of links to display in the block.'),
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

```

# Answer
I think I know what is going on. I've had this problem several times before.

The issue is that on some pages, multiple pagers may be in use. Which would explain why theme('pager'); wouldn't work.

I just had the same problem, and I got it working by doing this:

```
theme('pager', array('element' => 1));

```

On my end, I wasn't displaying multiple pagers, but I think something else on the page must have been doing this, because the above code made it work! I hope this helps anyone else who encounters the same problem.
> 1 votes

# Answer
I have just solved this myself. What a head-banger this one was.

Just try replacing:

```
$query = $query->extend('PagerDefault')->extend('TableSort');

```

with:

```
$query = $query->extend('PagerDefault')->element(0)->extend('TableSort');

```
> 1 votes

# Answer
After the code `$result = $query->execute();` try adding the following code for initializing a pager for `theme('pager')`.

```
pager_default_initialize($total,5);

```

`$total -> total` result count and argument '5' means 5 results should show in each page.
> 0 votes

# Answer
I'm assuming this is still some kind of bug in Views, but the pager tends to fail when trying to create an HTML template for it. In most cases your could manage with CSS.
> 0 votes

# Answer
The ‘-\>extend(‘PagerDefault’) extension in the query had to be the first function in the daisy chain. If not there is no error but the function seems to not be called.And one more thing, fields('table',array('id','name','created','uid')) check you mention fields properly,This is working for me.

$query = db\_select('address\_book', 'n') -\>extend('PagerDefault') //Pager Extender -\>fields('n', array('address\_id')) -\>condition('status', 1) -\>orderBy('created', 'DESC') -\>limit(10);

see this link https://stackoverflow.com/questions/9614549/drupal-7-themepager-table-gets-rendered-but-without-pager
> 0 votes

---
Tags: 7, paging
---


# Question
Title: How to display 'Terms and conditions' before starting a download, possibly using Rules?
We have a page displaying various download options. When the user clicks one of the options we would like to display a terms and condition page and then take the user further to the actual download page.

There is only one terms and conditions but multiple download pages.

I looked at the Legal module. But this seems to be for users who register and users don't need to register for download.

I also looked at Rules module. But this is for recurring events. But it is not a *recurring* event but an *on click* event.

Has anybody got an idea which strategy would be helpful here?

**Note**: terms and conditions are the same for every option.

# Answer
It should be possible to implement a procedure that fits your requirement, using a combination of the Rules and Flag modules. Here is how you could do so:

1. Create a Flag (using the Flag module), related to your "terms and conditions" page (=TOC). The actual perpose of your flag is to have the user "flag" the TOC-page to confirm something like "I agree to the terms and conditions".
2. For any of the relevant download pages, try to have a path for each of them that starts with something like `downloads/`. It can be any path you like, just make sure it's something that uniquely indicates "this is one of the download pages for which we want to make sure the user agreed to the TOC as on the TOC-page".
3. When the user then requests the download page to be viewed (opened), add a rule that is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work for this case also:

* Change `node` to `downloads` (as in my assumptions above in "2.").
    * Add a Rules '*Condition*' like "If this user did NOT flag the TOC-page yet".
    * Change the "Message" (in the Rules '*Action*'- to something to indicate that the user must first "accept the TOC" (by flagging the TOC-page, as in "1.".
    * Add an extra Rules '*Action*' to issue a redirect from the selected download page to ... you guessed it ... the TOC-page!

Haven't experimented/tried creating this Rule (= variation of the rule in the answer I mentioned above), but pretty sure it'll work. Hopefully you'll be able to complete the rest of the puzzle in my answer on your own (if not let me know where you get stuck and I might enhance my answer for it also).
> 1 votes

---
Tags: rules, files
---


# Question
Title: Show a default value when user doesn't fill in a field
I would like to show a default value if the user doesn't fill in a field in the user profile.

For example:

I have a Hair type field. If the user fills it in, i would like the following output:

**Hair type: long.**

It is already working. If the user doesn't fill in the field, i would like the following output:

**Hair type: Not specified.**

I use Display Suite to display the user profile. I don't want to set a default value to the field, because i just want to show the Not specified value on the user profile page.

Which contrib modules or hooks can i use to solve this problem?

# Answer
You can use hook\_node\_view\_alter to alter the build array. This is a render array so this should be an easy way to update the data.
> 1 votes

# Answer
To add default value to User Profile field. Go to admin/config/people/account settings/manage fields and edit that particular field. When you on the edit form of that field, there is a field to set `Default Value`. You can add any default value that you want in that field.
> 1 votes

# Answer
Here is a method that does it with Display Suite.

Install modules: Entity, Display Suite UI, Display Suite Format

Go to Manage Display page for 'Account' where you already have Display Suite active.

Create a Custom Field of type 'code field'. Select 'User' in Entities section, and in Field code box make sure Display Suite Code is the text format, and add this:

```
<?php
$entity_user = entity_metadata_wrapper('user', $entity);
$set = FALSE;
if (!$entity_user->field_hair_type->value()) {
  $entity_user->field_hair_type->set('Not specified');
  $set= TRUE;
}
print render(field_view_field(
  'user', $entity, 'field_hair_type')
);
// set it back to empty, just in case someone calls save on it which is highly unlikely
if ($set) $entity_user->field_hair_type->set('');
?>

```

Your field name will be different so just sort that out.

And lastly just drag your field into the layout area of display suite where you want it displayed. Leave the original field to not display.
> 0 votes

# Answer
Sorry, this sentence doesn't make sense to me: "I use Display Suite to display the user profile. I don't want to set a default value to the field, because i just want to show the Not specified value on the user profile page."

I think Krishna Mohan answered your question.
> 0 votes

# Answer
You can easily do this using Rules module. In user accounts I create a field and I called it `field_hair_type` of type `text`.The Event, condition and action are as follow:

# Event

The Event must be `After updating an existing user account`

# Condition

The condition must be `Data value is empty`. Now using *Data Selector* select the `hair type` field, as follow

# Action

The action must be `Set a data value`, again same as **condition** section select the `hair type` field in *Data Selector* and after saving and set the value to `Not Specified.` as follow

**Now it is done**
> 0 votes

---
Tags: 7, entities, users, display-suite
---


# Question
Title: Taxonomy tags are not saved - Field API - Drupal 7
I am creating a new content type and I want to add a *Tags* field. I created a vocabulary and a taxonomy\_term\_reference, field but this field is giving this notice every time I try to add content and click save:

> Notice: Undefined index: `tid` in `taxonomy_field_is_empty()` (line 1562 of /var/www/html/drupal/modules/taxonomy/taxonomy.module).

This is the code I am using.

### news.install

```
function news_install() {
  node_types_rebuild();
  $types = node_type_get_types();
  // Add the body field to the node type
  node_add_body_field($types['news']);

  // Load the instance definition for our content type's body
  $body_instance = field_info_instance('node', 'body', 'news');
  // Configure the body field
  $body_instance['type'] = 'text_summary_or_trimmed';
  // Save our changes to the body field instance.
  field_update_instance($body_instance);
  // Create all the fields we are adding to our content type.
  foreach (_news_installed_fields() as $field) {
    field_create_field($field);
  }

  // Create all the instances for our fields.
  foreach (_news_installed_instances() as $instance) {
    $instance['entity_type'] = 'node';
    $instance['bundle'] = 'news';
    $instance['required'] = True;
    field_create_instance($instance);
  }

  // Create vocabulary for tags
  $news_tags_vocab = (object) array(
    'name' => 'Tags vocabulary',
    'description' => 'This vocabulary is used for the tags field',
    'machine_name' => 'news_tags_vocab',
    );

  taxonomy_vocabulary_save($news_tags_vocab);
}

function _news_installed_fields() {
  $t = get_t();
  return array(
    'news_title' => array(
      'field_name' => 'news_title',
      'label' => $t('Title'),
      'type' => 'text',
      ),
    'news_image' => array(
      'field_name' => 'news_image',
      'label' => $t('Image'),
      'type' => 'image',
    ),
    'news_tags' => array(
      'field_name' => 'news_tags',
      'label' => $t('Add Tags'),
      'type' => 'taxonomy_term_reference',
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => 'news_tags_vocab',
            'parent' => 0,
            ),
          ),
        ),
      ),
    ),
  );
}

/**
 * Return a structured array defining the field instances associated with this content type.
 */
function _news_installed_instances() {
  $t = get_t();
  return array(
    'news_title' => array(
      'field_name' => 'news_title',
      'type' => 'text',
      'label' => $t('The heading of the news topic'),
      'widget' => array(
        'type' => 'text_textfield',
      ),
      'display' => array(
        'news_display_option' => array(
          'label' => $t('The heading of the news topic (display option)'),
          'type' => 'text',
          ),
        ),
      ),
      'news_image' => array(
        'field_name' => 'news_image',
        'type' => 'image',
        'label' => $t('Add Image'),
      ),
      'news_tags' => array(
        'field_name' => 'news_tags',
        'type' => 'taxonomy_term_reference',
        'label' => $t('Add Tags'),
        'widget' => array(
          'type' => 'taxonomy_autocomplete'
        ),
        'display' => array(
          'default' => array('type' => 'hidden'),
          'teaser' => array('type' => 'hidden')
        ),
      ),
    )
  );
}

/**
 * Implements hook_uninstall().
 */
function news_uninstall() {
  // Delete the taxonomy with its terms
  $vocab = taxonomy_vocabulary_machine_name_load('news_tags_vocab');
  taxonomy_vocabulary_delete($vocab->vid);

  // Gather all the example content that might have been created while this
  // module was enabled.
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(':type' => 'news'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }

  // Delete all the nodes at once
  node_delete_multiple($nids);
  // Loop over each of the fields defined by this module and delete
  // all instances of the field, their data, and the field itself.
  foreach (array_keys(_news_installed_fields()) as $field) {
    field_delete_field($field);
  }
  // Loop over any remaining field instances attached to the news
  // content type (such as the body field) and delete them individually.
  $instances = field_info_instances('node', 'news');
  foreach ($instances as $instance_name => $instance) {
    field_delete_instance($instance);
  }
  // Delete our content type
  node_type_delete('news');
  // Purge all field infromation
  field_purge_batch(1000);
}

```

What's wrong in my code, and how can I fix it?

# Answer
The solution for this problem is to implement `Hook_form()` So, the following code must be added into `news.module` file.

```
function news_form($node, $form_state){
  return node_content_form($node, $form_state);
}

```

Tricky but easy :)
> 1 votes

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


# Question
Title: Delete button not working in Checkout page
* I created a Rule on event 'After adding to cart' to action 'Page redirect' to redirect straight to Checkout page (at /checkout) so it skips the Cart page.
* The cart page by default has the Line Item: Delete button and its title is 'Remove' and it works.
* I decided I wanted same in the Checkout page and it is easy to add, just edit the view and add the 'Line Item: Delete button'.
* But it does not work. Also for some reason its title is 'Delete', not 'Remove'.
* When clicking Delete it refreshes the page giving errors 'There are errors on the page. Please correct them and resubmit the form.' under 'Shopping cart contents' and another error under 'Billing information' which simply says to fill in the form details:

> ```
> Address field is required.
> Postal code field is required.
> City field is required.
> Full name field is required.
>
> ```

Which makes no sense, I'm just trying to update the cart contents inside the checkout page.

Even better. If I do fill the forms and click to delete the product from cart, it redirects straight to Review page. But I didn't even click the 'Continue to next step' button.

?

# Answer
> 1 votes
Have never done something of that sort but what I assume is, once you move ahead with checkout, a order is created with status IN CHECKOUT or something like that.

So until a product is there in cart, you can remove that & but once you enter into checkout & order id with other details is created...product can't be removed. Maybe someone from Drupal Commerce maintainer can confirm more on this..

---
Tags: 7, views, commerce
---


# Question
Title: Error message - Trying to get property of non-object
i'm getting a notice

> Error message - Trying to get property of non-object

here's my function:

```
<?php
function func()
{
        $node = menu_get_object();
        global $user;
        if ($node->type == 'hall' &&
            in_array('instructor', array_values($user->roles)))
        {
            return " hall-instructor ";
        }
}
?>

```

# Answer
You need to check what `node_get_object()` returns since it could not return an object. This is particularly true when the user is not watching a node page, but even in the case the viewed page is a node one, the function could not return an object. This is why Drupal code always check the returned value.

```
function book_page_alter(&$page) {
  if (($node = menu_get_object()) && !empty($node->book['bid'])) {
    $active_menus = menu_get_active_menu_names();
    $active_menus[] = $node->book['menu_name'];
    menu_set_active_menu_names($active_menus);
  }
}

```

```
// template_preprocess_page()
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

```

```
// template_preprocess_html()
// If on an individual node page, add the node type to body classes.
if ($node = menu_get_object()) {
  $variables['classes_array'][] = drupal_html_class('node-type-' . $node->type);
}

```
> 1 votes

# Answer
You are not preparing node object & trying to access that. Your are using menu\_get\_object(), which returns node ID only. So something like this should work -

```
<?php
function func()
{
     $nid = menu_get_object();
     $node = node_load($nid);
     global $user;
     if ($node->type == 'hall' && in_array('instructor', array_values($user->roles))) {
         return " hall-instructor ";
     }
}
?>

```
> 0 votes

---
Tags: nodes, routes, users
---


# Question
Title: drush sql-sync error: [mysqldump: command not found]
I have a production server set up in my drush aliases as @prod, and a UAT server set up as @uat. I am using MySQL as the database of my Drupal sites. I can successfully execute drush command like `drush rsync @prod @uat`. However, when I execute

```
drush sql-sync @uat @prod

```

Error prompts:

```
bash: mysqldump: command not found

```

After googling, the solution is to set the $PATH to include `/usr/local/mysql/bin`, however, I do not have right to install MySQL client.

Here I have 2 questions:

1. Is it a must to have **mysqldump** in order to run `drush sql-sync`?
2. If so, apart from installing MySQL client, is there any other way to do it?

Thanks.

# Answer
1. Looking at the drush github repo, mysqldump appears to be a non-negotiable dependency. More broadly speaking, given it's functionality, I'm unclear why it wouldn't be. So, **yes**, drush requires mysqldump for mysql exports.
2. There's always another way, or expressed without my opinion; **"yes."** Whether it is a good practice to MacGyver such a solution depends on how much free time you have. There's an interesting php implementation of mysqldump discussed here, but here's where my caveat becomes more clear. Check out the commit activity page — not bad, but on the sparse side for a production solution for my tastes and capacity. So the answer may really depend on how much of this development your client is willing to absorb.

Personally, I'd either convince my sysadmin to allow mysqldump (something I haven't had to do in years) or move my site to a host that will provide such a basic service.

ps: I may be wrong but the Backup and Migrate may give you mysql export capability without mysqldump.
> 1 votes

---
Tags: drush
---


# Question
Title: Specify the reason for the refusal of publication node
Please tell me whether it is possible to realize the functional moderation node using the Rules and Rules Link modules.

When you click the "Decline", moderation offers fill in the "Cause"?

3 day looking for a solution, shoveled a lot of information already. Now implemented regular rulesov link "Decline" for no reason.

# Answer
> 0 votes
Looks like you were looking for the editablefields module (and some scripts to attache a link). Here is an excerpt from its project page:

> ... allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

---
Tags: rules
---


# Question
Title: Using Panels for Layout versus custom .tpl files
I'm working through some layouts that aren't entirely complex but are definitely outside of the core Drupal provides.

It really does seem like there a 20 ways to do one thing in Drupal.

Should you edit .tpl files with different regions for specific content types and nodes, or should I just stitch everything together with Panels?

I have this fear that Panels would make everything more complex and start to bog things down from a performance perspective.

# Answer
> 6 votes
# Panels module

"Learn Page manager" is an interesting / amazing set of videos. They contain various topics related to the Panels module. After you reviewed these videos, you'll understand that it'll be hard to come close to all the features that come with the Panels module.

Here is a summary of the entire set of videos about this topic (quote from the link above):

> * Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
> * The screencast series is targeted at experienced Drupal developers.
> * Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
> * Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
> * Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
> * Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
> * Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about Panels.

# Some more words about Page Manager:

* In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

> It supports the creation of new pages, and allows placing blocks within that page.
>
> Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.
>
> Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.
>
> It utilizes the core `Conditions`, `Context`, and `Blocks` APIs to accomplish this.
* In Drupal 7, Page Manager was the foundation of the Panels module.

# Bean module

When talking about layout in Drupal, one often brings up "Blocks" also. If you also use the (great) Bean module, it'll open lots of new possibilities. Here is a quote about it (from its project page):

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

Refer to my answers to the question about "How to control Block revisions before being published?" for more details about the Bean module (things you can also do, etc).

PS: The Bean module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. AND it has been integrated (already) in core in D8 (refer to this issue for more information). Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8.

# Answer
> 5 votes
I used to use panels for everything but have since switched back to tpl files - even for fields - simply so that changes to the site look and layout can be tracked in code and versioned using git. I have even stopped using regions and block all together. Any views or blocks (from modules that provide specific stuff like the profile completeness module) that I need are called in code and access checks are either in code or via view configuration.

The key is a well organized folder structure in your `/templates` folder.

If you have non developers needing to make layout changes however, then I would use panels.

# Answer
> 2 votes
I certainly resisted the Panels module for a long time. But then I bit the bullet and drank the koolaid and now I definitely will never go back.

Instead of a `templates/` directory stuffed to the hilt with overrides I usually just have one file (to remove a colon or something silly). I have a `panels/layouts` directory with one or two layouts that are a bit funky with a couple of extra classes to help the theming. And I have a bunch of features.

I think layout is one of the smaller tasks that I now rely on Panels for. More powerful are:

* the per role layout selectors,
* the visibility per pane,
* the CSS selectors per pane (making my component based CSS stretch much further)
* the super super tight Views integration.

Every now and then there is a kink in the road. But by and large it's a much (much) cleaner experience.

---
Tags: theming, panels
---


# Question
Title: How to limit flagging of articles to users with sufficient userpoints using Rules?
I am using User Points and Rules. Users earn points for publishing and commenting but are deducted points for flagging their articles for announcement on the front page (a kind of a fee). The fee per announcement is say 150 points.

Obviously, if they don't have at least 150 points, they should not be able to flag. So I need a rule that would check if the author has at least 150 points and if not - block the flagging action with an error message: `Sorry, you don't have enough`.

Yet, I just can't figure out how to set up such a rule. Any help would be highly appreciated.

# Answer
> 0 votes
Here are the headlines of a possible solution to answer this question:

# Step 1 - Create a designated role

Create a new "role" corresponding to users with (say) 150 points, assume you name the role `UsersWith150Points`.

# Step 2 - Limit access to the flag

Secure the access to the flag to users with role `UsersWith150Points`.

# Step 3 - Create some Rules logic

Any time a user gains points, use a rule to ***check if the user has at least 150 points***. If so, have the Rules module grant access to the `UsersWith150Points` role.

Similarly, if a user looses points, also use a rule to ***check if user no longer has at least 150 points***. If so, have the Rules module remove access to the `UsersWith150Points` role.

Sounds easy and pretty forward ... except ... there is no (easy) solution to have a Rules Condition to "check the current user points for a user" (unless you're willing to use custom PHP logic in your Rules Condition). However, the clue to make this rule work anyhow, is to use as a very first Rules Action "Load user points of a user". For an example rule, which is close that what you'd need, refer to "How to create rule to change user role based on points (using User Points module)?": you'd only have to add a Rules Action to grant or remove some role (and adapt the user points threshold to your '150').

---
Tags: users, rules, flags, userpoints
---


# Question
Title: Help with rules - remove shipping option if coupon applied
I am in a situation where if a coupon code is applied to an order I'd like it to remove a free shipping option, if no coupon is applied then the allow the free shipping option.

I have a rule setup which has a condition to check if shipping address is in UK. I'd like to disable this rule if a coupon code 10off is added to the order but not sure how, any help would be greatly appreciated!

Many Thanks Max

# Answer
Check for shipping address and coupon code application in the same rule.
events: "After updating an existing commerce order".
conditions: your conditions
actions:
Condition IF -\> "Coupon code for a particular discount has been added to the order"(Select your 10off discount from drop down list) -\> "Remove all shipping line items from the order".
Condition ELSE -\> "Apply shipping rate to an order".

Although your business logic may require a different approach.
> 1 votes

---
Tags: commerce
---


title: Inline fields on node edit form

text:
# Question
Title: Inline fields on node edit form
I managed to get fields inline on node display, but cant find a module to help me do it on node input. I am mostly using DS, field collection and field group (field gruop has this option but only for display, not for edit.)

# Answer
> 1 votes
Display processors are not used when rendering the node form. It's a completely different process. I'm not aware of any contrib modules that will help you accomplish this. However you can write your own.

You need to start by creating a very simple custom module with just a .info, a .module and a .css file. You can find lots of tutorials online.

Then you want to write that CSS to make your particular form fields inline and attach the css to the form using `hook_form_alter`. If you named your module "hook" the code would look like this (This code goes in your hook.module file):

```
// Replace hook with name of module and yourcontenttype
// with machine name of your content type
hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'yourcontenttype_node_form') {
    $form['#attached']['css'][] = drupal_get_path('module', 'hook') . '/hook.css';
  }
}

```

After that enable the module, clear all caches and it should be including the new CSS in the admin form.

---
Tags: 7, display-suite
---


# Question
Title: Change toolbar config to latest CKEditor toolbar groups
There is a ckeditor plugin that I really want to use (Line Height), but after looking at its `.js` file I can see that it is configured to work with the ckeditor `config.toolbarGroups` concepts, which configures the toolbar like so:

```
CKEDITOR.editorConfig = function( config ) {
config.toolbarGroups = [
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
    { name: 'forms', groups: [ 'forms' ] },
    '/',
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
    { name: 'links', groups: [ 'links' ] },
    { name: 'insert', groups: [ 'insert' ] },
    '/',
    { name: 'styles', groups: [ 'styles' ] },
    { name: 'colors', groups: [ 'colors' ] },
    { name: 'tools', groups: [ 'tools' ] },
    { name: 'others', groups: [ 'others' ] },
    { name: 'about', groups: [ 'about' ] }
];
};

```

However, I use the ckeditor module, with a drupal 7 codebase, and after I install the plugin and its dependencies, the button for the lineheight plugin doesn't show up when I go to `admin/config/content/ckeditor/edit/**{text format}**`.

Is there a way to edit the **lineheight** plugin code so that it works with the **ckeditor** module?

```
editor.ui.addRichCombo( comboName, {
        label: editor.lang.lineheight.title,
        title: editor.lang.lineheight.title,
        toolbar: 'styles,' + order,
        allowedContent: style,
        requiredContent: style,
        panel: {
            css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat(   config.contentsCss ),
            multiSelect: false,
            attributes: { 'aria-label': editor.lang.lineheight.title }

```

Or, is there a way to convert the **ckeditor** module to from using the method below to using the new method above?

```
// Toolbar definition for all buttons
Drupal.settings.cke_toolbar_DrupalFull = [
['Source'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','SpellChecker',   'Scayt'],
['Undo','Redo','Find','Replace','-','SelectAll'],
  ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','Iframe'],

'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript','- ','RemoveFormat'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl','-','Language'],
['Link','Unlink','Anchor','Linkit','LinkToNode', 'LinkToMenu'],
'/',
['Format','Font','FontSize'],
['TextColor','BGColor'],
['Maximize', 'ShowBlocks'],
['DrupalBreak', 'DrupalPageBreak']

```

# Answer
> 0 votes
If you use the dev version of the wysiwygmodule, you'll be able to use the latest CKEditor ***library*** with all the fancy plugins.

---
Tags: 7, wysiwyg
---


# Question
Title: How replace city text box in shipping address with select component in drupal 7 commerce
I want to know, is there any way to change city textbox in shipping address (in Drupal commerce 7) to select component?

in normal mode, user have to write the name of city but I want to change it to select field so user can select a city between available items in select field.

Also I want to add another select field to address that contains provinces.

# Answer
> 2 votes
In drupal several module can solved your problem:

https://www.drupal.org/project/addressfield\_vn

https://www.drupal.org/project/addressfield\_cl

https://www.drupal.org/project/addressfield\_peru

https://www.drupal.org/project/addressfield\_ro

https://www.drupal.org/project/addressfield\_hu

you can choose on of them and edit for your country. for example in addressfield\_vn change country code «VN» to your country code. and add your province and city name to module. for iran address i create a module. if you want then email to me.

---
Tags: commerce, entities
---


# Question
Title: Drupal equivalent of wget (with permissions)?
I'm working on a drupal 6 module and need a way to save a static html version of a node to the server, using the user's permissions. Basically I need the equivalent of "wget -O out.htm http://mydrupalsite.org/node/1635" in drupal, that uses the activating user's permissions and login, but don't know enough about drupal to make this work without some pointers in the right direction. I've looked through the functions list and the module code for http://drupal.org/project/print, but no luck. Any help?

Thanks in advance.

EDIT: Clarification: What I'm trying to accomplish is have a sidebar link for users to use that saves a copy of the current page -exactly as apache just sent it the user- to the server. I'm trying to do this through drupal -without- using wget or any other system utility.

# Answer
Is this for your site users to have a preview a static html page or node on your site?!

* Cant you use drupal\_render at a custom menu callback URL or Rule to get the HTML generated for 1 of your pages and save it to a file in your `webroot` or `sites/all/files/SOMEDIR`
* then using `RewriteCond` in your Apache site configuration to ignore these static files so you can access them via a non-drupal URL ...
* In drupal 7 at least there is like function node\_view that lets you load a node for viewing, it respects user access rigts for visibility of stuff on the node.

There are programmatic ways to create and load a user (with assigned roles as well) in any version of Drupal. So you could tie all these bits together as:

Generate HTML fragment of node/page logic could be:

* switch to some user by UID.
* node\_load() some node owned by user NID.
* node\_view() the node contents as some user.
* drupal\_render() get the raw HTML.
* save to some filesystem location as .HTML file.
> 1 votes

# Answer
This would have HUGE security implications.

wget has no login challenge:response system like mail retrieval systems. The only way would be to embed the username and password, or a login hash, directly in the requested url, and to have Drupal authenticate the user from the parameters. This would require programming on your part to include this functionality, and would open your site to attack if you opened up programmatic access.

If you are only interested in looking at a few pages, I would suggest you log in, open the pages one by one, and 'View Source'. Use cut and past to assemble the file you need.
> 0 votes

# Answer
You actually can do this using `wget`, but it is probably more trouble than it is worth (why not just log in as the user and capture this data through the browser?)

From the `wget` man page:

```
   This example shows how to log to a server using POST and then proceed to download the desired pages, presumably only accessible to authorized users:

           # Log in to the server.  This can be done only once.
           wget --save-cookies cookies.txt \
                --post-data 'user=foo&password=bar' \
                http://server.com/auth.php

           # Now grab the page or pages we care about.
           wget --load-cookies cookies.txt \
                -p http://server.com/interesting/article.php

   If the server is using session cookies to track user authentication, the above will not work because --save-cookies will not save them (and neither will browsers) and the cookies.txt file will be empty.  In that case use
   --keep-session-cookies along with --save-cookies to force saving of session cookies.

```

So, for drupal:

```
wget --post-data 'name=xxx&pass=xxx&form_id=user_login' --save-cookies cookies.txt --keep-session-cookies http://example.com/user
wget --load-cookies cookies.txt http://example.com/interesting

```

I've tested this against a copy of D7 and it works. (By the way, the example in the man page suggests using -p on the second request; this will retrieve page assets like CSS, JS, and images. I think in most cases you don't want this, so I've excluded it from my drupal example.
> 0 votes

# Answer
If you have access to drush on the Drupal web server, you can use this `wget` command with `drush uli` to save authenticated session cookies for any Drupal user.

```
wget --save-cookies cookies.txt --keep-session-cookies \
  --post-data 'op=Log In' -O /dev/null \
  "$(drush uli)/login"

```

Now use those cookies to save the page or file that requires authentication.

```
wget --load-cookies cookies.txt \
  http://example.com/admin/reports/status

```
> 0 votes

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


# Question
Title: How to file_save_data with utf encoding?
`file_save_data` is saving files with ANSI encoding. I want `utf8`. How can I specify encoding?

# Answer
you do it with UTF8 add BOM

```
file_put_contents($File_name, "\xEF\xBB\xBF".  $content);

```
> 1 votes

---
Tags: 7, files
---


# Question
Title: Dropdown whose options are dependent on a choice made in a previous dropdown
I have two taxonomies (class type and level). I load one in drop-down (class type) and another depended on result of choice (level).

I handle lot of cases (when choice class type load level ) && (if level have data and class type load it when first load) but when I choice empty class type load default data of level :(

```
function ria_form_alter(&$form, &$form_state, $form_id) {
        $classTypeSelected = false;
        // load class type fron taxonamy
        $classTypes = Utilities::LoadTaxonamy ( 'class_type' );
        $form ['field_level'] ['und'] ['#prefix'] = '<div id="dropdown-second-replace">';
        $form ['field_level'] ['und'] ['#suffix'] = '</div>';
//dpm($form_state ['values'] ['field_class_type'] ['und'] [0] ['tid']);
        if ( isset($form_state ['values'] ['field_class_type'] ['und'] [0] ['tid'] )) {
            $classTypeSelected = $form_state ['values'] ['field_class_type'] ['und'] [0] ['tid'];
        }  else {
            $classTypeSelected = false;
        }

        $form ['field_level'] ['und'] ['#options'] = load_level ( $classTypeSelected );
        $form ['field_level'] ['und'] ['#default_value'] = isset ( $form_state ['field_level'] ['und'] ['#default_value'] [0] ) ? $form_state ['field_level'] ['und'] ['#default_value'] [0] : '';
        $form ['field_class_type'] ['und'] ['#ajax'] = array (
                'callback' => 'ajax_example_dependent_dropdown_callback',
                'wrapper' => 'dropdown-second-replace'
        );

    }

function ajax_example_dependent_dropdown_callback($form, $form_state) {
    return $form ['field_level'] ['und'];
}

function load_level($class_type) {
    $levels = array ();
    if ($class_type && $class_type != '_none') {
        $levels = Utilities::DataFromTaxonamy ( $class_type );
    }
    return $levels;
}

```

# Answer
Maybe you should consider using thee Reference field option limit module to implement what you're trying to do. Here is a quote from its project page:

> ... allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

Here is an example of how to use this module (also from its project page):

> Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
>
> With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
>
> Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.
> 1 votes

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


# Question
Title: How can I add a custom price to a cart as an attribute of product type in Drupal Commerce?
How can I add **custom price** to cart as an attribute of **product type** in Drupal Commerce?

In detail am creating a custom tshirt design UI where user have the options to design a tshirt(add image,text etc) and add to cart. I have loaded all the products in the site to the UI and user have the option to add product to cart after designing. User is charged with an extra amount for designing like adding each images to tshirt which increases the base price of tshirt. But my issue is that the products get added to cart with the base price. I have used the folowing code to add the product to cart.

```
commerce_cart_product_add_by_id($pid, $quan, $combine = TRUE, $uid);

```

When I searched and found that there is no way to add the custom price as parameter of the above function so that the altered price gets added to cart. But found another solution that it can be done by adding as an attribute of the product.

**How can I map the custom price I have created as an attribute of the product and add to cart for altering the price section?**

# Answer
Below these modules will help you with bit of customization or addons

**Commerce Product Attributes**

> This module provides some enhancements to the Drupal Commerce attribute handling.

**Commerce Product Option**

> This module allows you to add user-customizable options to the commerce "add to cart" form. You do this by defining "option sets", to which you can attach any field of your choosing. These option sets can then be added to your commerce products using entity reference, after which the fields in your option set will show up in the add to cart form.

**Commerce Pricing Attributes**

> This module provides some enhancements to the Commerce Product Option and Commerce Product Attributes handling by applying pricing rules to custom product attributes. So, you can add attributes to products that affect the final product price.
> 1 votes

# Answer
Consider using Drupal Commerce's core product pricing rules system as explained in the Product Pricing Rules documentation (on DrupalCommerce.org). This is the only supported way to make consistent line item unit price alterations that are reflected in the final order total.
> 0 votes

# Answer
Use the following functions :

```
 $line_item = commerce_product_line_item_new($product, $quantity, $order_id, $data = array(), $type);

// You can add the required additional price components here.

    //Later using the following function will create the line item with the required price.

    commerce_cart_product_add($uid, $line_item, $combine = TRUE);

```

//If you insist on changing the Base price of the products and not adding price components to Line item then you need to include Price change logic into the line item refresh hook.

Get more details on this hook : http://api.drupalcommerce.org/api/Drupal%20Commerce/sites!all!modules!commerce!modules!cart!commerce\_cart.api.php/function/hook\_commerce\_cart\_line\_item\_refresh/DC
> 0 votes

# Answer
Check the following links. May be this will be useful.

http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!line\_item!commerce\_line\_item.module/function/commerce\_line\_item\_rebase\_unit\_price/7

https://www.drupal.org/node/1719316
> 0 votes

---
Tags: 7, commerce
---


title: How to link an image with a PDF?

text:
# Question
Title: How to link an image with a PDF?
Actually, I have a content type with 2 fields, image field (multiple) which will contain some pictures and an attachment field (accept only one file) which is file of type PDF.

I have a view where I put my gallery and each picture opens in a colorbox. The PDF file (actually global pdf for all images) is only a button.

There was a change and the new requierement is: "For every image that goes up, must have its own PDF. Every image should have its own associated file."

Another requirement is, if the image is opened on a colorbox also appears a button (in the colorbox) which displays the PDF associated with the corresponding image.

Any idea??? Sorry for my bad english.

# Answer
> 0 votes
You can create and use https://www.drupal.org/project/field\_collection to have a new field containing an image field and a file field for your pdf. You set the field in unlimited. Problem is that you might have to reupload every picture manually or write an update script that does the conversion for you.

Then for the colorbox popup with your button, have a look at https://www.drupal.org/project/entity\_popup

---
Tags: 7, views, media, files, javascript
---


# Question
Title: How to approve comments from a user with previously approved comments
WordPress has a useful option for comment moderation in its Discussion Settings panel called "Before a comment appears: Comment author must have a previously approved comment".

How can one configure Drupal to approve future comments if a user has a previously approved comment in the site?

This is a follow-up from an unresolved post on Drupal.org: Auto-publish comments after that anonymous user’s previous comments have been approved \[X\] number of times

# Answer
You need to create a small custom module. In D6 you override hook\_comment:

```
function MYMODULE_comment(&$comment, $op) {
    if ($op=='insert' && !$comment['uid'] && $comment['status']==COMMENT_NOT_PUBLISHED){ //only perform on operating  insert for new comments and if the user is anonymous
        // query database for a previously approved comment by this email
       $has_published=db_result(db_query("SELECT cid FROM {comments} WHERE status=%d AND mail='%s'", COMMENT_PUBLISHED, $comment['mail']));
       if ($has_published){
          db_query("UPDATE {comments} SET status=%d WHERE cid=%d",COMMENT_PUBLISHED,$comment['cid']); //set the current comment to unpublished
          $comment['status']=COMMENT_PUBLISHED; //return with a status of not published so the user is notified that their comment is  awaiting approval
       }
    }
}

```

It should be easy to convert this to D7 using hook\_comment\_insert.

The solution was originally suggested here.
> 3 votes

# Answer
If you don't have programming skills use the Rules module.
> 4 votes

# Answer
You can use the Comment Trust module (Drupal 7 only) in order to **auto-approve** comments from **trusted** visitors.

> Comment Trust auto-approves comments by users with previously-approved comments. It rewards trusted commenters with immediate approvals, while requiring you to approve the comments by new visitors. Works for both anonymous and authenticated users.
> 1 votes

---
Tags: users, comments, workbench
---


title: submit custom form drupal 7

text:
# Question
Title: submit custom form drupal 7
I've created one custom module to display product review form on custom created block but i'm not able to submit form and also I can't see form name while I checked with inspect element. give me solution please. Here is my code for it.

```
function my_module_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'my_module_config':
      $block['subject'] = '';
      $block['content'] = my_module_form();
      break;
  }
  return $block;
}

function my_module_form($form, &$form_state) {

  $form['rating'] = array(
    '#type' => 'label',
    '#title' => t('Rating'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );

  $options = array(1 => t('1'), 2 => t('2'), 3 => t('3'),);
   $form['rating']['options'] = array(
    '#type' => 'select',
    '#title' => t('Rating'),
    '#options' => $options,
    '#description' => t('Give your rating.'),
    //'#access' => $admin,
  );

  $form['comments'] = array(
    '#type' => 'label',
    '#title' => t('Comments'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );
  $form['comments']['prod_comments'] = array(
   '#type' => 'textarea',
   '#title' => t('Comments'),
   '#cols' => 60,
   '#rows' => 5,
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit Review!'),
  );
  $form['#submit'][] = 'my_module_submit';
  return $form;
}
function my_module_submit($form, &$form_state) {
    drupal_set_message(t('The form has been submitted.'));
}

```

# Answer
> 4 votes
You wrote $block\['content'\] = my\_module\_form(); which mean you called a function which return just an array.

You need to tell drupal that i am creating a form, for this use drupal\_get\_form

```
case 'my_module_config':
  $my_module_form = drupal_get_form('my_module_form');
  $my_module_form = drupal_render($my_module_form);
  $block['subject'] = '';
  $block['content'] = $my_module_form;
  break;

```

# Answer
> 2 votes
Your mistake is here in `my_module_block_view`

instead

```
      $block['content'] = my_module_form();

```

use

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

```

and also if it is not work instead of your submit handler add it to your action submit handler with

```
  $form['actions']['submit']['#submit'][] = 'my_module_submit';

```

# Answer
> 1 votes
You don't need to add

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

```

your module ll automatically call the function

```
function my_module_submit($form, &$form_state) {
    drupal_set_message(t('The form has been submitted.'));
}

```

# Answer
> 0 votes
check out this Advanced Form Block

you can add fields according to your requirement

---
Tags: 7, forms
---


# Question
Title: Concatenate and minify css with Gulp still necessary?
I'm using Gulp as part of my theming workflow and was wondering if it was necessary to add the concatenate and minify tasks into Gulp if Drupal already does that when I check the option under Performance.

# Answer
No, it's not necessary, unless you decide there's an appreciable performance benefit by using the gulp method as well (possible but unlikely).

You'll just be minifying twice otherwise, wasted CPU cycles.
> 1 votes

---
Tags: workflows
---


# Question
Title: How to debug views_handler_field_node_revision handler?
I believe I have updated some of my modules, then the following debug message pop on the calendar page. Does anyone know what is this message and how to solve it?

> Debug:
>
> > 'Handler views\_handler\_field\_node\_revision tried to add additional\_field nid but node could not be added!'
>
> in views\_handler\_field-\>add\_additional\_fields() (line 142 of /public\_html/sites/all/modules/views/handlers/views\_handler\_field.inc).

# Answer
I had this problem when the "Content revision: Title" field on my view was set to "Link this field to the original piece of content" however it wasn't using the relationship to the content.

I set it to use the "Content revision: Content" which fixed the link and the error.

I think this error is displayed with problems regarding a node\_revision view and an error in the relationship, as Nels mentioned.
> 2 votes

# Answer
When I get this error, it's because I have a bad Relationship in the View creating a page.

For instance, I want to display the title of a referenced piece of content, but the relationship is either not setup or incorrect.

In my case, the title I want is actually referenced from a piece of content that is referenced from a field on the Entity type is displaying. I needed to add a second Relationship (using the first Relationship).

Hope that helps someone.
> 1 votes

---
Tags: views, debugging
---


# Question
Title: Want to use exposed filters to pass arguments to a view
The title explains a lot.

I have a view which shows everything of the content type and has exposed filters.(\<-main view)

Now I made another view where I used the exposed form style because I want it to act as a "search block". It shares the same filters as the main view and I want this to pass its arguments to the main one.

For example: A user is on the main page, fills in the filters, submits-\> Redirects to the main view where the filters the user filled in are now being used.

I looked for a lot of solutions but couldnt find any. Thanks in advance!

# Answer
> 1 votes
In your view on right hand side there is "Advance" toggle under that "Expose form" is there click on Exposed form in block "No" to "Yes". Now you can find that expose filter in system block. You can place that block anywhere you want you will redirect to that main view.

# Answer
> 1 votes
1. First add views using **Page** display.
2. On right side under **Advance \> Exposed Form \> Exposed Form in block \> Yes**
3. Now you can see an expose filter block is created automatically. Go to **admin \> structure \> blocks** find and place your newly created block at desired region. You can check that it will redirect to that main view.

---
Tags: views
---


# Question
Title: Modules that will allow search for external data using either Apache Solr or Elastic Search
I have data within a Teamsite application which we will be indexing within either Apache Solr or Elastic Search (have not decided yet). I plan on creating search pages within Drupal 7 that will allow the user to search against the external indexed data mentioned above and list the search within a Drupal results page.

Are there any Drupal 7 module that will allow this to done for external data using either Apache Solr or Elastic Search similar to what can be done with Drupal 7 modules that connect to Solr or Elastic Search for Drupal indexed data?

# Answer
> 1 votes
You need **Search API** with either of the plugin modules. Search API is a fantastic way to abstract out the engine from the logic. Although I've only use the Solr implementation I've spoken with several developers who have switched to Elastic.

Search API also works with Facet API (which supports the ApacheSolr module too -- the 'competitor' to Search API). https://www.drupal.org/project/facetapi

In Drupal 8 those two modules (Search API and ApacheSolr) have become one.

# Answer
> 0 votes
I found the Sarnia drupal module appears to handle external data indexed within Apache Solr so that it can be searched within Drupal but I found no such module for Elastic Search.

---
Tags: search
---


# Question
Title: How to give confirmation for deletion through link?
I have tabular format data and each row I have an edit and delete links , on clicking on the delete link it should ask for a confirmation to delete and if press delete only I need to delete. Now its asking for confirmation but not deleting any. Instead its giving me a blank page. Is it because it's submitted to the same function? It's not going to the `products_delete_confirm_submit()` on submission by the way. Or is there any workaround for this?

Here is the try :

**Menu call back:**

```
 function mailusers_menu() {
     $items['mailusers/usergroup/delete'] = array(
        'title' => 'Delete User group',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('products_delete_confirm', 3),
        'type' => MENU_CALLBACK,
        'access callback' => TRUE,
        'access arguments' => array('access admin tab'),
      );
 return $items;
}

```

**callback function**

```
function products_delete_confirm($form,$product_code) {
$form['_product'] = array(
        '#type' => 'value',
        '#value' => $product_code,);
//$form['#action'] = url("mailusers/products_delete_confirm_submit");
//      //drupal_set_message($product_code);

return confirm_form($form,t('Are you sure you want to delete '.$product_code.' Product?'),
        isset($_GET['destination']) ? $_GET['destination'] : "mailusers",t('This action cannot be undone.'),t('Delete'),t('Cancel'));

}

```

**Delete submit handler:**

```
function products_delete_confirm_submit($form, &$form_state) {
  $form_values = $form_state['values'];
  if ($form_state['values']['confirm']) {
  $param = $form_state['values']['_product'];
    drupal_set_message(t('Product ' .$param.' will get deleted.'));
    db_query('DELETE FROM {content_type_usergroup} WHERE vid = %d', $param);
    drupal_set_message(t('usergroup has been deleted.'));
    drupal_goto('mailusers');
 }
}

```

And in the table I am calling the delete link `href="mailusers/usergroup/delete/10"`

# Answer
Don't bother testing the value of confirm, the user is only given a choice to submit or go back (with cancel link).

```
function products_delete_confirm_submit($form, &$form_state) {
  $param = $form_state['values']['_product'];
  drupal_set_message(t('Product ' .$param.' will get deleted.'));
  db_query('DELETE FROM {content_type_usergroup} WHERE vid = %d', $param);
  drupal_set_message(t('usergroup has been deleted.'));
  $form_state['redirect'] = 'mailusers';
}

```

Also, your access callback is set to TRUE, which bypass all permission checking.

**Final answer**

It should be `products_delete_confirm(&$form_state, $product_code)`, see the example at https://www.drupal.org/node/751826#creating, you were messing with your form structure.
> 1 votes

---
Tags: 6, forms
---


title: Ctools multistep returning user

text:
# Question
Title: Ctools multistep returning user
I am trying to implement a multistep registration form where if the user drops off the first step I then email them a link several weeks later for them to continue to step-2

http://example.com/user/register/step-2

After step two is complete the receive an email asking them to verify the account.

How do I load the users previous data if I send them directly to step2 at a later date. My ctools multistep currently looks like this after following this guide

```
function MYMODULE_registration_ctools_wizard($step = 'step-1') {
  // Include required ctools files.
  ctools_include('wizard');
  ctools_include('object-cache');

  $form_info = array(
    // Specify unique form id for this form.
    'id' => 'multistep_registration',
    //Specify the path for this form. It is important to include space for the $step argument to be passed.
    'path' => "user/register/%step",
    // Show breadcrumb trail.
    'show trail' => TRUE,
    'show back' => FALSE,
    'show return' => FALSE,
    // Callback to use when the 'next' button is clicked.
    'next callback' => 'MYMODULE_registration_subtask_next',
    // Callback to use when entire form is completed.
    'finish callback' => 'MYMODULE_registration_subtask_finish',
    // Callback to use when user clicks final submit button.
    'return callback' => 'MYMODULE_registration_subtask_finish',
    // Callback to use when user cancels wizard.
    'cancel callback' => 'MYMODULE_registration_subtask_cancel',
    // Specify the order that the child forms will appear in, as well as their page titles.
    'order' => array(
      'step-1' => t('Step One'),
      'step-2' => t('Step Two'),
      'step-3' => t('Step Three'),
    ),
    // Define the child forms. Be sure to use the same keys here that were user in the 'order' section of this array.
    'forms' => array(
      'step-1' => array(
        'form id' => 'user_register_form'
      ),
      'step-2' => array(
        'form id' => 'MYMODULE_registration_group_info_form',
        // Be sure to load the required include file if the form callback is not defined in the .module file.
        //'include' => drupal_get_path('module', 'MYMODULE_registration') . '/MYMODULE_registration_groups_form.inc',
      ),
      'step-3' => array(
        'form id' => 'MYMODULE_registration_invite_form',
      ),
    ),
  );

  // Make cached data available within each step's $form_state array.
  $form_state['signup_object'] = MYMODULE_registration_get_page_cache('signup');

  $output = ctools_wizard_multistep_form($form_info, $step, $form_state);

  return $output;
}

function MYMODULE_registration_get_page_cache($name) {
  ctools_include('object-cache');
  $cache = ctools_object_cache_get('MYMODULE_registration', $name);
  // If the cached object doesn't exist yet, create an empty object.
  if (!$cache) {
    $cache = new stdClass();
    $cache->locked = ctools_object_cache_test('MYMODULE_registration', $name);
  }

  return $cache;
}

```

# Answer
> 0 votes
you need to save your signup object in `MYMODULE_registration_subtask_next`

like:

```
<?php
    function MYMODULE_registration_subtask_next (&$form_state) {
      MYMODULE_registration_set_page_cache('signup', $form_state['signup_object']);
    }

```

and - in `MYMODULE_registration_subtask_cancel` and `MYMODULE_registration_subtask_finish` you should clean that cache, like `MYMODULE_registration_remove_page_cache('signup');`

# Answer
> 0 votes
I would say that the guide is not complete, it provides a way to store the data but it doesn't do anything with it.

For the values in the cache to be loaded upon each request, you should put them in $form\_state\['input'\] just after loading them

```
  // Make cached data available within each step's $form_state array.
  $form_state['signup_object'] = MYMODULE_registration_get_page_cache('signup');
  // This will override values with cache if the user has not submitted something yet
  if (empty($form_state['input']) && $form_state['signup_object']) {
    $form_state['input'] = $form_state['signup_object'];
  }

```

Watch out for the PHP session expiration time (it should be over 2 weeks) as ctools uses that to retrieve cached data. You should aso add a cron that expire ctools cached data or you ctools cache will grow very big due to input by non-returning anonymous users.

---
Tags: users, chaos-tool-suite, forms
---


title: Inline Entity Form Order by field value

text:
# Question
Title: Inline Entity Form Order by field value
I'm attempting to sort the form table generated by IEF by the value of a specific field - but running into a stumbling block (in other words - it's not working). Has anyone else used the hook\_inline\_entity\_form\_table\_alter and sorted by a field value successfully?

# Answer
I did it using hook\_form\_alter().

If you have a field with an inline entity form:

```
$form['field_newsletter_content'][LANGUAGE_NONE]['entities'];

```

Then you can change the '#weight' property on the individual entities.

So, to change the weight of element 0 to 1, do this.

```
$form['field_newsletter_content'][LANGUAGE_NONE]['entities'][0]['#weight'] = 1;

```

And if you change the weight of element 1 to 0, then they will have traded places in the inline entity form.
> 0 votes

---
Tags: forms, entities
---


# Question
Title: Custom nested element and its child sub-elements callbacks
I'm trying to create a custom element that consist of a few other elements, namely some select box and one timeperiod element.

I've set up custom `#process`, `#value_callback`, and `#element_validate` and everything works well with one exception. The #element\_validate\` of timeperiod element is run after my own elemen's callback is which means I can't effectively use the results of that field for either validation or creation some structured output.

As far as I know it's a normal drupal7 behaviour, callbacks on forms are supposed to be run top-\>down. That said, however, I still need some after-submit callback on higher-level element that can access already final results of all of its children elements.

---

I'd also love to know why has top-down approach been chosen. Because no matter how much I think about it it's just completely non-sensical.

---

Specific example:

```
function TST_element_info() {
  return array(
    'station_channel' => array(
      '#input' => TRUE,
      '#tree' => TRUE,
      '#process' => array('TST_element_process'),
      '#value_callback' => 'TST_value_callback',
      '#element_validate' => array('TST_element_validate'),
    ),
  );
}

function TST_element_process($element, &$form_state, $form) {
  global $user;
  $opts = array(/* magic */);
  $element['Sel'] = array(
    '#type' => 'select',
    '#options' => $opts,
    '#empty_option' => t('Tsss'),
    '#empty_value' => 'default',
  );

  ...

  $element['Per'] = array(
    '#type' => 'timeperiod_select',
    '#title' => t('Tsss:'),
    '#required' => true,
     '#units' => array(
       '86400' => array('max' => 365, 'step size' => 1),
       '3600' => array('max' => 23, 'step size' => 1),
       '60' => array('max' => 55, 'step size' => 5),
     ),
  );
  return $element;
}

function station_channel_value_callback($element, $input = FALSE, &$form_state) {

  if (empty($input) || $input == 'default') {

    if(isset($element['#default_value'])) {

     /*magic*/

    } else {

      return false;

    }

  } else {

    $Sel =  $input['Sel'];
    $Per = $input['Per'];

  }

  return array(
    //I'd need need to return something like (or I could do it in validate):
    //But can't do it here because $input['Per'] contains raw input from its three textfields instead of computed timestamp (and even if I altered the module to do the computation in its #value_callback it would still not help because their callback is run after mine).

    'path' => "weirdStuff/$Sel/period/$Per/json"

     //Therefore I have to return:
    'Per' => $Per,
    'Sel' => $Sel,

  );
}

function TST_element_validate(&$element, &$form_state) {

  // Magic validation

  $Sel = $element['#value']['Sel'];
  $Per = $element['#value']['Per'];

  $validated_input_array = array(
     //Again, I'd need to do this but can't because timeperiod's element_validate is run after mine which means their $element['#value']['Per'] still contains raw data.
     'path' => "weirdStuff/$Sel/period/$Per/json"
  );
  form_set_value($element, $validated_input_array, $form_state);

}

//It's perfectly ok in form_submit, the form_state['#values'] contains computed (timestamp) data for the period field. But that is kinda too late for my own element.

```

---

PS: Consider this example but with one of the sub-elements that are used for connection string connection being a bit more complex one that computes its true value in #element\_validate.

# Answer
> 2 votes
The whole workflow of form API is shown here  (source: https://www.drupal.org/node/165104).

You can notice that `#process` is top-bottom whereas `#after_build` is bottom-top, and `#element_validate` is a whole another step and bottom-top. You can also see that `#value_callback` is called quite early (even before #process).

Thus, and by experience, your `#value_callback` should not be more than 15 lines long, and in the case of a nested element, always take form\_type\_checkboxes\_value or form\_type\_radios\_value as examples: they only care about edge cases and rarely modify values.

This said, another input to take into consideration is the timeperiod module, because your way of handling will depend entirely of this module. (source: http://cgit.drupalcode.org/timeperiod/tree/timeperiod.module)

```
/**
 * Implements hook_element_info().
 */
function timeperiod_element_info() {
  // A duration form element which represents the duration in seconds.
  $types['timeperiod_select'] = array(
    '#input' => TRUE,
    '#tree' => TRUE,
    '#default_value' => 0,
    '#value_callback' => 'timeperiod_element_value',
    '#process' => array('timeperiod_element_process', 'ajax_process_form'),
    '#after_build' => array('timeperiod_element_after_build'),
    '#pre_render' => array('form_pre_render_conditional_form_element'),
    // Controls the available units. Array keys are the units, see
    // timeperiod_element_units(). The values control the number of available
    // values per unit, taking steps in the configured size starting from 0.
    '#units' => array(
      '3600' => array('max' => 23, 'step size' => 1),
      '60' => array('max' => 55, 'step size' => 5),
    ),
  );
  return $types;
}

```
* `timeperiod_element_value()` does literally nothing (see its comment)
* `timeperiod_element_process()` breaks down into units and sets up sub-elements
* `timeperiod_element_after_build()` actually sets the value

So based on these informations, you also need to implement `#after_build`, which is bottom-up, so it will run after timeperiod, and set the value using `form_set_value()`

Remember that validation is only for validation, and will always have processed values as input.

# Answer
> 0 votes
In your function `TST_element_valdate`, to get the value of your timeperiod element, instead of `$Per = $element['#value']['Per'];` try either `$Per = $element['Per']['#value'];` or `$Per = $form_state['values'][$element['#name']]['Per'];` to see if you can get what you need.

---
Tags: 7, forms
---


# Question
Title: Unable to implement photo slider in theme template
I downloaded a theme from here and I chose this theme because I wanted to builder a slider photo gallery as shown in the screen shot here.

However, I am unable to achieve the desired effect because I am new at Drupal 7.

I have tried the following steps for implementing the photo gallery. Please help me out by pointing my mistake.

1- Identify block regions. These are as follows:

2- Make a content type with Image type as the field as follows:

3- Then I placed it inside the Slide show block provided by the template as shown in the figure.

4- I even made a view and placed it inside the same Slide show block provided by the template but I am not getting the slider that I want.The previous screen shot shows the view as well.

At best, I get a picture on the front page when I choose it as 'published to front page'.

So, does this mean I cannot implement a photo slider this way? And my only option then is to use a contributed module for a photo slider?

If the latter is true then what use is the template other than a basic mark up for html and css?

Lastly, **is the solution to my problem that I use a contributed photo slider module and then place it in one of the pre-defined blocks provided by the theme?**

Appreciate your help on this.

# Answer
What you did in your website is create a new content type that holds a static image for each entry. From what I see in the template link you posted, the theme you chose uses Nivo Slider as the default solution for a slider and even has an installation instructions link (which is not working).

My advice would be to follow the instruction on this link: Nivo Slider Module, and install the module yourself. It will create a new content type for you to make the slider you need.
> 0 votes

---
Tags: views, theming
---


title: Aggregating Views and conditional field

text:
# Question
Title: Aggregating Views and conditional field
I have created a **views** for label printing;

1st item in the row is **name**,

2nd item in the row is **address**,

3rd row is **city**,

4th row is **state**,

5th row is **Country**.

All of them are fields of type contact.

Now I want two things;

1. If country is **India**, then it should not be displayed.
2. If two records has same **Address** & **city** & **State** & **Country** they should be aggregated.

# Answer
> 1 votes
Using Views Conditional Module you can set conditions for fields . The other module which may become useful is Views Field View.

Here are some description about Views Conditional Module :

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> * Equal To
> * Not Equal To
> * Greater Than
> * Less Than
> * Empty
> * Not Empty
>
> Views conditional allows you to output text based on the result of the condition.

# Answer
> 0 votes
The module I use for aggregation is Views Aggregator Plus and it offers functions that run after the SQL query, altering the results with PHP. It's a lightweight and easy to use method.

---
Tags: views
---


# Question
Title: Drupal 7 - div popup inside the overlay (node/123/edit)
I'm trying to display a pop up dialog (using a hidden block) inside the overlay when editing a node.

When i click to edit a node, the overlay appears with all the custom fields of a given content type as usual. It is clean and white and everything in the background is darkened out.

So now i have logic in place (using jQUery) that's supposed to change my div's display to 'show' on keyup for a specific field on top of the overlay edit node.

I've tried adding a z-index of over 1000 and still nothing. The drupal overlay is using a z-index of 501 but my custom div still wont display on top of/over it.

**This is my CSS for the hidden block:**

```
#block-block-block-26 {
  z-index: 2000 !important;
  position: fixed;
  display: none;
  text-align: center;
  border: 1px solid #333;
  width: 200px;
  height: 80px;
  border-radius: 5px;
  padding: 10px;
}

```

**This is my function inside jQuery:**

```
 $('#edit-field-pi-estimated-ini-capital-und-0-value').keyup(function() {
        var txtVal = this.value;
        if(txtVal == 0 && txtVal != '') {
          $('#block-block-block-26').show();
          return false;
        }
  });

```

any idea how to make my div appear over the overlay?

Thanks

# Answer
> 0 votes
The code is fine, problem was with jquery version.

---
Tags: 7, modal-dialogs
---


title: Callbacks order in Drupal 7

text:
# Question
Title: Callbacks order in Drupal 7
I have 2 modules (filters): `html_pre_filter` and `syntaxhighlighter`.

`syntaxhighlighter_prepare_callback` executes before `html_pre_filter_prepare_callback`.

How to reoder them?

I tried this

```
function html_pre_filter_module_implements_alter(&$implementations, $hook)
{
    if($hook == 'filter_prepare')
    {
    $group = $implementations ['syntaxhighlighter'];
    unset($implementations ['syntaxhighlighter']);
    $implementations ['syntaxhighlighter'] = $group;
    }
}

```

but it doesn't work

# Answer
> 2 votes
The code you are trying doesn't work because `syntaxhighlighter_prepare_callback()` and `html_pre_filter_prepare_callback()` are not hooks: They are simply callback functions defined in the implementation of `hook_filter_info()` done from those modules.

In fact, the code used by `check_markup()` to invoke the input format filters is the following one.

```
  // Get a complete list of filters, ordered properly.
  $filters = filter_list_format($format->format);
  $filter_info = filter_get_filters();

  // Give filters the chance to escape HTML-like data such as code or formulas.
  foreach ($filters as $name => $filter) {
    if ($filter->status && isset($filter_info [$name]['prepare callback']) && function_exists($filter_info [$name]['prepare callback'])) {
      $function = $filter_info [$name]['prepare callback'];
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
    }
  }

  // Perform filtering.
  foreach ($filters as $name => $filter) {
    if ($filter->status && isset($filter_info [$name]['process callback']) && function_exists($filter_info [$name]['process callback'])) {
      $function = $filter_info [$name]['process callback'];
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
    }
  }

```

No hook is invoked, or you would see a call to `module_invoke()` or similar function.

If you are looking at a way to programmatically re-order filters used by input formats, the only way I can see is altering the cache where Drupal stores the information about the input filters. See `filter_list_format()`, which is the function that returns an ordered list of filters used by an input format.
More easily, this can be accomplished from the user interface, since on admin/config/content/formats you order the input filter for each input format.

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


# Question
Title: Showing only certain product attributed in a view rather than them all in Commerce
I am using Drupal Product Pricing, Product Options and Product attributed modules.

I have created a number of different attributes for products but my issue is that when including them in a view it just displays all of them.

This is an issue since I am using Billy Mail PDF module which uses a line item view. So when I include the attributes in the view it just displays them all. This includes an image and potentially alot of text which could be inputted by the customer.

I just need to include 1 of the product attributes but this does not seem to be possible as there is no option for this inside the fields settings in views.

# Answer
> 1 votes
I found a solution in the form of a patch here \> https://www.drupal.org/node/1696656

---
Tags: commerce
---


title: Overriding Drupal core base class

text:
# Question
Title: Overriding Drupal core base class
I need to override the block configuration form in Drupal 8.

To override the configuration form for a new block we are creating can be done by implementing BlockBase::buildConfigurationForm method.

But I need to alter the configuration form for all the blocks which means overriding the `BlockBase` class. How can I implement this?

Is there a generic way to override all `Drupal Core classes`?

# Answer
No, you can't change the base class. This is a PHP language construct, it's not possible to override it.

I'm not exactly sure what you are trying to do but it is likely that what you are looking for is a plain old `hook_form_alter()` \+ third party settings on the block config entity.

The Block class D8 sandbox is a simple module that is doing exactly this and allows to configurabe custom CSS classes for every block.

Note that this is on a different level, you are altering the block config entity and it will only apply to how Drupal core/block.module uses block plugins but not e.g. page\_manager. Doing it in a more generic way is simply not possible.
> 4 votes

# Answer
Use hook\_entity\_info\_alter (from memory) and change the form class for the block entity

See entity.api.php for examples
> 1 votes

---
Tags: forms, blocks, 8
---


title: Disable caching for custom entity

text:
# Question
Title: Disable caching for custom entity
I have set up access to some custom data by creating ContentEntity classes in my module, so I can query and display that data through Drupal entities. However, that data is also updated by a non-Drupal service, that changes some columns in the database directly. After the data is changed by that service I have to use "Clear all caches" in order to see any changes in Drupal.

**How can I stop Drupal 8 from caching an entity type at all - so it always queries the fields fresh from the database?**

I have tried annotating my Entity class with

```
render_cache = FALSE,
field_cache = FALSE

```

as these are the cache related options listed in the documentation (*Structure of an Entity annotation*) and suggested in How to avoid caching of fields in Entity View? However, this didn't have any noticeable effect in my scenario.

# Answer
> 3 votes
The flag you are looking for is `persistent_cache`, field\_cache is no longer used, that documentation is a bit out of date. You're welcome to update it :)

See the API documentation of the EntityType class for a up to date list, maybe that documentation page should just link to that instead of trying to maintain a duplicate list.

That said, unless you have almost as many or more writes/changes to your entity type as loads, I'd considering changing your architecture and either update the entity type through the API or invalidate the changed entities. But there can be cases where that doesn't make sense, e.g. because of mass updates and if those entities aren't very frequently. But for example displaying them in views can be quite slow if they need to be loaded all the time.

Also, speaking of views, while render\_cache disables the caching of viewing an entity, I don't think it disables views row-level caching. Maybe it should, you should consider opening a core issue for that if you need that, otherwise your rows will still return cached output even if the entity is changed.

---
Tags: entities, caching, 8
---


# Question
Title: How can I evaluate the security of a contrib module?
Are there security standards for each stage of a module on Drupal.org?

> Create sandbox project \> full project with dev version only \> official release

What is the process for the security of contrib modules? Do audits happen?

Historically, I have functionality rather than security on my mind when selecting a contrib module. Partly because I don't know how to *easily* evaluate security (that is, without studying the entire code). How can I evaluate how secure a contrib module is?

# Answer
Currently there is no correlation between project status and presumed security of code. From The Security Team Handbook page

> in general the team does not review core nor contributed code

The Drupal security team works to resolve vulnerabilities that others find. Any review that happens to sandbox modules would be part of normal project review (no guarantees). When code is explicitly reviewed for security, it is most likely because someone was hired to review it.

In general, you can use the Writing Secure Code guide as a starting point. Also checkout presentations from Cons and Camps.
> 1 votes

---
Tags: 7, security
---


# Question
Title: Most maintainable way to make page with one top half and alternative bottom halves selected by tabs?
I want to make a page which has one top part, a row of two or more horizontal tabs beneath it, and alternative bottom parts which appear beneath that and can be selected by clicking on the tabs.

For example, imagine a page that someone might write about their cat. The top half is a photo of the cat and some text. At the moment, it's static, but I might later add a Twitter feed. Under it are tabs labelled "Poem", "Photo", and "Blog". The bottom half that gets selected when the user clicks on "Poem" is a poem, static HTML. That which gets selected when clicking on "Photos" is also static HTML, another image. And that which gets selected when clicking on "Blog" is dynamic: a blogroll implemented as a View.

Just to make sure that’s unambiguous, there are pictures of the top half and the three bottom halves at http: //www.j-paine.org/dobbs/kitty\_page\_top\_264.gif, http: //www.j-paine.org/dobbs/kitty\_page\_poem\_257.gif, http: //www.j-paine.org/dobbs/kitty\_page\_photo\_296.gif, and http: //www.j-paine.org/dobbs/kitty\_page\_blog\_279.gif. Apologies for the deformed HTML, but this thing only lets me post two links.

I’ve found quite a lot of methods that on first sight, may do what I want. These include the modules Quick Tabs and Node Tab, as well as the trick with views menus that Ron Golan describes in "Views Menu Tabs Quick Guide" (see https://www.urbaninsight.com/2013/11/01/views-menu-tabs-quick-guide). There are also assorted PHP code hacks. But I can't find recommendations about which solution is best for reliability and maintainability. It does appear that some of the techniques were written for older versions of Drupal, and may have been superseded.

One thing is that unskilled site administrators should easily be able to find all the content (tops, tabbed menus, and alternative bottoms). That might rule out of some of the modules: I can’t find the reference again, but at least one of them is said to implement its own special interface for keeping track of tabbed content rather than extending the standard Drupal interface.

This problem raised another question. How should I think about Drupal when working out how to do this? It’s well known that programming needs three key concepts, used both in describing control and describing data: sequencing, alternation, and repetition. If I were programming the problem in Pascal, I would represent the page as a record. The first field would represent the top half of my page; the second would represent the bottom halves. Because these require alternation, I’d represent them as a discriminated union. I’d also need some pragmatic information saying that the union is to be displayed using tabs and giving the tabs’ labels.

Now, it’s clear that some of the built-in Drupal menus implement that kind of alternation. I get the impression, actually, that they’re more important than the content itself, because users on various discussion groups have wondered why they couldn’t see their content, then been told by an expert that this was because it’s not attached to a menu. But I don’t think the Drupal documentation says this anywhere. A formal semantics of Drupal would be good, but I can’t find one. So when designing a structure like my page with one top and multiple bottoms, where should I start? What’s the equivalent of C.A.R. Hoare's famous essay "Notes on Data Structuring" that every computer scientist will know from the classic *Structured Programming*?

# Answer
> 1 votes
Looks like you need to look at some of the typical "page layout" modules, such as these ones (excerpts from their project pages):

* Display Suite.

> ... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
* Panels.

> ... allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Not sure if *Display Suite* will be sufficient for all your needs, but *Panels* will pretty sure be helpfull. Possibly also with 'mini-panels' added to that.

Be prepared however to invest some time in learning about these amazing modules. A great resource for learning about Panels is the (free) video training about Learn Page manager. *Panels* uses 'Page manager', which is one of the sub-modules of Chaos tool suite (ctools)).

---
Tags: views, routes
---


# Question
Title: How do I enable a custom JS file in my Drupal site?
In my Drupal themes' folder I've created a file named "**custom-js.js**".

I created this file to use 2 jQuery manipulations on a small text block that appears in all pages of the site.

My question is, how do I enable this JS file? How do I "*link it*" with Drupal, so that it's actually being used in my site?

# Answer
There are several ways to add JS files to Drupal, depending on the requirements.

If the JS is related to your theme and used on every page, perhaps easiest to add the file to your theme's `.info` file

1. create the JS file in *mytheme/custom-js.js* and configure it for the theme in *mytheme.info*

scripts\[\] = js/custom-js.js
2. Flush all caches to register the new JS file.

More info: https://www.drupal.org/node/756722
> 2 votes

---
Tags: javascript, .info
---


# Question
Title: How can I prevent 'Error messages' to be shown to anonymous users?
Like any Drupal site, my site also shows red notifications from time to time...

The problem is that when these notifications are **error messages**, they appear at the bottom of the site in a new "Pseudo-reigion"... I use the term "Pseudo-region" because they establish a new "Region" under the site.

It's not really a region but rather a white area with an H1 and some text under it. It is displayed with the word "*Error*" (as a title, using a `<h1>` HTML tag), and the text below it is "*The website encountered an unexpected error. Please try again later.*". This is how it looks like in my site:

So my single aim is to not display these error messages (and this whole "Pseudo region" actually), at least for anonymous users, since it's uglyfies my site.

I've tried to use the following CSS syntax but with no success:

```
body.not-logged-in div.messages.error {display: none !important;}

```

This "error" pseudo-region is extremely problematic since it appears even in cases when I hide the notifications themselves via the "Disable messages" module.

I'm sure this error is native to Drupal but I've already tried everything I know to remove it, so any help is appreciated.

## An important note

**It's a long story why**, but disabling the errors through `/admin/config/development/logging` doesn't help in this case. I'm looking for a solution which is either CSS, a Javascript (not jQuery) tweaking of the css by the text itself, or, some change in the Drupal PHP code that will prevent to program of printing this error.

# Answer
> 0 votes
Like @Screenack suggested.

1. Navigate to /admin/config/development/logging
2. Set the radio to **None**
3. Select Save Configuration

Please note that I recommend keeping the errors on locally and trying to fix them.

---
Tags: debugging, users
---