# Question
Title: Multiple select do not save for my custom field with custom widget
I'm trying to save multiple values from multi select option form which I created in the custom widget with:

```
$element['labs'] = array(
  '#type' => 'select',
  '#options' => $list,
  '#multiple' => 'multiple',
  '#title' => t('Labs'),
);

```

The biggest problem is the values won't save! As I know the delta should increment automatically if cardinality is set to more than 1.

1) I can't change cardinality or some other setting after activating the field in the **edit field form**

2) I can't see my custom field in the **field type list** to select from if I try to alter existing widgets:

```
'default_widget' => 'options_select',
'default_formatter' => 'status_field_options',

```

How could I extend standard list field type to populate the multiselect with my own generated data?

OR

How could I write my widget that Drupal let me save multiple values with different delta?

# Answer
The values won't save when you don't have any storage to write into.

Make sure your widget implements `hook_field_schema()` and provide necessary schema for a field structure in your `.install` file. E.g.

```
/**
 * Implements hook_field_schema().
 */
function MYMODULE_field_schema($field) {
  switch ($field['type']) {
    default:
      $columns = array(
        'value' => array(
          'type' => 'text',
          'not null' => FALSE,
        ),
      );
      break;
  }
  return array(
    'columns' => $columns,
    'indexes' => array(
      'value' => array('value'),
    ),
  );
}

```

Then in `hook_field_info()` make sure you've `FIELD_BEHAVIOR_DEFAULT` for `multiple values` behavior, e.g.

```
/**
 * Implements hook_field_widget_info().
 */
function MYMODULE_field_field_widget_info() {
  return array(
    'my_widget' => array(
      'label' => t('Default'),
      'field types' => array('select'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

```

When implementing multiple field properties as part of one widget (such as address field), please check: How to override default cardinality for the field widget?

For complete example, check existing modules under `field` core module or check field\_example module (part of Examples).
> 1 votes

---
Tags: entities
---


# Question
Title: How to add to 'Secondary Local Tasks' on Order page
Can someone tell me how I can add another item on the Orders page to the existing 'Secondary Local Tasks' which is currently two buttons :- 'Apply Pricing Rules' and 'Simulate Checkout Completion'.

I am overriding page--admin--commerce--orders.tpl.php and would like to add a button to the $secondary\_local\_tasks variable but can't find where it's set. It's not a menu and isn't in template.php. Any ideas?

# Answer
Just emulate what you see in the other modules:

```
  if (module_exists('commerce_order_ui')) {
    $items['admin/commerce/orders/%commerce_order/edit/refresh'] = array(
      'title' => 'Apply pricing rules',
      'description' => 'Executes the cart order refresh used to apply all current pricing rules on the front end.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('commerce_cart_order_refresh_form', 3),
      'access callback' => 'commerce_cart_order_refresh_form_access',
      'access arguments' => array(3),
      'type' => MENU_LOCAL_ACTION,
      'file' => 'includes/commerce_cart.admin.inc',
    );
  }

```

The important thing is the `type` and the `path`.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to override default cardinality for the field widget?
I've custom widget which consist multiple input elements in `hook_field_widget_form()` as part of one field (like address field).

The problem is that Drupal complains about:

> this field cannot hold more than @count values

which happens in `field_default_validate()`, when I've multiple input filled, so it doesn't recognise that this is one single field.

I've tried to change my cardinality in every possible place as below, but without success:

```
/**
 * Implements hook_field_info().
 */
function my_address_field_field_info() {
  return [
    'my_address_field' => [
      'label' => t('My Address Field'),
      'settings' => array('cardinality' => FIELD_CARDINALITY_UNLIMITED),
      'instance_settings' => array('cardinality' => FIELD_CARDINALITY_UNLIMITED),
      'default_widget' => 'my_address_field_widget',
      'default_formatter' => 'my_address_field_default',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ],
  ];
}

/**
 * Implements hook_field_widget_info().
 */
function my_address_field_field_widget_info() {
  return [
    'my_address_field_widget' => [
      'label' => t('Default'),
      'field types' => ['my_address_field'],
      'settings' => array(
        'size' => 60,
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_NONE,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ],
  ];
}

/**
 * Implements hook_field_widget_properties_alter().
 */
function my_address_field_field_widget_properties_alter(&$widget, $context) {
  $widget['cardinality'] = FIELD_CARDINALITY_UNLIMITED;
}

/**
 * Implements hook_field_formatter_info().
 */
function my_address_field_field_formatter_info() {
  return [
    'my_address_field_default' => [
      'label' => t('Default'),
      'field types' => ['my_address_field'],
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ],
  ];
}

/**
 * Implements hook_field_widget_form().
 */
function my_address_field_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $widget = array();
  $widget['label'] = array(
    '#title' => $instance['label'],
    '#theme' => 'form_element_label',
  );
  $widget['address_line_1'] = array(
    '#type' => 'textfield',
    '#title' => t('Address line 1'),
  );
  $widget['address_line_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Address line 2'),
  );
  // more text fields here ...

  return $widget;
}

```

Including defining `hook_field_validate` which I thought it'll override default field validation handler, but this was not the case.

What's the right way of assigning unlimited cardinality for my widget?

# Answer
Since the widget form (`hook_field_widget_form`) returns multiple elements at once, by default Drupal recognise them as multiple values of one widget. To override that behaviour, you need to define your properties in `property_callbacks` hook as part of your `hook_field_info` which can return value of your property (in the format documented for your data type). See: Entity property information.

Then make sure corresponding properties have their Field API schema for a field structure by implementing `hook_field_schema` in your .install file. Also don't forget to define `hook_field_is_empty` which tell what constitutes an empty item for a field type.

Here is example code:

```
/**
 * Implements hook_field_schema().
 *
 * This should be placed in .install file.
 */
function MYMODULE_field_schema($field) {
  $column_names = array(
    'addressline1',
    'addressline2',
  );
  $columns = array();
  foreach ($column_names as $column_name) {
    $columns[$column_name] = array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
    );
  }
  return array(
    'columns' => $columns,
  );
}

/**
 * Implements hook_field_info().
 */
function MYMODULE_field_info() {
  return array(
    'MYFIELD' => array(
      'label' => t('My Field'),
      'description' => t('Provides a custom field.'),
      'settings' => array(),
      'instance_settings' => array(),
      'property_type' => 'MYFIELD',
      'property_callbacks' => array('MYMODULE_property_info_callback'),
    ),
  );
}

/**
 * Callback to alter the property info of custom field.
 */
function MYMODULE_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $name = $field['field_name'];
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];

  $property['type'] = 'MYFIELD';
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';

  unset($property['query callback']);
}

/**
 * Implements hook_field_is_empty().
 */
function MYMODULE_field_is_empty($item, $field) {

  // Check if required address components are empty.
  foreach (array('addressline1', 'addressline2') as $required_component) {
    if (empty($item[$required_component])) {
      return TRUE;
    }
  }

  return FALSE;
}

```

For complete example, check how Address Field module implements its field properties, so they work correctly with cardinality settings.

See also: How to write a property callback for a custom field
> 1 votes

# Answer
You can use Field instance cardinality module which allows the cardinality of specific instances of fields to be overridden.

> This module allows the cardinality of specific instances of fields to be overridden.
>
> This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to write a property callback for a custom field to use with the Entity module
I have a custom field with multiple values. I would like it to work with the Entity module. I need to create the correct property\_callbacks in hook\_field\_info(). My field schema looks like this:

```
'ref' => array(
  'type' => 'varchar',
  'length' => 32,
  'not null' => TRUE,
),
'title' => array(
  'type' => 'varchar',
  'length' => 255,
  'not null' => TRUE,
  'default' => '',
),
'description' => array(
  'type' => 'text',
  'not null' => TRUE,
  'size' => 'big',
),
'weight' => array(
  'type' => 'int',
  'unsigned' => TRUE,
  'not null' => TRUE,
  'default' => 0,
),
'status' => array(
  'type' => 'int',
  'unsigned' => TRUE,
  'not null' => TRUE,
  'default' => 1,
),

```

Does anyone know how to actually do this? There is very little documentation around for it.

# Answer
Kind of :) ... if its just numbers and strings you can cheat a little. I added some basic integer columns to the User table and wanted EntityAPI and views etc to be aware of them and did the following:

```
/**
 * Implementation of hook_entity_property_info(). This dpeends on the EntityAPI.
 *
 * This defines the properties/attributes/"fields" of our Entity regardless of
 * whether they are drupal Fields or custom data (in the base table).
 */
function dew_nagging_entity_property_info_alter(&$info) {
  $properties = &$info['user']['properties'];
  $properties['dew_survey_count_to_complete'] = array(
    'label' => t('Number of Surveys to Complete'),
    'type' => 'integer',
    'description' => 'When a student logs in the system derives how many surveys they must complete. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_count_to_complete',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_survey_completed_count'] = array(
    'label' => t('Number of Completed Surveys to Date'),
    'type' => 'integer',
    'description' => 'This is a count of the completed surveys completed by a student in real-time. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_completed_count',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_surveys_all_completed'] = array(
    'label' => t('Has the student completed all their Surveys?'),
    'type' => 'integer',
    'description' => 'This is a boolean indictator (0,1) of whether or not a student has completed their surveys. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_surveys_all_completed',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  return $info;
}

```

entity\_property\_verbatim\_set and \*_get just pull the field from the database if `$info['schema field']` is defined.

I also had to make the DB changes in my .install file with `db_add_field()` for each database column. I also had to notify EntityAPI of my schema changes to the user table via `hook_schema_alter()`. All these DB schema fields and EntityAPI meta data field defintions must correlate properly.

---

if its more complicated, you do something like found in Ubercart products, you're just returning the item from the given Node and Field.

See http://api.ubercart.me/api/drupal/ubercart%21uc\_order%21uc\_order.module/function/uc\_order\_uc\_order\_get\_properties/7.

### EDIT

Apparently the `entity_metadata_*` functions have been deprecated and you should call entity\_property\_verbatim\_get(), or `entity_property_verbatim_set()`.
> 5 votes

# Answer
Here is simpler example:

```
/**
 * Callback to alter the property info of custom field.
 */
function MYMODULE_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $name = $field['field_name'];
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];

  $property['type'] = 'MYFIELD';
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';

  unset($property['query callback']);
}

```

This should be called from `property_callbacks` in your `hook_field_info` and it should automatically store your values per each property.
> 0 votes

---
Tags: entities
---


# Question
Title: What are Ctools plugin (content type, access, etc), and how does one create them?
What are Ctools plugins, and how does one create them?

# Answer
Every now and then when working with Ctools Page manager, and Panels, it is useful to add custom Ctools plugins.

Ctools plugins comes in a large number of forms, and other modules, such as Feeds, Addressfield and Openlayers all make use of Ctools to provide plugins extensible by other modules. The most common forms of plugin though, are probably "content type", and "access". The first must **not** be confused with the entity "content" and its bundles, also called content types.

**First, the boilerplate**:

For any module to provide ctools plugins, they should first tell Ctools where to look for them. The hook below, says that we provide plugins for ctools, of the types "content\_types", and "access". The function could be made simpler, but this way we ensure that only the right module gets told about the plugins, as well as only having it scan the disk for files when we actually provide the type of plugin being asked for.

```
function HOOK_ctools_plugin_directory($owner, $plugin_type) {
  // We'll be nice and limit scandir() calls.
  if ($owner == 'ctools' && ($plugin_type == 'content_types' || $plugin_type == 'access')) {
    return 'plugins/' . $plugin_type;
  }
}

```

Below is an example directory structure for a module providing two plugins. One content type and one access plugin.

```
module/
module/module.info
module/module.module
module/plugins/
module/plugins/content_types/
module/plugins/content_types/two_views_in_one.inc
module/plugins/access/
module/plugins/access/term_depth.inc

```

**Content type plugin**

A content type in the Ctools vocabulary, is more often known as a "Pane", as provided by for example Views. In this question: Is there a way to intercept a list of NID's created by a view and use them as a filter for another view?, the author asks about programmatically feeding arguments to a view. While that in it self it not very hard, the follow up question quickly becomes, "How do I display the results?".

One answer, will be to create a new "content type".

Now, the actual content type plugin, again using the Views question from above, could look like this:

```
$plugin = array(
  'title' => t('Render a View with arguments from another'),
  'single' => TRUE,
  'category' => array(t('My custom category'), -9),
  // Despite having no "settings" we need this function to pass back a form, or we'll loose the context and title settings.
  'edit form' => 'module_content_type_edit_form',
  'render callback' => 'module_content_type_render',
);

function module_content_type_render($subtype, $conf, $args, $context = NULL) {
  $block = new stdClass;
  $block->title = 'My View';

  $view = views_get_view('get_nids');
  $view->preview('display_machine_name', array($arg1, $arg2));

  $nids = '';
  foreach($view->result as $node) {
    $nids += $node->nid . ',';
  }
  $nids = rtrim($nids, ',');
  $view = views_get_view('get_related');
  $view->execute_display('display_machine_name', array($nids));
  $block->content = $view->render();

  return $block;
}

/**
 * 'Edit form' callback for the content type.
 */
function module_content_type_edit_form($form, &$form_state) {
  // No settings beyond context, which has already been handled.
  return $form;
}

```

With this module enabled, there should now be a new category in Panels, 'My custom category', where in one should find a single pane, rendering the code from above.

**Access plugin**

The access plugin below will provide the ability to filer out variants and/or panes based on the depth of a term as measured from the root of the vocabulary.

```
<?php
/**
 * @file
 * Plugin to provide access control based upon a parent term.
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Taxonomy: term depth"),
  'description' => t('Control access by the depth of a term.'),
  'callback' => 'term_depth_term_depth_ctools_access_check',
  'default' => array('vid' => array(), 'depth' => 0),
  'settings form' => 'term_depth_term_depth_ctools_access_settings',
  'settings form validation' => 'term_depth_term_depth_ctools_access_settings_validate',
  'settings form submit' => 'term_depth_term_depth_ctools_access_settings_submit',
  'summary' => 'term_depth_term_depth_ctools_access_summary',
  'required context' => new ctools_context_required(t('Term'), array('taxonomy_term', 'terms')),
);

/**
 * Settings form for the 'term depth' access plugin.
 */
function term_depth_term_depth_ctools_access_settings($form, &$form_state, $conf) {
  // If no configuration was saved before, set some defaults.
  if (empty($conf)) {
    $conf = array(
      'vid' => 0,
    );
  }
  if (!isset($conf['vid'])) {
    $conf['vid'] = 0;
  }

  // Loop over each of the configured vocabularies.
  foreach (taxonomy_get_vocabularies() as $vid => $vocabulary) {
    $options[$vid] = $vocabulary->name;
  }

  $form['settings']['vid'] = array(
    '#title' => t('Vocabulary'),
    '#type' => 'select',
    '#options' => $options,
    '#description' => t('Select the vocabulary for this form. If there exists a parent term in that vocabulary, this access check will succeed.'),
    '#id' => 'ctools-select-vid',
    '#default_value' => $conf['vid'],
    '#required' => TRUE,
  );

  $form['settings']['depth'] = array(
    '#title' => t('Depth'),
    '#type' => 'textfield',
    '#description' => t('Set the required depth of the term. If the term exists at the right depth, this access check will succeed.'),
    '#default_value' => $conf['depth'],
    '#required' => TRUE,
  );

  return $form;
}

/**
 * Submit function for the access plugins settings.
 *
 * We cast all settings to numbers to ensure they can be safely handled.
 */
function term_depth_term_depth_ctools_access_settings_submit($form, $form_state) {
  foreach (array('depth', 'vid') as $key) {
    $form_state['conf'][$key] = (integer) $form_state['values']['settings'][$key];
  }
}

/**
 * Check for access.
 */
function term_depth_term_depth_ctools_access_check($conf, $context) {
  // As far as I know there should always be a context at this point, but this
  // is safe.
  if (empty($context) || empty($context->data) || empty($context->data->vid) || empty($context->data->tid)) {
    return FALSE;
  }

  // Get the $vid.
  if (!isset($conf['vid'])) {
    return FALSE;
  }
  $depth = _term_depth($context->data->tid);

  return ($depth == $conf['depth']);
}

/**
 * Provide a summary description based upon the checked terms.
 */
function term_depth_term_depth_ctools_access_summary($conf, $context) {
  $vocab = taxonomy_vocabulary_load($conf['vid']);

  return t('"@term" has parent in vocabulary "@vocab" at @depth', array(
    '@term' => $context->identifier,
    '@vocab' => $vocab->name,
    '@depth' => $conf['depth'],
  ));
}

/**
 * Find the depth of a term.
 */
function _term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_select('taxonomy_term_hierarchy', 'th')
      ->fields('th', array('parent'))
      ->condition('tid', $tid)
      ->execute()->fetchField();

    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + _term_depth($parent);
    }
  }

  return $depths[$tid];
}

```
> 85 votes

# Answer
CTools plugins are small files which can be part of any module as the way to extend its functionality. They can be used to provide components (panes), add additional styles options to your panels, etc.

Please check CTools Plugins without Panels page for step by step documentation. So briefly it goes like:

1. You need to add CTools dependencies into your `.info` file as:

```
dependencies[] = ctools
dependencies[] = panels

```
2. Tell CTools where your plugin is located:

```
<?php
function MYMODULE_ctools_plugin_directory($module, $plugin) {
  if (($module == 'ctools') && ($plugin == 'content_types')) {
    return 'plugins/content_types';
  }
}
?>

```
3. Implement plugin in a `.inc` file (by default as `$module.$api.inc`). Example plugin code:

```
<?php
$plugin = array(
  'title' => t('Twitter feed'),
  'description' => t('Twitter feed'),
  'category' => 'Widgets',
  'icon' => '',
  'render callback' => 'twitter_block',
  'defaults' => array(),
);

// render callback
function twitter_block() {
  // Add twitter widget javascript
  $url = TWITTER_USER
  $widget_id = TWITTER_WIDGET_ID;
  $data = array();

  $data['url'] = $url;
  $data['widget_id'] = $widget_id;

  $content = array(
    '#theme' => 'my_block',
    '#content' => $data,
  );

  $block = new stdClass();
  $block->content = $content;
  $block->title = '';
  $block->id = 'twitter_block';

  return $block;
}
?>

```

The default location of the plugins looks like:

```
MYMODULE/
    plugins/
        content_types/
        templates/
    MYMODULE.info
    MYMODULE.module

```

For more examples, please check `ctools_plugin_example` module which as part of CTools module, or checkout the Help page (*CTools Plugin Examples*) in Drupal UI after enabling the module.

---

In Drupal 8, this is now part of core (see: Drupal\Component\Plugin) and it provides Object inheritance, Object interfaces and Single file encapsulation. See: Drupal 8 Now: Object Oriented plugins in Drupal 7
> 1 votes

---
Tags: panels, chaos-tool-suite
---


title: Getting more organized data?

text:
# Question
Title: Getting more organized data?
I get the impression the module works best for blog-type websites. My website's nodes have many many different (short) text fields with about 30-50 characters worth of text each. It would be incredibly helpful if I could get the search results data formatted differently. It looks like *snippet* is just a markup string ready to be printed. Whereas I would benefit a lot more from structured data. Let's say I search for the word "communication" then I would want data that looks more like:

```
 array(
  'matched_node_id' => 'xyz',
  'node_title' => 'abc',
  'matched_fields' => array(
               'matched_field_1' => 'full text for this field',
               'matched_field_38' => 'full text for this field'),
   );

```

This way I would be able to structure my page a lot more cleanly for my users. The data sort of resembles tabular data, and showing snippets without organization would be very unhelpful. Any ideas on how this could be implemented? Monkeying with theme\_preprocess\_HOOK? Perhaps a new module?

# Answer
It turns out that all of this information was already available, and I just had to work within mytheme\_preprocess\_item\_list\__search\_results. I had the Node objects for all the nodes that matched, and so I was able to reconstruct the render array exactly the way I wanted.
> 0 votes

---
Tags: 8, search
---


# Question
Title: Block visibility using PHP to show Vocabulary and Terms not working
In Drupal 6 I used PHP for Block visibility on selected vocabularies and terms.

The same PHP code does not work in Drupal 7 on a Centos 7 computer. Does PHP 4.4. not work on a PHP 4.5 server? I am using the same examples found here: https://www.drupal.org/comment/reply/69076#comment-form

# Answer
> 1 votes
If you're willing to consider using the "Rules" module, then you shouldn't need that "PHP code" anymore (sometimes a solution to a problem is to just avoid the problem from happening ...). Provided you can express your actual "logic" (about selected terms?) in appropriate Rules logic of course (as is often the case). More details about doing so are explained below.

# Part 1: Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules implement the "PHP code" logic you used before.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `1`.

With that, we're coming close to an actual answer to your question. All that needed is to massage your "PHP code" in an equivalent (set of) Rules Condition(s) (+ use that instead of the sample condition in my sample above), and then continue with Part 3 below.

# Part 3:

Head over to the "Block" settings for the block you want to conditionally hide. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.

# Answer
> 2 votes
Modules written for Drupal 6 are not designed to work with Drupal 7. Some do, by fluke, but it's quite rare. Sounds like you have one of the more common ones, that doesn't.

I'm not sure what you mean by

> Does php4.4. not work on a php4.5 server?

I think you're confusing several things there, none of which would be related to Drupal.

If you want to know what versions of PHP Drupal supports, see the requirements. If you want to know what version your server supports, your hosting provider will be able to tell you.

Some modules have specific minimum PHP version requirements; you can find those in the module's .info file, and you'll also be informed in the UI if your system can't support it.

---
Tags: 7, blocks
---


# Question
Title: Drupal Commerce: Calculating a shipping rate: Custom Shipping Price
I have a variety of products that have different fixed shipping prices. Each product has a custom field associated with it that contains a decimal price for shipping. Using Flat Rate Shipping, on the event "Calculating a shipping rate", how may I go about bringing in the custom field (scoping) to calculate that shipping price?

# Answer
It's probably easier to have multiple flat rates, and a conditional rule that the product for that price is in the cart.

**Notes**:

* There's a commerce shipping rules module that has a "cart contains item" condition.
* If you could get at the logic behind the prices you could deal with this more easily, like weight based or size based shipping. For hundreds of products it's unreasonable that there's no logic behind it outside of what they want to charge for shipping. What I could think of is a custom module using hook\_commerce shipping method alter where the shipping method matched the shipping price in the field. I've written a small module that alters the shipping weight, but that again assumes logic the weight based shipping.
> 1 votes

---
Tags: commerce
---


# Question
Title: Drupal Commerce - (free) Shipping , Pickup option , Order Comment?
I'm still facing some issues with my Drupal Commerce.

The shop is only available for authenticated users. When they want to checkout they should be able to pick a shipping option or a pickup option.

When the order total is less than 25 euro and they want to get it deliverd they will be a shipping fee of x euro's. When it is higher than 25 euro shipping will be free. When they pick the option to pick it up, it will be free.

I also want in both cases that a text fields appears so they can give a date/time that they want the package to be delivered.

I also have customer profiles enabled, but when I'm at the checkout my profile isn't getting filled in.

Any thoughts on how to achieve this?

Best regards.

# Answer
> 1 votes
* Install https://www.drupal.org/project/commerce\_flat\_rate
* Go to "admin/commerce/config/shipping/methods" and create following flat rate services
    + Pickup at store (0 $)
    + Free shipping (0 $)
    + Shipping (x $)
* Configure the last 2 flat services (free shipping / shipping) by clicking "configure component"
    + Free shipping rate -\> add condition "Order amount comparison" \>= 25 $
    + Shipping -\> add same condition, but check "negate"

Now picking up at store will always show up, the other 2 depending the order amount.

For the textfields, you can put that in the shipping profile for the customer.

---
Tags: commerce
---


# Question
Title: How do I access the first value of a multiple value text field using replacement patters inside a rule?
For example, lets say I have a list of objects each stored as separate values of a text field. How would I access the individual values? I have tried using delta and I have tried using entity token but nothing has worked. I hope my syntax was just a little off.

# Answer
> 0 votes
Have a look at the tutorial about "Using Entity Reference in Rules". Starting from about 2:50, and up to about 4:15, it shows how in a Rules Action you can access the 1st, or 2nd, or ... value of a multiple value field, provided you also included a Rules Condition like "Entity has field" (related to the multi value field). So if you have a content type with a multi value field with (say) `myfield`, then you'd use `node:myfield:0` for the very first value of that field (or `node:myfield:1` for the 2nd value, etc).

However, the same tutorial, starting from about 4:20 and up to about 6:40, also explains how to loop through multiple-value references, using a Rules ***loop***, and which I think is more appropriate to answer your question. If you're not familiar with such loops, then I strongly recommend to also have a look at the tutorial titled "Lists and loops".

---
Tags: entities, tokens
---


title: Entity UUID and uniqueness

text:
# Question
Title: Entity UUID and uniqueness
We have a multisite install that will have a few shared blocks. As we spin up more sites we'd like to just take the yml file associated with the block and add it to the config directory of the new site. The issue though is the UUID. Do these need to be unique across the entire install or just within a sub-site?

# Answer
A multisite is really just multiple sites that happen to share the same code base. Unless you do crazy things with sharing prefixes (which I would really, really recommend against), the fact that you are sharing code is completely irrelvant to the running site/configuration.

So, there is no such thing as sub-sites. Just sites. And it doesn't matter if the have the same UUID's in different sites.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Why can't my module install a database table?
I'm following the instructions on a module development training video. I try to install a table using the `mysite/update.php` page and everything goes well but no table is installed in the database. I'm lost for what might be wrong. Here's my code on a `my_module1.install` file:

```
/*
Implements hook_schema
*/
function my_module1_schema(){
    $schema = array();

    $schema['my_module1_node_views'] = array(
        'fields' => array(
            'nid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
            ),
            'uid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
            ),
            'view_count' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('nid', 'uid'),
    );
    return $schema;
}

/*
Implements hook_update_N
*/
function my_module1_update_7000(){
    drupal_install_schema('my_module1_node_views');
}

```

# Answer
> 2 votes
The argument to `drupal_install_schema()` is the module name, not the table to install.

Generally speaking (and assuming you might have more than one table eventually), if you want to create all tables that are defined in `hook_schema()`, use:

```
drupal_install_schema('my_module1');

```

If you just want to create that one table:

```
$table = drupal_get_schema_unprocessed('my_module1', 'my_module1_node_views');
db_create_table('my_module1_node_views', $table);

```

---
Tags: 7, database, updating
---


# Question
Title: What to replace entity_uri() with in Drupal 8?
So I have the following code in my Drupal 7 module:

```
$uri = entity_uri('node', $node);
$breadcrumb[] = l($node->title, $uri['path'], $uri['options']);

```

Anyone know how to convert the above code to Drupal 8?

Since l() is depreciated, I believe the second line should be replaced as follows:

```
$breadcrumb = array(Link::createFromRoute($node->title, $uri['path'], $uri['options']));

```

I'm struggling with what to do with entity\_uri() since the change records don't really indicate how that function is to be replaced.

Note: this is being used within the BreadcrumbBuilderInterface class.

# Answer
Try with this code:

```
$link = $node->toLink($node->getTitle(), 'canonical', $options);

```

Get more information about Node object here: "Node Object"
> 2 votes

---
Tags: 8
---


# Question
Title: Ajax callback return 500 Internal Server Error
file mymodule.inc :

```
        $items['ajax/channel/%/get-program'] = array(
        'title' => t('get channel program by ID'),
        'type' => MENU_CALLBACK,
        'page callback' => 'get_channel_program',
        'page arguments' => array(2),
        'access arguments' => array('access content'),
      );

      return $items;
//channel program
function get_channel_program($channel_id){
  $channel_id = (isset($_POST['channel_id']) ? $_POST['channel_id'] : '');
  if (!is_numeric($channel_id)) :
    drupal_not_found();
  else :
    drupal_json_output($channel_id);
  endif;
}

```

file mudule.js :

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

            // CSS Selector for the button which will trigger the AJAX call

            $('.channel-tv-tabs .tab .tabset .single-prog', context).click(function () {

                var channel_id = $(this).data('channel-id');

                $.ajax({
                    url: '/'+Drupal.settings.pathPrefix + 'ajax/channel/'+channel_id+'/get-program', // This is the AjAX URL set by the custom Module
                    type: "POST",
                    data: { channel_id : channel_id }, // Set the number of Li items requested
                    dataType: "json",          // Type of the content we're expecting in the response
                    success: function(data) {
                        var parsed_data = $.parseJSON(data);
                        console.log(parsed_data);  // Place AJAX content inside the ajax wrapper div
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        console.log(errorThrown);
                    }

                });

            });

        }
    };

```

Pls help me and tell what i do wrong? When I try go to link http://hostname/ru/ajax/channel/25/get-program I recive page not found

# Answer
> 1 votes
Change the callback into this:

```
function get_channel_program($channel_id){
  if (!is_numeric($channel_id)) :
    drupal_not_found();
  else :
    drupal_json_output($channel_id);
  endif;
}

```

Change the jQuery into this:

```
$('.channel-tv-tabs .tab .tabset .single-prog', context).click(function () {
     ...
     $.get('/ajax/channel/'+channel_id+'/get-program', function(data) {
     alert("got "+ data);
   });
});

```

This uses HTTP GET verb.

> According to the design of the HTTP specification, GET (along with HEAD) requests are used only to read data and not change it

instead of POST

> The POST verb is most-often utilized to **create** new resources.

---
Tags: 7, ajax, routes
---


title: Rename "Read More"

text:
# Question
Title: Rename "Read More"
I wanted to rename "Read more" in teaser (node--blog--teaser.html.twig) to something like "Continue" or anything else.

How can I achieve this?

# Answer
> 6 votes
In your theme open file THEMENAME.theme, example in my case THEMENAME is bartik and file is bartik.theme add code below:

```
/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#title'] = t('Read more custom text');
    }
}

```

Clear all cache and see result.

About add custom class to readmore link you can check here: Add custom classes to node links

---
Tags: theming, 8, nodes
---


# Question
Title: Remove case sensitivity from username when logging in
When I try to login, my usernames are treated as case sensitive. As in if username is `john` and I try entering `John`, it is not accepted.

Is it possible if I could make all the characters lower case before they could be submitted?

Thanks

# Answer
> 1 votes
Using hook\_user\_insert, you can convert every letter of username to lower case once a user is being created. Then when a user is submitting the login form, you can convert its username field to lower case. So from now on all of the usernames will be in lower case it is no longer case sensitive

---
Tags: users
---


# Question
Title: How to create a multi vendor Drupal commerce website?
What is the best way to create a multi vendor Drupal commerce website in which every vendor has the option to create:

1. Their own store.
2. Their own menu/vocabulary.
3. Every vendor have access to its own menu/vocabulary.

A hint would be enough.

# Answer
eCommerce in Drupal generally comes down to 2 modules:

* Ubercart
* Commerce.

Commerce is very powerful and flexible, and I'm sure you could use it to build your use case, but it might take a lot of work. It has a great distro called Commerce Kickstart to get you up and running quickly. And Pantheon will give you free hosting for you dev site and install the distro for you!

Ubercart is older, and still powerful, not quite as flexible. But this module may meed your use case exactly: Ubercart marketplace.

Other module :
> 1 votes

# Answer
Here is a "hint" you're asking for: use the Drupal Commerce module (in Drupal 7), and combine it with a "multi-site" setup (1 site for each vendor).

So that all shops are running the same "software", but each Vendor has the access for "their" shop as you're asking for.

**Note**: if you have like "100" vendors (as in your comment below my answer here), maybe you'd then want to create (eg) 10 Drupal installations with each 10 sites (or 20 installations with each 5 sites). And/or you could also consider the technique of "table prefixes" to have multiple sites share the same (single) database (with a prefix that corresponds to each vendor).
> 0 votes

---
Tags: 7, commerce
---


title: How do I embed views in node template

text:
# Question
Title: How do I embed views in node template
Please how can I embed a view in a node template like `node--blog--full.html.twig`.

I have configured an about-the-author views to be embedded in full mode of blog content type using `views-embed-view()`, but it doesn't work. I have enabled the "Allow embedded displays" from views settings and followed a few tips online, but none seems to work.

1. Is there a better way to embed views in D8 node template?
2. How can I use `views-embed-view` correctly in D8?

Many thanks

# Answer
> 1 votes
Just to be sure, are you calling `views-embed-view()`, or `views_embed_view()` (Note the dashes/underscores). The second version (`views_embed_view()` is the correct one).

Also, how do you call the function? Which parameters do you pass?

As per this page, the correct way of embedding a view is 1 of the following ways.

**Option 1:**

```
// Get the embeded view and render it.
drupal_render(views_embed_view('VIEW_NAME', 'DISPLAY_ID'));

```

**Option 2**

```
// Get the embeded view and render it.
\Drupal::service('renderer')->render(views_embed_view('VIEW_NAME', 'DISPLAY_ID'));

```

In this example you will have to replace `VIEW_NAME` with the machine name of your view, and the `DISPLAY_ID` should be replaced with the ID of the display you want to use (Or can be omitted to use the default display).

*Also note that the second option is the better one, since the drupal\_render function is deprecated, and will be removed before Drupal 9.0.0 (More info).*

---
Tags: views, theming, 8
---


# Question
Title: Superfish menus getting clipped in blocks
I'm showing a Superfish block with a selected menu in the Homebox module.

The problem is that child menus are getting clipped in the left and right and using browser console I'm not able to remove this clipping either by `z-index` or using `overflow-x/y` css properties.

How to make it work?

The div enclosing the Quick Links Staff block has "`overflow`" set to "`hidden`". Now if I disable it then the sub-menus show correctly but now the block height drops :

# Answer
> 0 votes
If you can't remove it with `z-index: 4;` then it might mean that your menu does not have a background; thus, it's transparent.

So add a background to your menu ex: `background: white;`

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


title: Gmap and many markers with popup

text:
# Question
Title: Gmap and many markers with popup
**Situation**

We use gmap module to generate gmap and display markers on it. When user click on marker we display popup, it works well if website display 100-200 markers only, however when it gets to 1000++ Drupal can't display such page.

**Issue**

Issue happens because Drupal exports all required information to display popup directly on page and it takes to much time generate that.

**What I've done so far**

I googled and did not find anything that could help me. I know that google map API may deal with feed/xml (that's a direction I'm moving to), however I do not wanna create new wheel if it is already exist.

Thanks!

# Answer
In order to move information for popup from the page we have to use options: RMT callback path in a view.

It allows to make AJAX request to load content and so you do not need to put it on page with map. It's big performance improvement.
> 0 votes

---
Tags: google-maps
---


# Question
Title: How can I trigger rerender of an element in a preprocess function?
**Update:** My current solution is to use the Field formatter conditions module, to suppress output of the fullname field when a first name is present. It seems like it should be very simple to replace the value of the fullname field with the contents of the two name fields and hide those fields, but my node.tpl.php file seems not to do anything now that I'm using display suite and I can't figure out how to accomplish what I want in template.php. Some help with that would still be greatly appreciated.

**Note:** I would like not to create a module just for the purposes of wrangling a couple of fields. I am still looking for an answer to this, or a solid explanation of why a module is definitely the right way to go.

I'm probably taking the wrong approach to this. With everything I try to do, I seem to try every wrong way first before throwing up my hands and asking the internet to tell me the right way, and invariably the right way feels wrong.

Today, I'm trying to replace the value of one field in a paragraphs bundle item with the values of two others. Here is the relevant code from template.php:

```
function enviroscope_preprocess_paragraphs_items(&$variables, $hook) {
    $element = &$variables['element'];
    foreach ($element['#items'] as $delta => $item) {
        if ($element[$delta]['entity']['paragraphs_item'][$item['value']]['#bundle'] == 'doc_other_contrib_pb') {
            $person = &$element[$delta]['entity']['paragraphs_item'][$item['value']];
            if (isset($person['field_pb_doc_other_first_name']) && isset($person['field_pb_doc_other_family_name'])) {
                $person['field_pb_doc_other_fullname'][0]['#markup'] = $person['field_pb_doc_other_first_name'][0]['#markup'] . ' ' . mb_strtoupper($person['field_pb_doc_other_family_name'][0]['#markup']);
            }
        }
    }
}

```

I verified that the #markup element of the fullname field is updated, but everything still shows up the same. Is there anything I can do to rerender?

# Answer
If I need to manipulate the text and/or display based on some PHP logic, I would do it using hook\_node\_view(). Implement this HOOK in you custom module. Use of this module will be like.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if( $view_mode == 'full' ){
        if( $node->type == 'YourContentType' ){
            $node->content['field_pb_doc_other_first_name'] = array(
                '#markup' => $node->content['field_pb_doc_other_first_name']['#markup'] . ' ' . mb_strtoupper($node->content['field_pb_doc_other_family_name']['#markup']);
        }
    }
}

```

My logic may be wrong, you need to check the $node variable inside this function for all the fields value. The above code is just a sample code to demonstrate use of HOOK\_node\_view.
> 0 votes

---
Tags: 7, theming
---


title: Watchdog message is not proper

text:
# Question
Title: Watchdog message is not proper
Used sqlquery to get the error log messages from watchdog table. Getting message like,

1. 'Sending mail to: @to'.
2. '%type: !message in %function (line %line of %file)' (which seems not relevant).

How can I get error log message similar as shown at SiteReports--\>Recent Log Messages view?

# Answer
The data is serialised and uses an array of named placeholders, so you'll need to use PHP to assemble the full message:

```
// Get data from the DB, each record stored in $row, then...
$message = $row->message;
$variables = unserialize($row->variables);

$full_message = strtr($message, $variables);

```
> 3 votes

---
Tags: log-messages
---


title: Drupal db_select join 3 fields

text:
# Question
Title: Drupal db_select join 3 fields
I want join to my select three fc fields:

* field\_data\_field\_show\_block\_carousel
* field\_data\_field\_poster\_film
* field\_data\_field\_film\_link

I try this:

```
$nids = db_select('node', 'n');
  $nids->join(array('field_data_field_show_block_carousel', 'field_data_field_poster_film', 'field_data_field_film_link',), 'fc', 'n.nid = fc.entity_id');
  $nids->fields('fc', array('field_poster_film_fid','field_film_link_url',));
  $nids->fields('n', array('nid', 'title', 'uid',))
    ->condition('n.type', 'vodeo_library')
    ->condition('fc.field_show_block_carousel_value', 1)
    ->execute(); // returns an indexed array
  $result = $nids->execute()->fetchAllAssoc('nid');

```

but recived sql error? pls tell me what I do wrong?

# Answer
You should try to write each join on a new line, not as an array. See Joins and public function SelectQuery::join.

So try it like this:

```
$nids = db_select('node', 'n');
  $nids->join('field_data_field_show_block_carousel', 'fc', 'n.nid = fc.entity_id');
  $nids->join('field_data_field_poster_film', 'fp', 'n.nid = fp.entity_id');
  $nids->join('field_data_field_film_link', 'fl', 'n.nid = fl.entity_id');
  $nids->fields('fp', array('field_poster_film_fid'));
  $nids->fields('fl', array('field_film_link_url'));
  $nids->fields('n', array('nid', 'title', 'uid',))
    ->condition('n.type', 'vodeo_library')
    ->condition('fc.field_show_block_carousel_value', 1)
    ->execute(); // returns an indexed array
  $result = $nids->execute()->fetchAllAssoc('nid');

```

Depending on what your module attempts to achieve, you might also want to have a look at the default Drupal functions for attaching fields to nodes (you only have a condition on one field):

You can get a rendered field value like this:

```
$node = node_load($nid);
$poster= field_get_items('node', $node, 'field_data_field_poster_film');
$output = field_view_value('node', $node, 'field_data_field_poster_film', $poster[0]);

```

And if you don't mind a little overhead, you might want to try an EntityFieldQuery. It will give you all fields and is a little slower then a regular SQL query, but is much easier to read and change.

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'vodeo_library')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_show_block_carousel_value', 'value', 1, '=');

$result = $query->execute();

if (isset($result['node'])) {
  $news_items_nids = array_keys($result['node']);
  $news_items = entity_load('node', $news_items_nids);
}

```
> 1 votes

# Answer
Please use following query.

Note: Change table alias in $nids-\>fields('fc', array('field\_poster\_film\_fid','field\_film\_link\_url')); accordingly.

```
$nids = db_select('node', 'n');
$nids->join('field_data_field_show_block_carousel', 'fc', 'fc.entity_id = n.nid');
$nids->join('field_data_field_poster_film', 'ff', 'ff.entity_id = n.nid');
$nids->join('field_data_field_film_link', 'fl', 'fl.entity_id = n.nid');
$nids->fields('fc', array('field_poster_film_fid','field_film_link_url'));
$nids->fields('n', array('nid', 'title', 'uid'))
    ->condition('n.type', 'vodeo_library')
    ->condition('fc.field_show_block_carousel_value', 1, '=')
    ->execute(); // returns an indexed array
$result = $nids->execute()->fetchAllAssoc('nid');

```
> 0 votes

---
Tags: 7, nodes, database
---


# Question
Title: Why can my view not access the data of a new node when using Rules event After saving new content?
Using the Rules module and Drupal 7, I set up a rule "After saving new content of type X".

This is what I want to happen when adding a new content of type "X":

> Based on its nid, call a view, which returns back a JSON, from where I fetch the info to work later. The info I need is on this view, not in the node I am inserting, but to get this view I need the **nid** and some other info from the node I am creating

The problem is that even if I get the nid of the new node, when I call the view it just returns an **empty result**. It seems like the data it's still not on Drupal database, so the view results empty. I tried to add a sleep(10) before calling the view, giving some time to Drupal, but no success.

The Content is published, and I added also a 'Save entity' Action to the Rule

Hope with this code here helps to understand; it's in *Editing action "Execute custom PHP code"*, "After saving new content of type X"

```
dsm($node);  //I can see al attributes from the node I am inserting

$url="http://localhost/bopa/?q=export_cultivos/$node->nid";

dpm($url);

//it gives me a correct URL, that tested later directly on the browser, works
//If instead of $node->nid I use an existing nid, I get back results correctly, so the code below is correct

sleep(10);
$data=file_get_contents($url);

$data2 = json_decode($data,true);

dsm($data2);
//EMPTY array

```

# Answer
> 0 votes
IMO your "issue" (about "*It seems like the data it's still not on Drupal database, so the view results empty*") is because of the event (= "*after saving new content*") you are using, which might simply not be the right event.

Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).

# Answer
> 0 votes
It sounds like a permissions problem with the view. Is `$node->uid` getting set properly?

Also, ensure the following:

1. The anonymous user has permission to the view that you're trying to access. Check this by using Privacy/Incognito mode in your browser.
2. Ensure the view can be seen by others.
    1. On the View editing page, under *Page Settings*, there will be an item that says *Access*.
    2. Ensure that it says *None*.
    3. Note that even though the item says "Access" it is short for "Access Restrictions" and having it set to none simply means that it won't be disabled.
3. You may need to change the view to 'bypass access control' so that an anonymous user can see entries. To do this:

1. Go to the view you're editing and expand *Advanced*. (1)
    2. Click on the link to access *Query Settings*. (2)
    3. Disable SQL-rewriting.
    4. Save your view and try again.

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


# Question
Title: How to extend Views Plugin ViewsSelection.php to have $form_state
I need to add in the current `$form_state` into the ViewsSelection. I have copied the file `/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php` to `/modules/custom/fsed_entry/fsed_project_entity_reference_options/src/Plugin/EntityReferenceSelection/ProjectsSelection.php` where I have the file overriding views' implementation. However, I can't seem to figure out how to get `$form_state` into my variables so that I can use a value from another form element. I have been trying to experiment with `FormCache` but I have not been successful. Any ideas on best approach here?

For background, I need the `$form_state` because the field that is being rendered (and this plugin is used on) here was ajaxed in and I want to pass in a value that I can add onto the `handler_settings -> view -> arguments` that this plugin uses.

# Answer
There is no form state, at least not with autocomplete. And since the same code is designed to work with autocomplete and other widgets, it can't rely on form state anywhere.

If you have autocomplete you can possibly pass in the settings in the entity\_autocomplete form element which should be passed to your plugin. Not sure about other widgets, you might need your own widget to be able to do that.
> 1 votes

---
Tags: views, entities, 8, plugins
---


# Question
Title: How to automatically modify a field after saving content?
I have posted this question on drupal.org (via a comment titled "*field modification triggered by saving action*"), but I realized that the thread is more than five years old. So I reproduce here the question made there:

## field modification triggered by saving action

I need to modify a field, but this change has to be triggered when saving the term and it depends on the value of another field, let me explain ...

term

* field 1: filled with options A/B/C
* field 2: `<info>`random\_name

I save and if value in

* Field 1 is A, then value in Field 2 must change to "Source: random\_name"
* Field 1 is B, then value in Field 2 must change to "Destination: random\_name"
* Field 1 is C, then value in Field 2 must change to "Product: random\_name"

Note that the label `<info>` is the one that must change.

# Answer
You can use the Rules module to get this logic implemented. Have a look at my answer to "How to set the values of some fields depending on the value of a list box?".

The rule shown there uses these fields:

* a selection list field with machine name `field_optionlist` (corresponds to your field 1).
* a text field with machine name `field_free_format_text` (corresponds to your field 2).

If you adapt the machine names in that rule (in Rules export format) to the names from your 2 fields, should be straight forward to further tune (customize) it to also match the values as in your case.

However, to make this to work with only 1 rule (instead of writing 3 rules, ie one for each possible value of field 1, so one for "A", one for "B" and one for "C"), you also need the "Conditional Rules module. That way you could expand the prototype to say dozens of different possible values. For an example using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

**Best practice advise**: the more you start using the Rules module, the more you should try to group rules together using the Rules Conditional module. Just to keep the entire set of rules manage-able (eg to have related business logic shown on a single Rule UI screen). A good sample of how easy it is to end up with a lot of rules, is what you can see in the Answers module (current 7.x-4.x-rc2 version):
> 0 votes

---
Tags: 7, taxonomy-terms, rules, actions
---


# Question
Title: Prevent WYSIWYG+CKEditor from stripping html classes
I'm using WYSIWYG editor with CKEditor. I'm finding that when adding custom classes to my elements from the "source" view, CKEditor strips those classes when switching out of the source view.

When googling for a solution to this, I found the CKEditor module page which describes how to fix this when using CKEditor alone. (Basically, we need to set up a JS config `config.allowedContent = true` in its Advanced Content Filter settings).

However, when using CKEditor via WYSIWYG, these settings are not exposed in the admin interface. How do you achieve the same when using CKEditor via WYSIWYG?

PS: I cannot use CKEditor alone because it does not integrate with the media plugin.

# Answer
What version of CKEditor are you using? There is an issue with CKEditor 4.1+, which has a feature called Automatic Content Filter (ACF) that will automatically strip attributes not defined for the editor: https://drupal.org/node/1956778

Patch #37 in the issue worked for me.
> 4 votes

# Answer
I found a solution.

This turns off the filtering, it's working, but not a good idea...

```
config.allowedContent = true;

```

To play with a content string works fine for id, etc, but not for the class and style attributes, because you have () and {} for class and style filtering.

So my bet is for allowing any class in the editor is:

```
config.extraAllowedContent = '*(*)';

```

This allows any class and any inline style.

```
config.extraAllowedContent = '*(*);*{*}';

```

To allow only class="asdf1" and class="asdf2" for any tag:

```
config.extraAllowedContent = '*(asdf1,asdf2)';

```

(so you have to specify the classnames)

To allow only class="asdf" only for p tag:

```
config.extraAllowedContent = 'p(asdf)';

```

To allow id attribute for any tag:

```
config.extraAllowedContent = '*[id]';

```

etc etc

To allow style tag (\<style type="text/css"\>...\</style\>):

```
config.extraAllowedContent = 'style';

```

To be a bit more complex:

```
config.extraAllowedContent = 'span;ul;li;table;td;style;*[id];*(*);*{*}';

```

Hope it's a better solution...
> 11 votes

# Answer
This seems like something that should be added into the WYSIWYG module, the ability to add custom settings to editors is a pretty widespread requirement. But in the absence of that, I still recommend not editing the module itself since it would break on upgrades... fortunately the module does provide a call to `drupal_alter`, so in a custom module:

```
function mymodule_wysiwyg_editor_settings_alter(&$settings, $context){
    //check if the editor is ckeditor and the version is at least 4.0
    if($context['profile']->editor=='ckeditor' && $context['editor']['installed version'][0]>3){
        //add custom settings for ckeditor 4.+ here
        $settings['allowedContent'] = TRUE;
    }
}

```

where "mymodule" is obviously the name of your custom module. This accomplishes the task without editing someone elses module.
> 2 votes

# Answer
Try adding the following to modules/wysiwyg/editors/ckeditor.inc

`'allowedContent' => TRUE,` to `function wysiwyg_ckeditor_settings($editor, $config, $theme)`

so that it now reads:

```
function wysiwyg_ckeditor_settings($editor, $config, $theme) {
  $settings = array(
    'width' => 'auto',
    // For better compatibility with smaller textareas.
    'resize_minWidth' => 450,
    'height' => 420,
    // @todo Do not use skins as themes and add separate skin handling.
    'theme' => 'default',
    'skin' => !empty($theme) ? $theme : 'kama',
    // By default, CKEditor converts most characters into HTML entities. Since
    // it does not support a custom definition, but Drupal supports Unicode, we
    // disable at least the additional character sets. CKEditor always converts
    // XML default characters '&', '<', '>'.
    // @todo Check whether completely disabling ProcessHTMLEntities is an option.
    // ADDED  'allowedContent' => TRUE, to keep WYSIWYG from removing classes
    'entities_latin' => FALSE,
    'entities_greek' => FALSE,
    'allowedContent' => TRUE,
  );

```
> 0 votes

# Answer
Without hacking any sources, and also without trying to figure out WHERE the bleep these settings are being read, you could add this to you own custom module

```
function mymodule_wysiwyg_editor_settings_alter(&$settings, $context) {
    if ($context['profile']->editor == 'ckeditor') {
        $settings['extraAllowedContent'] = array(
            'a[download,type,length,href]',
            'span;ul;li;table;tr;td;style;*[id];*(*);*{*}'
        );
    }
}

```

The settings the OP is asking for are `*(*);*{*}` from the answer of @Tommy above. This seems to allow class and style attributes on any element. The rest are just example entries. As another example, this entry allows the tags needed by the media module.

```
'img[title,alt,src,data-cke-saved-src](wysiwyg-break,drupal-content);video[width,height,controls,src](*);source[src,type];audio[controls,src](*);img[*](media-element,file-default)',

```
> 0 votes

# Answer
The Filtered HTML-filter strips out the classes from elements that are not in its *allowed HTML elements*. The paragraph tag (`<p>`) is not in there by default (which may be confusing and unnatural), eventhough it may the most frequent element where class is applied upon. Once you put it in there, Filtered HTML will no longer strip the classes from these tags. Same goes for image tags (`<img>`).
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to re-create vanilla field configuration strings programmatically for any field?
After a D7 update and migration of fields, most of our problems with converted fields result from invalid or incompatible field settings. Field settings are stored in the
`field_config_instance.data` column in the database as serialized php objects.

How can I, for any given field instance, generate a fresh field configuration string, as if the field was just created in D7, while leaving the already stored field data intact?

My manual approach seems to work but is very cumbersome:

* create a new content type
* add an existing field to the new content type, generating new settings string
* search the new and old field in the database
* using sql: replacing the string in the data column of the old field (with the same name) with the new data content.

There must be a way to automate this a bit.

# Answer
> 1 votes
I guess you will need a combination of field\_update\_field() and field\_create\_field().

During `field_create_field()`, the settings are loaded from the default field definition as each field has defined in its own hook\_field\_info().

```
$field['settings'] += field_info_field_settings($field['type']);

```

What you are looking for is to apply this logic to `field_update_field()`.

Basically you will need to load all fields:

```
$fields = field_info_fields();

```

Optionally limit the fields to your selection:

```
foreach ($fields as $field_name => $field) {
  if ($field['type'] == 'some type') {} // Filter by type
  if ($field_name == 'some name') {} // Filter by name
}

```

And update the fields:

```
$field['settings'] = field_info_field_settings($field['type']);
field_update_field($field);

```

So I guess it should look something like this:

```
$fields = field_info_fields();
foreach ($fields as $field_name => $field) {
  if ($field['type'] == 'some type') {
    $field['settings'] = field_info_field_settings($field['type']);
    field_update_field($field);
  }
}

```

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


title: Matching content with views

text:
# Question
Title: Matching content with views
I have 2 roles. Each role can create a certain content type. Both content types are using the same taxonomy terms in several fields:

```
Content type 1: Project
- Field: Service Type (Term reference)
- Field: Cost (Term reference)

Content type 2: Preferences
- Field: Service Type (Term reference)
- Field: Cost (Term reference)

```

Role 1 can create unlimited projects (1:n), while role 2 can only create 1 preferences node (1:1).

Now I want to create a view for role 2 users, displaying all the projects that match their preferences. I know this is done by certain relationships in the view. I just can't figure out which ones to set.

Thoughts?

# Answer
You'll need a relation from the 'settings node' to the taxonomy term, and then from the taxonomy term to all other nodes.

The corresponding relations are called `Content: Taxonomy terms on node` and `Taxonomy term: Content with term` (which only becomes visible after adding the first one).

From there you can apply filters to the nodes. The relations you select for the filters distinguish between the base node and all linked nodes.
> 2 votes

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


# Question
Title: How to create a better (more userfriendly) admin interface for non-technical "admin user"?
I'm trying to make Drupal admin interface easier for non-technical users.

Actually, I'm trying to "create" a **new** interface for these kind of users. I'm using Views, VBO, Rules etc. to make a better admin interface experience without scaring them with a complex structure.

## Easily;

* edit, enable/disable blocks,
* edit-rearrange main menu,
* manage users,
* manage contents,
* manage files, images etc. uploaded via Drupal interface,

### What should be done to increase user experience of this admin interface?

Is there any must-use module you suggest?

# Answer
I don't use this myself as I prefer the slimer Administration Menu, but I think Navbar is more newbie friendly
> 1 votes

---
Tags: 7, users, theming
---


# Question
Title: Showing Discount labels for products that are linked to any discount offer?
I created a view (table) of my products and I want to display the ID field of the related discount.

* So I added a relationship with `Trade Discount Offer referencing products from commerce_free_products` and `referencing Trade Discount Trade Discount Offer from commerce_discount_offer`
* Then added the field `Trade Discount: Discount ID` I have my column but in the 0 if I add `(referencing Trade Discount Trade Discount Offer from commerce_discount_offer) Trade Discount: Title for administration (Title for administration)` my column is empty.

What did I do wrong? I found it this ticket but it does not help.

# Answer
If by "ID field" you mean the name of the discount shown to customers, this is doable.

You must have a product that is the object of a "Free product" offer.

Once that is done, you'll need to add two relationships to the view. The first, you've already gotten is the link from the product to the offer:

> **Commerce Discount Offer referencing products from commerce\_free\_products**
> *Trade Discount Offer referencing products from commerce\_free\_products*

The other relationship is the link from the offer to the Discount entity itself:

> **Commerce Discount referencing Commerce Discount Offer from commerce\_discount\_offer<br>** *A bridge to the Commerce Discount entity that is referencing Commerce Discount Offer via commerce\_discount\_offer*

Then you can add fields attached to the *Commerce Discount entity*:

* Commerce Discount: Name
* Commerce Discount: Admin title

And now your labels should be visible.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to tell if a view is cached from generated HTML output?
I have a view on my page and I've cached it using Views caching. Is there a way to tell that the view is cached from the output or the headers? This question says that Drupal sets the header `X-Drupal-Dynamic-Cache` but I don't see that in my browser's inspector. I do see the header `X-Generator:Drupal 7 (http://drupal.org)` so that's nice.

It would be nice to see an HTML comment, like what the Boost module does.

# Answer
> 2 votes
The answer you linked to is wrong. `X-Drupal-Dynamic-Cache` only exists in Drupal 8. Beyond that, the answer itself is also wrong. Will comment there.

In Drupal 7, you can't tell that the view is cached based on output (HTML markup) or headers.

---
Tags: 7, views, caching
---


# Question
Title: How to properly call drush command from another drush command?
I have a drush command that does some stuff and at the end of its execution I want to invoke `twig-compile --uri=foobar.com`. When I call `drush_invoke('twig-compile')` I get error about unknown arguments(those were passed to my drush command). I tried things like this before invoking the command `drush_set_context('options', ['uri', 'foobar.com']);` but no success yet.

How should I reset the options so twigc won't complain about them or how do I invoke the twigc command directly with the uri argument?

# Answer
If you use drush\_invoke, you should first use `drush_set_option('strict', FALSE);` to turn off strict option checking for the subcommand. `drush_invoke` runs a subcommand in the same process, which can be more efficient; however, there are a number of ways that this can go wrong, so it is often better to use `drush_invoke_process` instead, to run the subcommand in its own process. If you do this, there is no need to disable strict option handling.

`drush_invoke_process('@self', 'twig-compile', $args, $options);`.
> 1 votes

---
Tags: 8, drush
---


# Question
Title: How to set Navbar to be a sidebar by default?
Drupal 7's Navbar module is:

* **In wide windows**, a bar across the top, with no dropdowns, just links to main sections like Content, Structure etc
* **In medium-width and narrow windows**, a sidebar or dropdown menu, with accordion-style dropdowns allowing primary menu items to be expanded and secondary menu items shown without leaving the page.

I want to give users the sidebar view, even on wide screen devices, so they can use the secondary menu dropdowns it offers.

I want it to look like this when the menu is chosen, even in wide devices, similar to the old Admin module:

I can't find any way to do this within Navbar. What's the simplest way to do this, with minimal hacking to the Navbar module or hard-coded overrides?

# Answer
I found a way to do this in a very simple custom module **without any hacking or patching to Navbar code**.

Just create and enable a custom module that contains (assuming your module is called `custom`):

```
/**
 * Implements hook_navbar_breakpoints_alter().
 *
 * Nullifies the breakpoint that switches the navbar to horizontal orientation
 */

function custom_navbar_breakpoints_alter( &$data ) {
    $data["wide"] = "not all";
}

```

The navbar module defines a hook, `hook_navbar_breakpoints_alter`, using `drupal_alter`, that allows its hard-coded breakpoints to be overwritten.

`not all` seems to me the cleanest and most intuitive way to implement an impossible media query condition (related: How to set a media query condition that is never met?).

This makes the switchable horizontal masthead view of the navbar menu, quite literally, the default on not any device.
> 2 votes

# Answer
With the navbar in horizontal format as on your widescreen devices, click this button in the top right corner of the window:

This will make the navbar show vertical, until the time when the user clicks the button at the end of the vertical sidebar to reverse this.

It's not by default vertical for widescreen devices with that, though. It still needs a user action to make it vertical.
> 1 votes

# Answer
If what you are looking for is having the navbar showing *by default* as vertical for any screen size, you can follow the suggestion presented here:

`if(localStorage){
 localStorage.setItem('Drupal.navbar.trayVerticalLocked',true);
}`

on

```
navbar/js/navbar.js

```

If you prefer, just grab this commit I made.
> 1 votes

---
Tags: 7
---


title: How to tell if a view gets cached?

text:
# Question
Title: How to tell if a view gets cached?
I assume that as soon as you add a contextual filter, that is not a fixed value, the View becomes uncachable since it becomes dynamic, right?

Is there a clear cut way to tell if the View gets cached or not?

# Answer
> 5 votes
> I assume that as soon as you add a contextual filter, that is not a fixed value, the View becomes uncachable since it becomes dynamic, right?

No.

That just means that the view's output varies based on the URL. Specifically, a query argument.

This is why we in Drupal 8 have the concept of cache contexts: https://www.drupal.org/developing/api/8/cache/contexts.

For the Views module to efficiently determine whether a view can have a cached version or not, we need to know ahead of time which contexts a particular view display varies by. So, upon saving a modified view, the Views module iterates over all plugins that a particular view display uses and gathers its cacheability metadata. It then stores it in the `view` config entity.

Concrete example: the "Taxonomy Term" view that ships with Drupal 8 core. It has a path of `/taxonomy/term/%`, with that `%` being a particular taxonomy term ID. Open `core/modules/taxonomy/config/optional/views.view.taxonomy_term.yml` and scroll all the way to the bottom. You'll see this:

```
page_1:
    id: page_1
    display_title: Page
    display_plugin: page
    position: 1
    display_options:
      query:
        type: views_query
        options: {  }
      path: taxonomy/term/%
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_interface'
        - url
        - 'user.node_grants:view'
        - user.permissions
      max-age: -1
      tags: {  }

```

Note the presence of the `url` cache context. That describes that this view varies by URL, in particular by the value for the `%` wildcard in the `/taxonomy/term/%` URL.

# Answer
> 4 votes
You can read cache status inside the HTTP response header.

CASE: cache enabled

```
$ curl -I   d8.example.com/PathToYourView
HTTP/1.1 200 OK
...
X-Drupal-Dynamic-Cache: MISS

```

CASE: cache disabled

```
$ curl -I   d8.example.com/PathToYourView
HTTP/1.1 200 OK
...
X-Drupal-Dynamic-Cache: UNCACHEABLE

```

# Answer
> 3 votes
If enabled, the view should always be cached unless you are relying on a certain field/filter/sort/... plugin that disables caching. For example a random sort.

Filters, Arguments and many other contexts are considered when defining the cache key.

You can see if a view is cacheable by looking at the calculated cacheable metadata in the exported yml file.

---
Tags: views, 8, caching
---


# Question
Title: pagination broken on custom theme's search system page
I do not have pagination on the system search page .../search\*.

When I toggle off my custom theme I have pagination on the search-result.tpl.php page, I can see the `$pager` variable. But on my custom theme I cannot find that variable, it doesn't show up. I have checked hook\_query\_alter() throughout all of my site and I do not see any conflict. I checked the template.php file and there is no issue there. I will begin to remove everything, piece by piece to find out if I can find a solution.

No real code to show, and I would send you a stock search-results.tpl.php page, but the code block doesn't want to show it because `<?php ?>` is interspersed with html tags. It is something like:

```
if ($search_results) {  print t('search results');   print $pager; }

```

I simplified it because of the aformentioned issue, but this is essentially it - it is so minimal it is laughable and it works for any other theme, but mine. So I just copy the search-results.tpl.php file over to bartik, then do `drush cc -v all` and recheck and I can use xdebugger to see the `$pager` variable, but the same file with my custom theme I never get the `$pager` variable.

# Answer
> 0 votes
So i found out that a view on the search page had pagination and it caused a conflict with the search results pagination! I removed pagination in the View's configuration screen.

Removed the pagination of the pager settings.

---
Tags: 7, search, paging
---


# Question
Title: Unable to change theme that applies to view
In a drupal page view under `advanced=>Theme:Information=>Change Theme`, I'm able to select a theme from the dropdown. Custom templates I've created go bold as expected. But when I save the view and check the theme information, it always reverts to the site default theme. I've tried this with a custom theme I created and a view themes that came with my installation.

# Answer
> 1 votes
To use a different theme for a specific page, try the ThemeKey module. It allows you to define rules for automatically selecting a theme. You can create a rule to switch theme for a particular path, which is probably the one you want. Another useful one is to select the theme based on the user's role. For example you can test theme modifications on a production site by showing one theme for anonymous users and your work-in-progress theme for the administrator role

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


# Question
Title: import csv to build several nodes all at once
I'm new to Drupal. What's the easiest way to create multiple nodes on Drupal 7 all at once? I built a special content type and have the fields data in a CSV file.
Thank you

# Answer
> 1 votes
Yes there is, you can using:

## Feeds

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
>
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * **Import or aggregate CSV files**
> * Import or aggregate OPML files
> * PubSubHubbub support
> * **Create nodes**, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

Video Tutorial

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


# Question
Title: Display expiry date of licence in list of orders
I'm using Drupal Commerce and Commerce Licence.

I need to show in the list of orders in user profile, the expiry date of the purchased license.

I looked at the orders view, but it would seem that it is not possible to make a different view for "Commerce Order" and "Commerce licence".

Is there a solution?

# Answer
I simply added a relation and it worked! Thanks Neograph734
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How to print node id in a block in a module?
I have created a ctools jump menu in a block in a module. I need to get the node id for use in the links. How can I get the node id printed in the block?

Here is my code;

```
<?php

function boathood_block_info() {
$blocks = array();
$blocks['boathood_ABC'] = array(
'info' => t('Boathood Block'),
);
return $blocks;
}

 function boathood_block_view($delta = '') {
 $block = array();
switch ($delta) {
case 'boathood_ABC':
  $block['subject'] = '';
  $block['content'] = _boathood_BLOCK_ABC_CONTENT();
  break;
 }

  return $block;
  }

 function _boathood_BLOCK_ABC_CONTENT() {
$output = boathood_page();
 return $output;
 }

 function boathood_page() {
 global $user;
 ctools_include('ajax');
 drupal_add_js($sample_style, 'setting');
 ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
 ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');
 ctools_include('jump-menu');
 $form = drupal_get_form('boathood_jump_menu_form');
 $output .= drupal_render($form);
 return array('markup' => array('#markup' => $output));
 }

  function boathood_jump_menu_form() {

 $mynid = $node->nid;

 $url = url('node/' . $mynid);
 $url2 = url('node/' . $mynid);
 $url3 = url('node/' . $mynid);
$form_state = array();
$form = ctools_jump_menu(array(), $form_state, array($url =>    t('one!'),$url2 => t('two'),$url3 => t('three')), array());
return $form;
}

```

# Answer
> 3 votes
You can get the ID of the current full-page node with `menu_get_object`:

```
$node = menu_get_object();
if ($node) {
  // Do something with $node->nid
}

```

---
Tags: blocks, chaos-tool-suite
---


# Question
Title: Missing Main Page Content Block in Blocks List
I have the region for Main page content in my theme.info file which is `regions[content] = Content`. But still, in Blocks list, there is no Main page content block. This is causing me problems.

Can i re-create a new block with the same name. What should i do?

# Answer
> 1 votes
Recently had this issue. When I enabled my custom theme some files were missing and Drupal threw some errors and warnings. After adding the files everything worked fine except the Main page content block was missing.

To fix, I did the following:

* Set Bartik as the default theme
* Navigated to the block interface and configured the Main page content block (which was showing now that Bartik was the default theme)
* My custom theme was still enabled so it showed up in Region settings and I was able to select a region

Set my custom theme as the default again and all was good. Main page block was showing again.

---
Tags: blocks, theming
---


# Question
Title: I am trying to enable the jQuery UI module, but I am hitting with error
I am trying to enable the Jquery UI module in drupal 7, but I am hitting with error: The jQuery UI plugin is missing. Download and extract it to your jquery\_ui module directory. (Currently using jQuery UI Not found)

I downloaded and extracted the plugin from the link into my Jquery\_UI folder in sites/all/modules/jquery\_ui. still I could not enable the module.

# Answer
Looks like the module is expecting this structure:

`modules/jquery_ui/jquery.ui/(actual jquery ui files)`

However, it looks like jQuery UI library removed the version.txt file that this module checks for. If it does not find that text file, it considers the plugin 'not installed' which is kind of a bad check.

People are talking about it here, with a fix for Drupal 6 (and some talk for 7): https://www.drupal.org/node/1954136

However the project page advises you to use jQuery Update instead:

> Drupal 7+ Since Drupal 7 ships with jQuery UI, the jQuery UI module has been deprecated and moved to the jQuery Update module.

https://www.drupal.org/project/jquery\_update

You should dump this module and use jQuery Update and go from there.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Programmatically format integer field display
I am trying to programmatically format how an integer field displays. So far I have only been able to produce "1.00", and I am trying to get it like so: x.xx.x. The content type is "Project" and the field is "Drupal version".

Here is my code:

```
<!-- Display the drupal version with decimals -->
      <?php if (isset($node) && $node->type == 'project'): ?>
          <?php $drupal_version = field_view_field('node', $node, 'field_drupal_version', array('label'=>'default')); ?>

          <?php $formatted_drupal_version = number_format((float)$drupal_version, 2); ?>
          <?php echo "Drupal version: " . render($formatted_drupal_version); ?></span>
      <?php endif; ?>

```

output: Drupal version: 1.00

Does anyone know why this is the output, and how I can extend this function number\_format to produce something in this format x.xx.x, for example "Drupal version: 7.41.1" ?

Thanks!

# Answer
You can do this using the following code:

```
$drupal_version = (int)$drupal_version; // make sure this is an int
$parts = array();
preg_match('/^(\d{1})(\d{2})(\d+)$/', "$drupal_version", $parts);
array_shift($parts); // get rid of the first element in $parts which is the whole matched string
$formatted_drupal_version = implode($parts, '.');
echo "Drupal version: " . $formatted_drupal_version;

```

As examples, these integers will turn into the following strings:
7411 =\> 7.41.1
74110 =\> 7.41.10

Which means, that this code, will work parsing the provided integer from left to right, and collecting, 1 digit for the major version, 2 digits for the medium version, and all the remaining digits for the minor version.

Hope this helps!

P.S.: You question is a bit misleading, as @No Sssweat says, you cannot format an integer like that. That is why string parsing is the only way to provide you with the desired result.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: When creating content with new term, show all term fields for input also
Taxonomy terms are clubs and there are many in vocabulry, with fields to enter address, long/lat etc.

User adds content Concert and can pick a club (terms) from Simple Hierarchical select. If club is not in vocabulary user can add new term. While doing this he should also be able to input fields for new term (address, long/lat) while creating content.

How can i achieve this ?

# Answer
> 0 votes
You can use combination of two modules. First is Entity Reference, where you have to create your taxonomy term reference field. Then install module Inline Entity Form and use widget `Inline entity form - Multiple values` (in number of values of this field select: 1).

In node create form you will have then field, where you can select from existing terms (autocomplete) and also you will be able to create new term, if term does no exists - this will create inline form, which would have all fields specified in taxonomy vocabulary structure (see image below).

If you select existing term, or create new, it will looks like this:

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


title: Drupal Views Non-admin user permissions

text:
# Question
Title: Drupal Views Non-admin user permissions
I have a view that seeks to find users that have not filled in a form on the site which is a personal profile. It works correctly for admin user, but not for other user roles although the permissions have been set to allow this.

The view is a view of users and uses a relationship to their authored content.

The full view code is:

```
$view = new view();
$view->name = 'mentees_without_profiles_';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Mentees without profiles ';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Mentees without profiles ';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  3 => '3',
  6 => '6',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: User: Content authored */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'users';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = 'User Name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Field: User: E-mail */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['element_label_colon'] = FALSE;
/* Sort criterion: User: E-mail */
$handler->display->display_options['sorts']['mail']['id'] = 'mail';
$handler->display->display_options['sorts']['mail']['table'] = 'users';
$handler->display->display_options['sorts']['mail']['field'] = 'mail';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Roles */
$handler->display->display_options['filters']['rid']['id'] = 'rid';
$handler->display->display_options['filters']['rid']['table'] = 'users_roles';
$handler->display->display_options['filters']['rid']['field'] = 'rid';
$handler->display->display_options['filters']['rid']['value'] = array(
  4 => '4',
);
/* Filter criterion: Content: Title */
$handler->display->display_options['filters']['title']['id'] = 'title';
$handler->display->display_options['filters']['title']['table'] = 'node';
$handler->display->display_options['filters']['title']['field'] = 'title';
$handler->display->display_options['filters']['title']['relationship'] = 'uid';
$handler->display->display_options['filters']['title']['operator'] = 'empty';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'mentees-without-profiles';
$translatables['mentees_without_profiles_'] = array(
  t('Master'),
  t('Mentees without profiles '),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('nodes'),
  t('User Name'),
  t('E-mail'),
  t('Page'),
);

```

# Answer
> 2 votes
Check whether those users have the permission to view other user profile.

I am posting this as an answer instead of comment because I don't have enough reputation to add comment, so don't down vote it.

# Answer
> 0 votes
Even if you set the permission for view correctly, the problem won't be solved. There is a problem with the that relationship: "User: Content authored". Only admin can view the results. Issue submitted here

One solution recommended is to use Views Field View to create a view (name it form\_values\_view for example) that get the form values required then add a views field inside your view `mentees_without_profiles_` that read the values of view `form_values_view`.

you can also use module Views PHP filter and write your own handler

Another solution is to use Views Api to add your custom filter handler or use hook\_views\_query\_alter() and join your form tables then filter the view result

---
Tags: views
---


# Question
Title: Can I allow users to choose what input widget a Drupal field should use on a node by node basis?
This is a question I've asked on Stack Overflow but perhaps this is a better place for it. Apologies if this is seen as cross-posting...

I have a "transcription" field available within a content type in Drupal 7. Is there a way I can add a switch to allow the user to select whether that transcription content should allow tabular data input (via the TableField module) or whether it should be rich text/html?

# Answer
In your content type definition, create two different fields, eg: data\_tab and data\_text. Then have a third field where the user can indicate their format, and use the Conditional Fields module to display the correct data input field.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to facilitate meetings / events with participant registration, agenda and documents?
How to manage meetings in Drupal? I would like to do the following:

* Participants can register for an event or be added by the admin.
* The meeting has an agenda, consisting of a number of agenda points.
* Documents can be attached to the various agenda points.
* Participant details, the agenda and documents are shown.
* Record that the meeting is one in a series of meetings of the same group.

An example of what is needed is here, but the site is Joomla and it seems to be a custom module.

# Answer
There are many options in Drupal allowing you to add registrations to content. So if you add a content type of 'meeting', you can add file fields, dates and an agenda text field. Add a taxonomy field for grouping by type.

Then with any of the registration modules you can register users.

Basically it is not one module, but a combination of fields and modules to get the desired functionality.
> 2 votes

# Answer
# Use a distribution

Have a look at Open Atrium. Here are some details about it (from its project page):

> A new architecture for Drupal 7 that is built upon Organic Groups and Panopoly and intended as an extensible collaboration framework. Adds the ability to have private "sections" within a collaboration space with granular access control. Drag/drop layout control with dozens of widgets that can be placed on dashboards and landing pages. Comes with Discussions, Events, Files, Issue tracking, and Document Wiki out of the box, along with the dashboards to manage it all.

# Use modules that fit your needs

If you'd rather want to roll your own cookies, then there are quite some contributed modules that should help to get you going. Refer to my answers to these questions for more details:
> 1 votes

---
Tags: 7
---


title: Dynamically add User into a role

text:
# Question
Title: Dynamically add User into a role
I have set up a Drupal site to connect to an external payment gateway (not using Drupal Commerce) for subscription-based billing. So making use of Drupal Webform, I have created forms for users to provide their payment information. Live site will be behind SSL.

What I would like to know is:

1. Where do I start by taking the details of the completed Webform and submitting it to the Payment Gateway's XML web service? Essentially, what I'm looking for is some hook into when the form is filled in, to trigger some code (which I already have setup and tested in a separate plain PHP app) to call the Web Service; and then
2. Based on the response that I get from the Payment Gateway, to add the logged in user to a specific role?

Your help will be greatly appreciated! Thank you in advance

# Answer
> 1 votes
While you could utilize hooks like hook\_form\_FORM\_ID\_alter setting custom #validate & #submit functions or hook\_webform\_submission\_insert, I've had better success using the Payment module and writing a custom Payment Method class.

---
Tags: 7, webforms, users, payment-gateways
---