title: Line items without products

text:
# Question
Title: Line items without products
I would like to use an external source for Products, and skip creating commerce\_product entities.

I have used hook\_commerce\_line\_item\_type\_info()

```
 $line_item_types['external_product'] = array(
'name' => t('Bridged Product'),
'description' => t('Custom Line Item type that references external product data sources.'),
'product' => FALSE,
'base' => 'external_product',
'type' => 'external_product',
);

```

and hook\_enable() commerce\_line\_item\_configure\_line\_item\_fields(array('my\_module'));

However, I get an entity\_metadata\_wrapper fatal error on line\_item\_save() of unknown data property commerce\_product.

Is it not possible to create line items without this property? Is that not what product\>false does?

# Answer
Thanks. Commerce feeds isnt really feasible - the products are ~6M records (including different currencies), and iterating and doing entity saves via feeds is a huge processing bottleneck.

my code to create line items is

```
// Create the new line item.
$line_item = entity_create('commerce_line_item', array(
  'type' => external_product',
  'order_id' => $order->order_id,
  'quantity' => $item['qty'],
));

   $line_item = commerce_line_item_save($line_item);

```

but I get that error about a missing parameter (commerce\_product'). I have removed the module from the sys table, cleared all cache and re-enabled the module to make sure the custom line items are registered with fields, but still a no go.
> 0 votes

---
Tags: commerce
---


title: Geolocation Field - Map Marker in Views

text:
# Question
Title: Geolocation Field - Map Marker in Views
I'm trying to show a map with multiple markers with the help of Views and Geolocation field. It would be nice for example if I can show the image in the tooltip display of the marker. But when I add an image as a field to achieve this, the image automatically gets selected as the icon source field by default (See Views UI - FORMAT - Advanced settings). Is it possible change this behavior?

# Answer
> 2 votes
You need to create a display in your content type where you will put the field that you want to show in the tooltip.

Home » Administration » Structure » Content types » YOUR CONTENT TYPE » Manage display

Then in your view select in the format to show Content and in the View mode the display that you created before with your fields.

# Answer
> 0 votes
In views you can hide image field and it will't be shown on map. In advanced settings you can change custom icon which you want to be shown on map and for tooltip can add custom text or title or body.

---
Tags: views, 8, location, google-maps
---


# Question
Title: Prevent caching of variable in twig template
In my custom page.html.twig I have a variable that adds an alert bar to the page if the user is expired. This is based on a custom user field.

It's generated here in my custom\_theme.theme file like so.

```
function custom_theme_preprocess_page(&$variables){
    $uid = \Drupal::currentUser()->id();
    $current_user = \Drupal\user\Entity\User::load($uid);
    $now =strtotime('now');
    $paidThrough = strtotime($current_user->field_expiration_date->value);
    if($paidThrough < $now){
         $variables['alert'] = 'Your account has expired';
    }
    $variables['#cache'] = [
        'max-age'  => 0,
        'contexts' => ['url.path']
    ];

}

```

and then inside my page.html.twig file I have

```
<div class="alert">{{ alert }}</div>
<div class="main">{{ page.content }}</div>

```

Even though some users have been updated to no longer see the alert, they still see it on the home page. If they click around to different pages they no longer see the report, but on the home page they always see it. I'm guessing they no longer see it on other pages because those pages were not cached for them. Also I'm using the page manager and panels plugins for many of these pages including the home page.

Why would twig variables be cached for authenticated users? Is there a way to prevent twig variables from being cached?

I did see a similar post here Twig/Drupal caching and dynamic variables But I'm not sure how that would work or how to implement that.

UPDATE: It was mentioned that using $variables\['#cache'\]\['contexts'\]\[\] = 'url'; would be problematic but if this is a dynamic alert box that appears on every page wouldn't that be necessary?

UPDATE 2: Actually it occurred to me that I'm already using

```
$variables['#cache']['contexts'][] = 'url';

```

in my own way here

```
$variables['#cache'] = [
    'max-age'  => 0,
    'contexts' => ['url.path']
];

```

But that didn't seem to resolve the issue. Unless 'url' and 'url.path' makes a difference.

# Answer
> 2 votes
This seems a bit chaotic. You don't need an url context on a page, because this is set already. You don't need other cache data, if you have max-age = 0. If your message depend on the current user, you need a user context. And always add cache data, never replace it.

I would use a block for the message which, if it depends on the current user, can be auto-placeholdered. Then you don't need to disable page caching, which is better for performance, see https://www.drupal.org/docs/8/api/render-api/auto-placeholdering

---
Tags: theming, 8, caching
---


# Question
Title: How do I change icons in the "Mobile sliding menu" module?
I want to change the menu-item icons for the Mobile sliding menu module. I have set up the icomoon library and changed the CSS file according to the documentation. I have added custom icon classes to the menu items (which works as long as they are not as block in a mmenu). The mmenu always overwrites this with its own markup.

I have found some occurrences of menu icon assignments in the source code, but I don't want to hack modules.

mmenu.api.php describes some hooks.

```
/**
* Allows modules to add more mmenu icon classes.
*/
function hook_mmenu_icon() {
  $icons = array(
    'path' => array(
      'home' => 'icon-home',
      'about' => 'icon-office',
      'contact' => 'icon-envelope',
    ),
    'block' => array(
      array(
        'module' => 'system',
        'delta' => 'main-menu',
        'icon_class' => 'icon-enter',
      ),
    ),
  );
  return $icons;
}

/**
 * Allows modules to alter mmenu icon class settings.
 */
function hook_mmenu_icon_alter(&$icons) {
  $icons['path']['home'] = 'icon-home1';
}

```

I have no clue how to use these. I have tried to put them in my template.php like this.

```
function mythemename_mmenu_icon() {...}

```

It's not working. Apart from that, this wouldn't be a user-friendly solution. Ideally it would support icon-api. So any help is highly appreciated.

# Answer
> 3 votes
Here is what I ended up with, after using `hook_mmenu_icon()` and configuring the Icon API to use the icomoon bundle.

### How I did it?

First of all, I opted for using the Icomoon module, which allows me to import my own defined icons collections, assembled using the icomoon app.

This is an example of a custom collection I created (and the renaming/mapping of icons to the menu points I had in mind).

After, I had to go to the administration interface of Icon API providers and import the icons (/admin/config/media/icon/import). I named the imported bundle 'icomoon', which will be important for the code I wrote. This is what that admin interface looked like.

### The code

The code you need will use `hook_mmenu_icon()`, since you want to define your own path to icon class associations.

This is what my code looks like.

```
/**
* Implements hook_mmenu_icon().
*
* Here we map URLs to icon classes.
*/
function YOUR_CUSTOM_MODULE_mmenu_icon() {
  $icons = array(
    'path' => array(
      'home' => 'icon-home',
      'node/1' => 'icon-node1',
    ),
  );
  _inject_inline_css($icons);
  return $icons;
}

```

Notice the use of Drupal's internal paths as the key to the `$icons` array. This is needed by the module (inside `mmenu_get_icon_class()`) in order to assign our custom CSS class to the menu item that points to it.

The rest of the code is quite custom and just a random idea of how you could go about doing the assignments you need. Probably there are better approaches.

```
/**
 * Function for injecting Icon API icons as CSS background images.
 */
function _inject_inline_css($icons) {
  // Load a bundle provider from the Icon API.
  $bundle = icon_bundles('icomoon');

  // Sanitization, normalization.
  if (empty($bundle)) {
    return;
  }
  if (!isset($bundle['settings']['extension'])) {
    $bundle['settings']['extension'] = 'png';
  }

  $css_data = array();

  // Configure an existing icon class, 'home'.
  $icon_path = $bundle['path'] . '/' . strtoupper($bundle['settings']['extension']) . '/home' . '.' . $bundle['settings']['extension'];
  $icon_info = image_get_info($icon_path);
  $icon_url = file_create_url($icon_path);
  $css_data[$icons['path']['home']] = array(
    'background-image' => 'url("' . $icon_url . '")',
    'background-size' => 'contain',
    // Or, as an alternative.
    // 'background-size' => '$icon_info['width'] . 'px ' . $icon_info['height'] . 'px'',
    'background-repeat' => 'no-repeat',
    'background-position' => 'center',
  );

  // Add a custom icon class, 'node/1'.
  $icon_path = $bundle['path'] . '/' . strtoupper($bundle['settings']['extension']) . '/node1' . '.' . $bundle['settings']['extension'];
  $icon_info = image_get_info($icon_path);
  $icon_url = file_create_url($icon_path);
  $css_data[$icons['path']['node/1']] = array(
    'background-image' => 'url("' . $icon_url . '")',
    'background-size' => 'contain',
    // Or, as an alternative.
    // 'background-size' => '$icon_info['width'] . 'px ' . $icon_info['height'] . 'px'',
    'background-repeat' => 'no-repeat',
    'background-position' => 'center',
  );

  // Generate and add inline CSS, mapping the mmenu icon classes to the icomoon icons.
  $css_string = '';
  foreach ($css_data as $class => $css_properties) {
    $css_string .= '.' . $class . ' {';
    foreach ($css_properties as $css_property => $css_value) {
      $css_string .= "$css_property: $css_value;";
    }
    $css_string .= '}';
  }
  drupal_add_css($css_string, array('type' => 'inline'));
}

```

# Answer
> 0 votes
The hooks should be implemented in a module.

Create two files: mymodule.info + mymodule.module in path a module search path like **/sites/all/modules/custom/mymodule/**

The documentation on https://www.drupal.org/node/2324139 is indeed inconclusive where to implement the hooks.

---
Tags: 7, hooks
---


# Question
Title: How to create reviews for user comments?
I want use user review for my content. For example they can send their comment in my content and review in comment ( with fivestar field ).

Five star and other module not work in drupal 8.

# Answer
> 1 votes
The scenario is not very encouraging for Drupal 8 in voting modules at this time, but you can check some modules that can help you:

Votingapi Widgets

> A flexible field based Voting System based on https://www.drupal.org/project/votingapi .

Like Button

> Add a Like button to Drupal content and comments! Get instant statistics and insights! Sort content by likes!

Star Rating

> Star Rating is a simple module that provides star rating field and display formatter using Drupal 7's Field Type API.

---
Tags: 8, nodes, users, rating
---


# Question
Title: How to output just the Name and Status in drush listing modules
Running `drush pm-list` gives the modules and theme list through some fields. By default, it gives me the Package, Name, Status and Version. I am trying to make a shell script that outputs only module and status to be consumed by other scrips, and things will be much easier if the `drush pm-list` shows only Name and Status.

Is there a way to prints only the information about the Name and Status from the `drush pm-list` and omits the Package and Version information?

# Answer
Using Drush 8 or Drush 9:

```
drush pm-list --fields=Name,Status

```

If you want to consume the output from another script, you might also want to consider:

```
drush pm-list --format=json

```

In that instance, all fields will appear in the output; however, since the output will be in json, it is easy to parse and then use only the fields of interest.
> 2 votes

---
Tags: drush
---


# Question
Title: Disable reaching a node by its internal path
I want a node to be reached only by its alias but not its internal path. The reason behind this is that I will create a node type, allow anon users to create such nodes, but the alias will contain a random text, so that only the user with the actual url information can revisit this page. Example: www.example.com/node/9 -\> only accessible by admin www.example.com/34h356hrgc35yh4geg -\> only accessible to anon users with this information.

If an anon user tries www.example.com/node/9, they should see Forbidden error or Not Found.

# Answer
> 5 votes
You can do this, if speed is important, in a middleware, checking if the request has no session and then block right away or in a request event subscriber after authentication checking for the path. Or a bit slower after routing if you want to check that the matched route is the canonical entity route and use the node entity in your logic.

The easiest but slowest is in a page preprocess hook. You can even do this in a theme.

```
function mytheme_preprocess_page(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    if (isset($variables['node'])) {
      $node = $variables['node'];
      if ($node instanceof \Drupal\node\NodeInterface) {
        if ($node->getType() == 'article') {
          // use PathInfo instead of RequestUri to ignore query strings
          $path = \Drupal::request()->getPathInfo();
          if (preg_match('#/node/\d+/*$#', $path)) {
            throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
          }
        }
      }
    }
  }
}

```

The cached page is varied by path and user permission by default and so the not found exception.

This doesn't work if you have installed the Redirect module with the setting *Global Redirect - Enforce clean and canonical URLs* enabled. In this case you need a request event subscriber with a priority higher than 33.

---
Tags: 8, users
---


# Question
Title: How do I include a JavaScript file and pass the value of a PHP variable with a single function call?
I'm trying to pass a PHP variable to my JavaScript file. The file is js/backgroundConfig.js, it's in the theme directory, and this is the content of the file.

```
(function($, Drupal){
  Drupal.behaviors.backgroundAnimation = {
    attach: function(context, settings) {
      alert(Drupal.settings.variableName);
      alert(Drupal.settings.basePath);
    }
  };
})(jQuery, Drupal);

```

`Drupal.settings.basePath` is displayed correctly, but I've no idea how to pass `variableName` from template.php. I've tried a couple of methods but none of them work.

There are tons of examples on the web but none of them contains the filename and the settings together. Like this one:

```
drupal_add_js(array('variableName' => 'value'), 'setting');

```

Alright, but where I should put my filename? I always add my JavaScript file like this.

```
drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

```

How do I combine it together?

# Answer
> 3 votes
> How to combine it togather?

You don't - Javascript files and settings are two completely different things. Anything you add to the settings will be available on the global `Drupal` object, which will be available by the time the code in your JS file is invoked.

Your code should be:

```
drupal_add_js(array('variableName' => 'value'), 'setting');
drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

```

Or the other way round, it really doesn't matter.

# Answer
> 2 votes
You are really close. There's a small error and perhaps a bit of misunderstanding.

First, adding a setting should be (taken from api.d.o):

```
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

```

This setting can now be accessed in a .js file via `Drupal.settings.myModule.key`. The first array key above is the name that you will use to access your settings object in `Drupal.settings`. This way you can add multiple settings to `Drupal.settings.myModule` if required.

When you're adding js via `drupal_add_js`, there's really two different things that can happen. If you're adding a *file*, like `backgroundConfig.js`, Drupal will actually load that file into the HTML, allow it to be aggregated, etc.

When adding a setting, there is no file to be added, rather all it does is create that setting as an object within the global `Drupal.settings` JavaScript object that is present on every page.

So, in summary, you can add a file, or add a setting. Often this setting will be used by a module/theme's behaviour to determine how it is to function on a given page or context.

Also, in your browser, try opening up your Web Inspector, go to the console, and type `Drupal` to get a better idea of what's happening here and how other modules and themes use this feature.

# Answer
> 1 votes
An example would probably be best:

The PHP:

```
drupal_add_js(array('myvar' => 'value'), 'setting');

```

The JS:

```
(function($){
  Drupal.behaviors.backgroundAnimation = {
    attach: function(context, settings) {
      alert(settings.myvar); // Should alert 'value'
    }
  };
})(jQuery);

```

It's usually good idea to group your settings using the module name like so:

```
drupal_add_js(array('mymodule' => array('myvar' => 'value')), 'setting');

```

So to access it via JS you do like so:

```
settings.mymodule.myvar

```

# Answer
> 0 votes
In general, you cannot use a single `drupal_add_js()` call to add:

* Two or more internal scripts
* Two or more external scripts
* An external script, an internal script, and a setting

If you need to add one or more of those, you simply call `drupal_add_js()` more than once. The code you shown is perfectly fine.

```
drupal_add_js(array('variableName' => 'value'), 'setting');
drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

```

Eventually, to avoid conflicts with other themes/modules, and if the value is used only from your theme, you should use the name of your theme/module as array key for the settings.

```
drupal_add_js(array('themename' => array('variableName' => 'value')), 'setting');
drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

```

# Answer
> -3 votes
Suppose there is some function in template.php

```
function THEMENAME_preprocess_page(&$vars) {
  drupal_add_js(array('backgroundAnimation' => array('variableSetting' => 'VariableSetting_output', 'variableSetting1' => 'Himanshu')), array('type' => 'setting'));
  drupal_add_js(path_to_theme().'/js/backgroundConfig.js');
}

```

Place the file backgroundConfig.js at proper location. Then in JS file write like

```
(function ($) {
Drupal.behaviors.backgroundAnimation = {
    attach: function (context, settings) {
        alert('js file loaded');
        console.log(settings);
        alert('basePath is ' + settings.basePath);
        alert(settings.backgroundAnimation.variableSetting);
        alert(settings.backgroundAnimation.variableSetting1);
    }
};

```

})(jQuery);

---
Tags: javascript
---


# Question
Title: More information about content in Link field autocomplete dropdown?
In a project we have a Link field where editors can link to internal content or external content.

There are several cases where nodes of different content types have the same title.

Is there a way to display more information than just the node title in Link fields autocomplete widget - so that we can make it easier for Editors to pick the right node?

We are using LinkIt but that does not support the link module at the moment.

# Answer
> 1 votes
The autocompletion matches are provided by `EntityAutocompleteMatcher::getMatches`. The format is hardcoded as `$key = "$label ($entity_id)"`. Label and entity id come from selection manager, which packages entity id and label pairs in an array keyed by entity bundle, so that could be used as a source for adding content type into the results. You'll need to override `system.entity_autocomplete` route's controller to get to your own matcher.

The same controller is used for rendering the selection dropdown though it does not display the entity ids, only labels (in `web/core/misc/autocomplete.js`). Overriding that is another thing you'll need to do.

# Answer
> 1 votes
Here is a simple module that I released on github. With some modification you may display anything you need in the autocomplete results/suggestions.

https://github.com/minnur/Alter-Entity-Autocomplete

---
Tags: 8, navigation
---


# Question
Title: How to stop a form refreshing after callback
I have a form, which is made up of a listbox and a textarea, the listbox holds a number of items that related to records in the database. The user can select an item from the listbox and select the retrieve button (which is of type submit) the record selected is retrieved from the database and the textfield on the form is updated to show one of the fields from the database record (e.g. answer). The form looks like this:

The first time a record is selected from the listbox and the retrieve button is selected - the form functions as expected e.g. the callback function is run, the section of the form is updated (rather than the whole form updating) and the textarea is updated to show the database entry.

On the second run, however, when a record is selected from the listbox and the retrieve button is pushed - rather than the textarea updating to show the selected record... the form looks like it completely refreshes and reloads rather than calling the callback function as it does in the first run.

On the third attempt the form works correctly again - but, that's no doubt because the form looks like it reloads on the second go - rather than the callback function running.

The form's buildForm function is as follows:

```
    public function buildForm(array $form, FormStateInterface $form_state)
{
    // TODO: Implement buildForm() method.

    $this->app_instance_id=\Drupal::request()->query->get('api');

    $form=array();

    $this->set_listbox_options();

    $form['page']=array(

        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );

    $form['page']['fieldset_1']=array(
        "#prefix"=>"<div id='wrapper_tab1_q1' class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row1']=array(
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row2']=array(
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row3']=array(
        "#prefix"=>"<div class='row'>",
        "#suffix"=>"</div>",
    );
    // ----------- ---------------------
    $form['page']['fieldset_1']['row3']['column1']=array(
        "#prefix"=>"<div class='".$this->col1_width."'>",
        "#suffix"=>"</div>",
    );
    // ---------- ----------------------
    $form['page']['fieldset_1']['row3']['column1']['the_answer']=array(
        "#type"=>"textarea",
        '#attributes' => array(
            'rows'=>'9',
        ),
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    // ---------- ----------------------
    $form['page']['fieldset_1']['row3']['column2']=array(
        "#prefix"=>"<div class='".$this->col2_width."'>",
        "#suffix"=>"</div>",
    );
    $form['page']['fieldset_1']['row3']['column2']['record_select_list']=array(
        "#type"=>"select",
        "#options"=>$this->listbox_options,
        '#attributes' => array(
            'width'=>'10',
            'size'=>'8',
            'multiple'=>'multiple',
        ),
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row3']['column2']['submit_list_selection']=array(
        "#type"=>"submit",
        "#value"=>"Retrieve",
        "#ajax"=>array(
            "callback"=>"::run_callback_code",
            "wrapper"=>"wrapper_tab1_q1",
        ),
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",

    );
    // ----------- ---------------------
    $form['page']['fieldset_1']['row4']=array(
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );

    return $form;
}

```

The callback function "run\_callback\_code" is as follows:

```
    public function run_callback_code (array &$form, FormStateInterface $form_state)
{

    // ---------------------------------------------

    $listbox_selection=$form_state->getValue("record_select_list");

    $answer_db_object=new db_select();
    $answer_db_object->set_setTable("tbl_frm1_tab1_q1_ans");

    $qry_fields=[
        'frm1_tab1_q1_ans_id',
        'data_request_app_instance_id',
        'user_id',
        'answer',
    ];

    $answer_db_object->set_fieldArray($qry_fields);

    $qry_fieldValues[0]['field']="frm1_tab1_q1_ans_id";
    $qry_fieldValues[0]['condition']="";
    $qry_fieldValues[0]['type']="";
    $qry_fieldValues[0]['value']=$listbox_selection;

    $answer_db_object->set_condition($qry_fieldValues);

    $results=$answer_db_object->select_qry();

    $form['page']['fieldset_1']=array(
        "#prefix"=>"<div id='wrapper_tab1_q1' class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row1']=array(
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row2']=array(
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row3']=array(
        "#prefix"=>"<div class='row'>",
        "#suffix"=>"</div>",
    );
    // ----------- ---------------------
    $form['page']['fieldset_1']['row3']['column1']=array(
        "#prefix"=>"<div class='".$this->col1_width."'>",
        "#suffix"=>"</div>",
    );
    // ---------- ----------------------
    $form['page']['fieldset_1']['row3']['column1']['the_answer']=array(
        "#type"=>"textarea",
        '#attributes' => array(
            'rows'=>'9',
        ),
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );

    if (is_array($results)){
        if (sizeof($results)>0){
            $form['page']['fieldset_1']['row3']['column1']['the_answer']['#value']=$results[0]->answer;
        }
    }
    // ---------- ----------------------
    $form['page']['fieldset_1']['row3']['column2']=array(
        "#prefix"=>"<div class='".$this->col2_width."'>",
        "#suffix"=>"</div>",
    );
    $form['page']['fieldset_1']['row3']['column2']['record_select_list']=array(
        "#type"=>"select",
        "#options"=>$this->listbox_options,
        '#attributes' => array(
            'width'=>'10',
            'size'=>'8',
            'multiple'=>'multiple',
        ),
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );
    $form['page']['fieldset_1']['row3']['column2']['submit_list_selection']=array(
        "#type"=>"submit",
        "#value"=>"Retreive",
        //"#submit"=>array("::run_submit_code"),
        "#ajax"=>array(
            "callback"=>"::run_callback_code",
            "wrapper"=>"wrapper_tab1_q1",
        ),
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",

    );
    // ----------- ---------------------
    $form['page']['fieldset_1']['row4']=array(
        "#prefix"=>"<div class='row'><div class='col-md-12'>",
        "#suffix"=>"</div></div>",
    );

    $form_state->setRebuild();
    return $form['page']['fieldset_1'];
}

```

I have not added any code to the validation and submit functions as yet, because I haven't been able to get the form to function as required and so have not included them here.

Does anyone know, why the form appears to reload on the second/forth/sixth attempt rather than continuing to call the callback function? (Even if I remove the $form\_state-\>setRebuild () line of code the form continues to refresh itself on the second/forth/sixth etc goes). The reason I am using a callback e.g. ajax is so that only part of the form is updated at run-time rather than the whole form.

Side Note: The is bespoke code written related to running the select query, which is used in the callback function, but that shouldn't impact the form as it's purely just dealing with retrieving data from the database using the standard Database API.

# Answer
Extrapolating from the link Mo-ster shared, add this to your form element:

'#attributes' =\> array('onclick' =\> 'return (false);')

The API says that buttons trigger a validate and rebuild, but not a submit: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Button.php/class/Button/8.2.x
> 1 votes

---
Tags: 8, forms, ajax
---


title: Age gate not showing on home page

text:
# Question
Title: Age gate not showing on home page
I am working on a client's website and need to implement this age gate on it. The problem is it only shows on a specific url/page but not on other pages. Been looking for solutions since past 2 days but couldn't find anything on google about it.

This is what I did:

Added the shown below in `html.html.twig` and uploaded the relevant css and html. But the age gate popup only shows on www.xyz.com/?AvpClearCookie=1 but not on the www.xyz.com

```
<!-- Age Gate: START -->
<script defer="defer" async>
(function(doc, url, tag) {
var js=doc.createElement(tag),fjs=doc.getElementsByTagName(tag)[0];js.src=url;fjs.parentNode.insertBefore(js,fjs.nextSibling);
}(document, '//avp3.azureedge.net/api/ballantines/avp/?language=en&callback=test_cb', 'script'));
</script><div id="avp"></div>
<!-- Age Gate: END -->

```

I was trying to show it on home page but with the very limited knowledge I have about drupal it seeming difficult for me to get it done. Really appreciate if anybody could show me some light on this.

# Answer
> 0 votes
Maybe it's a cache issue, so you can try to externalize your script and call it with random parameter

```
<script type="text/javascript" src="path/to/my/script.js?itok=1561313215" defer="defer" async></script>

```

You can generate a random value with php with microtime by sample

Try it and let us know if helps you

---
Tags: 8, hooks, users
---


# Question
Title: Apply page template suggestion to a specific view by a hook?
I have a website running Drupal 8.x with different views. I would like to use a page--template.html.twig template basing to the view ID. Is this possible?

I was thinking of using code similar to the following.

```
function mythemename_theme_suggestions_page_alter(array &$suggestions, array $variables, $hook) {
 if ($hook === 'views_view') {
   if ($variables['view']->id() === 'movies') {
     $suggestions[] = 'page__movies';
   }
 }
}

```

# Answer
> 2 votes
First of all, the code is never run, because you have the hook `page` in the function name and check for the hook `views_view`. Secondly the variables in a page hook don't contain variables from the view, so you have to get them from the route:

```
function mythemename_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $view_id = \Drupal::routeMatch()->getParameter('view_id');
  if ($view_id === 'movies') {
    $suggestions[] = 'page__movies';
  }

}

```

---
Tags: views, theming
---


title: Read drupal log programmatically

text:
# Question
Title: Read drupal log programmatically
I want to get all the logs, which are available under `admin/reports/dblog` as shown in the screenshot below:

Below are the two approaches, I can think of:

1. Access logs programmatically in Python or PHP
2. Download the database as a SQL file and read the database

I am not sure if the above approaches are possible or not. Any suggestions, please?

# Answer
> 1 votes
Yes, assuming you have the dblog module enabled, that data is in the database, so you can use whatever language or method you want to extract and analyse it.

The data is kept in the `watchdog` table.

# Answer
> 1 votes
I see three main options:

**Use Syslog**

Use the Syslog core module:

> The Syslog module logs events by sending messages to the logging facility of your web server's operating system.

Using this module you can access all log messages thanks to the syslog subsystem.

**Access the data directly**

As Clive suggests, use the data that DBlog saves in the `watchdog` table. The tables's structure for Drupal 7 is like this:

```
+-----------+---------------------+------+-----+---------+----------------+
| Field     | Type                | Null | Key | Default | Extra          |
+-----------+---------------------+------+-----+---------+----------------+
| wid       | int(11)             | NO   | PRI | NULL    | auto_increment |
| uid       | int(10) unsigned    | NO   | MUL | 0       |                |
| type      | varchar(64)         | NO   | MUL |         |                |
| message   | longtext            | NO   |     | NULL    |                |
| variables | longblob            | NO   |     | NULL    |                |
| severity  | tinyint(3) unsigned | NO   | MUL | 0       |                |
| link      | text                | YES  |     | NULL    |                |
| location  | text                | NO   |     | NULL    |                |
| referer   | text                | YES  |     | NULL    |                |
| hostname  | varchar(128)        | NO   |     |         |                |
| timestamp | int(11)             | NO   |     | 0       |                |
+-----------+---------------------+------+-----+---------+----------------+

```

The error message is in the `message` column, and the values of the tokens in the message are in the `variables` column. To get the complete message you can use the function t, as dblog does:

```
 $output = t($event->message, unserialize($event->variables));

```

In this case you probably access the data after the event is created and processed by drupal, in a batch process. Useful if you just want to store messages but not if you want to react in real time.

**Hook to the watchdog**

You can write your own module and get all watchdog messages when they are delivered. To do this you have to implement the hook\_watchdog. In this case you receive the event at the time it's generated.

---
Tags: 7
---


title: Commerce Product using Display Suite

text:
# Question
Title: Commerce Product using Display Suite
Im using Commerce for Drupal 8. When using Display Suite to create a two column display for Products, the Price and Attributes disappear. Is it possible to use Display Suite for Commerce Products to achieve a two column display?

# Answer
> 0 votes
No. Display Suite is not compatible with Commerce Products.

Commerce issue: https://www.drupal.org/node/2723689 Display suite issue: https://www.drupal.org/node/2725077

---
Tags: commerce
---


# Question
Title: Problem to display name from current logged
I've created a custom block to display info from current user. When i'm logged with username "David", i see on my custom block the username from my last login with other user account.

I have to clear the cache to see the correct username from current user logged.

See here my code :

```
    class UserProfilBlock extends BlockBase {

  public function build() {

    $userinfo = [];

    $account = \Drupal::currentUser();
    $uid = \Drupal::currentUser()->id();

    $user = \Drupal\user\Entity\User::load($uid);

    $userinfo['name'] = $user->get('name')->value;

    return [
      '#username' => ucfirst($userinfo['name']),
      '#theme' => 'user_info_block',
    ];

  }

  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['userprofilinfo_settings'] = $form_state->getValue('userprofilinfo_settings');
  }
}

```

Something is wrong on my custom module ?

# Answer
> 5 votes
I guess the problem is the block is cached for every user. You have to tell Drupal that it should be cached depending on the current logged in user. To do this you have to make use of Cache Tags.

In your case, you have to tell Drupal that the cache of that block should be invalidated when the current logged in user changes. That's because a Cache Context (the user) has changed.

How to do it? You are returning a Render Array, a structure that tells Drupal how to render certain data. In the render array you can set the cache contexts that affect this render array (if the context changes then the cached data changes). In the specific page that talks about the Cacheability of Render Arrays you can see an example of a render array that is cached for each user:

```
$build = [
  '#markup' => t('Hi, %name, welcome back to @site!', [
    '%name' => $current_user->getUsername(),
    '@site' => $config->get('name'),
  ]),
  '#cache' => [
    'contexts' => [
      // The "current user" is used above, which depends on the request,
      // so we tell Drupal to vary by the 'user' cache context.
      'user',
    ],
  ],
];

```

So, I guess that you should add the `#cache` key to your render array, probably in your theme function, but it may work in the build function (long time since I don't do theming, so I'm not sure).

The code to add is:

```
'#cache' => [
  'contexts' => ['user']
]

```

# Answer
> 4 votes
You need to configure the render array's cache to vary when presented with a different user. The core `user` context can be used for that:

```
return [
  '#username' => ucfirst($userinfo['name']),
  '#theme' => 'user_info_block',
  '#cache' => [
    'contexts' => ['user'],
  ],
];

```

---
Tags: 8, blocks
---


# Question
Title: What's the prupose of the version property of a theme library?
Reading the 2 articles below, I'm creating a new theme.

In the example below, I don't understand what is the purpose of the `version` property of the `global-styling` library :

```
global-styling:
  version: 1.x
  css:
    theme:
      css/layout.css: {}
      css/style.css: {}
      css/colors.css: {}
      css/print.css: { media: print }

```

Is it a reference to the site version with which this library is compatible ?

Is it the version of the library itself ? And in this case, when will it be used and for what ?

# Answer
For Javascript files, `version` would allow modules that implement `hook_library_info_alter()` to check if the version of the JavaScript file is older than the one the module is trying to add, for example with code similar to the following. (It's the same code the documentation page reports as example.)

```
  // Update Farbtastic to version 2.0.
  if ($extension == 'core' && isset($libraries['jquery.farbtastic'])) {
    // Verify existing version is older than the one we are updating to.
    if (version_compare($libraries['jquery.farbtastic']['version'], '2.0', '<')) {
      // Update the existing Farbtastic to version 2.0.
      $libraries['jquery.farbtastic']['version'] = '2.0';
      // To accurately replace library files, the order of files and the options
      // of each file have to be retained; e.g., like this:
      $old_path = 'assets/vendor/farbtastic';
      // Since the replaced library files are no longer located in a directory
      // relative to the original extension, specify an absolute path (relative
      // to DRUPAL_ROOT / base_path()) to the new location.
      $new_path = '/' . drupal_get_path('module', 'farbtastic_update') . '/js';
      $new_js = [];
      $replacements = [
        $old_path . '/farbtastic.js' => $new_path . '/farbtastic-2.0.js',
      ];
      foreach ($libraries['jquery.farbtastic']['js'] as $source => $options) {
        if (isset($replacements[$source])) {
          $new_js[$replacements[$source]] = $options;
        }
        else {
          $new_js[$source] = $options;
        }
      }
      $libraries['jquery.farbtastic']['js'] = $new_js;
    }
  }

```

Technically, the same type of code could be used to check which CSS file version is being used, before replacing it with a different one. I can imagine doing that for an external CSS file, for example when a specific version used from a library causes problem with other libraries. I haven't seen a module using similar code, though.

Otherwise, `version` has only identification purposes, much more helpful when a module implements `hook_library_info_build()` to dynamically load different versions of a CSS file.
> 3 votes

---
Tags: theming, 8
---


title: Access to custom user edit form

text:
# Question
Title: Access to custom user edit form
I've created a path (/user/{user}/edit/ and use a custom template to user Profilform. I have a problem with restricting access. I have a "Access denied" when i want to go to my custom path

See my checkAccess function into Controller class :

```
  public function checkAccess(AccountInterface $user) {

    $currentUser = \Drupal::currentUser();
    $currentUserID = \Drupal::currentUser()->id();
    return AccessResult::allowedIf($user == $currentUserID);
  }

```

And my routing.yml file :

```
 entity.user.edit_form:
  path: '/user/{user}/edit'
  defaults:
    _title: 'Update your profile'
    _controller: '\Drupal\custom_user_profil\Controller\UserEditController::content'
  requirements:
   _custom_access: '\Drupal\custom_user_profil\Controller\UserEditController::checkAccess'

```

What is the solution to allow access only if current logged has same id AS parameter {user} on the path ?

# Answer
> 0 votes
The code chunk you posted above is really interesting so to speak:

1.

```
 $currentUser = \Drupal::currentUser();
 $currentUserID = \Drupal::currentUser()->id();

```

You put the `currentUser` into a variable and you call the static Drupal function again to get its ID. What is the sense?

2.

```
return AccessResult::allowedIf($user == $currentUserID);

```

The `$user` object should equal to an ID? (probably int) This doesn't really make sense in the first place. Why don't you debug it? I mean, it keeps giving you back DENIED. Why don't you `kint` or `vardump` the two variables you are trying to compare?

3. Letting just the user with the same id watch his user form is not a wise idea. You should also let `administrator` role and `user-id: 1` (admin user) to access it as well.

---
Tags: users
---


# Question
Title: User images slideshow: first slide from reference entity
I wish to do a slideshow with a first slide of my node picture and then others slides with pictures submitted by users (affiliated to a node via entity reference).

What I want to do is (Node Entity Reference Image) (userA pic1) (userA pic2) (userA pic3) (userB pic3).

I edited a view template

```
  <div class="carousel-inner">
<div class="item active">content(image) goes here</div></div>
    <?php foreach ($rows as $key => $row): ?>
      <div class="item">
        <?php print $row ?>
      </div>
    <?php endforeach ?>
  </div>

```

How can I output my "field\_passager\_image" defined by relationship to Content entity referenced from "field\_passager\_id" passed through an url argument (node id from url) ?

# Answer
Found a solution here using view field views module by putting my user entity field view inside my node entity view.
> 0 votes

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


title: View access based on roles

text:
# Question
Title: View access based on roles
I have 1 view /admin/people, and its 2 display, both are of type page.

I want `display = page` will be shown to admin role while `display = LMA` is for xyz role.

After setting roles for 2 different pages with same access url /admin/people, I logged as admin role and xyz role. Display for admin role is working fine, but for xyz role, it says access denied.

Whats the correct way to have views display for different roles.

# Answer
This didn't work for me either. I worked around this one by creating a panel page and using two different variants, placing each view block in the appropriate page and restricting the access based on user roles.
> 0 votes

---
Tags: views, 8, users
---


title: Any way to bulk delete menu items?

text:
# Question
Title: Any way to bulk delete menu items?
I just deleted 25 menu items and it took me some time to do it.

Just wondering if is there any way (module) to bulk delete menu items.

# Answer
Try Menu Editor module

> Menu Editor enhances the menu editing form with inline text fields for title, path and description, and provides placeholders for new items.
> 3 votes

# Answer
Confirmed! Menu Editor Module lets you multi-select menu items to delete, as well as some other cool functions.
> 2 votes

# Answer
Just an addition, Menu Editor won't delete the links which are being generated by other modules, such as taxonomy menu etc. In order to delete those links, you ll have to refer to the concerned module.
> 1 votes

# Answer
You can do a bulk delete directly from the database.

Just delete the items in menu\_links table that you need.

Take in consideration these fields: menu\_name: The name of your menu mlid: Internal menu id item plid: Parent id menu item. This field is distinct to 0 if the menu item has a parent weight: The weight is the field for ordering the menu items depth: This is the depth of the menu item

Example: Delete all the menu items of the main menu where the depth is greater than 2 and the parent id is not 597.

```
DELETE
FROM yourDatabaseName.menu_links
WHERE menu_name LIKE 'main-menu'
AND depth > 2
AND plid != 597

```
> 0 votes

# Answer
Not a module sollution, but this helps getting this update trough OTAP.

You could also do this in a hook\_update\_n

Hide all module items where parent id = 5947, including the parent item itself. Of course delete works as well, but I find it a nice solution to disable the menu items.

Look in the database `menu_links` table for the fields to make a condition on.

```
/**
 * Hide old menu item.
 */
function module_name_update_7000() {
  db_update('menu_links')
    ->fields(array('hidden' => '1'))
    ->condition('menu_name', 'main-menu', '=')
    ->condition('p1', '5947', '=')
    ->execute();

  drupal_flush_all_caches();
}

```
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How to display a specific page number of a views mini pager?
I'm displaying a view on a pager with a mini pager. It has total number 15 pages.

I want to display page number 5 by default. The the next link will point to page number 6 and the previous link will point to page number 4.

I have tried the below code.

```
function mymodule_views_pre_execute(&$view) {
  $view->query->pager->current_page = 5;
}

```

It just moves the page number in the page number, displaying it as `page 5 of 15` but the views displaying the results of the page 1.

It it possible to set the default page number of a pager? How? I'm using ajax in views.

# Answer
I have found the answer. I'm sharing here the solution.

I used the following code and it worked.

```
function mymodule_views_pre_build(&$view) {
  $view->set_current_page(5);
}

```
> 0 votes

---
Tags: 7, views, paging
---


title: How to insert a View in a Panel?

text:
# Question
Title: How to insert a View in a Panel?
I want to create a page with a panel (using the Panels module). Then want to put a view in it. But I don't see anything in the content section, this is how it looks like:

I saw the question about "How to add Views into a Panels page", but in my Views display there is no `panel pane` display.

Where is my problem, do I need some additional module?

# Answer
> 1 votes
Welcome to Drupal, you had just one step more to do that, go to your module list in `admin/modules` and in `Panels` package enable `Views content panes` module then all views exists for using in panels. also it provide a news dispaly in views.

Also you can see this video for more getting involve with views pane

# Answer
> 0 votes
Can't add this as a comment :( But, oh well...

`Views content panes (views_content)` is in Chaos tool suite \[`Chaos tools (ctools)`\] not `Panels (panels)`.

```
# drush pmi views_content
 Extension     :  views_content
 Project       :  ctools
 Type          :  module
 Title         :  Views content panes
 Description   :  Allows Views content to be used in
                  Panels, Dashboard and other modules
                  which use the
                  CTools Content API.
 Version       :  7.x-1.12
 Package       :  Chaos tool suite
 Core          :  7.x

 Files         :  plugins/views/views_content_plugin_display_ctools_context.inc,
                  plugins/views/views_content_plugin_display_panel_pane.inc,
                  plugins/views/views_content_plugin_style_ctools_context.inc
 Requires      :  ctools, views
 Required by   :  none

```

---
Tags: views, panels
---


title: How to deploy a site?

text:
# Question
Title: How to deploy a site?
I have Drupal 8 website created with composer. I put all files to my remote server in the sitename/www/ but my page won't load. I receive such an error:

> Fatal error: Class 'Drupal\Core\DrupalKernel' not found in /home/bx273629/drupal8.com.ua/www/index.php on line 16

I think it is because I created that website with the Composer. Does any body know how to deploy correctly such a websites?

Website perfectly works locally!

I have such an error:

> 'Fatal error: require(): Failed opening required '/home/bx273629/drupal8.com.ua/www/../vendor/autoload.php' (include\_path='.:/usr/local/pear/php56') in /home/bx273629/drupal8.com.ua/www/autoload.php on line 17'

And on the line 17 of these file I have such a string:

```
return require DIR . '/../vendor/autoload.php';

```

It is from the outer folder which was installed with composer.

# Answer
> 1 votes
I had faced this problem a while ago. After lot of research, I found that running `composer install` from the site root resolves any problem.

# Answer
> 0 votes
You need to copy your `vendor/` folder (generated by `composer update` on your local) into `/home/bx273629/drupal8.com.ua/` dir (one level above `www/`), then `index.php` and rest files into `/home/bx273629/drupal8.com.ua/www/` as normally **`vendor/` folder should be copied one level above of Drupal root** (so it's not accessible from the outside), so the file `www/../vendor/autoload.php` will exists (same localization as on local).

If you cannot copy to the folder above your docroot (`www/`) due to access restriction, modify your `autoload.php` to point to the current folder, e.g.

```
return require __DIR__ . '/vendor/autoload.php';

```

and copy the `vendor/` along with your Drupal files.

---
Tags: composer, deployment
---


# Question
Title: How can i pragmatically fill a field collection when creating a new node?
I'm creating nodes pragmatically but I don't know how to fill field\_collection fields. Most of the examples i've seen have field\_collections being updated from existing nodes and i'm not entirely certain they can also be used when creating new nodes.

```
function createNode($Obj){
  global $user;
  $node = entity_create('node', array(
    'type' => 'event',
    'uid' => 1,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  ));
  $body = "<p>" . (string)$Obj->BuildingCode;
  $body .= " " . (string)$Obj->RoomNumber . "</p>";
  $body .= "<p>" . (string)$Obj->Description . "</p>";

  $entity = entity_metadata_wrapper('node', $node);
  $entity->language(LANGUAGE_NONE);
  $entity->title = (string)$Obj->ActivityName;
  $entity->body->set(array(
    'value' => $body,
    'summary' => (string)$Obj->Description,
    'format' => 'full_html',
  ));
  $entity->field_activityid = (string)$Obj->ActivityId;
  $entity->field_location_room = (string)$Obj->RoomNumber;
  $entity->field_location_building = (string)$Obj->BuildingCode;
  $entity->field_location_address->set(array(
    'country' => '',
    'thoroughfare' => '',
    'premise' => '',
    'locality' => '',
    'administrative_area' => '',
    'postal_code' => '',
  ));
  // $enitity->field_event_organizer->set(array(
  //   'field_event_presenter_name' => (string)$Obj->ContactFirstName,
  //   'field_event_presenter_title' => "TEST",
  //   'field_event_presenter_organizati' => "ORG",
  // ));

  $values = array(
    'field_name' => 'field_event_organizer',
    'field_event_presenter_name' => array(
      LANGUAGE_NONE => array(array('value' => (string)$Obj->ContactFirstName)),
    ),
    'field_event_presenter_title' => array(
      LANGUAGE_NONE => array(array('value' => "PTITLE")),
    ),
    'field_event_presenter_organizati' => array(
      LANGUAGE_NONE => array(array('value' => "PORGANI")),
    ),
  );

  $entity->save();
}

```

EDIT: main collection field:  sub fields:

I tried to add a modified version the code below in hopes it would work for me:

```
$field_collection_item = entity_create('field_collection_item', array(
    'field_name' => 'field_event_organizer'
  ));
  $field_collection_item->setHostEntity('node', $node);
  $field_collection_item->field_event_organizer_name = "PROG NAME";
  $field_collection_item->save();

  $entity->field_event_organizer = $field_collection_item->item_id;

```

However i got an error EntityMetadataWrapperException: Unknown data property propertyInfo. in EntityStructureWrapper-\>getPropertyInfo() (line 354 of /Applications/MAMP/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

EDIT: Re-tweaked the answer given to me by SN\_26 and it manages to create the node with the field\_collection filled in but I get the following error message:

```
The website encountered an unexpected error. Please try again later.
Status message Registration settings have been saved.
Error messageEntityMetadataWrapperException: There can be only numerical keyed items in a list. in EntityListWrapper->get() (line 1038 of /Applications/MAMP/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

```

full updated code:

```
function createNode($Obj){
  global $user;
  var_dump($Obj);
  $node = entity_create('node', array(
    'type' => 'event',
    'uid' => 1,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  ));
  $body = "<p>" . (string)$Obj->BuildingCode;
  $body .= " " . (string)$Obj->RoomNumber . "</p>";
  $body .= "<p>" . (string)$Obj->Description . "</p>";

  $entity = entity_metadata_wrapper('node', $node);
  $entity->language(LANGUAGE_NONE);
  $entity->title = (string)$Obj->ActivityName;
  $entity->body->set(array(
    'value' => $body,
    'summary' => (string)$Obj->Description,
    'format' => 'full_html',
  ));
  $entity->field_activityid = (string)$Obj->ActivityId;
  $entity->field_location_room = (string)$Obj->RoomNumber;
  $entity->field_location_building = (string)$Obj->BuildingCode;
  $entity->field_location_address->set(array(
    'country' => '',
    'thoroughfare' => '',
    'premise' => '',
    'locality' => '',
    'administrative_area' => '',
    'postal_code' => '',
  ));
  $entity->field_event_date[0]->set(array(
    'value' => _unix_date_time($Obj->StartDate, $Obj->StartMinute),//Y-m-d H:i:s
    'value2' => _unix_date_time($Obj->EndDate, $Obj->EndMinute),
  ));

  $field_collection_item = entity_create('field_collection_item', array(
    'field_name' => 'field_event_organizer'
  ));
  $field_collection_item->setHostEntity('node', $node);
  $field_collection_item->field_event_organizer_name[LANGUAGE_NONE][0]['value'] = "PROG NAME";
  $field_collection_item->save();

  $entity->field_event_organizer[LANGUAGE_NONE][0]['value'] = $field_collection_item->item_id;

  $entity->save();
}

```

# Answer
After much trial and error I found that this works by **NOT** assigning the `$field_collection_item` to the entity was the correct way to do this.

```
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_event_organizer'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->field_event_organizer_name[LANGUAGE_NONE][] = array('value' => $fullName);
$field_collection_item->save();

```
> 0 votes

# Answer
This should do the trick to insert a new field collection item:

```
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_some_collection'));
$field_collection_item->setHostEntity('node', $entity);
$field_collection_item->field_my_field_in_the_fc[LANGUAGE_NONE][0]['value'] = 'hello';
$field_collection_item->save();

$entity->field_some_collection[LANGUAGE_NONE][]['value'] = $field_collection_item->item_id;

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to disable anonymous user permissions on site build
Using the configuration below I am trying to have my site install without giving anonymous users permission to "View content". I have no other code that would set this permission, and I have this configuration file below in my custom profile. All of my other configs in this profile get imported correctly, but for some reason Anonymous users always get the "View content" permission.

user.role.anonymous.yml

```
langcode: en
status: true
dependencies: {  }
id: anonymous
label: 'Anonymous user'
weight: 0
is_admin: false
permissions: {  }

```

# Answer
I found where it is set: node.install

```
function node_install() {
  // Enable default permissions for system roles.
  // IMPORTANT: Modules SHOULD NOT automatically grant any user role access
  // permissions in hook_install().
  // However, the 'access content' permission is a very special case, since
  // there is hardly a point in installing the Node module without granting
  // these permissions. Doing so also allows tests to continue to operate as
  // expected without first having to manually grant these default permissions.
  if (\Drupal::moduleHandler()->moduleExists('user')) {
    user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access content']);
    user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access content']);
  }

```

So instead in my profile I am going to just use this function: `user_role_revoke_permissions()`

```
my_profile_install() {
  user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access content']);
}

```

With that function call in `my_profile.install` I get the permissions set the way I need them.
> 0 votes

# Answer
Use Content Access to block anonymous users viewing any content except logon page, and point 403 page to logon page.
> 0 votes

---
Tags: users, installation-profiles
---


title: Feeds: Imported dates wrong by 2 hours

text:
# Question
Title: Feeds: Imported dates wrong by 2 hours
I'm using feeds to import a couple of xlsx-files (MS Excel). In these there are two cells, which are mapped to start/enddate in the imported nodes.

When importing from some of the xlsx, the dates are shifted by 2 hours (instead of 08:00 its changed to 10:00).

Other xlsx-files are importing the right date value.

In the date field settings I have turned off timezone conversion.

How can I solve that problem? Is there a timezone setting inside an excel-file?

# Answer
> 0 votes
I guess you are at a time zone having 2 hours difference with UTC.

Excel store time fields in UTC format. Adjusting the time in the excel to take care of this behaviour is the easiest solution (use excel formulas)

---
Tags: datetime, feeds
---


# Question
Title: How to limit access to content for which the Content Access module doesn't limit access?
I run a small business, and have created a website in Drupal 8 (should have used 7, bit late now, oooops).

Part of the website is designed to be behind a subscription, which I've got working and works well. Only problem is, the content types I want to only be visible to people who have paid, are visible to everyone.

I installed the Content Access module and have set it up thus:

>

As you can see, "view any checklist content" is set as only "subscriber - bronze" which is currently the only role that'll need it.

When logged out, the page is visible; when logged in (as admin or a test account using that role) it's visible.

>

Rebuilding permissions is a pain (~20k nodes), but using Drupal Console I can do so and it runs successfully, but no change to the page's permissions.

# Answer
> 5 votes
I prefer to use Node view permissions for this. As long as all you are trying to do is control access to content types based to user type.

# Answer
> 5 votes
Maybe you want to give it a try to use the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

For this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

For the *part of the website that is behind a subscription* (as in your question), it seems that you would want to grant access to what, in Group, is called "Members" ("people who have paid" in your case). But you wouldn't allow access to that part of the website for:

* "Outsiders" (= logged in users who are not a member of a group).
* "Anonymous" (site visitors that are not logged it).

# Resources

---
Tags: 8, nodes, users
---


title: Feeds multiple csv files

text:
# Question
Title: Feeds multiple csv files
I need to import products from four csv files using Feeds. Do I have to create four importers or is there a way to make one importer read four csv files? The tables are identical in each file, only products are different.

# Answer
There are two possibilities:

First, as you mentioned, use four importers, you can easily duplicate an exporter using the export/import function.

Second, Feeds includes an option in the File Fetcher plugin to 'Supply path to file or directory directly '. If you check this, you can enter the path to the directory in your site's file structure where you have uploaded your to-be-imported files and Feeds will import them at once. Just upload your files to the specified folder.
> 0 votes

---
Tags: feeds, importing-exporting
---


# Question
Title: 8 - Caching for custom blocks doesn't work on <front>
I'm working on a project based on Drupal 8.3.x . It comes with cache already enabled which is great if we know how to customize it. I've been going through the different tutorials and I was able to implement the following cache for my custom block:

```
$build = [
      '#cache' => [
        'tags'=>['node'], // Invalidate cache whenever a new node is created/modified/deleted
        'contexts'=>['url'] // Invalidate cache per url
      ]
    ];

```

The problem I'm having is my website depends on cities and display different content for different cities. I have the following scenarios:

* When I visit www.example.com/city1 the block should display nodes from city 1
* When I visit www.example.com/city2 the block should display nodes from city 2
* When I visit www.example.com the block should display the nodes from the latest visited city

With the snippet above I'm able to make the point 1 and 2 work. however when visiting `front` only the content of the first visited city appears, which make sense because the Invalidation of the cache depends on the url and is only 1 url.

I tried this but didn't work:

```
global $selected_city;
'#cache' => [
    'keys'=>['home_slider_'.$selected_city],
    'tags'=>['node'],
    'contexts'=>['url']
  ]

```

Where `$selected_city` is coming from the cookie or the request depending on separate logic.

Is there a way to Invalidate the cache per url + global variable ?

EDIT: The answer below fixes the issue for authenticated users but doesn't fix it for anonymous users. Any help with that would be appreciated.

# Answer
> 0 votes
The issue I had is the front page always returns the first visited city. Which is normal because the cache was invalidated by url OR node and the homepage has 1 URL. So unless I create/update/delete a node the cache would not be invalidated.

The solution was to create my own cache context, i.e city and merge it with the url context. This would invalidate the cache per url per city and create a combination of the different possibilities.

Here is the code :

city/city.services.yml

```
cache_context.cw_city:
    class: Drupal\city\CacheContext\CityCacheContext
    arguments: []
    tags:
      - { name: cache.context }

```

city/src/CacheContext/CityCacheContext.php

```
<?php
namespace Drupal\city\CacheContext;

use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Cache\CacheableMetadata;

class CityCacheContext implements CacheContextInterface {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {

    return t('some label');
  }
  /**
   * {@inheritdoc}
   */
  public function getContext() {
    // The logic goes here
  }
  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
}

```

And on the block I merged the new context with the parent contexts like this :

```
/**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(
      parent::getCacheContexts(),
      ['city']
    );
  }

```

For more information please check this post

---
Tags: 8, blocks, caching
---


# Question
Title: hook_module_preuninstall doesn't run early enough
Uninstalling my module threw this error:

\[error\] my\_module: The My Field field type is used in the following field: my\_module.my\_field

But, since my module defines both an entity and a field, both of which will be uninstalled when I uninstall this module, it doesn't make sense. I'm trying to handle this by removing all of the fields programmatically in hook\_module\_preuninstall, which I have in the .module file because it wasn't working in the .install file.

The problem is, this hook runs *after* the checks for field dependencies. It would make more sense if it ran before, in my opinion, but, what can I use to get ahead of these checks? Anything? If not, what should I do so that my module realizes it needs to uninstall these things when the module is uninstalled?

Also, shouldn't this hook run earlier? If not, what is the point of it?

# Answer
Yes, there is currently no hook to do this.

The only thing you can do is have your own custom uninstall form that allows you to prepare the uninstall by deleting all data and then delete the field through the API, then point the user to the uninstall form.
> 2 votes

---
Tags: 8, installation
---


title: Loading menu on basis of user profile

text:
# Question
Title: Loading menu on basis of user profile
We are working in Drupal 8 website and same user will have two different user profiles buyer and seller.

We want to show a user drop menu and when user click on "buy" link in drop down then main menu of the site would be changed as per "buyer" profile.

And if user click on "sell" link in drop down menu then main menu of the site would be changed as per "seller" profile.

# Answer
> 2 votes
The primary way to control visibility is through block visibility conditions.

There is no default condition available for what you are trying to achieve, so you have to implement your own.

See \Drupal\user\Plugin\Condition\UserRole, that does visibility based on the user role, what you want would be fairly similar, visibility based on a field, so like any other plugin, you can copy that into your module into the plugin namespace (\Drual\yourmodule\Plugin\Condition) and then adjust it to check the field instead and also offer the same select.

Then you place two blocks in the same region, each with a visibility configuration using your plugin. You need to think about what should happen when a user is not logged in, so maybe you have a default or hide both for anon users/users without a selection.

---
Tags: 8, users, blocks
---


title: Cache is not updating

text:
# Question
Title: Cache is not updating
I have 2 Drupal7 application, both is having the same code. Both application is connecting to 1 database and 1 file storage which is a separate folder/directory. My problem is when I save/edit/delete something on the other application, the other application is not updated not unless I clear its cache. What will I do in order for the updates to reflect immediately in both application without clearing the cache?

# Answer
By looking at the filecache module description:

> This module allows Drupal cache bins to be stored in files instead of storing in database.

This means that the data is stored in a folder and I guess this folder is not shared between your web servers.

I think you have 3 options:

1. (easy solution) Disable Filecache and rely on the builtin cache of drupal. This will store the bins content on your database and it will be shared/invalidated for your two servers as they share the same DB
2. (best solution) Replace FileCache with another caching module as Memcache or Redis. Depending on your server you might want to run those in a separate virtual machine and link them back to your web servers.
3. Share the folder used by FileCache across your servers.

Hope this helps.
> 0 votes

---
Tags: caching
---


# Question
Title: How update programmatically node entity with empty field_image?
i need to make an import from one mysql table in my base.

I create node with :

```
$value= array(
                'type' => strtolower($typeProduit),
                'field_1'=>"test",
                'title'=>"test",
                'body' => array(
                    'value' => "test",
                    'format' => 'full_html',
                ),
                'field_2'=>"",
                'field_3'=>"",
                'field_4'=>"",
            );

 $nodeEntity=\Drupal::entityTypeManager()
        ->getStorage('node')
        ->create($value);

    $nodeEntity->save();

```

All node are create and if i have an image, i add it to my $value before save() :

```
$value['field_image_video']=array(
                    'target_id' => $fileImageVideo->id(),
                    'alt' => $catalogue->titreVideo,
                    'title' => $catalogue->titreVideo,
                );

```

if i have no image, i do nothing for this field.

I need to update some node programmatically after this first step.

And when i just try to change the title like this :

```
     $nodeEntityUpdate = \Drupal::entityTypeManager()
                    ->getStorage('node')
                    ->load(273);

     $nodeEntityUpdate->title="blabla";
     $nodeEntityUpdate->save();

```

if node don"t have image field set, i got this error :

> PHP Fatal error: Call to a member function getFileUri()

If node has image, update work.

How can i set my image\_field to null ?

i try to set my image field like that on creation :

```
$value['field_image_video']=array();

```

But that didn't work.

this image field is set to unlimited values

# Answer
> 0 votes
i got it in the update :

i set my image\_field in the update:

```
  $nodeEntityUpdate = \Drupal::entityTypeManager()
                    ->getStorage('node')
                    ->load(273);

     $nodeEntityUpdate->title="blabla";
     $nodeEntityUpdate->field_image_video =array();
     $nodeEntityUpdate->save();

```

I try to set this field in the create, but that change nothing.

As i can see, we need to set image field in the update if she is empty at the creation.

---
Tags: 8, nodes, updating
---


# Question
Title: How to consume RESTful web services in a custom module?
I have an API which I would like to consume to do specific actions on my Drupal 7 website after getting data from the user via a webform form. I plan to write my own custom module to do that but don't know how where I should start from.

Is there any hook that could help me add supplementary action after getting data from my webform ? How am I supposed to proceed to consume my web services ? Any code snippet, advice, will be appreciated.

# Answer
> 2 votes
Module RESTClient is for this purpose.

It provides 4 APIs:

* `restclient_get()`
* `restclient_post()`
* `restclient_put()`
* `restclient_delete()`

# Answer
> 0 votes
Most would agree here that there is no need to re-invent the wheel. There are already at least 4 wheels here that can be used. The Services module, which also has support for the Webform module (through another contributed module), is the most popular module for this job:

The other big players would be the RESTful module, restws and as Jimmy Ko mentioned, RESTClient. Although I don't personally have experience with these last 3, all 4 will have their pros/cons. Each should have sufficient documentation and code examples in the wild to get you started.

# Answer
> 0 votes
Web Service Clients was the only module I could get to work.

You create a connection via UI. Then you can use the API and make your requests from code.

Example API usage:

```
// 'my_connection' is the machine name of the connection.
$result = clients_connection_call('my_connection', 'method.name', $param1, $param2, $param_etc);

```

---
Tags: 7, hooks, webforms, services
---


# Question
Title: Accessing custom taxonomy term fields in a rules loop
I am building a rule that on node save will loop through taxonomy terms added to an entity reference (taxonomy term) field, build up a list of users from an entity reference (user) field in those taxonomy terms, and e-mail those users.

The problem I'm having is that my data selector won't give me the tokens for the user reference field in the taxonomy term loop. This rules issue tells me that I need to have the "entity has field condition" condition applied or the "content is of type" condition. Unfortunately all my conditions are referencing the node that is being saved.

I'm guessing that the answer would be to build the loop into some type of component so I can do a second condition check, but I'm not sure what the right approach for that would be. How can I let rules know what kind of entity I'm looping through, so it will give me access to the custom fields on that entity?

# Answer
Have a look at the question about "How to access commerce\_product field of line-items using Rules to flag the Commerce Product?". The accepted answer to it (disclosure: it's mine ...) explains how that question can be solved (also) by creating a ***Rules Component***, and which looks like so:

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

```

Note the ***parameters*** used in this Rules Component, i.e. `selected_line_item` ( = the line item being processed). And also note the `type` of that parameter (a Commerce line item).

The main rule just executes this Rules Component, as part of a Rules Loop in it, whereas in each iteration of that loop the actual *line item* being processed is passed as the value for that parameter. So with this example in mind, it seems that this might be a solution to your questions:

> How can I let rules know what kind of entity I'm looping through

The ***type*** of the ***parameter*** you pass to the Rules Component.

> ... so it will give me access to the custom fields on that entity

I think your Rules Component would not need any extra Rules Conditions, though if needed (as shown in my Rules Component example with the Rules Condition related to "Commerce Product"), you could add relevant other Rules Conditions if needed.

For the sake of completeness, some more details about that Rules Component:

* By adding the Rules Condition, I got access to the value of the id (key) of the Commerce Product that the line item was about.
* Since I had made the value of that id (key) of the Commerce Product avaiable, I could use the Rules Action to *fetch an entity by id* (entity being the Commerce Product). And by doing that, from then on I had ALL the data (fields) of the Commerce Product available.
> 2 votes

---
Tags: 7, rules
---


title: Question and Answers setup

text:
# Question
Title: Question and Answers setup
Trying to figure how to setup drupal 8 to function like StackExchange.

My goal is to be able to allow users to mark answers helpful so that best answers get moved to the top. Similar to StackExchange.

I can think of two ways to do this but would like some feedback from the experts.

Option 1: Create content Question and add comments to it. Use flag module to flag helpful replies. Create a template for question comments so that each top replies + its replies are groped together.

Option 2: Create Question, Create comment type Answer, Create a new comment type called replies and attach it to comment type Answer.

Or is there another alternative that I am not thinking off?

What would be the best way to create a similar setup such as StackExchange?

# Answer
> 1 votes
Your *Option 1* and *Option 2* seem to both implement "*answers*" as comments...

Another option (= Option 3) would be to implement *Answers* as another content type, combined with an entity reference field (multiple values allowed) added to your *Questions* content type.

By using a content type for both Questions and Answers, it would probaby simplify anything about voting (either Question or Answers), and you could also use the Flag module (e.g. to mark "an" answer as the "accepted" answer).

At this time it's too early (= not ready for D8 yet) for some typical other modules that could be added to this later on:

* the Rules module, to implement whatever logic you'd want (eg: only question authors can flag one, and only one. answer with the fag to mark an answer as accepted.
* the Userpoints module, to implement your reputation system.

PS: you probaby have a good reason why it has to be implemented in D8, but if D7 would be "good enough" (at least for now), you could implement something similar to this *Option 3* by using what is explained in this answer to "How to implement a reputation based system with badges in Drupal similar to StackExchange sites?".

---
Tags: theming
---


# Question
Title: Website returning 404 and not 403 for forbidden pages
My site is returning a 404 error for users who have tried to access a restricted page. I understand that this can be seen as a useful security features, however, I would like to return a 403 error instead.

I note that drupal is recording "access denied" in the logs, but somehow this is getting converted to a 404 for the user.

I have tried changing theme to see if that helps, and had no success. I have also removed custom 404 and 403 pages but this did not help either.

Googling the problem found the following file, drupal/core/lib/Drupal/Core/Controller/ExceptionController.php. This does not seem to exist in my installation of drupal.

I am not confident (or competent!) at altering php files.

Any help that can be provided would be greatly appreciated, as I am at a loss on how to proceed.

# Answer
> 0 votes
I've found a workaround using the "redirect 403 to login" module. It is not yet in alpha for D8, but seems pretty stable.

---
Tags: 8, users, debugging
---


title: How do I set the drush tmp directory?

text:
# Question
Title: How do I set the drush tmp directory?
I understand how to use /etc/drush/drush.ini; however, I don't know what exactly to put in there in order for Drush to use a different temp directory when creating an archive-dump.

# Answer
You can change drush temp directory by seting the TEMP environment variable.

In linux:

```
export TEMP=/mnt/tmp

```

will instruct drush to store your temporary dump to /mnt/tmp.

Depends on operating system, it can be set with different variable. For more details, the code is here: drush/includes/filesystem.inc: function drush\_find\_tmp()

https://github.com/drush-ops/drush/blob/de8106ba13a286320fcced88f04fbe6ae119fd4b/includes/filesystem.inc#L436
> 3 votes

# Answer
```
$options['dump-dir'] = '/path/to/dumpdir';

```

found in example.drushrc.php :)
> 2 votes

# Answer
For Drush 7 sql-sync you can specify --target-dump

That specifies the actual file Drush will write to on the target.

```
$ drush sql-sync @site.prod @site.self --target-dump=/tmp/self/prod-db.sql.gz

```

NB This should answer " Perhaps I should clarify a bit. I need to be able to have a drush archive-dump use a different directory than /tmp (which I think is set via an environment variable.) My /tmp mount point is too small to handle a drush archive-dump; so the dump fails. – Mike Broyles Mar 13 '13 at 0:34", but I don't have reputation here so therefor a new answer.
> 1 votes

# Answer
For Drush 6, see https://drupal.org/node/1806416. That patch may or may not get backported to Drush5. See that link for current status.
> 0 votes

---
Tags: drush
---


# Question
Title: Feed import of 20,000 nodes. How to batch up 1000 at a time?
I setup my Drupal 7 feed importer to import from a csv file with 20,000 nodes. I'm able to get it working with 20 nodes just to test to make sure everything is working. But is there a setting to be able to process X amount of nodes at once? My csv file is 12MB and I'd like to just do 300 at a time, but I don't see an option for this anywhere.

How would I make it process a set amount?

# Answer
> 2 votes
Recent versions of Feeds (since 7.x-2.0-beta1) will try to import as many items as it can per cron run. Imports can be ran on cron runs by either using the "Process in background" option or by setting the "Periodic import" option. By default, Feeds indeed imports items in batches of 50, but on each cron run Feeds will try to run as many batches as it can one minute.

If you want Feeds to run longer than one minute on each cron run, you can do so by altering the time limit of the queue 'feeds\_source\_import' by implementing `hook_cron_queue_info_alter()`:

```
/**
 * Implements hook_cron_queue_info_alter().
 */
function mymodule_cron_queue_info_alter(&$queues) {
  // Run Feeds imports at max. 5 minutes per cron run.
  $queues['feeds_source_import']['time'] = 300;
}

```

You can also increase the batch size by setting the 'feeds\_process\_limit' variable:

```
// Process 250 items per batch.
variable_set('feeds_process_limit', 250);

```

Do so only if you are using an alternative way of importing the data (as on cron runs Feeds will already try to import multiple batches).

Finally, the dev version of Feeds has improved support for larger files downloaded with the HTTP Fetcher. I'm still working on the issue that a large CSV file must be completely imported within 6 hours. If you need more than 6 hours to complete the import (for example: if cron doesn't run often), try the patch from https://www.drupal.org/node/1029102.

# Answer
> 1 votes
Which version of Drupal are you using? I haven't checked on Feeds for Drupal 8, but Feeds for Drupal 7 (unless it's changed in the last few years) has a hard-coded item limit of 50. If you're importing from a CSV, your node architecture is probably pretty simple. You could try the Feed Import module instead of Feeds, in my experience it's better suited for very large imports.

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: How can I migrate the Domain publishing settings for nodes via SQL?
I am using Drupal 7 and Domain Access (latest stable versions).

In my source site, there are nodes with "Domain access options", "publish to.." then a number of selected domains.

I migrate the data in the node\_access table, mapping the old nid to the new nid using the migrate\_map\_xxx table.

However when I view a Node which has rows in the node\_access table, publishing the node to certain domain id, the relevant box is not ticked on the node edit page.

When I rebuild permissions, the rows of data I migrated into node\_access disappear and the node is still published to just the default domain (three other rows were inserted into the node\_access table, now there is just one).

How can I migrate the publishing options for nodes from one DB to another?

# Answer
> 0 votes
OK, I figured it out... The domain\_access table is the one I need to migrate the data from and to.

Key is to rebuild permissions after updating the domain\_access table, so the node\_access table is updated with the latest domain publishing options.

So I executed the following SQL to migrate the old domain\_access records in to the new DB, then update with the new nid values from the migrate\_d2d mapping table:-

```
delete from destinationdatabase.domain_access
    where nid in (select destid1 from destinationdatabase.migrate_map_blognodearticle);

CREATE TABLE IF NOT EXISTS destinationdatabase.domain_access_tmp LIKE destinationdatabase.domain_access;

INSERT INTO destinationdb.domain_access_tmp (nid, gid, realm)
SELECT nid, gid, realm
FROM sourcedatabase.domain_access
where sourcedatabase.domain_access.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

UPDATE destinationdatabase.domain_access_tmp AS ds, destinationdatabase.migrate_map_blognodearticle AS new
SET ds.nid=new.destid1
WHERE ds.nid=new.sourceid1
and ds.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

INSERT INTO destinationdatabase.domain_access (nid, gid, realm)
SELECT nid, gid, realm
FROM destinationdatabase.domain_access_tmp;

```

Then ran `drush eval 'node_access_rebuild();`

---
Tags: 7, migrations, domain-access
---


# Question
Title: Add class to all labels in a comment form
Pretty straight forward. For every label within a comment form, I wish to add a particular class to it. Using only functions in template.php, in Drupal 7, how can this be done? If it can't be done this way, what is the most straight-forward alternative?

# Answer
> 0 votes
Can't come up with a cleaner solution than implementing theme\_form\_element\_label and adding the classes there depending on the elements name (comment\_body) etc.

Maybe an option is to implement hook\_form\_comment\_form\_alter() and add specific identifiers to the elements you want to change the css class for the labels on in theme\_form\_element\_label().

# Answer
> 0 votes
My solution a few years ago was to override comment-wrapper.tpl.php and comment.tpl.php in my sub-theme and I added my custom classes there, no need for functions or custom modules. You can find templates in comment core module.

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


title: Override module's template in theme

text:
# Question
Title: Override module's template in theme
Suppose i have this hook\_theme() in my module, choosing a template inside the module:

```
/**
 * Implements hook_theme().
 */
 function module_theme($existing, $type, $theme, $path) {
   return array(
     'module-output' => array(
       'template'  => 'output-template',
       'variables' => array(),
   ),
 }

```

If i put the same output-template.tpl.php inside my active theme, Drupal picks up the module's template.

Is there a way to make Drupal understand that if a template with the same filename exists somewhere in the theme, to pick the theme's template and not the module's (like an override)?

# Answer
You can override tpl files defined in modules inside your active theme (under the `templates` directory). But Drupal will look for a file name using the defined theme key name and not the defined template file.

In your case, you should create a `module-output.tpl.php` file within your theme. Maybe a good practice to name your template file the same as your theme definition.
> 8 votes

# Answer
Just to mention here that you can even change the template file name also if you implement `template_preprocess_page()` for your theme.

So, you can add a new theme suggestion like this:

```
/**
 * Implements template_preprocess_page().
 */
function YOURTHEMENAME_preprocess_page(&$variables) {
  // Let's assume your tpl file is page--home.tpl.php.
  $variables['theme_hook_suggestions'][] = 'page__home';
}

```

Also you can re-order the priority of these theme suggestion as per your needs.

But you should think to write a semantic code as you can.

I usually add new theme suggestion when the client asks to use the front page.tpl for all static page content type like this way:

```
// Check if this page has defined node object or not.
if(isset($vars['node']) && isset($vars['node']->type) && ($vars['node']->type == 'page')){
  // Make all page nodes wear page--home.tpl.php.
  $vars['theme_hook_suggestions'][] = 'page__home';
}

```

Good luck!
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do I display the products and nodes of the same author in the current page?
I wish to display a block with the products of the same author as the current page.

Contextual filters work on node pages, but not on product pages.

In contextual filters, I add "Product: Author" but no options are available for products.

There is no check box for products, as for content "Also look for a node and use the author of the node".

Thank you, but that's not my question.

"User 1" created:

* product 1, product 2, product 3.
* node 1, node 2, node 3.

"User 2" created:

* product 4, product 5, product 6.
* node 4, node 5, node 6.

When I visit node 5, I have the products and nodes of the same author in a block in the second sidebar:

* product 4, product 5, product 6.
* node 4, node 6.

When I visit product 3, nothing is displayed. Because the contextual filter does not find the author in the product page.

Normally it should display the products and nodes of the same author in a block in the second sidebar:

* product 1, product 2.
* node 1, node 2, node 3.

# Answer
The trick is in the relations and contextual filters.

You need to add a relation to the Author and then another relation to Product using the Author as a relationship, then go to add a Contextual filter Content ID (Provide default value \[Content ID from URL\]) and use Product as Relationship.

Something like this:
> 1 votes

---
Tags: views, 8, nodes, users, commerce
---


# Question
Title: How to change the language of strings like "read more" and "submitted by"?
I've managed to create a website with Drupal 8.3.7.

How do I get Drupal to print things like "Read more" in views and "Submitted by", "Wednesday, August 23" in an article or `t("something supposedly translated")` in another language?

I'd like the administration interface to remain in English. I'd like to avoid a language prefix in URLs (yes: /mycurrenturlalias, no: /XX/mycurrenturlalias) but at this point I really don't even care anymore.

I've tried installing the Language module, adding a new language, setting it as the default and only language, installing some translation modules and fiddling with their settings. I've broken the site in some interesting ways but what I haven't gotten is a single translation of those strings anywhere. I must be doing something horribly wrong, but please ignore that and just tell me what should work.

# Answer
1. Install the core modules Language and Interface Translation
2. Add other language (admin/config/regional/language)
3. Configure the Selected language setting (admin/config/regional/language/detection)
4. To have a different language in admin enable the detection method ***Account administration pages***
5. Go to user/1/edit and in *Language settings* section select your *Administration pages language*
6. Translate your strings (admin/config/regional/translate)
> 1 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: Modify parent entity from within custom field formatter
How can I modify parent entity's output from within my custom field. I am writing a custom field that adds css class to blocks. Everything is set, except I don't know how to modify the parent entity.

# Answer
It's not possible to do this from inside the field.

To modifiy the classes of the parent entity use hook\_entity\_view().

Check, if the field is in `$build` and then add the classes to the entity:

```
$build['#attributes']['class'][] = 'new-class';

```
> 2 votes

# Answer
You can do this from inside the field formatter. Each of the `$items` passed into the `viewElements` method has a `getEntity()` method that will give you the entity.

```
class MyFieldFormatter extends FormatterBase {

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $entity = $items[0]->getEntity();
  }

}

```

However, this is not recommended since it inverts the normal control flow. In normal situations, everything needed to render a field is a value on a column in the field itself. Grabbing the entity is icky, but is definitely possible for strange edge cases.
> 3 votes

---
Tags: entities, 8
---


title: Block title not show for exposed filter

text:
# Question
Title: Block title not show for exposed filter
My exposed filter's form is placed in a region, within a block. I have activated the *Config Block \> Display Title* option (I also overrode the title) but I see no title (a `h2` should be added on top of the form, like it is displayed in other custom blocks below the filter, I suppose)

```
<div class="views-exposed-form bef-exposed-form
            contextual-region block block-views
            block-views-exposed-filter-blockcar-model-view-page-1"
     data-drupal-selector="views-exposed-form-car-model-view-page-1"
     id="block-exposedformcar-model-viewpage-1">
    <!-- A H2 with the title doesn't show up here like in other blocks -->
    <div data-contextual-
        id="block:block=exposedformcar_model_viewpage_1:langcode=en|
        entity.view.edit_form:view=car_model_view:location=exposed_filter
        &name=car_model_view&display_id=page_1&langcode=en"
    class="contextual" role="form">
        <div class="content">
            <!-- The form with the filters -->
        </div>
    </div>
</div>

```

Why is this happening? Could I add the title within a `form_alter` hook?

# Answer
> 1 votes
It is a known issue and there appears to be a patch for it: https://www.drupal.org/node/2720101

---
Tags: views, blocks, theming
---


# Question
Title: What is the best way to verify controller arguments?
For example, I have a path on my site.

Let it be www.mysite.com/year/{year}/month/{month}/day/{day}

Could you clarify me, what is the best way to avoid getting of wrong arguments, such as year/3000/month/15/day/32 ?

Should I verify them inside the function called with the controller? Or is there a separated function or method to verify them, which wouldn't let invoke the controller function in case of wrong arguments?

# Answer
Here my working example:

**.routing.yml**

```
forcontu_pages.calculator:
  path: '/forcontu/pages/calculator/{num1}/{num2}'
  defaults:
    _controller: '\Drupal\forcontu_pages\Controller\ForcontuPagesController::calculator'
    num1: 20
    num2: 10
    _title: 'Calculator Page'
  requirements:
    _permission: 'access calculator'
    _custom_access:  '\Drupal\forcontu_pages\Controller\ForcontuPagesController::access'

```

**ForcontuPagesController.php**

```
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
...
  public function access(AccountInterface $account, $num1, $num2) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    return AccessResult::allowedIf($num1 > $num2);
  }
...

```

I just verify that $num1 is greater than $num2, but you can add your other params and your validations.

See that you can add more params:

> The access method arguments are resolved similar to normal routing. The following arguments are optionally available; they will be populated if they are properly type hinted:
>
> * The slugs, like with normal routing.
> * \Symfony\Component\HttpFoundation\Request $request
> * \Symfony\Component\Routing\Route $route
> * \Drupal\Core\Routing\RouteMatch $route\_match
> * \Drupal\Core\Session\AccountProxy $account

***Read***: What is a slug?

Reference: Access checking on routes
> 2 votes

# Answer
Depends on what is expected to happen if the parameters are wrong, if it should return a page not found you can define constraints using regular expressions to validate the parameters in the route definition:

```
example.user
  path: '/example/{name}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'
    name: '[a-zA-Z]+'

```

https://www.drupal.org/docs/8/api/routing-system/parameters-values-validation-in-routes
> 1 votes

---
Tags: 8, routes, page-controller
---