# Question
Title: How to send new content notifications based on taxonomy selection in user profiles?
I am building a website in Drupal 7 where the requirement is for users to sign up, create profile2 where they must select from a list of checkboxes pulled in from my interests taxonomy terms. For example: jobs, research collaboration, media interviews.

Once another user posts an opportunity (content type) I need to send all users a notification based on the interest categories selected when creating the opportunity (compared to each user's interest selections in profile2).

Probably the Rules module? Has anyone done anything like this before? I can't seem to wrap my head around the problem.

# Answer
> 2 votes
You may want to give it a try to *process the results of a VBO enabled view via Rules*, as detailed below.

### Step 1 - make it work for a single (1st) term

Remark: this is an intermediate step to prepare a prototype for Step 2 (if you have enough Rules experience, just start straight from Step 2).

Create a rule like so:

* Rules Event: After saving a node of type "Opportunity"
* Rules Condition: Check if the node was tagged with your 1st term, using "List contains item" (and the list to be checked being the field of the node that contains the interest categories).
* Rules Actions:

+ Load the VBO list of users that you want to be processed.
    + Add a loop to perform a Rules Action, for each row contained in your Views results. Within this Rules Action, you then send a notification to the user being processed.

Some more details about the VBO-view you'd have to create for this:

* The view should list all users who have some specific term selected (which corresponds to the 1st term).
* It should include an appropriate filter for the term ID to be processed.
* It should have exactly 1 result (row) for each user to be notified.
* One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

### Step 2 - make it work for all terms (not just the 1st term)

Since the Opportunity may have been tagged with multiple terms, you need to improve the solution from Step 1 to handle all the terms (not just the 1st one). To do so, these are the steps to improve the rule from Step 1:

* Add a "Rules Loop" as your very first Rules Action, to iterate over each term that the Opportunity was tagged with.
* For each term in this iteration, perform these sub-items:
    + check which term you're actually processing. This check is similar to the Rules Condition from Step 1, but you should use the Conditional Rules module to be able to include such Rules Condition as part of a Rules Action. BTW you can either use IF/THEN constructs, or CASE/WHEN constructs.
    + If the check succeeds, then perform a Rules Action similar to the Rules Action from Step 1.
* Remove the Rules Condition from Step 1 (it is now included via the previous check using Conditional Rules).

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


# Question
Title: How to filter Date Views with correctly timezone
I am using latest Drupal 8.2.5 for Live-score website. I have the Views for display all games daily. It's including DateTime for schedule and storing on Europe/London timezone (by default).

On the views FILTER CRITERIA, I added Match\_Date\_Fields between:

* Today
* +1 day

For getting the matchs from today events and next events. So, the views will filter by default timezone (london), sure. But when the visitor access to my site from Thailand. This filter seem to wrong. Because here difference between timezone from London to Thailand.

For example: The game is play on "January 15, 2017 19:45" for London timezone, but from Thailand it's "January 16, 2017 02:45".

I made it successfully print with depends on the local's time zone. But have no idea How to filter with correctly local's timezone?

# Answer
Ok, I made it working. My solution is created a custom drupal 8 module with the file: .views\_execution.inc inside your module folder.

Inside that, I added function modulename\_views\_query\_alter($view, $query) with:

```
//Filter by timezone for bettingsafe's local ip
switch ($view->element['#name']){
    case 'league_match':
        $key = 0;
        foreach ($query->where as $key => $value){
            $key_2 = 0;
            foreach ($value['conditions'] as $key2 => $condition){
                $length = strlen('DATE_FORMAT');
                if (substr($condition['field'], 0, $length) === 'DATE_FORMAT'){
                    $condition['field'] = str_replace('DATE_FORMAT(<date field>', 'DATE_FORMAT(CONVERT_TZ(<date field>, <from timezone>, <to timezone>')', $condition['field']);
                    $query->where[$key]['conditions'][$key_2]['field'] = $condition['field'];
                }
                $key_2+=1;
            }
            $key+=1;
        }
    break;
}

```

From my server Centos, I install the tool CONVERT\_TZ:

```
shell> mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql -p<sql root's password>

```

Restart mysqld and clear Drupal cache.

Hope that's will help someone.
> 0 votes

---
Tags: 8, views, datetime
---


# Question
Title: How do I change a theme based on the URL?
I have a Drupal instance running on example.org. Which has a theme X installed and activated. Now for a limited period an event is supposed to be held on the site for which a special section has been "carved out." All the things related to that event will go to example.org/event2011.

I want to have a different theme to be shown whenever a page under this section is viewed (e.g. http://example.org/event2011/about, http://example.org/event2011/node/123). How do I do that?

I have gone through many modules, but none of them is supporting Drupal 7. Preferably, I would like it to be done using modules and don't want to change anything my self at the code level.

# Answer
> 33 votes
Since the change is for a limited period of time, and implementing it isn't much difficult, I would suggest to create a custom module, or add the code to change the theme used for specific pages in an existing, suitable, custom module.

It is enough to implement `hook_custom_theme()`, for example using the following code.

```
function mymodule_custom_theme() {
  if (arg(0) == 'event2011') {
    return 'the theme to use for that page';
  }
}

```

If the theme must be changed for http://example.com/event2011, but not for http://example.com/event2011/node/123, code similar to the following one could be used.

```
function mymodule_custom_theme() {
  if (arg(0) == 'event2011' && !arg(1)) {
    return 'the theme to use for that page';
  }
}

```

As for using theme callbacks in a menu callback definition, the documentation says:

> As a general rule, the use of theme callback functions should be limited to pages whose functionality is very closely tied to a particular theme, since they can only be overridden by modules which specifically target those pages in `hook_menu_alter()`. Modules implementing more generic theme switching functionality (for example, a module which allows the theme to be set dynamically based on the current user's role) should use `hook_custom_theme()` instead.

# Answer
> 24 votes
A custom solution like the other comment suggests is probably best, but if you really want to use a module, your best bet is ThemeKey. As of 5/23/11, it has a stable release.

# Answer
> 9 votes
Alternatively you can use the new `theme callback` option of the menu system `hook_menu_alter()` as outlined below. p.s Checkout hook\_menu() for more details on the `theme callback`

```
<?php
/**
* Implements hook_menu_alter().
*/
function mymodule_menu_alter(&$items) {
  // Set the theme callback function for all node pages. As per the
  // standard behavior for hook_menu() properties, this will be
  // inherited by all paths underneath node/%node as well, unless
  // they define their own theme callback.
  $items['node/%node']['theme callback'] = 'mymodule_default_node_theme';

  // Set a different theme callback for node edit pages, and pass
  // along the node object to this function so we can make decisions
  // based on it.
  $items['node/%node/edit']['theme callback'] = 'mymodule_edit_node_theme';
  $items['node/%node/edit']['theme arguments'] = array(1);
}
/**
* Defaults to using the 'some_theme' theme for node pages.
*/
function mymodule_default_node_theme() {
  return 'some_theme';
}

/**
* For editing page nodes, uses the 'some_other_theme' theme.
*/
function mymodule_edit_node_theme($node) {
  return $node->type == 'page' ? 'some_other_theme' : mymodule_default_node_theme();
}
?>

```

Additionally there is also an example of using the more traditional `hook_custom_theme()`

```
<?php
/**
* Implements hook_custom_theme().
*/
function mymodule_custom_theme() {
  // check path using arg(0)
  // check $user
  // do whatever special checking you want and simply return theme key (name of theme folder most of the time)
    return 'special_theme';
  }
}
?>

```

*Taken from: http://drupal.org/node/224333#custom\_theme*

# Answer
> 7 votes
You can simply use Context and use the theme to get applied when the path is /event2011/ you can simple set the path in condition of cotext and change the theme in the action of the content. This was you can very easily switch between themes on a site based on URL. Even works for mobiles ;)

# Answer
> 7 votes
Using **ThemeKey** is simple and it's the most popular and powerful module so far (with support for 8.x) for theme switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. Beside the standard features ThemeKey automatically extends it's features of many contrib modules and has modules extending it.

**Usage (7.x)**

After enabling module, go to `admin/config/user-interface/themekey`. There are many options for switching the theme, but probably you would be interested with `path:node_alias`, so set the value as you want like you say /my\_url and then select the theme you want to enable at this url. You can also use wildcards such as `web/*` or `/^web/.*`.

Check: How Load a Theme For Path

**Advanced usage**

ThemeKey 7.x contains an optional module called ThemeKey Example to demonstrate developers how to extend ThemeKey.

**Help (7.x)**

Check out video tutorial by Mustardseed (7.x).

More help on that topic can be found at `/admin/help/themekey`.

Also check other SE questions related to .

---

Alternatively there is also Switchtheme (7.x) which adds a block to allow users to switch between enabled themes.

# Answer
> 6 votes
When using URL aliases or the Pathauto module, be aware of the subtleties and differences when using components of the current Drupal path.

There are situations where you may not want to use arg(). In fact, the Drupal API documentation actually suggests avoiding use of this function where possible, as resulting code is hard to read.

Consider the following example, as proposed by **kiamlaluno**:

```
function mymodule_custom_theme() {
  if (arg(0) == 'event2011') {
    return 'custom_theme_machine_name';
  }
}

```

In Drupal 7, if a node has an alias of *event2011*, using `arg(0)` will return `node` as the first URL component, as opposed to the alias.

```
print_r(arg(0));

Array
(
    [0] => node
    [1] => 150
)

```

Instead, if you need to work with an alias there are several ways to get the current URL in Drupal, including `menu_get_object()`, `current_path()`, `request_path()` and others.

Here's a re-worked example that uses an alias as a trigger for switching the theme:

```
function mymodule_custom_theme() {
  $current_page_path = explode('/', request_path());

  if ($current_page_path[0] == 'event2011') {
    return 'custom_theme_machine_name';
  }
}

```

# Answer
> 3 votes
How to switch theme depending on user role:

Create a custom module and copy & paste the following:

```
<?php
/**
 * Implementation of hook_init().
 */
function mymodule_init() {
  global $custom_theme, $user;
  if (in_array('my special role', $user->roles)) {
    $custom_theme = 'mytheme';
  }
}
?>

```

You have to replace:

`mymodule` =\> with your module name

my special role =\> with the name of the role that your users will need to have in order for them to see a different theme.

`mytheme` =\> with the name of the theme that you want to switch to

# Answer
> 2 votes
You could use the Page Theme module to achieve exactly that

> The Page Theme module is a simple and easy module to use which allows to use different themes than the site default on specific pages.
>
> Features
>
> * Assign a theme to a single page or list of pages. (Set a page as a Drupal path)
> * Allow to use '\*' character as a wildcard in Drupal paths.
> * Allow to arrange themes. (If pages are several defined, the first theme in the list will be used)
> * Allow to enable/disable a theme.
> * Drupal novice friendly.

# Answer
> 1 votes
If you want to use a theme that is different from the theme site default on content creating, editing, and viewing pages you can use the Content Theme module.

---
Tags: 7, theming, uri
---


title: Get Checkbox Value From Another Form

text:
# Question
Title: Get Checkbox Value From Another Form
How do i get the value of a checkbox from another form/page and how do i make it so if the checkbox is enabled, it'll allow a button to be visible?

checkbox in SettingsForm.php:

```
$form['#tree'] = TRUE;
    $form['clients_enabled'] = array(
      '#title' => t('Enable PixelPin OpenID Connect'),
      '#type' => 'checkboxes',
      '#options' => array('pixelpin' => $this->t('Enable')),
      '#default_value' => $clients_enabled,
    );

```

button ion LoginForm.php:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $definitions = $this->pluginManager->getDefinitions();
    foreach ($definitions as $client_id => $client) {
      foreach ($this->pluginManager->getDefinitions() as $client_name => $client_plugin) {
        if (!$this->config('pixelpin_openid_connect.settings.' . $client_id)
          ->get('enabled')) {
          $url = \Drupal::service('path.current')->getPath();

          $find = 'login';

          $pos = strpos($url, $find);

          if ($pos === false){
                $value = 'Register Using @client_title';
            } else {
                $value = 'Log in with @client_title';
            }

          $element = 'clients_enabled[' . $client_plugin['id'] . ']';
          $form['pixelpin_openid_connect_client_' . $client_id . '_login'] = array(
            '#type' => 'submit',
            '#value' => t($value, array(
              '@client_title' => $client['label'],
            )),
            'visible' => array(
              ':input[name="' . $element . '"]' => array('checked' => TRUE),
            ),
            '#name' => $client_id,
            '#prefix' => '<div>',
            '#suffix' => '</div>',
          );
        }
      }
    }
    return $form;

```

# Answer
> 0 votes
Create a config file inside `your_module/config/install/`.

Inside SettingsForm.php write,

```
$form['#tree'] = TRUE;
$form['clients_enabled'] = array(
  '#title' => t('Enable PixelPin OpenID Connect'),
  '#type' => 'checkboxes',
  '#options' => array('pixelpin' => $this->t('Enable')),
  '#default_value' => $clients_enabled,
);

public function submitForm(array &$form, FormStateInterface $form_state) {
  $config = $this->config('pixelpin_openid_connect.settings');
  $config->set('clients_enabled_key', $form_state->getValue('clients_enabled'))->save();

}

```

Inside LoginForm.php, get it :

```
public function buildForm(array $form, FormStateInterface $form_state) {
$definitions = $this->pluginManager->getDefinitions();
foreach ($definitions as $client_id => $client) {
  foreach ($this->pluginManager->getDefinitions() as $client_name => $client_plugin) {
$is_enabled = isset($this->config('pixelpin_openid_connect.settings')
      ->get('clients_enabled')) ? $this->config('pixelpin_openid_connect.settings')
      ->get('clients_enabled') : false;
    if ($is_enabled) {
      $url = \Drupal::service('path.current')->getPath();

      $find = 'login';

      $pos = strpos($url, $find);

      if ($pos === false){
            $value = 'Register Using @client_title';
        } else {
            $value = 'Log in with @client_title';
        }

      $element = 'clients_enabled[' . $client_plugin['id'] . ']';
      $form['pixelpin_openid_connect_client_' . $client_id . '_login'] = array(
        '#type' => 'submit',
        '#value' => t($value, array(
          '@client_title' => $client['label'],
        )),
        'visible' => array(
          ':input[name="' . $element . '"]' => array('checked' => TRUE),
        ),
        '#name' => $client_id,
        '#prefix' => '<div>',
        '#suffix' => '</div>',
      );
    }
  }
}
return $form;
}

```

---
Tags: 8, forms
---


# Question
Title: Drush pm-updatestatus No JSON output on success
My sites are running Drupal 7, Drush 8.0.3.

I'm creating a dashboard to check what core and module versions my Drupal sites are running (they're all on the same server). I use a shell script to get Drush to check available updates, write them to a JSON file then my dashboard script reads the JSON file.

```
/usr/local/bin/drush --root=/home/www/html/www.mysite.com rf
/usr/local/bin/drush --root=/home/www/html/www.mysite.com ups --security-only --format=json > /home/www/html-private/mysite.json

```

This works fine but the problem I have is that when there are no updates available I get an empty JSON file. How can I tell the difference between this and a failure to write the JSON properly? Can I get it to output 'No updates available' or something so I can tell it ran correctly?

# Answer
Did you check to see if `$?` is correctly set? It should be `0` for success, and `1` if there was an error. Please open an issue in the Drush queue if this is not the case.
> 0 votes

---
Tags: drush, updating
---


# Question
Title: Get Media entity field values in custom validation handler
I am trying to put a custom validation on node form which has paragraph attached to it. The problem is I am not getting paragraph field values available in form\_state of my validation handler.

I just see the delta of entites when I do a debug on form\_state

As in the screenshot field\_asset the entity\_reference\_revision referencing a media entity, I only see two entities attached in form\_state in custom submit handler on node\_form but how can I get value of those refernced entities?

Update: I realised it was not paragraph entity but media entity.

# Answer
Digging the form\_state I found the user submitted values for embedded media entites lies at form state storage. My validation code now looks like

```
/**
 * Implememts hook_form_alter().
 */
function mymodulename_form_alter(&$form, \Drupal \Core\Form\FormStateInterface $form_state, $form_id) {
  $operative_form = array(
    'my_node_add_form',
    'my_node_edit_form'
  );
  if (!in_array($form_id, $operative_form)) {
    return;
  }
  $form['#validate'][] = '_mymodulename_validate_element_node_form';
}

/**
 * Custom validation handler for EDP.
 */
function _mymodulename_validate_element_node_form($form, $form_state) {
  $form_storage = $form_state->getStorage();
  $form_storage_embed_entities = $form_storage['inline_entity_form'];
  foreach ($form_storage_embed_entities as $key => $value) {
    $media_entities = $value['entities'];
    foreach ($media_entities as $media_entity) {
      if ($media_entity['entity'] instanceof \Drupal\Core\Entity\EntityInterface) {
        if ($media_entity['entity']->getEntityTypeId() == 'media') {
          $asset_type[$media_entity['entity']->field_asset_type->value] = $media_entity['entity']->field_asset_type->value;
        }
      }
      if (count($asset_type) > 1) {
        // early bail.
        break;
      }
    }
    // Validation condition goes here.
    if ($validation_condition) {
      $form_state->setErrorByName('field_asset', t('Did you try turning it on and off.'));
    }
  }
}

```
> 0 votes

---
Tags: 8, media
---


# Question
Title: Views sort criteria by date does not order properly
I have a drupal 7 site with the most recent updates to core and the views module. I am trying to build a view to show three pieces of content (training events) that should display the three most recent pieces of content, based on the date field set by the user corresponding to the date of a training event (i.e. the input date set by the user, not the date of the content's creation). The date field to set to accept start and end times to show the duration of the event.

The view is based on the content type with the date field and I am trying to implement a sort criteria set on the date field in descending order. The issue I'm having is that the dates do not order as expected: the ordering that is output is as follows: March 7th, 2019; February 2nd, 2019; and then September 27th, 2016. The ordering is also incorrect for an ascending sort, with September 27th, 2016 followed by September 5th, 2016, and then February 2nd, 2019. The sort order seems to be incorrect regardless of which field I base sort ordering on (start date or end date), so I'm not sure what's going on here. I don't have the option to specify a granularity, so I'm not sure which value the dates are actually being ordered by. The ordering seems to disregard the ordering of months and individual dates, (e.g. ordering March before February in descending order, then ordering September 16th, 2016 before September 5th, 2016 in ascending order), so I'm not sure which value in the date the view is actually being sorted by. Any advice on how to approach this would be greatly appreciated.

Here is the export of the view:

```
$view = new view();
$view->name = 'upcoming_training_events';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Upcoming Training Events';
$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'] = 'Upcoming Training Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$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'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_date_of_training' => 'field_date_of_training',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_date_of_training' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['text'] = '[title]';
$handler->display->display_options['fields']['title']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['path'] = '[field_link_to_training]';
$handler->display->display_options['fields']['title']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['link_to_node'] = FALSE;
$handler->display->display_options['fields']['title']['node_in_colorbox_width'] = '600';
$handler->display->display_options['fields']['title']['node_in_colorbox_height'] = '600';
$handler->display->display_options['fields']['title']['node_in_colorbox_rel'] = '';
/* Field: Content: Training Description */
$handler->display->display_options['fields']['field_training_description']['id'] = 'field_training_description';
$handler->display->display_options['fields']['field_training_description']['table'] = 'field_data_field_training_description';
$handler->display->display_options['fields']['field_training_description']['field'] = 'field_training_description';
/* Field: Content: Date of Training */
$handler->display->display_options['fields']['field_date_of_training']['id'] = 'field_date_of_training';
$handler->display->display_options['fields']['field_date_of_training']['table'] = 'field_data_field_date_of_training';
$handler->display->display_options['fields']['field_date_of_training']['field'] = 'field_date_of_training';
$handler->display->display_options['fields']['field_date_of_training']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
  'show_remaining_days' => 0,
);
/* Field: Content: Link to Training */
$handler->display->display_options['fields']['field_link_to_training']['id'] = 'field_link_to_training';
$handler->display->display_options['fields']['field_link_to_training']['table'] = 'field_data_field_link_to_training';
$handler->display->display_options['fields']['field_link_to_training']['field'] = 'field_link_to_training';
$handler->display->display_options['fields']['field_link_to_training']['label'] = '';
$handler->display->display_options['fields']['field_link_to_training']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_link_to_training']['click_sort_column'] = 'url';
$handler->display->display_options['fields']['field_link_to_training']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_link_to_training']['multi_type'] = 'ul';
/* Sort criterion: Content: Date of Training -  start date (field_date_of_training) */
$handler->display->display_options['sorts']['field_date_of_training_value']['id'] = 'field_date_of_training_value';
$handler->display->display_options['sorts']['field_date_of_training_value']['table'] = 'field_data_field_date_of_training';
$handler->display->display_options['sorts']['field_date_of_training_value']['field'] = 'field_date_of_training_value';
$handler->display->display_options['sorts']['field_date_of_training_value']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$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: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'upcoming_training' => 'upcoming_training',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

**UPDATE**

Per comment request here are the results from `drush pml grep|date` Seems to be a conflict between date and commerce\_cart

```
PHP Fatal error:  Only variables can be passed by reference in /var/www/html/phisigmarho.org/sites/all/modules/commerce/modules/cart/commerce_cart.module on line 1344
PHP Stack trace:
PHP   1. {main}() /home/nizzok/.composer/vendor/drush/drush/drush.php:0
PHP   2. drush_main() /home/nizzok/.composer/vendor/drush/drush/drush.php:11
PHP   3. Drush\Boot\BaseBoot->bootstrap_and_dispatch() /home/nizzok/.composer/vendor/drush/drush/drush.php:70
PHP   4. drush_bootstrap_to_phase() /home/nizzok/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php:56
PHP   5. drush_bootstrap() /home/nizzok/.composer/vendor/drush/drush/includes/bootstrap.inc:429
PHP   6. Drush\Boot\DrupalBoot7->bootstrap_drupal_full() /home/nizzok/.composer/vendor/drush/drush/includes/bootstrap.inc:313
PHP   7. drupal_bootstrap() /home/nizzok/.composer/vendor/drush/drush/lib/Drush/Boot/DrupalBoot7.php:74
PHP   8. _drupal_bootstrap_full() /var/www/html/phisigmarho.org/includes/bootstrap.inc:2523
PHP   9. module_load_all() /var/www/html/phisigmarho.org/includes/common.inc:5267
PHP  10. drupal_load() /var/www/html/phisigmarho.org/includes/module.inc:24
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Only variables can be passed by reference in
/var/www/html/phisigmarho.org/sites/all/modules/commerce/modules/cart/commerce_cart.module,
line 1344

```

# Answer
> 0 votes
Could you try this view.

```
$view = new view();
$view->name = 'upcoming_training_events';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Upcoming Training Events';
$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'] = 'Upcoming Training Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$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'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_date_of_training' => 'field_date_of_training',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_date_of_training' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['text'] = '[title]';
$handler->display->display_options['fields']['title']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['path'] = '[field_link_to_training]';
$handler->display->display_options['fields']['title']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['link_to_node'] = FALSE;
$handler->display->display_options['fields']['title']['node_in_colorbox_width'] = '600';
$handler->display->display_options['fields']['title']['node_in_colorbox_height'] = '600';
$handler->display->display_options['fields']['title']['node_in_colorbox_rel'] = '';
/* Field: Content: Training Description */
$handler->display->display_options['fields']['field_training_description']['id'] = 'field_training_description';
$handler->display->display_options['fields']['field_training_description']['table'] = 'field_data_field_training_description';
$handler->display->display_options['fields']['field_training_description']['field'] = 'field_training_description';
/* Field: Content: Date of Training */
$handler->display->display_options['fields']['field_date_of_training']['id'] = 'field_date_of_training';
$handler->display->display_options['fields']['field_date_of_training']['table'] = 'field_data_field_date_of_training';
$handler->display->display_options['fields']['field_date_of_training']['field'] = 'field_date_of_training';
$handler->display->display_options['fields']['field_date_of_training']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
  'show_remaining_days' => 0,
);
/* Field: Content: Link to Training */
$handler->display->display_options['fields']['field_link_to_training']['id'] = 'field_link_to_training';
$handler->display->display_options['fields']['field_link_to_training']['table'] = 'field_data_field_link_to_training';
$handler->display->display_options['fields']['field_link_to_training']['field'] = 'field_link_to_training';
$handler->display->display_options['fields']['field_link_to_training']['label'] = '';
$handler->display->display_options['fields']['field_link_to_training']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_link_to_training']['click_sort_column'] = 'url';
$handler->display->display_options['fields']['field_link_to_training']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_link_to_training']['multi_type'] = 'ul';
/* Sort criterion: Content: Date of Training -  start date (field_date_of_training) */
$handler->display->display_options['sorts']['field_date_of_training_value']['id'] = 'field_date_of_training_value';
$handler->display->display_options['sorts']['field_date_of_training_value']['table'] = 'field_data_field_date_of_training';
$handler->display->display_options['sorts']['field_date_of_training_value']['field'] = 'field_date_of_training_value';
$handler->display->display_options['sorts']['field_date_of_training_value']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$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: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'upcoming_training' => 'upcoming_training',
);
$handler->display->display_options['filters']['type']['group'] = 1;
/* Filter criterion: Content: Date of training (field_date_of_training) */
$handler->display->display_options['filters']['field_date_of_training_value']['id'] = 'field_date_of_training_value';
$handler->display->display_options['filters']['field_date_of_training_value']['table'] = 'field_data_field_date_of_training';
$handler->display->display_options['filters']['field_date_of_training_value']['field'] = 'field_date_of_training_value';
$handler->display->display_options['filters']['field_date_of_training_value']['operator'] = '>';
$handler->display->display_options['filters']['field_date_of_training_value']['group'] = 1;
$handler->display->display_options['filters']['field_date_of_training_value']['default_date'] = 'now';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

---
Tags: 7, views
---


# Question
Title: help using hook_url_outbound_alter() to append "#id" to node/edit url
My node/edit form pages are long. When the user visits the node/edit page, I wish to direct the user toward the interesting part of that page. This part of the page has the id : `<div id = "my_id">`

I try to use hook\_url\_outbound\_alter to change the path node/xxx/edit into the path node/xxx/edit/#My\_id

I began testing for a specific example with the code below. But it doesn't work : the path stays as original.

```
function MY_MODULE_url_outbound_alter(&$path, &$options, $original_path) {
  if ($path == 'node/17609/edit?destination=node/17592') {
    $path = 'node/17609/edit?destination=node/17592#my_id';
  }
}

```

(I think that the Pathauto module could have done this but I can't install it on my website for incompatibility reason)

Thanks for your help

# Answer
> 0 votes
The `$options` parameter passed by reference to the `hook_url_outbound_alter()` implementations is described as follows. (Emphasis is mine.)

> `$options`: A set of URL options for the URL so elements such as **a fragment** or a **query string** can be added to the URL.

What that documentation page doesn't explicitly say is that `$options` is the same array `url()` accepts, which includes the following array indexes.

> * 'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
> * 'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.

---
Tags: hooks
---


# Question
Title: The "migration" entity type does not exist." error after switching site file structure
I am working on D6-\>D8 migration. We initially stared the site out using the \[drupal-project\](https://github.com/drupal-composer/drupal-project template), and I had my migration working. However, the site is hosted on Acquia, and Acquia requires a different file structure, so to get started, I spun up a D8 site on the Acquia free tier, and cloned that repo to my local. I got all my contrib modules and themes installed via Composer, and installed our custom modules, including my migration module. However, I am unable to bring up my site or even run a drush command (including trying to uninstall/install my migration module) because I get the following error:

```
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "migration" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

```

I have removed the migration configuration records from the config table and run a cache rebuild, but to no avail. I've also tried to run the `drush migrate-upgrade --configure-only` command, but I get this error:

```
Argument 3 passed to migrate_plus_migrate_prepare_row() must be an instance of Drupal\migrate\Entity\MigrationInterface, instance of    [error]
Drupal\migrate\Plugin\Migration given migrate_plus.module:66

```

How do I get around this?

Thanks.

# Answer
The proof is in your last error message, it was expecting an Entity but it is now getting a Plugin. Migrate changed from using Config Entities to Plugins in Drupal 8.1.x so I'm presuming you've somehow triggered an upgrade.

See the change record: https://www.drupal.org/node/2668742
> 2 votes

---
Tags: 8, migrations, configuration
---


# Question
Title: Status report for Commerce Kickstart 7.x-2.41 reads Not supported
Just upgraded from commerce\_kickstart-7.x-2.38 to commerce\_kickstart-7.x-2.41. When I view the status report it shows "Unsupported release" for module and theme update status. When I click on the list, it shows the following message:

> Distro Update Manager: libraries version 7.x-2.2 does not match .make file version 7.x-2.3 from commerce\_kickstart.

Any ideas how to fix this?

# Answer
> 0 votes
This is a common problem. The best solution, but not necessarily the easiest, is to use drush. You can find the instructions at Installing & upgrading Drupal Commerce under the "Updating your files" section.

**tl;dr**

Here’s the workflow. Be sure to backup your files and database first!

1. Move your */sites* folder, *.htaccess* and all non Drupal stuff out of your docroot
2. Delete your old *commerce\_kickstart* installation. Your docroot folder should be empty.
3. Run `drush dl commerce_kickstart`. It will fetch and intall the latest commerce\_kickstart version
4. Move back your */sites* folder, *.htaccess* from above
5. Run `drush updatedb -y`

# Answer
> 0 votes
So I figured out the problem. The .make file for commerce\_kickstart. was changed to reference version 7.x-2.3 of the Libraries module. This module is not included in core or in commerce kickstart, so the module is in my /sites directory. I was still running version 7.x-2.2. I upgraded to version 7.x-2.3 and the error went away.

---
Tags: 7, commerce
---


title: Dates disappear on 'Edit'

text:
# Question
Title: Dates disappear on 'Edit'
We are still on Drupal 6 which has worked fine for years, and I have not done any updates. We have Date/Time boxes on our "Events" items with pop-up boxes (see image). But since recently the when you 'Edit' an event the dates/times go blank, but they didn't use to. We've done nothing to alter the setup at all!

It is not only annoying, but as the 'Front Page' is set to Chronological order, if the date is blank the event disappears (past it's date presumably), so the author can't even see it to notice & correct it!

There is another question similar "when using Scheduler......" The only answer was "it must be a bug - report it" BUT it used to work fine, and we have not changed or updated anything (I don't know how to!) Apart from this the site works fine!

I am not a Drupal programmer so don't ask me to update any code! I presume it must be a 'setting' somewhere, or could it be to do with lack of memory????

one image is date/time boxes as they appear on editing, the other image is how they look when the event is first posted (or when dates re-entered)

Mike

# Answer
Try looking at yoursite.ca/admin/build/themes/settings.

When there, check that under "Display post information on" that your content type is checked.

After looking at this, it seems like a bug in the date module. Try updating the date module, but **make sure** that you have a **backup** of the site before doing so.

You should also soon upgrade to Drupal 7 or 8, as Drupal 6 sites risked being hacked.
> 0 votes

# Answer
I think this issue is the likely culprit: https://www.drupal.org/node/1808416

PHP version 5.4 and above caused some issues with the Date module in Drupal 6 that appear to match your symptoms.

The changes in the patch in comment #19 are probably what is needed.

This change should be included in the 2.10 release.

I would also recommend upgrading to Drupal 7 or 8 as soon as you can for security and longevity.

Hope this helps!

Finn
> 0 votes

---
Tags: 6
---


# Question
Title: How to pass a literal string into drush config-set
I'm currently attempting to configure the ClamAV module via `drush config-set`. When using the executable mode, the module allows us to specify command-line options to run when the ClamAV executable is triggered.

My attempt to do so is: `[root@localhost html]# drush config-set clamav.settings mode_executable.executable_parameters '--max-filesize=4095M --max-scansize=4095M --max-embeddedpe=4095M --max-htmlnormalize=4095M --max-htmlnotags=4095M --max-scriptnormalize=4095M --max-ziptypercg=4095M --pcre-max-filesize
=4095M' --y`

Unfortunately, I get the error: `Unknown option: --max-filesize. See`drush help config-set`for available options. To suppress this error, add the option --strict=0.`

Using sh/bash, how do I write this command as to pass in the executable parameters as the setting (a literal string), not as options to drush config-set, as is currently happening?

# Answer
> 1 votes
It's possible to use the `--value` option instead of inferring the value by location. See https://drushcommands.com/drush-8x/config/config-set/ for the config-set docs.

This won't work, due to a drush bug - see https://drupal.stackexchange.com/a/225739/64107)

`drush config-set clamav.settings mode_executable.executable_parameters '--max-filesize=4095M'`

but this will:

`drush config-set clamav.settings mode_executable.executable_parameters --value='--max-filesize=4095M'`

# Answer
> 2 votes
Short answer, preface the value with an empty space (inside the quotes).

This appears to be a drush bug. This fails with the unknown option bit:

```
drush config-set system.site name '--max-filesize=blah'

```

However, if I preface the value with a space:

```
drush config-set system.site name ' --max-filesize=blah'

```

this works as expected.

**Edit:** It is also worth noting that `drush config-edit` would bypass this issue altogether, and allow the value to be set via your preferred text editor.

---
Tags: 8, drush
---


title: How to redirect to modal?

text:
# Question
Title: How to redirect to modal?
I use the module "Bootstrap Login Modal".

How to redirect

```
/user/login

```

to

```
<a href="#" data-toggle="modal" data-target="#login-modal"></a>

```

all over the site ?

# Answer
*Edit*

According to the Readme.txt,

> You should now see login and register links on the right of the main bootstrap nav bar.

Enabling the module should show a link on the nav bar by default.

According to the project page,

> You should now see login and register links on the right of the main bootstrap nav bar.

*/Edit*

You can update all the links on your content, or use Javascript on a page load to modify them.

If you want to go with JS. This should get you started:

```
  var aTags = document.getElementsByTagName("a");
  for (var i = 0; i < aTags.length; i++) {
    if(atags[i].href == "/user/login") {
      //Modify your links
    }
  }

```
> 0 votes

---
Tags: 7
---


# Question
Title: Editing the 'default front page' base URL
I rebuilt a new server from another server's image. And I want to use it for a new domain, but I'm finding that the new server continues to redirect to the original server's domain.

Going to the new server's drupal admin console, I see that the domain (ie, https://mysite.com/) is uneditable under Configuration \> System \> Site Information \> Front Page \> Default Front Page.

I tried setting the 'base\_url' in /etc/drupal/7/sites/default/settings.php to my new domain and flushed the cache, but that didn't resolve the problem (and the old domain still persists in the console).

# Answer
Have you tried the below changes in your settings.php and .htaccess?

```
 /sites/default/settings.php

$base_url = 'http://www.example.com'; // NO trailing slash!

```

and

```
.htaccess

  # Modify the RewriteBase if you are using Drupal in a subdirectory and
  # RewriteBase /drupal

```

Try using this.
> 1 votes

# Answer
Have a closer look at settings.php the value may be hardcoded there

In particular: `$conf['site_frontpage']` or `$base_url`

You may also just need to flush all caches at Admin \> Config \> Performance
> 0 votes

# Answer
This could be set in a lot of places.

You should try searching all your code for mention of the previous domain and go from there.

```
grep -irn "example.com" .

```

Where `example.com` is the old domain.

This will list all matches of `example.com`. At the beginning you'll see the files. Then the line numbers. Then the string that it matched.
> 0 votes

---
Tags: 7, uri
---


title: Set site name in installation profile

text:
# Question
Title: Set site name in installation profile
I'm writing a custom installation profile, and most things work, except that I can't get it to change the site name.

```
function myprofile_install() {
  include_once DRUPAL_ROOT . '/profiles/standard/standard.install';
    standard_install();

    // ...

    variable_set('site_name', st('My Site Name'));

    // ...
}

```

the `variable_set` has no effect. So I tried adding

```
$GLOBALS['config']['site_name'] = "My Site Name";

```

at the end of the function to see if it got a different result, but it did not. Other parts of my profile work, so I know it's running. Other profiles seem to be able to use `variable_set` in their `hook_install`, so I don't think it's forbidden. Is there something else that I need to do to get the variables to "take"?

This question seems to indicate that I am doing it correctly, as do this one and this one. I've re-checed the RTFM and sample profiles to see if there's a step I'm missing, but if there is, I can't find it. The title of this question looked promising, but it turned out to be an unrelated issue.

If I add an echo statement inside of `myprofile_install` it indicates that the value has been set properly (and that the `myprofile_install` function is being read all the way through), but when I log into the site, it has the default 'site-install' name.

I am building the site via a drush command, not via the gui:

```
drush -y si myprofile --db-url=mysql://###:###@localhost:8080/mysite username=### pass=### dbname=###

```

**In response to @clive's comment** (thanks!), I neglected to mention that I also have

```
function myprofile_form_install_configure_form_alter(&$form, $form_state) {
    if (!function_exists("system_form_install_configure_form_alter")) {
        function system_form_install_configure_form_alter(&$form, $form_state) {
            $form['site_information']['site_name']['#default_value'] = 'mysite';
        }
    }
 }

```

in the `.profile` file. I assumed this code wasn't being called at all, since I wasn't using the gui form. But if the form were invisibly clobbering the values I set in the `.install` file, it seems like it would be setting it to `mysite` rather than to `site-install`?

# Answer
The work-around that I'm currently using (because I really need to move on and accomplish other things) is to add a

```
drush -y vset site_name "My Site"

```

call to the bash script that I'm using to create the mysql database and run the installation. Not an elegant solution, (and it bypasses localization, but that's not an issue yet, since the site is currently in only one language), but it gets the job done for now so that I can get other things working.

Leaving this here in case it helps someone, but not "accepting" it, since it's a work-around, not an answer.
> 0 votes

# Answer
For Drupal 8 you need to perform this drush command:

```
drush config-set system.site name 'Project X'

```
> 0 votes

---
Tags: installation-profiles
---


title: Site search plus google search

text:
# Question
Title: Site search plus google search
I am searching for a way to have the drupal search pull up pages from the drupal site PLUS search results from google in general (not site specific search). Does anyone know some direction how to accomplish this?

# Answer
> 0 votes
You need to check with this two Google Site Search & Google Custom Search Engine modules.

---
Tags: search
---


# Question
Title: How can I set “This block (override)” programmatically on a view's display
I need help about a specific implementation in Drupal 8.

I have been trying for two days to create a view programmatically, or more precisely to create a new display of an existing view.

The objective is to create (at the same time as creating new content) a duplicate display of a view, which is almost the same than the original, with just the title and a condition in filter criteria (a node id) changed, in order that the final user never needs to add display or modify the view.

The issue that I am coming up against is that the generated view's display lost an important property, the “This block (override)” parameter is replaced by the default state “All displays (excepts overridden)” so once I have generated the second view’s display programmatically, the first view’s display has its properties (title, filter criteria) replaced inevitably by the values of the second.

So I would like to programmatically set the parameter “All displays (excepts overridden)” at “This block (override)” but I haven’t found anything of relevance in the D8 API.

Thank you in advance for any ideas or suggestions.

function HOOK\_node\_insert(Drupal\Core\Entity\EntityInterface $node) {

```
if ($node->type->target_id == "SPECIFIC_CONTENT_TYPE") {

    $node_title = $node->getTitle();
    $node_id = $node->id();
    $machine_title = strtolower(str_replace(" ","_",$node_title));
    $block_id = 'block_'.$machine_title;

    $view = Views::getView("api_domain");//"api_domain" is the view's machine name
    if (empty($view)) {
        return;
    }
    $display_id = 'default';
    if (!$view->access($display_id)) {
        return;
    }

    $view->newDisplay('block',$node_title, $block_id);
    $options_array = array(
        'id' => 'field_api_domain_target_id',
        'table' => 'node__field_api_domain',
        'field' => 'field_api_domain_target_id',
        'relationship' => 'none',
        'group_type' => 'group',
        'admin_label' => '',
        'operator' => '=', 'value' =>  array('value' => $node_id));

    $view->setHandler($display_id, 'filter', 'field_api_domain_target_id', $options_array);//works
    //$view->setTitle($node_title);//doesn't works
    $view->display_handler->setOption('title', $node_title);// works
    //$view->display_handler->overrideOption('title', $node_title);// works too, but the "override" problem still persists
    $view->save();
}

```

}

# Answer
> 0 votes
If you can't find a way to do this with the methods of Views API, you can try another approach by using the view entity (storage), which provides a more direct access to the display settings in an array.

**Example**

```
$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
// add a new display
$storage->addDisplay('block', $new_title, $block_id);
// get the new display by reference
$new_display = &$storage->getDisplay($block_id);
// copy the configuration and change the filter settings
$old_display = $storage->getDisplay($old_display_id);
$new_display = array_replace_recursive($old_display, $new_display);
$new_display['display_options']['filters']['nid']['value']['value'] = 123;

$storage->save();

```

---
Tags: views, 8, hooks
---


# Question
Title: Create a content type node programmatically
I have a content type called **`ip_range`** and i was trying to create a node **programmatically** . I tried the follows :

```
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
    $data = array(
      'type' => 'ip_range',
      'title' => '192.168.7.100/24',
      'field_ip_range_gw' => '192.168.7.100',
      'field_ip_range_hidden' => '',
      'field_ip_range_blocked' => '192.168.7.200',
      'field_ip_range_access_type' => 'Blocked',
      'field_ip_threshold' => '20',
      'field_ip_range_sec_zone' => 'C2',
      'field_ip_range_vlan_name' => 'Network58',
      'field_ip_range_vlan_tag' => '4054',
      'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
    );
    $node = Drupal::entityManager()
      ->getStorage('node')
      ->create($data);

    $node->save();

```

But its not creating any . Any idea ?

**UPDATE**

---

Its creating the node . But its creating as **anonymous** user . So i cant see it in front end . That was the problem . How to create it as a admin user ?

# Answer
> 4 votes
Try this Code in **MigrateContentController**:

```
<?php

namespace Drupal\migrate_contents\Controller;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;

class MigrateContentController extends ControllerBase {

 function migrateContent() {
 $updated = 0;
 $data = array(
   'type' => 'ip_range',
   'title' => '192.168.7.100/24',
   'field_ip_range_gw' => '192.168.7.100',
   'field_ip_range_hidden' => '',
   'field_ip_range_blocked' => '192.168.7.200',
   'field_ip_range_access_type' => 'Blocked',
   'field_ip_threshold' => '20',
   'field_ip_range_sec_zone' => 'C2',
   'field_ip_range_vlan_name' => 'Network58',
   'field_ip_range_vlan_tag' => '4054',
   'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
 );
 $node = Node::create($data);
 $node->save();
 $updated++;

 return array(
   '#markup' => $updated,
 );
 }
}

```

> Inside your\_module.routing.yml

```
migrate_contents.migrate_node:
  path: '/migrate-contents'
    defaults:
    _controller: 'Drupal\migrate_contents\Controller\MigrateContentController::migrateContent'
    _title: 'Migrate Contents'
  options:
    _admin_route: TRUE

```

**Note**: Clear the cache before proceeding.

---
Tags: nodes, 8
---


# Question
Title: Access denied page for users without permission "View published content"
My site access is only for registred users, then when you try to access drupal returns the "access denied" page. I want to customize my "access denied" page but the anonymous user doesn't have the "View published content" permission. Then they can't see a basic page node with my access node page customization.

How can I resolve this ? -It can be a static html (but I don't know how to redirect when this error is raised). But drupal throws an error when I put in /admin/config/system/site-information because isn't a drupal path -If is a node (my access denied page) how can I grant the anonymous users to view ?

I'm using Drupal 8

# Answer
> 1 votes
You can try Custom error module, It allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.

---
Tags: 8, users
---


title: How to suppress default HtmlException?

text:
# Question
Title: How to suppress default HtmlException?
I need to turn off 404 & related Exceptions. Need to handle it in custom way.

I've implemented an `EventSubscriber` with listener for `kernel.exception` event.

But `$event->setException()` cannot receive NULL.

Any ideas?

# Answer
This is the correct approach. Don't do all the work yourself, extend `DefaultExceptionHtmlSubscriber` for 403/404 or `HttpExceptionSubscriberBase` for general exceptions.

As example see this question for access denied: How can we catch the acces denied exception in drupal 8

The most important thing is to use a higher priority than the core event you want to override.
> 3 votes

---
Tags: 8, event-subscribers
---


# Question
Title: How to: Admin flags content, owners of content gets email nofication
I'm building a site where users of the role Contributor submits content (songs). Songs gets rated by users of the role Curator and the best rated Songs are added to Playlists by the Admin.

The Admin is presented with the best rated tracks in a Views table. I'd like to have a flag on each Song with these values:

* Playlist add confirmed
* Playlist add pending (default mode)

When admin flags the Song with the 'Playlist add confirmed' mode this should fire an email (via rules?) to the Contributor who submitted the Song in mention notifying the Contributor of the good news.

The admin table of best rated tracks are ready and working but I'm stuck at getting the Flags and email notifications working.

How would you do this?

# Answer
> 1 votes
# Part 1 - Rules Component to send an eMail

Here is a Rules Component (in Rules export format) to send an eMail to a user indicated as a parameter of the Rules Component (adapt the subject and eMail body to your own needs):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Your eMail subject goes here ...",
          "message" : "Your message body goes here ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

# Part 2 - Rule to trigger the Rules Component

Here is the rule (in Rules export format) to execute the Rules Component from Part 1 (adapt the machine name of the flag you're using prior to importing it in your own site):

```
{ "rules_send_email_to_author_of_a_flagged_node" : {
    "LABEL" : "Send eMail to author of a flagged node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_playlist_confirmation" : [] },
    "DO" : [
      { "component_rules_send_email_notification" : { "user_to_notify" : [ "flagged-node:author" ] } }
    ]
  }
}

```

This rule gets triggered (Rules Event) when a node is flagged with a flag that has machine name `playlist_confirmation`. Note the value of the parameter passed to the Rules Component, i.e. `flagged-node:author` (the author of the node being flagged). Obviously, you want to limit access to this flag to users like your admin only.

That's really it.

PS: you don't really need to use a Rules Component, since you could "integrate" (hardcode) what the Rules Component does in your actual rule also. So that's rather a matter of coding style. If you'd make your eMail subject and message body another parameter for the Rules Component, you can re-use that Rules Component for all sorts of eMails you want to send via Rules. And if some day you'd want to replace sending eMails (by Rules) by using the (amazing) Message module, you'd only have to adapt your Rules Component for it.

---
Tags: views, rules, flags
---


# Question
Title: Where is the content of the pop up bubble in my form validation coming from?
I use the Clientside Validation module for my webforms.

I get a "Please enter an email address" pop up bubble next to the email text field when an incorrect email is entered. I am not quite sure where this is coming from.

I would prefer this functionality instead:

> Submitting the form with an empty email field displays a different error message to when an invalid email is entered eg. http://validation7.ubu001.attiks.com/node/1?utm\_medium=atix&utm\_source=cv7b

Can anyone shed some light about it?

# Answer
> 4 votes
In our instance we used clumsyfingers's code but with parsing fix:

novalidate cannot be "1". It has to be either:

* no value
* empty value
* value = attribute name

like so:

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

  if(strstr($form_id,'webform') !== FALSE) {
    // prevent html5 validation, i.e. on input type="email" fields
    form['#attributes']['novalidate'] = 'novalidate';
  }

}

```

CSE HTML validator was returning this message:

> The "novalidate" attribute for the "form" element has an invalid value "1". This is a boolean (true or false) attribute. The presence of a boolean attribute represents true and absense of the attribute represents false. Setting a value is not necessary, but if a value is set, then it must be an empty string or be a case-insensitive match for the attribute's name. NOTE: Never use the values "true" and "false".

# Answer
> 2 votes
Know this was asked a little while ago, but started investigating and found a "solution". Apparently when Webform has a form component with type "Email" it sets the input type to "email". On browsers IE8+ and modern browsers (Chrome, FF) there is an automatic, browser-side verification on these fields. It's nothing to do with the script. It seems to be an html5 "feature", see https://stackoverflow.com/questions/9399528/disable-form-validation-in-browser.

Two options:

1. Don't use the "Email" type in Webforms. This kind of breaks the ability to use form values as "To" or "From" emails in the Webform Emails feature, so it's not great.
2. Add the *novalidate* rule to the \<form\> generated by Webform. I do so via a custom hook:

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

  if(strstr($form_id,'webform') !== FALSE) {
    // prevent html5 validation, i.e. on input type="email" fields
    form['#attributes']['novalidate'] = '1';
  }

}

```

This is just if you want to remove it. Now you can use Webform clientside validation module to set custom messages. Or you can style like here: https://stackoverflow.com/questions/5713405/how-do-you-style-the-html5-form-validation-messages

# Answer
> 0 votes
Client-side validation in this context means you let the browser check the validity of form elements. And every browser then comes with its own pop-ups you don't really have much control about. So, yeah, maybe you should get rid of this module first ^^ And then make use of Drupal's Form API and for example use `#element_validate`

---

I stumbled upon this post while looking for a way to disable client-side form validation in Drupal 8. My problem was when I use `$form['#attributes']['novalidate'] = 'novalidate'` (like suggested in on of the other answers) then the `novalidate` attribute gets added to the form wrapper instead of to the form itself. This doesn't prevent client-side validation. Form elements still validate in the browser.

Finally solved it by adding the following JS globally:

```
$('form').attr('novalidate', 'novalidate');

```

---
Tags: forms
---


# Question
Title: How to prevent the results from being truncated?
I want to remove the limit of character imposed from Drupal 7 on the search result page. That is, displaying my result in full rather than truncating the results and adding ... at the beginning and end of the result. I already have a search-results.tpl.php in my templates and looks like that:

```
<?php if ($search_results): ?>
<?php print $search_totals.' << '.str_replace('%20',' ',basename($_SERVER['REQUEST_URI'])).'>>';?>
  <ol class="search-results test <?php print $module; ?>-results">
    <?php print $search_results; ?>
  </ol>
  <?php print $pager; ?>
<?php else : ?>
  <h2><?php print t('Your search yielded no results');?></h2>
  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

```

How can I prevent the results from being truncated?

# Answer
> 1 votes
You can simply add a new view mode for search results:

1. Go to `admin/structure/types/manage/page/display` (where "page" is your content type)
2. Expand the `Show Custom display settings` fieldset
3. Check `Search index`

4. Click Save
5. Go to `admin/structure/types/manage/page/display/search_index` (again, where "page" is your content type)

My advice would be to use download the Display Suite module (and enable the Display Suite module and Display Suite UI module) for extra fields and more options. No custom theming or coding required!

---
Tags: 7, search
---


# Question
Title: How can I cache the operations on the admin content overview per user?
The `admin/content` view page gets cached, but the operations column is different for the various users. When a user visits the page after the cache is cleared, their operations are correct. Another user, with the same role, may have different access to other nodes, but the result of the first user is shown =\> this leads to unwanted, in `access denied` resulting edit buttons.

I installed Views Custom Cache Tags and set the cache tag to user:\[user:id\], but it didnt work (looking at the module I'd guess it supports tokens).

How can I set that the output of `admin/content` is cached per user? I dont want to completely disable the cache for that view.

# Answer
> 1 votes
This is not a cache tag issue. You need a cache context.

You can use a contextual filter for the user, then Views would add the cache context automatically.

Another option is to add the context to the render array of the View:

```
function mymodule_views_pre_render($view) {
  if ($view->id() == 'content') {
    $view->element['#cache']['contexts'][] = 'user';
  }
}

```

The cache context `user.permissions` is used by default in drupal caching. If this doesn't give you the variations you need in cache use the more general `user` context. Then for each user a new version of the View is cached, which will obviously use more database space.

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


# Question
Title: How to link a view´s field to attachment´s field?
I am stuck with links in views. I need to rewrite one field of a view to a link to a field of view´s attachment.

Basicaly: view displays a grid of images. This view has an attachment. In the attachment is a list of \[body\]. The click on the image should navigate to appropriate \[body\] in the attachment.

I have set view (with exposed filter, relationships...), but I cannot think how to set up the link. I added field: nid to the attachment, but still don´t know how to link to it from the main view. Maybe I did something wrong, still learning on the go. Could you, please, help me?

# Answer
So, my mistake, it is quiet simple. If you struggle with similar problem: in the Attachment: -add a field content: NID, hidden

-In global: custom text add, for example, `<h3 class=[nid]>[title]</h3>`

This way we have an NID anchor we can link to.

In the block view: -add a field content: NID, hidden (so our link field gets NID as a value, not as a string "nid")

-we rewrite some field (for example title): output this field as a link. Link path: `#[nid]`

Voila, it works. My problem was I forgot to include content: nid in block view.
> 0 votes

---
Tags: views, entities
---


title: How to display vocabulary?

text:
# Question
Title: How to display vocabulary?
I want to display all the vocabulary that i've created in the /fr/admin/structure/taxonomy page and each vocabulary linked to the list of terms it containes.

How can display them in a page ?

# Answer
> 0 votes
I've done this by creating a view only. Please find the attached screenshots.

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


# Question
Title: Email sending doesn't work through Webform
I'm trying to get drupal webform to send confirmation emails to logged in users after they validated a booking form. (Windows and IIS Server)

I monitored Drupal Log reports/dblog and got this:

```
Notice : Undefined index: und in eval() (line 22 in   C:\.....\modules\php\php.module(80) : eval()'d code)

```

Also, after submitting the booking form it gives this error: *Impossible to send mails, please contact administrator if problem persists.*

And to add, generally Mail sending works when tryin to reset my admin password.

Apparently I'm not the only one with this problem.

# Answer
> 0 votes
It appears you're running your site on Windows. Either IIS or Apache?

Sending mail on windows based servers is a bit different. It cannot used php's normal method for sending mail if it were on a linux server.

You must configure an SMTP server in either your PHP.ini, or leverage the SMTP Auth module and connect to an SMTP server.

PHP.ini setup:

---
Tags: emails
---


# Question
Title: Installing Bootstrap theme using Composer
I am new to using Composer.

How can I install a theme, say https://www.drupal.org/project/bootstrap using **composer**

I've tried:

```
composer require drupal/bootstrap

```

But didn't work.

I also tried:

```
composer require twbs/bootstrap

```

Installation was completed successfully but I couldn't see the theme appearing at Drupal admin page.

What is the standard way to extract the name of the theme or module to be used with `composer require`?

# Answer
> 8 votes
That is because every Drupal package is at `drupal/` \- `twbs` is not in the Drupal packagist. You have to add that to composer to get that to work as Clive said.

It is **not** in the composer.json file out of the box.

You need to add that, and then do:

`composer remove twbs/bootstrap` because this is NOT a Drupal ready theme.

After adding the repository to composer.json, *then* you can do:

`composer require drupal/bootstrap`

Also, not every module or theme has a composer.json file yet. Bootstrap for Drupal does, and thats where you can determine what the package name is if you are unsure.

http://cgit.drupalcode.org/bootstrap/tree/composer.json

I believe modules/themes **have** to provide this file in order to work with composer (**including** the repository addition in Clives answer).

Here is one of my projects composer.json, for example. Note the addition of the **repositories** and Drupal packages URL.

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/search_api_solr": "1.0.0-beta1",
        "drupal/search_api": "^1.0@beta"
    },
    "replace": {
        "drupal/core": "~8.2"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url":  "https://packages.drupal.org/8"
        }
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "modules/contrib/{$name}": ["type:drupal-module"],
            "themes/contrib/{$name}": ["type:drupal-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    }
}

```

The lack of the packages repository in composer.json is a small, easily missed and often overlooked thing. Hopefully it will be added in a future release.

# Answer
> 4 votes
You need to add the Drupal repository location to your composer.json file, e.g.

```
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

```

---
Tags: theming, 8, composer
---


title: Set panel width

text:
# Question
Title: Set panel width
I'm trying to set a panel width, I'm using the "two columns stacked" layout, but I want that one column is 2/3 width and the other 1/3. Is 50% by default.

By default looks like this:

If I put this in my theme css:

```
.panel-2col-stacked > .panel-panel > .block-region-left {
    width: 66%;
}
.panel-2col-stacked > .panel-panel > .block-region-right {
    width: 34%;
}

```

I looks like

What I have to achieve that the panels take all the space available as in the first screenshot ?

I'm using a bootstrap subtheme with fluid container enabled (I don't know if this is important)

# Answer
> 0 votes
Sorry, the CSS code is wrong. I have made it work with.

```
.panel-2col-stacked > .panel-panel:nth-child(2) {
     flex: 0 1 65%;
}
.panel-2col-stacked > .panel-panel:nth-child(3) {
     flex: 0 1 34%;
}

```

But, I finally I dicided to create my own layout.

I created my mytheme.layouts.yml

```
  two_column_66_34:
  label: Two Column 66/34
  category: La Liga News
  path: layouts/twocol_66_34
  template: twocol_66_34
  css: twocol_66_34.css
  regions:
    top:
      label: Top
    left:
      label: Left side
    right:
      label: Right side

```

then I created in the layouts/twocol\_66\_34 directory

the twig template, named twocol\_66\_34.html.twig

```
  <div class="panel-2col_66_34" {% if css_id %}{{ css_id }}{% endif %}>
  <div class="panel-panel panel-full-width">
    {{ content.top }}
  </div>

  <div class="panel-panel panel-col-left">
    {{ content.left }}
  </div>

  <div class="panel-panel panel-col-right">
    {{ content.right }}
  </div>
</div>

```

and its CSS (also in layouts/twocol\_66\_34) named twocol\_66\_34.css

```
.panel-2col_66_34 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.panel-2col_66_34 > .panel-col-left {
  flex: 0 1 65%;
}

.panel-2col_66_34 > .panel-col-right {
  flex: 0 1 34%;
}

.panel-2col_66_34 > .panel-full-width {
  flex: 0 1 100%;
}

```

More info at How to register layouts with Layout Plugin

---
Tags: theming, 8, panels
---


title: Implementing custom entity forms

text:
# Question
Title: Implementing custom entity forms
In **Making use of the admin UI, Step 3 - Implement the entity adding/editing form**, it says that you need to implement "a" form with the **ENTITY\_TYPE\_form()** signature for add/edit/clone operations...

However the wiki page is not specific in regards to whether you should implement one or two forms. I explain - the example creates two "entities": a "regular" entity, and a "bundle" entity. The example then implements ENTITY\_TYPE\_form() for the "bundle" kind of entity ONLY.

In attempt two answer the question: "Should I implement one or two forms?" I looked at the source code of both the Model and the Profile2 modules. The source of my confusion is that the Profile2 module implements only one form - like in the example \- for the "bundle" kind of entity. But on the other hand the Model module implements two forms: one for the "regular" entity, and another one for the "bundle" entity. Why? What's the correct use case? What's the difference between the two implementations? What additional ability does implementing the "regular" entity form give us, if any?

# Answer
You're essentially correct I think. You can write a hard-coded Entity or make something more flexible supporting bundles (hard coded bundles, or say user-defined bundles like the Profile2 module) .... it can get as complicated as you want! :D

Have you seen this sandbox released a few days ago showing the mimimum for 1 hardcoded entity using Drupal core API and then an Entity supporting bundles via the EntityAPI.

https://drupal.org/sandbox/AlexanderAllen/2062531

> This module aims to provide a developer friendly, ready to use, barebones implementation of a custom Entity.
>
> The master branch provides a single, hardcoded entity (bundles are not supported), lacks entity revisioning support, and the only CRUD operation supported is save(). At a total of 16 functions, 4 files, one class and one method - the mater branch is recommended for understanding what is the bare minimum needed to create a custom Entity by code - using the Drupal core Entity API only.
>
> The bundles branch adds bundle and automatic CRUD support with the help of the Entity API contributed module.
>
> This module was inspired by the Profile2 and Model modules. This module is simpler than Model in that it uses the default UI and Entity controllers. If you're already comfortable with Entities, you should refer to the Model module instead for help with creating custom UI and Entity controllers.
> 0 votes

# Answer
There are actually two entities in play in both examples. Model has two entity types, model and model\_type. Profile2 also has two, profile2 and profile2\_type.

The different bundle types are defined by the respective bundle entities.

In your example, the profile2 module only defines a form to create/edit bundles for the profile2 entity.

The model module in your example, defines a form for adding/editing both the bundle types for the entity, as well as the entity itself.

To answer your question. You will want one \_form hook for each entity you want to be able to edit/insert. If you want to be able to manipulate the bundle entity and the entity using forms, you will need to form hooks.

If you only want a form for one of them, you'll need only one form hook.
> 0 votes

---
Tags: 7, forms, entities
---


# Question
Title: Programmatically get the date field value
All I want to do is get the value out of a date field in Drupal 8, but they have done an expert job of making this impossible. The error I get is that 'dateTimeObject' is protected so I have no access to it.

# Answer
**Try this out** -

```
$schedule_start = $form_state->getValue('field_start')->format("Y-m-d H:i:s");
$schedule_end = $form_state->getValue('field_end')->format("Y-m-d H:i:s");

```

Provide your own desirable format.
> 5 votes

---
Tags: 8, entities, datetime
---


# Question
Title: Adding the is_front variable to a Paragraphs template
Is the is\_front variable not available in a Paragraphs template override?

I'm trying to do the following:

```
    <div{{ attributes.addClass(classes) }}>
      <div class="row">
        <div class="col-sm-7">
          {% if is_front and content.field_section_title %}
            <h2>{{ content.field_section_title }}</h2>
          {% elseif content.field_section_title %}
            <h4>{{ content.field_section_title }}</h4>
          {% endif %}

          {{ content.field_text }}
        </div>
        <div class="col-sm-5">
          {{ content.field_section_image }}
        </div>
       </div>
     </div>

```

However, when I set a node that uses this paragraph type as the homepage, it doesn't take the is\_front condition and just uses the h4 tag instead of the h2 which is what I would like for it to do.

Is there a way for my paragraphs templates to use the is\_front condition? Or is there a different way to go about this?

# Answer
> 5 votes
You should be able to add this with a preprocess function in `mytheme.theme` of your theme.

```
/**
 * Implements hook_preprocess_paragraph().
 * @param $variables
 */
function mytheme_preprocess_paragraph(&$variables) {
  $variables['is_front'] = Drupal::service('path.matcher')->isFrontPage();

  // Ensure the cache varies correctly.
  // Drupal 8.2.x or lower
  $variables['#cache']['contexts'][] = 'url.path';

  // Ensure the cache varies correctly.
  // Drupal 8.3.x+
  $variables['#cache']['contexts'][] = 'url.path.is_front';
}

```

This should add `is_front` as a variable to any paragraph twig template. Clear cache after adding this code.

Per 4k4's comment, if this is Drupal 8.3 you will also need to add a cache context.

---
Tags: theming, 8
---


# Question
Title: How do I apply a discount for the second and successive items only if the quantity for those items is higher than 1?
Using *Commerce Discount* and *Commerce Discount Extra* modules there is no problem to set discount rule conditions for product type and quantity. This way I can set up 20% off discount that is applied for a cart line item when this line item has specific product type and quantity more than one. 20% off discount is then calculated for this line item and multiplied by quantity.

However, my need is to apply such discount not to each item from line item quantity. I simply want to exclude applying discount for one (first one) on the basis: `0,2*(n-1)*X` where `n` is qty and `X` is product base price.

The problem is that line item discount type in Commerce Discount module is calculating before quantity calculation (only for qty of 1) and proper price component is added to line item price.

The solution I've tried was to divide calculated discount `(0.2*X/n)` but the result calculated for quatity 3 or 6 or 9 is inaccurate (wrong, decimal number).

Is there a hook or other solution that can allow me to "return" the part of discount that should not be applied, or am I simply missing something and there is a more natural way to achieve what I described (for example, the order discount rule)?

# Answer
You should be able to do this out of the box if you have the Commerce Discount Extra module installed. The offer type to use is *Per-quantity product discount (% off)*. This offer type (and the other per-quantity offer types) was created to support BOGO style offers (buy 1, get 1 free), but we developed them to support any type of discount for any number of matching products.

In your case, you'd set the "Buy #" to 1 and the "Get up to #" to a very high number... whatever you consider reasonable for the quantity you'd expect to discount. This will result in the creation of a new discount line item.

Note that the pattern for matching products will be SKU based or product category based.
> 0 votes

---
Tags: 7, commerce, hooks
---


# Question
Title: How to display an image in a report created with the Forena module?
I created a report using the Forena module. In this report I want to display image which is saved in a private folder. I am fetching the image url from the `file_managed` table using `file_load()` method on the basis of file id.

How can I display the image in my report?

# Answer
> 1 votes
### 1. Display an image with a hardcoded path

The body of a Forena report is an XHTML file, which you can edit using the WYSIWYG report editor (ie the layout tab). So if you just add an image tag with a path pointing to your image, you can display such image anywhere in your report.

### 2. Transform the hardcoded image path into a *Skin configuration option*

Using Report Skins, you can use the technique of Defining skin configuration options. This allows for defining arbitrary variables that can be referenced in reports using the skin data context.

For example, assume you define a variable in the skin like so:

```
imagepath = path/to/image

```

Anywhere in your report, you can then refer to the token `{skin.imagepath}`.

### 3. Create a separate data block

If it makes sense for this specific question, you might want to consider just creating a separate (additional) data block related to the image to be displayed. That way you just retrieve the relevant data (row) from your `file_managed` table (as in your question), and surround it with whatever HTML markup you'd want.

### 4. Available FORENA hooks for adding reporting extensions

Yet another option might be to use some of the available Forena hooks. Here are some of them that may help you:

* hook\_forena\_data\_alter
* hook\_forena\_parameters\_alter

Disclosure: I'm a Forena co-maintainer

---
Tags: 7, forena
---


# Question
Title: Move title below image in Views grid format with CSS
I'm trying to customize a View that I've created showing all of one published content type. The grid is set to have 3 columns. I also have it set as a Rendered Entity with view mode "Teaser" so that it displays the image and content.

Using CSS I've been able to modify the header size, hide the words in the teaser while leaving the image, and modifying the size of the teaser image.

I'd like to be able to display the title underneath the image rather than on top, as is the default. There is no setting in the Views module to achieve this that I can find, so I'm doing some modifications using CSS. I'm having some trouble figuring out which divs to use to do so (there seem to be quite a lot that don't move around so easily). The divs are currently positioned like so:

I did find that assigning `display: table-header-group` and `display: table-footer-group` to the images (`l-slat__media`) and header text (`l-slat__header`) respectively worked, after assigning `display: table` to `article`. But they were tiny and about 25% of the original size. Not really sure why this is happening.

Any input as to what I might be able to do to put the header text below the teaser image would be appreciated.

# Answer
> 1 votes
I dislike answering my own questions, but I was able to figure it out using CSS only and not downloading any new modules, which is what I had stated in my original question and preferred to do.

The answer is to set the header position as absolute and change the bottom padding of the text:

```
div.ViewClassName .l-slat__header {
    position: absolute;
    bottom: 30px;
 }

div.ViewClassName article {
    padding-bottom: 40px;
 }

```

Where `.ViewClassName` is the CSS class you can assign your View to alter it in the Views UI, `.l-slat__header` is a default value given to the header from the Views source code, and `article` is an object created by the Views source code. You could probably also create a selector to only get `articles` in a specific View. I dislike using pixels instead of `em` or `%`; it would probably take some more finagling to incorporate those, but I suspect it would work.

# Answer
> 2 votes
You could simply edit the "Teaser" view mode and place the title below the image using Display Suite Here are the instructions:

1. Download Display Suite and enable the "Display Suite" and "Display Suite UI" modules.
2. Go to `admin/structure/types/manage/article/display/teaser` where "article" is your content type.
3. In the "Layout for article in teaser" fieldset, select the "One column" layout and click Save.

4. You will now see a lot more fields, provided by the Display Suite module. One of those fields is the title field.

5. Now drag the title field up to the top, below the Image field, just like you requested. From what I understand from your question, you could remove the Body field as well.

6. All done! No custom theming required.

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


# Question
Title: Create a general rewrite rule in .htaccess
In an upgrade scenario I have to provide some alias URLs like `www.server.com/reading_23.html` that should actually deliver `www.server.com/reading/23`.

I spent lots of hours trying to make that work by adding a line in .htaccess:

```
RewriteRule reading_(.*).html reading/$1

```

I have put that line into the standard D8 .htaccess, right after `RewriteBase /`. Unfortunately none of my attempts worked. The `/reading` is a path that's provided by one of my `modules.routing.yml`.

EDIT, 18.1. This seems to be very special for Drupal because it just doesn't work with the existing D8 redirects. I can only make a redirection (`[L,R]`) work but I don't want my end-users to see the `reading/23` path in their browser. So actually the question is how to make URLs like `reading_23.html` possible with Drupal, the routing parameters can only live as separate parts of the path (like `reading/{number}` is ok but `reading_{number}.html` is bad).

Anyone who knows how to do this?

I do not want to create aliases in my Drupal DB for all node-Ids.

\[EDIT Nr 2. 18.Jan 2017\]

The Solution is an inbound Path Processor like 4k4 wrote. Thanks a lot.

\[END EDIT\]

# Answer
I think your rewrite collides with the other rewrites in drupal standard .htaccess. Try a redirect. The redirect will be executed right away and the rest of .htaccess will no longer be processed. And it will also tell search engines that the url has changed.

```
RewriteRule reading_(.*).html reading/$1 [L,R=301]

```
> 3 votes

# Answer
Rewrites this code for your problem in .htaccess. The code will work for any string in between `reading_` and `.html`

```
  RewriteEngine On
  RewriteRule ^reading_(.*)\.html$ http://www.server.com/reading/$1 [L,R=301]

```

Hope, this works fine for you.
> 2 votes

---
Tags: 8, path-aliases, .htaccess, routes
---


# Question
Title: Use form-submit to display results table on page
I’m struggling with how to get a form-submit to return the results of a database select-query. I can build the form and the submit-function does the select-query to collect the results and builds a render-array:

```
$table = array(
    '#theme' => 'table',
    '#header' => array(t($field_1), t($field_2)),
    '#rows' => $tableRowS,
);

```

However I can’t figure out how to get drupal to render this table instead of just rebuilding and showing the empty form again. I’ve examined the concept of redirect but don’t see a way of passing the table to the redirected page.

Any help would be appreciated.

# Answer
> 1 votes
I don't think you can return a themed table on form submit. Instead, what I suggest is to use `$_SESSION` variable to store the form field values to query the database and redirect to a URL. In the `callback function` of the URL query the database and return the themed page.

Example:

```
function mymodule_myform_submit($form, $form_state){
   $_SESSION['somevar'] = $form_state['values']['somefield'];
   drupal_goto('someurl');
}

```

And in the URL callback function get the value of the session variable `$somevar = $_SESSION['somevar'];`

---
Tags: 7, forms
---


# Question
Title: Apply discount on checkout when a specific quantity of products are purchased with a specific taxonomy
I have Commerce Discount installed that enables me to create a discount on a product with a certain taxonomy. However I only want this discount applied when a customer selects at least three of these products with the taxonomy.

It there a way I can update the rule created with the discount to achieve this?

This has already been logged as an enhancement Add option to specify amount of products that needs to be orderd

But I need to resolve this before my site can go live

Many thanks

# Answer
I managed to resolve this by adding a condition to the rule that was created by the discount.

And Total quantity of selected product comparison
> 0 votes

# Answer
There is another module that should work Commerce Taxonomy Conditions. I believe it allows you to add a quantity per taxonomy term discount condition.
> 0 votes

---
Tags: commerce, rules
---