# Question
Title: How to alter my query in hook_views_query_alter to use the right where expression?
I am displaying a fee schedule using views and need to skip paid fee schedules. For that, I need to add following JOIN in views query using `hook_views_query_alter()`.

```
LEFT JOIN ic_fee_schedule_payments AS FSP ON fee_schedule.fid = FSP.fid AND fee_schedule_students.uid = FSP.uid AND fee_schedule_instalments.iid = FSP.iid

```

with added where clause as:

```
AND FSP.pid IS NULL

```

I have tried the following code in `hook_views_query_alter()`, but it does not work.

```
# In order to add a new table to join, you'll need to create a new views_join object.
    $join = new views_join;
    $join->construct('fee_schedule', 'fee_schedule_payments', 'fid', 'fid');
    $join1 = new views_join;
    $join1->construct('fee_schedule_students', 'fee_schedule_payments', 'uid', 'uid');
    $join2 = new views_join;
    $join2->construct('fee_schedule_instalments', 'fee_schedule_payments', 'iid', 'iid');
    #$join->extra = array(array('table' => 'fee_schedule_payments', 'field' => 'pid', 'operator' => 'IS', 'value' => 'NULL'));
    // $join is the views_join object created above
    $query->add_relationship('fee_schedule', $join, 'fee_schedule_payments');
    $query->add_relationship('fee_schedule_students', $join1, 'fee_schedule_payments');
    $query->add_relationship('fee_schedule_instalments', $join2, 'fee_schedule_payments');
    $query->add_where('fee_schedule_payments', 'fee_schedule_payments.pid', 'NULL', 'IS');

```

EDIT: Tried the other way but still does not work.

```
$join = new views_join;
    $join->construct('fee_schedule', 'fee_schedule_payments', 'fid', 'fid');
    $join->extra = array(array('table' => 'fee_schedule_payments', 'field' => 'uid', 'operator' => '=', 'value' => 'fee_schedule_students.uid'), array('table' => 'fee_schedule_payments', 'field' => 'iid', 'operator' => '=', 'value' => 'fee_schedule_instalments.iid'));
    $query->add_relationship('fee_schedule', $join, 'fee_schedule_payments');
    $query->add_where('fee_schedule_payments', 'fee_schedule_payments.pid', 'NULL', 'IS');

```

Am I missing something or need to alter query in some other way?

# Answer
> 3 votes
I'm not 100% sure, but I think to add the "IS NULL" part, you may need spaces around "IS" such as:

```
$query->add_where('fee_schedule_payments', 'fee_schedule_payments.pid', 'NULL', ' IS ');

```

OR...maybe something using add\_where\_expression...

```
$query->add_where_expression(0, 'fee_schedule_payments.pid IS NULL');

```

# Answer
> 0 votes
In Drupal 8, the following seems to work:

```
$query->addWhere(0,'fee_schedule_payments.pid',NULL,'IS NULL');

```

---
Tags: database, views
---


# Question
Title: Default user image in user account menu!
I am trying to add a default image to render in the user account menu when the user does not have an image.

CODE:

```
function nestle_preprocess_menu(&$variables) {
  if($variables['menu_name'] == "account") {
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $name = $variables['user']->getUsername();
    $picture = file_create_url($file->getFileUri());
    $picture = $user->user_picture->view('large');
    $variables['items']['user.page']['title'] = $name;
    $variables['items']['user.page']['picture'] = $picture;
  }
}

```

What I did so far, is that I changed the "account" menu link to name of the logged in user and I added the picture of the user in the variables array so that I can render it using twig, The problem is I want to check when the $picture variable is empty ( ie: user has no photo ) it should render a default image from a URL.

PS: I am using Drupal 8, and this code is in the .theme file

# Answer
> 0 votes
You can check if a user picture exists this way:

```
if (!$user->user_picture->isEmpty()) {
  $picture = file_create_url($file->getFileUri());
  $picture = $user->user_picture->view('large');
} else {
  $picture_field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
  $default_image = $picture_field->getSetting('default_image');
  $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
  $picture = $file->getFileUri();
}

```

# Answer
> 0 votes
Custom Function:

```
function custom_ImageURL() {

  $imageURL = NULL;

  $imageFieldName = // However you're getting your field name.

  // Check the field exists.
  if (!empty(FieldConfig::loadByName('user', 'user', $imageFieldName))) {

    // Check there is a primary image.
    if ($user->$imageFieldName->entity) {

      $imageURL = $user->$imageFieldName->entity->url();

    }
    // No primary image, check for default image.
    elseif (FieldConfig::loadByName('user', 'user', $imageFieldName)
      ->getSetting('default_image')['uuid']) {

      $imageGetSettings = FieldConfig::loadByName('user', 'user', $imageFieldName)
        ->getSetting('default_image');

      $imageURI = Drupal::service('entity.repository')
        ->loadEntityByUuid('file', $imageGetSettings['uuid'])
        ->getFileUri();

      $imageURL = file_create_url($imageURI);

    }

  }

  return $imageURL;

}

```

To load with an image style replace `$imageURL = ...` with:

```
$style = \Drupal::entityTypeManager()
  ->getStorage('image_style')->load('thumbnail');

$imageStyleURL = $style->buildUrl($user
  ->$imageFieldName->entity->uri->value);

$imageURL = $imageStyleURL;

```

Then in whatever preprocess function you need:

```
function hook_preprocess_menu(&$variables, $hook) {

  $imageURL = custom_ImageURL();

}

```

I have found checking if the field exists via `FieldConfig::loadByName()` produces fewer use case errors than `->isEmpty` or `->isEmpty()`.

Then you can compare against `entity` existing for the primary value. The default value is stored in field settings array.

---
Tags: theming, 8, media
---


# Question
Title: after 8.6.14 set entity reference field via form alter failed
after the core update some how the form alter set field was broken, I tried multiple methods but its not working like :

> $form\['field\_trip\_reference'\]\['widget'\]\['#default\_value'\] = array(820);
> $form\['field\_trip\_reference'\]\['widget'\]\[0\]\['target\_id'\]\['#default\_value'\] = \Drupal\node\Entity\Node::load(820); $form\['field\_trip\_reference'\]\['widget'\]\[0\]\['target\_id'\]\['#value'\] = \Drupal\node\Entity\Node::load(820);
> $form\['field\_trip\_reference'\]\['widget'\]\[0\]\['target\_id'\]\['#default\_value'\] = 820; $form\['field\_trip\_reference'\]\['widget'\]\[0\]\['target\_id'\]\['#value'\] = 820; $form\['field\_trip\_reference'\]\['widget'\]\[0\]\['target\_id'\] = \Drupal\node\Entity\Node::load(820);
> $form\['field\_trip\_reference'\]\['widget'\]\[0\]\['target\_id'\] = 820;
> $form\['field\_trip\_reference'\]\['widget'\]\['target\_id'\]\['#default\_value'\] = 'node:820';

anything that needs to updated?

UPdate : (its my own mistake) this is the one that is working

```
$form['field_reference']['widget']['#default_value'] = $thenodeid;

```

# Answer
> 0 votes
turns out I am overwriting the form and the one that is working for me is :

> $form\['field\_reference'\]\['widget'\]\['#default\_value'\] = $thenodeid;

---
Tags: forms, hooks
---


title: Show full image path D8

text:
# Question
Title: Show full image path D8
I have set a Drupal 8 project into another server with some child directory. This D8 project is working good, But images are not showing due to path missing. E.g

My project is setup:- http://abc.xyz.com/client/development/**project-name**/

but when I was inspecting element then I got image URL:-http://abc.xyz.com/sites/default/files/images.png

I know client/develoment/project-name/ path is missing into the image path. May you let me know how to get full image path display?

Full path must show:-http://abc.xyz.com/client/development/**project-name**/sites/default/files/images.png

Thanks

# Answer
> 0 votes
Images are hardlinked inside the body field.

One way to correct it is to do a search and replace inside the database.

Perhaps also pathologic can help correct the problem with broken images.

* add pathologic support to your desired text formats (congig \> content authoring \> text formats)
* make sure you check *Correct URLs with Pathologic*

when visiting a page pathologic should correct those broken images

---
Tags: media
---


title: HttpFoundation Request POST parameters

text:
# Question
Title: HttpFoundation Request POST parameters
From VueJS, I am sending a POST HTTP request to my Drupal 8 controller.

Here is my Controller:

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class ExampleController extends ControllerBase {

  public function doSomething( Request $request) {

    \Drupal::logger('mymodule')->notice($request->getContent());
    \Drupal::logger('mymodule')->notice($request->request->get('message'));

    return [];
  }
}

```

The first log entry outputs:

`@"params":{"message":"hello world","headers":@"Content-Type":"application/json; charset=UTF-8","Access-Control-Allow-Origin":"http://localhost:8080"}`

**The second log entry fails** (it is empty).

What am I doing wrong and how am I supposed to retrieve this `message` POST parameter?

For completeness, here is the JS POST request:

```
this.$http.post('http://mydrupal8.url/simple_path', {
  params: {
    'message': 'hello world'
  },
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Access-Control-Allow-Origin': 'http://localhost:8080',
  }
}).then(response => {
  // response
}, response => {
  // error callback
});

```

mymodule.routing.yml file:

```
mymodule.api_example:
  path: 'simple_path'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ExampleController::doSomething'
  methods: [POST]
  requirements:
    _access: 'TRUE'

```

# Answer
> 0 votes
Apparently with Vue Resource, I need to add `emulateJSON`:

> `emulateJSON` **boolean** Send request body as `application/x-www-form-urlencoded` content type.

```
this.$http.post('http://mydrupal8.url/simple_path', {
  params: {
    'message': 'hello world'
  },
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:8080',
  }
}, {
  emulateJSON: true
}).then(response => {

  console.log(response);

}, response => {
  // error callback
});

```

Now in my D8 backend:

```
$params = $request->request->get('params');
$message = $params['message'];

```

And now it works as expected.

---
Tags: 8, http-request
---


# Question
Title: How do I alter/change the "field is required" message?
I have below code

```
$form['name'] = [
      '#type' => 'textfield',
      //'#title' => $this->t('Email'),
      '#size' => 60,
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#default_value' => $form_state->getValue('name', ''),
      '#required' => TRUE,
      '#attributes' => [
        'placeholder' => $this->t('Email'),
        'autocorrect' => 'none',
        'autocapitalize' => 'none',
        'spellcheck' => 'false',
        'autofocus' => 'autofocus',
      ],
    ];

```

When I comment title it shows blank. I would like to change error message of the required field.

In the validation handler, I tried with this code.

```
if ($form_state->isValueEmpty('name')) {
  $form_state->setErrorByName('name', $this->t('Email is required.'));
}

```

It's not showing the error message.

I would like to keep the form element required and alter the error message.

# Answer
Set the *required\_error* property as in the following code. This is available in Drupal 8.6.

```
$form['name'] = [
  '#type' => 'textfield',
  '#size' => 60,
  '#default_value' => $form_state->getValue('name', ''),
  '#required' => TRUE,
  '#required_error' => t('Please select something.'),
];

```

To make this work, you will have to disable HTML5 validation on the form.

```
$form['#attributes']['novalidate'] = 'novalidate';

```
> 2 votes

# Answer
Try this, it might work.

```
$name = $form_state->getValue('name');
if (empty($name)) {
   $form_state->setErrorByName('name', $this->t('Email is required.'));
}

```
> 1 votes

# Answer
For drupal 8 working for me, Remove '#required' =\> TRUE,

In Form validation you can write your message what you want.

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

$name = $form_state->getValue(['name']);

if(!$name) {
    $form_state->setErrorByName('name', $this->t('Enter valid name.'));
}
}

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Referenced entities show old value when changing properties
I have three custom entities, all generated with Drupal Console. I only added some basicFieldDefinitions to them before testing some CRUD operations on them.

I have these entities:

* ConfigEntity (config entity - lowest level)
* ChildEntity (content entity - has an entity\_reference field to ConfigEntity)
* ParentEntity (content entity - has an entity\_reference field to ChildEntity)

When I display the name of the ConfigEntity through the entire chain, it displays properly

```
// "Original Value"
$parentEntity->get('child_entity')->entity->get('config_entity')->entity->label()

```

When I update the name, it still displays the original value through the chain, although printing it from the entity itself, it is the new value.

```
// "Original Value"
$parentEntity->get('child_entity')->entity->get('config_entity')->entity->label();

$configEntity = ConfigEntity::load(1);
$configEntity->set('label', "New Value")->save();

$configEntity = ConfigEntity::load(1);

// "New Value"
$configEntity->label();

$parentEntity = ParentEntity::load(1);

// "Original Value" instead of "New Value"
$parentEntity->get('child_entity')->entity->get('config_entity')->entity->label();

```

Any idea if there's a cache tag mechanism I have to implement manually, or something I have to invalidate myself in code?

# Answer
> 1 votes
You can clear the static entity cache with EntityStorageBase::resetCache:

```
\Drupal::entityTypeManager()->getStorage('parent_entity')->resetCache([$parentEntity->id()]);

```

---
Tags: entities, caching
---


# Question
Title: How do I convert a pre-existing site to a Composer-managed application?
The latest Drush 9.x version recommends that Drupal 8 sites will be built using Composer, with Drush listed as a dependency. However, when you install Composer and Drush globally per step #1 on http://docs.drush.org/en/master/install and then proceed to step #2 Installing Drush Launcher and then try to run Drush on a pre-existing Drupal website (e.g. `drush --version`), then you will get:

> Drush Launcher Version: 0.6.0
> The Drush launcher could not find a Drupal site to operate on. Please do *one* of the following:
>
> * Navigate to any where within your Drupal project and try again.
> * Add --root=/path/to/drupal so Drush knows where your site is located.

How do I get around this problem, and make Drush work with pre-existing Drupal sites?

# Answer
> 5 votes

# Answer
> 3 votes
In case you use Drupal7, I did

```
drush pm-list --status="enabled" --no-core --fields=name,version > modules.txt
while read line; do comp=`echo $line | sed 's/.*(\(.*\))/\1/' - | sed 's/7\.x\-//' - | awk '$1=$1'`; echo \"drupal\/`echo $comp | awk '{ print $1 }'`\"\:\ \"`echo $comp | awk '{ print $2 }'`\"; done < modules.txt

```

You can cut&paste your modules list directly into your composer :D

---
Tags: drush, composer
---


title: How do I override a RenderElement?

text:
# Question
Title: How do I override a RenderElement?
There is a Drupal 8 RenderElement called HtmlTag, which controls how HtmlTags are rendered. I would like to override this so that I can change its default behaviour.

I could write a class that extends HtmlTag and override what I need, but then how would Drupal core and the theme system know to use my new class?

Alternatively, maybe I should be using `hook_theme_registry_alter()` to tell Drupal 8 to use my new class?

I'm not really sure of the best way of achieving this and there don't seem to be any examples of this being done.

# Answer
Using `hook_element_info_alter()` would be one option, not sure it's the best.

The existing class sets 2 pre render callbacks, which you can override in your own class:

```
function MYMODULE_element_info_alter(array &$types) {
  $types['html_tag']['#pre_render'] = [
    [\Drupal\mymodule\HtmlTag::class, 'preRenderConditionalComments'],
    [\Drupal\mymodule\HtmlTag::class, 'preRenderHtmlTag'],
  ];
}

...

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\HtmlTag as CoreHtmlTag;

class HtmlTag extends CoreHtmlTag {

  public function preRenderHtmlTag($element) {
    // ...
  }

  public function preRenderConditionalComments($element) {
    // ...
  }

}

```
> 7 votes

# Answer
If hook\_element\_info\_alter() doesn't go far enough for you, there's a core issue to add a hook\_element\_plugin\_alter() to directly alter the plugin class for an Element (of which RenderElements are a subset): https://www.drupal.org/project/drupal/issues/2987208

The core patch is a one-line addition of `$this->alterInfo('element_plugin');` in `ElementInfoManager`, which specifies this new alter hook.

Then in your custom module:

```
function hook_element_plugin_alter(array &$definitions) {
 // Use a custom class for the HtmlTag element.
 $definitions['html_tag']['class'] = '\Drupal\mymodule\RenderElement\MyHtmlTagElement';
}

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Where can I set cardinality for a custom field?
I have a custom field defined in a module I am writing, which works correctly. The default cardinality is unlimited and I want to limit it to 1.

I am sure I need to call `setCardinality(FieldStorageDefinitionInterface::1)` somewhere, but I can't understand where exactly I should add that call.

# Answer
> 5 votes
Yes, you can limit a custom field to single value by defining a cardinality in the annotations of the field type.

I don't know if you can find this in the docs, but you can use the core comment field as example:

```
/**
 * Plugin implementation of the 'comment' field type.
 *
 * @FieldType(
 *   id = "comment",
 *   label = @Translation("Comments"),
 *   description = @Translation("This field manages configuration and presentation of comments on an entity."),
 *   list_class = "\Drupal\comment\CommentFieldItemList",
 *   default_widget = "comment_default",
 *   default_formatter = "comment_default",
 *   cardinality = 1,
 * )
 */
class CommentItem extends FieldItemBase implements CommentItemInterface {

```

When you add a comment field to a content type the cardinality form element is hidden and instead this message is displayed:

> **Allowed number of values**
>
> This field cardinality is set to 1 and cannot be configured.

---
Tags: 8, entities
---


title: How load only some node fields?

text:
# Question
Title: How load only some node fields?
`entity.query` service is very handy when it comes to finding nodes with specific field values. Unfortunately all it returns are entity IDs and revision IDs.

In case in which result set is big it's really inefficient to load whole nodes if only data from specific fields is needed.

In D7 it was possible for example to use `field_attach_load()` function which (thankfully) has been removed in D8, as detailed in Fields are no longer handled individually and are bound to an entity type. The problem is that Drupal change log references `loadFieldItems()` and `doLoadFieldItems()` of `FieldableEntityStorageControllerBase` class neither of which exists in current release of D8.

What is the Drupal 8 way of loading data for specific node fields only?

# Answer
> 2 votes
According to Acquia articles and specifically this:

> In Drupal 7, we often accessed fields directly, using hooks to modify fields when they were loaded, changed, or saved. In Drupal 8, there is a focus on entities instead of fields. **Because of this, if we want to modify fields we need to get the fields out of the entities.**

So in Drupal 8 you can't directly access any fields without first loading the whole entity as the following example (taken from the Acquia article) demonstrates:

```
/**
* @var $entity \Drupal\Core\Entity\Entity
*/
$entity = $entity_storage->load($entity_id);

/**
* @var $field \Drupal\Core\Field\FieldItemList
*/
$field = $entity->get($field_name);

// We get the string value from the field.
$value = $field->value;

// Get the summary from a body field.
$summary = $body_field->summary;

$field->value = 'changed value';

```

Unfortunately the specific thing you want doesn't exist in the API. All field data is loaded in bulk via `ContentEntityStorageBase::doLoadRevisionFieldItems`, and the standard `SqlContentEntityStorage` doesn't contain any methods for extracting individual fields. If you haven't already done so, it might be worth benchmarking this to see if there's a real problem. A lot of work was done on the cache system for D8, things might not be as slow as you think.

Implementing this manually would be pretty easy, just re-implement `SqlContentEntityStorage::buildQuery` in a new service class and change it to only load data for the field(s) passed in as an arguments from the table mapping. But you don't get any cache goodness with that, which I suspect is at least part of the reason loading individual fields was removed in the first place.

# Answer
> 6 votes
I did some profiling with a query of 100,000 nodes, fetching the field `myfield` from all nodes of type `mybundle`.

# Good: A dynamic query with `addField()`

```
$connection = \Drupal::database();
$query = $connection->select('node__field_myfield');
$query->condition('node__field_myfield.bundle', 'mybundle');
$query->addField('node__field_myfield', 'field_myfield_value');
$result = $query->execute();
$values = $result->fetchAll();

```

This runs in about 250 milliseconds.

# Bad: An entity query with `loadMultiple()`

```
$query = \Drupal::entityQuery('node');
$query->condition('type', 'mybundle');
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$values = [];
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);
foreach($nodes as $node) {
  $values[] = $node->get('field_myfield')->getValue();
}

```

This took 3 minutes after a few repeated attempts when the cache was fully built. After a cache rebuild, it took more than half an hour.

# Answer
> 0 votes
> In case in which result set is big it's really inefficient to load whole nodes if only data from specific fields is needed.
>
> What is the Drupal 8 way of loading data for specific node fields only?

uh...ummmm....Views with a filter **and/or** fixed contextual filter with allow multiple values checkmarked...

**Note:** Drupal 8 comes with views by default.

# Answer
> -2 votes
Please create View/Reference/Block/Attachment with selected field. And Call that using contextual filter.

For example : http://localhost/project/admin/structure/views/view/view\_machine\_name/edit/your\_block

```
            $nameshipped = 'view_machine_name'; // please check the url
            $viewshipped = views_get_view($nameshipped);
            $display_id_shipped = 'your_block';
            $viewshipped->set_display($display_id_shipped);
            //$viewshipped->set_arguments(array($all_con_id)); // if we need to use contextual filter.
            echo $html = $viewshipped->render();

```

Please use the above code where you want to implement.

---
Tags: 8, entities
---


# Question
Title: How to force account creation before commerce checkout is complete?
I currently have a one-page checkout that works great for anonymous users. After payment is complete, an account is created with the 'Create a new account for an anonymous order' checkout rule.

Now I need to add a subscription product to the site, and plan to use Commerce License and Commerce License Billing to sell a role. To handle recurring payments, I plan to use Commerce Card on File.

This introduces a problem because Card on File requires an authenticated user in order to save cards. See https://www.drupal.org/node/1553468

How can I create a user account before checkout finishes so that Card on File can properly save cards?

Ideally, there would be a custom checkout page that forces account registration as a first step in checkout, but only for users purchasing subscription products.

I don't allow visitors to register on the site at the moment (except via Commerce Checkout), and I'd rather not change that.

# Answer
I suggest the following steps :

* create a custom checkout pane (see checkout\_pane\_example.module ) and embed the user register form in that pane:

```
/**
 * Implements hook_commerce_checkout_pane_info().
 */
function vts_register_commerce_checkout_pane_info() {
  $panes['register'] = array(
    'title' => t('Create an account'),
    'base' => 'vts_register_pane',
    'name' => t('NAME'),
    'page' => 'checkout',
    'weight' => -5,
  );
  return $panes;
}
/*
 * Add user_register_form to register pane
 */
function vts_register_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  $pane_form = drupal_get_form('user_register_form');
  return $pane_form;
}
/*
 * Alter checkout form register pane
 */
function vts_register_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  unset($form['register']['actions']);
}
/**
 * checkout form submission callback.
 */
function vts_register_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  $new_user = array(
    //dsm to find the correct $form_state['input'] for username here, because I have an altered user register form...
    'name' => $form_state['input']['field_name_first']['und'][0]['value'].'_'.$form_state['input']['field_name_last']['und'][0]['value'],
    'pass' => user_password(),
    'mail' => $form_state['input']['mail'],
    'init' => $form_state['values']['mail'],
    'status' => 1,
    'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
  );
  if($GLOBALS['user']->uid == '0') {
    $user = user_save('', $new_user);
    //ASSIGN the current order to created user
    $order->uid = $user->uid;
    commerce_order_save($order);
    $GLOBALS['user'] = $user;
  }
  //check that you got a new user and the order was assigned to him
  dsm($user, 'user');
  dsm($order, 'order');
}
/**
 * Validation callback.
 */
function vts_register_pane_checkout_form_validate($form, &$form_state, $checkout_pane, $order) {
  //validation stuff
  return TRUE;
}
/**
 * Ouputs Review checkout pane.
 */
function vts_register_pane_review($form, $form_state, $checkout_pane, $order) {
  // add some info to review pane
  return;
}

```
* Go to admin/commerce/config/checkout and set it as disabled
* Install Commerce Rules Extra, it adds the features you need :

> Rules conditions : Total product of type quantity comparison
>
> Rules actions : Change pane properties : Change visibility, page, weight of a pane

* Create a rule :
    + Event: Process checkout pane.
    + Conditions : user is anonymous ; subscription product quantity \> 0.
    + Action : Change pane properties : enabled: true; move to checkout.
> 1 votes

# Answer
In addition to Kojo’s excellent solution, I might add that I believe the correct username input field for normal Drupal install is located in:

```
'name' => $form_state['input']['name']

```

The module still redirects to the new user profile page, but I will be investigating the cause further today.
> 0 votes

# Answer
There's a setting also a setting in drupalcommerce for drupal 8.

```
/admin/commerce/config/checkout-flows/manage/default

```

Now there you will see

> Login or continue as guest

Click on gear icon, click and then uncheck `Allow guest checkout`.

That's all you need to do.
> 0 votes

# Answer
here is how i achieve to create the user\_register\_form commerce checkout pane :

```
/**
 * Implements hook_commerce_checkout_pane_info().
 */
function edw_commerce_dc_commerce_checkout_pane_info() {
  $panes['register'] = [
    'title' => t('Create an account'),
    'base' => 'edw_commerce_dc_register_pane',
    'name' => t('Authentication'),
    'file' => 'edw_commerce_dc.pane.inc',
    'page' => 'checkout',
    'weight' => -5,
  ];
  return $panes;
}

/*
 * Alter checkout form register pane
 */
function edw_commerce_dc_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  unset($form['register']['actions']);
  if(isset($form['register'])){
    $form_id = 'user_register_form';
    $hooks = array('form');
    $hooks[] = 'form_' . $form_id;
    drupal_alter($hooks, $form['register'], $form_state, $form_id);
  }
}

    /*
 * Add user_register_form to register pane
 */
function edw_commerce_dc_register_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  if (user_is_anonymous()) {
    $pane_form = drupal_retrieve_form('user_register_form', $form_state);
    $pane_form['#tree'] = FALSE;
    return $pane_form;
  }
}

/**
 * checkout form submission callback.
 */
function edw_commerce_dc_register_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  if (isset($form['register'])) {
    foreach ($form["register"]["#submit"] as $callback) {
      $callback($form['register'], $form_state);
    }
  }
}

/**
 * checkout form submission callback.
 */
function edw_commerce_dc_register_pane_checkout_form_validate($form, &$form_state, $checkout_pane, $order) {
  if (isset($form['register'])) {
    foreach ($form["register"]["#validate"] as $callback) {
      $callback($form['register'], $form_state);
    }
    if (!form_get_errors()) {
      return TRUE;
    }
  }
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Search API Solr Configured, Content Indexed, No Search Results
I'm running a Drupal 8.6.13 site with Search API 8.x-1.12 and Search API Solr Search 8.x-2.7. Everything seems to be properly installed and configured - my Solr admin panel shows a configured core and everything looks fine on my Drupal admin interface. I have the index set to process the body fields of my content and custom blocks using the fulltext type; I have 198 items indexed:

{ "response":{"numFound":198,"start":0,"maxScore":1.0,"docs":\[\] }}

The problem is that a search for a word that definitely appears in my content isn't producing any results. I'm using the config files from the Search API Solr Search module.

Solr Search Devel shows the request being sent to the server and an HTTP "200 OK" response being received. The logged response was:

{ "response":{"numFound":0,"start":0,"maxScore":0.0,"docs":\[\] }}

What else could I be missing?

Some more detail:

I can retrieve documents from the index using a command line query, like this:

$ curl "http://localhost:8983/solr/mycore/select?indent=on&q=*:*"

Here's an example of one of the returned documents:

```
  {
    "id":"6a1a2p-content-entity:node/100:und",
    "sm_context_tags":["search_api_X2f_index_X3a_content",
      "search_api_solr_X2f_site_hash_X3a_6a1a2p",
      "drupal_X2f_langcode_X3a_und"],
    "tm_body_1":["Ignition Timing (Vacuum advance disconnected, lines plugged) 6° BTDC Dwell Angle 30-33° Point Gap .020\" Spark Plug Gap .035\" Idle RPM * (Manual Transmission, no A/C) 725 Idle RPM * (Manual Transmission, with A/C) 725/500 ** Idle RPM * (Automatic Transmission, no A/C) 675 Idle RPM * (Automatic Transmission, with A/C) 675/500 ** Firing Order 1-5-4-2-6-3-7-8 * Set idle speed with headlights on high beam, air conditioning off. ** Higher RPM, solenoid energized. Lower RPM, solenoid de-energized.  "],
    "spell":["Ignition Timing (Vacuum advance disconnected, lines plugged) 6° BTDC Dwell Angle 30-33° Point Gap .020\" Spark Plug Gap .035\" Idle RPM * (Manual Transmission, no A/C) 725 Idle RPM * (Manual Transmission, with A/C) 725/500 ** Idle RPM * (Automatic Transmission, no A/C) 675 Idle RPM * (Automatic Transmission, with A/C) 675/500 ** Firing Order 1-5-4-2-6-3-7-8 * Set idle speed with headlights on high beam, air conditioning off. ** Higher RPM, solenoid energized. Lower RPM, solenoid de-energized.  "],
    "site":"http://example.com/",
    "sort_title":"PRD2\u0005\u000eRH\u0004NH2.:4:.*P:FDN\u0000",
    "_version_":1630197909793275904,
    "ss_search_api_datasource":"entity:node",
    "sort_body_1":":6D:P:FD\u0004P:B:D6\u0004\t<8e>T*.RRB\u0004*0T*D.2\u00040:N.FDD2.P20\u0006\u0004@:D2N\u0004H@R6620\t<90>\u0004\u001f\fS\u0004,P0.\u00040V2@@\u0004*D6@2\u0004\u0019\u0013\u0005\u000e\u0019\u0019\fS\u0004HF:DP\u00046*H\u0004\b\u0013\u0017\u0013\tx\u0004NH*L>\u0004H@R6\u00046*H\u0004\b\u0013\u0019\u001d\tx\u0004:0@\u0000",
    "index_id":"content",
    "ss_title":"Tune-Up Specifications",
    "hash":"6a1a2p",
    "ss_search_api_id":"entity:node/100:und",
    "timestamp":"2019-04-07T22:57:56Z",
    "ss_search_api_language":"und"}

```

So then I tried a query using a term found in the content above:

$ curl "http://localhost:8983/solr/mycore/select?q=solenoid" { "response":{"numFound":0,"start":0,"docs":\[\] }} $

Why might the second query fail to produce results if the search term is included in the document as shown in the full list of results?

# Answer
Few observations that might help you.

1. Term "solenoid" is only listed in 2 fields "tm\_body\_1" and "spell". Are you sure your solr instance is searching on these fields ?
2. Can you try creating a view and see if you get some response / results ?
3. Not sure, but did you copied over the Solr config files that are part of the module(search\_api\_solr), in your solr instance ?
4. Which version of Solr you are using, as module version 8.x-2.7 supports 6.x and 7.x version - https://git.drupalcode.org/project/search\_api\_solr/tree/8.x-2.7/solr-conf.

Hope that helps !!
> 0 votes

# Answer
Never mind, figured it out. I went back to the index and added a highlight postprocess query. I then adjusted the view settings to display the excerpt, and all is good. Thanks for giving me the right things to think about.

This was all for a Solr 7.7.1 server.
> 0 votes

---
Tags: search
---


# Question
Title: How do I display a field twice in a node's display?
In my full node display I want to show the same field twice, in a different mode each time.

Specifically, I have a collection of images, I want one up top and the rest below in my already existing gallery view of the node. What I don't know how to do is to show the field for my image twice in a single node display. Is there a module that will allow me to do this with a minimum of fuss?

# Answer
> 9 votes
Should be pretty easy if you use Display suite:

Add a dynamic field (admin/structure/ds/fields/manage\_ctools) and select the entity type (node).

Your new field should be in the manage display tab of the entity type selected, activate it (put it in the section you want).

Click on the gear icon and then 'select content'

Then drill down in the options (node -\> the field you would like to duplicate)

If you don't use display suite just print that field in a tpl.php file.

# Answer
> 0 votes
If you don't use Display suite for the given view mode, you can use https://www.drupal.org/project/entdispfieldui instead. (in combination with a number of other modules)

* Choose a way to integrate 3rd party composer libraries: Either using composer\_manager, or using https://github.com/drupal-composer/drupal-project
* Download and enable entdispfieldui and required modules, including cfrplugindiscovery (shipped with cfr).
* Scroll to the bottom of the view mode configuration page, create a new entdisp field, save.
* Move the newly created entdisp field up to the place where you want it.
* Configure the entdisp field as "Field with formatter", choose the field + formatter you like.
* Alternatively, choose "Image with processor" or "Images" (for multiple-value), then choose the image field as the source.

> I have a collection of images, I want one up top and the rest below in my already existing gallery view of the node.

This complicates the matter a bit. I am not sure if the usual formatter settings allow to specify which field items to display (e.g. only the first item, or all except the first). Something like this can be achieved with new custom renderkit components, but it depends a bit on your exact requirements.

---
Tags: 7, entities
---


title: Caching of blocks for anonymous user

text:
# Question
Title: Caching of blocks for anonymous user
I have a little probleme with my cache block.

This is my build function :

```
return [
  '#markup' => time(),
  '#cache' => [
    'max-age' => 10
  ]
];

```

I found this specification for block cache.

```
  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 20;
  }

```

Because in parent class we have `$max_age = Cache::PERMANENT;`

So, when I'm connected my rendered cache refresh each 10 seconds. But when I'm a anonymous user my rendered block never change.

I don't find the solution.

Big pipe isn't install, I have aggregations css and js but I don't have max age in admin/config/development/performance.

Finnaly I want a block without cache because this block will rendered message with close button. When the user click on the close button, I set a cookie for return an empty bluid in my block.

Do you have an idea ?

Thank you

# Answer
> 3 votes
You don't have to worry about the values which are set for cache max-age in other places, because when these are merged the lower time that you have set wins.

But you can't control with max-age the page cache for anonymous users. You have to use `\Drupal::service('page_cache_kill_switch')->trigger();` in the block build method to disable the page cache or you can simply uninstall the module *Internal Page Cache* if you plan to use the block on all pages.

> but I don't have max age in admin/config/development/performance

You should set this to the same max-age to control the browser cache and proxies.

# Answer
> 0 votes
Cache Control Override plugin intends to solve the problem with an anonymous user cache control. After installation, both methods will work:

```
return array(
  '#markup' => date("Y-m-d H:i:s"),
  '#cache' => array('max-age' => 10).
);

```

or

```
public function getCacheMaxAge() {
    return 10;
}

```

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


title: How to create custom VBO action?

text:
# Question
Title: How to create custom VBO action?
I need to update term references on nodes without updating the "changed" timestamp on the node. If I use VBO with "modify entity values" as action I can update the term reference but it will also update the "changed" timestamp.

How can I code a custom VBO action?

# Answer
> 5 votes
First, an explanation of why the `changed` timestamp gets updated. Actions can declare the attribute

```
'behavior' => array('changes_property')

```

in their `hook_action_info` entry. This attribute causes VBO to automatically call Entity API's entity\_save function after the action has been called. This function ends up calling node\_save, which updates the `changed` timestamp.

To avoid this behavior, simply create your own custom action by implementing hook\_action\_info in a custom module and follow the `action_example` of the Examples module. Make sure that your `hook_action_info` **omits** the attribute

```
'behavior' => array('changes_property')

```

Your action function will need to save the node or any other data by manipulating the database directly, or by making sure that you're using a function that doesn't trigger a `node_save` call.

# Answer
> 1 votes
The answer by infojunkie is correct, however if you completely remove the attribute rather than just setting it to:

> 'behavior' =\> array()

then it will default back to:

> 'behavior' =\> array('changes\_property')

and then you are back to the original problem. This was a gotcha for me for a while today so hoping to save someone some trouble in the future.

(See plugins/operation\_types/action.class.php lines 22-25 in the https://www.drupal.org/project/views\_bulk\_operations module on drupal.org for details.)

# Answer
> 0 votes
It appears that using:

```
'behavior' => array()

```

still reverts to the default as the VBO code adds the default if empty($this-\>operationInfo\['behavior'\]))...

To avoid this set behaviour to something else (made up will do) such as.

```
'behavior' => array('ignore')

```

---
Tags: 7, actions, views
---


# Question
Title: How can I render HTML tags in a variable in a twig template?
I have a variable in my twig template called *description*.
The variable is a string with an html em tag in it. When I go to the webpage to view the field, the html em tags are stripped out of the string.
I am on a **Drupal 8** site and my variable was rendered through
`\Drupal::service('renderer')->render()` The twig `autoescape` parameter is set to false.

Using the twig debugger, I can see that my markup object includes the html em tags so I know that the problem is how twig is processing the string.
I've read in other posts to use the `|raw` tag but this has no effect.
What can I do to make the HTML in my twig variable render properly?

**Update:** I've included a screenshot of my output from `{{ dump(description) }}`

# Answer
> 3 votes
> my variable was rendered through \Drupal::service('renderer')-\>render()

Don't do that - Drupal sets Twig up to understand render arrays. Just use:

```
{{ original_description_render_array }}

```

---
Tags: 8, theming
---


# Question
Title: Can't add iframe to paragraph - iframe is stripped for attributes
I have a problem with adding an iframe to a paragraph.

In Text formats and editors, I have checked "Limit allowed HTML-tags" and then added `<iframe>` to allowed tags.

But when adding an iframe tag with attributes to the CKEditor, all attributes are removed and only the tag is remaining.

When I uncheck "Limit allowed HTML-tags", the iframe is shown as expected but I do want to restrict HTML tags.

Is this a bug or am I adding the tag wrong?

# Answer
> 2 votes
If this is your output:

```
<p><iframe></iframe></p>

```

It's likely you need to specify the allowed attributes as well under *Limit allowed HTML-tags*. e.g.

```
<iframe width height src etc>

```

---
Tags: 8
---


# Question
Title: How do I put username into email when send mail to role in Rules?
I'm using Rules 7.x-2.11 and create new rules. I created additional fields in profile and when user select there from option list he got a new role. Next, i created new rule. When create new node with certain type drupal send mail to all users with this role.

EVENT Node insert

CONDITIONS Node is of type

ACTIONS Mail to users of role

It works, but i need put in email text username. In data selector i have only "node" and "site" selector's, how can i get "account" selector?

# Answer
add rules conditional module, now in actions you can add more conditions, in actions fetch entity by id, node-author, drill until you find UID, add a conditional, add an if, entity has field, entity-fecthed-author-by-id, select your field, now you have what you need, repeat as needed, for every field, a conditional, an if and your field. done. Your rule will look something like this:
> 0 votes

---
Tags: rules
---


# Question
Title: Can a Drupal Site Administrator view contents of settings.php or some other file in file system?
We are using Drupal 8.6.3.

I want to store some configuration in file system (in settings.php or some other file outside Web Root).

Can a Drupal Site Administrator view that configuration?

What parts of settings.php file can be viewed by a Drupal Site Administrator?

# Answer
For brevity, it helps to think about this question in terms of ***roles/permissions*** (since "site admin" is an overloaded term):

*Does the \____ role have an escalated permission to:*

* Write arbitrary files to the server?
* Execute arbitrary code on the server?

If the first/second answer is "Yes," the answer would be:

*\____ role could probably come up with a clever way to read the entire contents of settings.php by injecting/running arbitrary code.*

Generally, Drupal core tries to signal these potentially dangerous permissions with this warning:

> Warning: Give to trusted roles only; this permission has security implications.

However, there are many contrib modules out there that could have exploits (some known, some not) so you'll always have to take pro-active security steps like the *principle of least privilege* (if a role doesn't need a privilege to do the job, don't give it to them).

This also applies to your whole system (DB, web server, etc.), not just Drupal.
> 0 votes

---
Tags: 8
---


# Question
Title: Upgrade error: Attempt to create a field body that does not exist on entity type node
I am struggling with Drupal 8 upgrade for a months now. The Travis CI build is always failed with below errors.

I'm upgrading from Drupal 8.3.7 to 8.4.8 with Lightning (2.2.9), BLT 8.9.7, Drush version 8.2.3

```
Synchronized configuration: update views.view.frontpage.             [ok]
Synchronized configuration: update dropzonejs.settings.              [ok]
Synchronized configuration: update lightning_roles.settings.         [ok]
Finalizing configuration synchronization.                            [ok]
The import failed due for the following reasons:                     [error]
Unexpected error during import with operation delete for
node.type.page: Attempt to create a field body that does not exist on
entity type node.
Unexpected error during import with operation delete for
node.type.landing_page: Attempt to create a field body that does not
exist on entity type node.

```

I've successfully upgraded on localhost and exported the config file using `"drush [mywebsite] cex sync"` command. However, when I push to Github the Travis CI build failed with the errors above.

I've done the "`drush [mysite] updb`" command and it went without any errors. I also ran the command "`drush [mysite] entity-updates -y`"

Googling the errors without any luck, so I thought to post it here. Any help would be most welcome.

# Answer
> 2 votes
The solution is to manually create a "body" field in my landing\_page content type. Once I created the body field, the error no longer show up.

This can be apply to any other fields is show up in the error.

---
Tags: 8, upgrading
---


title: How to add image cache headers?

text:
# Question
Title: How to add image cache headers?
When doing SEO tests, we consistently seeing a message for cache headers on images. We were thinking of implementing but cannot find the appropriate way to test this as the x-cache still gives a MISS.

Below is the htaccess file we have to accommodate for adding cache header for images.

How can I test to see the performance gain if I did this?

```
# One month
<filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
  Header set Cache-Control "max-age=2628000, public"
</filesMatch>

```

# Answer
> 1 votes
Currenty working on that. The code

```
# One month
 <filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
  Header set Cache-Control "max-age=2628000, public"
 </filesMatch>

```

helped me to remove images from the list below https://developers.google.com/speed/

---
Tags: 8, caching, .htaccess, media
---


title: Menu migration update error

text:
# Question
Title: Menu migration update error
I migrate the menu by this drush command:

```
drush migrate-import --update page_menu

```

and .yml config:

```
id: page_menu
label: 'Page menu migration.'
migration_group: pages
source:
  plugin: csv
  path: path_to_file/pages.csv
  delimiter: ';'
  # enclosure: '"'
  header_row_count: 1
  # These are the field names from the source file representing the key
  # uniquely identifying each node - they will be stored in the migration
  # map table as columns sourceid1, sourceid2, and sourceid3.
  keys:
    - id
  column_names:
    0:
      id: 'Unique Id'
    4:
      menu_name: 'Menu'
    5:
      menu_title: 'Menu title'
    6:
      menu_weight: 'Menu item weight'
ids:
  id:
    type: string
destination:
  plugin: entity:menu_link_content
  default_bundle: menu_link_content
  no_stub: true
process:
  bundle: menu_link_content
  title:
    -
      plugin: skip_on_empty
      method: row
      source: menu_title
      message: 'Field field_name is missing'
    -
      plugin: get
  menu_name:
    -
      plugin: skip_on_empty
      method: row
      source: menu_name
      message: 'Field field_name is missing'
    -
      plugin: get
  'link/uri':
    -
      plugin: migration_lookup
      migration: pages
      source: id
    -
      plugin: generate_path
  weight:
    plugin: default_value
    default_value: 0
  expanded:
    plugin: default_value
    default_value: 1
  enabled:
    plugin: default_value
    default_value: 1
  changed: updated
migration_dependencies:
  required:
    - pages
dependencies:
  enforced:
    module:
      - custom_csv_import
      - migrate_source_csv

```

When I create menu items with this migration first time, the meigration works well. But if I want an update my menu with this command:

```
drush migrate-import --update page_menu

```

I get the error "Column 'bundle' cannot be null:":

```
      [error]  Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'bundle' cannot be null: UPDATE {menu_link_content} SET bundle=:db_update_placeholder_0, uuid=:db_update_placeholder_1, langcode=:db_update_placeholder_2
WHERE id = :db_condition_placeholder_0; Array
(
    [:db_update_placeholder_0] =>
    [:db_update_placeholder_1] => 24013691-38b5-44bf-a981-9961620eb7a2
    [:db_update_placeholder_2] => en
    [:db_condition_placeholder_0] => 21
)
 in Drupal\Core\Database\Connection->handleQueryException() (line 683 of C:\OSPanel\domains\example.loc\web\core\lib\Drupal\Core\Database\Connection.php).
 [error]  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'bundle' cannot be null: UPDATE {menu_link_content} SET bundle=:db_update_placeholder_0, uuid=:db_update_placeholder_1, langcode=:db_update_placeholder_2
WHERE id = :db_condition_placeholder_0; Array
(
    [:db_update_placeholder_0] =>
    [:db_update_placeholder_1] => 24013691-38b5-44bf-a981-9961620eb7a2
    [:db_update_placeholder_2] => en
    [:db_condition_placeholder_0] => 21
)
 (C:\OSPanel\domains\example.loc\web\core\lib\Drupal\Core\Entity\Sql\SqlContentEntityStorage.php:783)
 [error]  Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'bundle' cannot be null: UPDATE {menu_link_content} SET bundle=:db_update_placeholder_0, uuid=:db_update_placeholder_1, langcode=:db_update_placeholder_2
WHERE id = :db_condition_placeholder_0; Array
(
    [:db_update_placeholder_0] =>
    [:db_update_placeholder_1] => 36b7ae55-c15e-4be9-a857-ce811e6c9049
    [:db_update_placeholder_2] => en
    [:db_condition_placeholder_0] => 22
)
 in Drupal\Core\Database\Connection->handleQueryException() (line 683 of C:\OSPanel\domains\example.loc\web\core\lib\Drupal\Core\Database\Connection.php).
 [error]  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'bundle' cannot be null: UPDATE {menu_link_content} SET bundle=:db_update_placeholder_0, uuid=:db_update_placeholder_1, langcode=:db_update_placeholder_2
WHERE id = :db_condition_placeholder_0; Array
(
    [:db_update_placeholder_0] =>
    [:db_update_placeholder_1] => 36b7ae55-c15e-4be9-a857-ce811e6c9049
    [:db_update_placeholder_2] => en
    [:db_condition_placeholder_0] => 22
)
 (C:\OSPanel\domains\example.loc\web\core\lib\Drupal\Core\Entity\Sql\SqlContentEntityStorage.php:783)

```

Where I'm wrong?

# Answer
> 1 votes
The following basically means
*use the default process plugin `get` to look for a source column or constant named `menu_link_content` to determine the value for `bundle`*.

```
process:
  bundle: menu_link_content

```

which most likely returns `null`.

Try setting it with the `default_value` plugin instead:

```
process:
  bundle:
    plugin: default_value
    default_value: menu_link_content

```

---
Tags: 8, migrations
---


# Question
Title: How i can create VIEW table using Drupal hook_schema()
i want to create a view table in my custom module *.install* file and i want join with another table like i did in my `db_query` function but i want this thing in `hook_schema` function.

```
 db_query('CREATE VIEW Sample_Label_Data_By_CategoryId AS
                select
                `sample_label_library`.`SampleNumber` AS `SampleNumber`,
                `sample_label_category`.`CategoryName` AS `CategoryName`,
                `sample_label_and_category`.`CategoryID` AS `CategoryID`,
                `sample_label_library`.`MaterialName` AS `MaterialName`,
                `sample_label_library`.`EPANumber` AS `EPANumber`,
                `sample_label_library`.`SampleFilename` AS `SampleFilename`,
                `sample_label_library`.`LabelFilename` AS `LabelFilename`
                from ((`sample_label_and_category` join `sample_label_library`
                    on((`sample_label_and_category`.`SampleNumber` = `sample_label_library`.`SampleNumber`)))
                    join `sample_label_category` on((`sample_label_and_category`.`CategoryID` = `sample_label_category`.`CategoryID`)))')
    ->execute();

```

# Answer
> 2 votes
`hook_schema()` is only used to return a structured array representing your module's database tables. You can't execute a query from it. Well, you physically can, but you shouldn't.

Since `hook_schema()` is used on install, your code to create the View should be in `hook_install()`, and the code to remove it should be in `hook_uninstall()`

---
Tags: 7, views, database
---


title: Render sub-paragraph in parent template

text:
# Question
Title: Render sub-paragraph in parent template
I have a paragraph that has a field of type paragraph reference to sub-paragraphs.

Within my template, I need to access these sub-paragraphs and render the entity element. I have a loop that loops through a list of `Drupal\paragraphs\Entity\Paragraph` elements.

I need to render the paragraph markup. Is there a function?

I tried `item|render` and `item.view()`, but neither of them worked.

# Answer
> 1 votes
You should be able to render the sub paragraph - without any loop, just like every other field - with

`{{ content.field_name }}`

If you really need the loop for some special markup you can try something like

```
{% for key, item in content.field_name if key|first != '#' %}
  <div class="some_additional_markup">
    {{ item }}
  </div>
{% endfor %}

```

# Answer
> 1 votes
If you want to use a field value in child paragraph within the parent paragraph, you can use this (replace of course field\_with\_paragraph\_childs and field\_name\_field with the actual fieldnames):

```
{% for key, item in paragraph.field_with_paragraph_childs if key|first != '#' %}
        <div class="some_additional_markup">
                {{ item.entity.field_name_field.value }}
        </div>
{% endfor %}

```

---
Tags: theming, paragraphs
---


title: How do you add a region to a panel

text:
# Question
Title: How do you add a region to a panel
Novice question on Panels - I've inherited a D7 site with Panels 7.x-3.9.

I'm using a system page: *node\_view*, with a variant for the content type I'm working on.

The layout has a number of regions - and just to be clear, by regions, I mean the `$plugin['regions']` array in the template's `.inc` file.

**What I can't figure out is how to add new regions.**

(I want to add group some fields together so I can insert them using $content\['foo'\] in the template.)

Modifying the existing region names updates the descriptions used */admin/structure/pages/nojs/operation/node\_view/handlers/node\_view\__panel\_context\_\[UUID\]/content*

But any extra regions I add don't appear (having done `drush cc all`) and they also don't appear when creating a brand new variant using the same template.

Am I missing something in the UI (I'm logged in as user 1)?

(Thanks)

# Answer
I discovered the region is **only** visible in the variant drag/drop editor **after** it's been referenced in the template (because in fact you're looking at a site preview, not just an admin page - but that wasn't terribly obvious as none of the rest of theme was visible):

```
<?php print $content['foo'] ?>

```
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Display multi-value entity reference field in node edit form as draggable?
Is there a way to display a multi-value entity reference field as a draggable widget in a node edit form? I'm looking for the exact same behavior that a multi-value image field has by default. I would like a way for the content editor to easily reorder the referenced entities after they have been added via an autocomplete field. I really thought this was core functionality.

Thanks for your help.

I have found this module, but the UI is pretty bad and I really want the same UI that an image field has. https://www.drupal.org/project/entityreference\_dragdrop

# Answer
You can get the multiple values input in a table format with the draggable option if you choose `Autocomplete` widget for that field under `Manage form display` for that Content type (*not* the `Autocomplete (Tags style)`).

If your field accepts an unlimited number of values the widget will present as one autocomplete input field with a button to `Add another item`. As you add more items you will be able to drag and drop to rearrange the values order.

You can also get that reordering widget with Inline entity form widget (with the additional module Inline entity form).
> 3 votes

---
Tags: 8, entities, nodes
---


# Question
Title: Is there a way to pass multiple arguments to menu_name while creating menu links programmatically?
Am using Drupal 7. Below is my code where am trying to create menu links programmatically:

```
$links[] = array(
'menu_name' => 'management',
'link_path' => 'myheader/config',
'link_title' => 'Header Settings',
'options' => array(),
'weight' => 2,
'parent' => 'custom/header-settings',
);
$links[] = array(
'menu_name' => 'mycustommenu',
'link_path' => 'myheader/config',
'link_title' => 'Header Settings',
'options' => array(),
'weight' => 2,
'parent' => 'custom/header-settings',
);

```

In the above code, only menu\_name is different. Rest of them are same. Is there a way to pass multiple arguments to menu\_name?

# Answer
No. When you're building links for D7's menu system, you'll need to specify the entire link array because you're creating link metadata here. If you're trying to keep your code DRY you *could* try to create a template array (or function) then copy/update as you needed new links, but you're probably doing just as much work for little/no performance gain or clarity.
> 1 votes

# Answer
Your code seems to define some menu links. You have to return an array with all menu links you want to define, and there's no way to define multiple menu links using a parameter or similar.

What you can do is to construct the array programmatically:

```
$link_template = array(

  'link_path' => 'myheader/config',
  'link_title' => 'Header Settings',
  'options' => array(),
  'weight' => 2,
  'parent' => 'custom/header-settings',
);

$menu_names = array('management', 'mycustommenu');

$links = [];

foreach ($menu_names as $menu_name) {
  $links[] = array('menu_name' => $menu_name) + $link_template;
}

```

This way you have only one array where you can modify menu properties (the `$link_template` variable), and a list where you can easily add new menu entries (`$menu_names` variable).

No performance gain, but menu properties are defined just once.
> 0 votes

---
Tags: 7, navigation
---


title: Switch between View Modes from the URL

text:
# Question
Title: Switch between View Modes from the URL
Under the manage display for the user profile `/admin/config/people/accounts/display`, I have 4 view modes as below:

* Default
* Profile (Machine name: user.profile)
* Company (Machine name: user.company)
* Activities (Machine name: user.activities)

and under each view mode, I have a set of fields.

I also have a menu with below items:

* Profile
* Company
* Activities

Now, I need when a user click on the menu item (**Profile**), to redirect him to the **view mode: Profile** and so on for other menu items.

So basically, the link for the menu item should be something like:

```
/user/1/[view-mode]

```

I was thinking something easy like:

`/user/1#profile` will direct the user of uid=1 to the **view mode: Profile** of his profile page.

`/user/1#company` will direct the user of uid=1 to the **view mode: Company** of his profile page.

`/user/1#activities` will direct the user of uid=1 to the **view mode: Activities** of his profile page.

How to switch between view modes using the url only ?

is that doable!? if no, any alternative way ?

**UPDATE #1 (My requirement)**

Say on the user profile page, I have the below fields (as an example):

* field\_1
* field\_2
* field\_3
* field\_4
* field\_5
* field\_6
* field\_7
* field\_8
* field\_9
* field\_10
* field\_11
* field\_12

And a simple menu with below items:

* Profile
* Company
* Activities

I want when a logged in user click on the menu item:

* **Profile** (to display for him only field\_1 -\> field\_4)
* **Company** (to display for him only field\_5 -\> field\_8)
* **Activities** (to display for him only field\_9 -\> field\_12)

How can I do that ? (my javascript knowledge is very very limited)

# Answer
> 3 votes
I think this is what you are looking for.

https://www.drupal.org/project/view\_mode\_page

It will create viewable routes for view modes. Check the examples and readme. They will display on the page the way they are configured to display from the backend.

# Answer
> 0 votes
Field group can create **tab groups** (horizontal and vertical) and **tab elements** *on the same view mode*. Than you are able to access each tab with a hash. The `ID` of each tab becomes the has anchor (#company etc).

You have to setup the fields in 1 view mode and place them under the appropriate tabs.

Here is a screenshot of how the setup should look.

---
Tags: views, 8, navigation, tokens
---


# Question
Title: Drupal hash salt / private key is changing?
I've created a token that I store in database, here is how I create my token :

```
$token = drupal_hmac_base64($pid . " " . $order_id . " " . $solde, drupal_get_private_key() . drupal_get_hash_salt());

```

And then when a user go to my url that looks like that :

```
https://mycustomwebsite.com/order_id/token

```

With the token and another value : `order_id`, I get the line in my database with the `order_id` and then I create a new token :

```
$new_token = drupal_hmac_base64($pid . " " . $order->order_id . " " . $solde, drupal_get_private_key() . drupal_get_hash_salt());

```

I compare these two tokens just for a verification to grant the access or not.

This works fine but couple days after when I try to go on a link the access doesn't work anymore. When I look at the `new_token` generated for verification it's not the same ! But the value used to make this token (`pid`, `order_id` and `solde`) are the same, so here is why I ask my question.

Does the `drupal_get_hash_salt()` or `drupal_get_private_key()` can return different values in the time ?

# Answer
> 2 votes
`drupal_get_hash_salt()` is either:

* a manually-entered value stored in your `settings.php`
* ...or (by default) a hash of your serialized-DB config

`drupal_get_private_key()` is either:

* a stored variable called `drupal_private_key` if it's set
* ...or (by default) randomly generated bytes (that are saved to `drupal_private_key` after generation)

So, either one can change their value if:

* You changed your DB config (if `$drupal_hash_salt` isn't manually set in `settings.php`).
* You've lost/removed `drupal_private_key` from the `variable` DB table.

---
Tags: tokens
---


title: Ajax Exposed filter isn't changing URL

text:
# Question
Title: Ajax Exposed filter isn't changing URL
There must be something obvious I'm missing as it seems from other posts that Exposed Filters in views should generate URLS from its results out of the box.

I've got some filter with ajax enabled and they work fine, but the url doesn't change when using the filter.

How to I achieve this and become able to link to a specific setting on the filter?

# Answer
Exposed filters do create/update the page URL. You can construct a link with a combination of values for your Exposed filters and the Views results will react to it by displaying the "correct" results narrowed down to what is set in the URL.

The confusion you're having is the Ajax option. Ajax (**asynchronous** JavaScript and XML) option fetches only a particular *part* of the page data and replaces the old set of that *part* of the page.

Ajax doesn't reload the *entire* page.

**URL requests are related to entire pages, the URL in your browser can't change without a Page Reload/Refresh.**

The Ajax option in Views even tells you:

> Options such as paging, table sorting, and exposed filters will not initiate a page refresh.

With Ajax option turned on the Exposed filters are still working correctly, you get changes in your results based on the applied Exposed filters. But the changes happen without the page reloading so the URL doesn't change. It can be confusing if you at that moment compare the currently enabled Exposed filter options with the Exposed filter values in the URL, because they won't match. But that is just the circumstances of using Ajax.

With Ajax on you get better responsiveness/speed just because there is no page reloading, but the URL might be misleading, if that is what your users pay attention to at that moment.

But turning Ajax on doesn't prevent you from constructing specific Exposed filter combinations in URLs!

You can create different URLs for a Views page, add them to a menu, when the user clicks on it they will get the filtered out results and the Exposed form options will match the URL ones. Then users can interact with the Exposed form and with Ajax on the URL will not change but the results will.

Without the Ajax option turned on each change in the Exposed form will trigger a page reload, which makes things less interactive/fast, but the URL options will match what you see on the Exposed form.
> 3 votes

---
Tags: views
---


title: View for Taxonomy terms?

text:
# Question
Title: View for Taxonomy terms?
How can I output nodes which linked with taxonomy term through a view? How can I link taxonomy vocabulary with a view wich will output appropriate nodes for each term of this vocabulary?

In Drupal 7 we have two modules:

# Answer
You don't need additional modules to create different Taxonomy term pages, in D7 nor D8. Taxonomy Display and Taxonomy Views Integrator modules save steps in certain cases, but you can recreate their functionality with configuring different Views for different cases.

You can reuse the existing `Taxonomy term` Views (this lists nodes based on the taxonomy term in the URL).

If you need different Taxonomy page settings for each Vocabulary you can Duplicate the Taxonomy term Views (that shows Content tagged with a term) as many times as you have different Vocabularies, and add Filters to each to apply only to one Vocabulary.

Then you can also change all the other options related to how you want different Vocabulary terms Content to be displayed, because you'll have a different View for each Vocabulary.
> 5 votes

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


# Question
Title: Entity print get variable in twig template
I'm using entity print and I would like to get node variables in my twig template, so I can call them like {{ content.field\_name }}.

I tried using a preprocess function but I'm not sure I'm doing things well.

Assuming I have a twig template called *entity-print.html.twig*, here the preprocess functions I tried :

```
function THEMENAME_template_preprocess_entity_print(&$vars) {
    $vars['field_name'] = $entity->get('field_name')->getValue();
  }

```

I also tried

```
  function THEMENAME_template_preprocess_entity_print(&$vars) {
    $vars['field_name'] = $entity->get('field_name')->value;
  }

```

I'm calling field\_name with all of this twig variable for debugging purpose :

```
   1 {{ content.field_name.0 }}
   2 {{ content.field_name.value }}
   3 {{ content.field_name.0.value }}
   4 {{ field_name.content }}
   5 {{ content.field_name[0] }}
   6 {{ node.field_name.value }}

```

Nothing come. What am I doing wrong ? Do I have to make a custom module ?

# Answer
Looks like you need to review Entity Print in Drupal 8 again. I am using the Entity Print module and it works just fine. Here are some pointers I would recommend below. Your original post is regarding printing node variables in twig templates

1. On your content type, navigate to Manage Display--\>Expand Custom Display Settings--\>Enable PDF. This will create a PDF view mode (which is used for printing)
2. Create a twig template node--article--pdf.html.twig (replace article with machine name of your content type)
3. Update your\_theme.info.yml and your\_theme.libraries.yml as suggested in Entity Print in Drupal 8 so you can control the theme and assign a css file only for print
4. Copy and add entity-print.html.twig to your subtheme
5. Using node--article--pdf.html.twig, you can control whatever variable you need. However, I recommend you use the PDF view mode first to see what it can do for you.

I have yet to use a preprocess function and you should only need that if you need additional processing. Using the PDF view mode, entity-print.html.twig and the node--article--pdf.html.twig templates you will be able to print as you need.

Ultimately, you should use the PDF view mode so you can manage the PDF view mode (add classes, divs, order, add/hide/remove fields, etc.) through the UI. I have found that managing what fields are displayed through code can be cumbersome if you have a lot. The view mode can handle a lot of what you need, but you need to enable the PDf view mode first.

Sample entity-print.html.twig

```
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>{{ title }}</title>
  {{ entity_print_css }}
</head>
<body>
  <div class="optional_class">
      {{ content }}
  </div>
</body>
</html>

```

Sample node--article--pdf.html.twig:

```
<article class="optional_class_wrapper">
  {{ content.field_name }}
  {{ content.body }}
  {{ label }}
  {{ content.field_name.0.value }}
</article>

```
> 3 votes

# Answer
If you are writing a preprocess function, then the correct name of the function is `THEMENAME_preprocess_entity_print()`; replace THEMENAME with the machine name of the theme implementing it. If this is the case, what in the preprocess function you set as `$vars['field_name']`, where `$vars` is the array passed as reference to the preprocess function, it is accessible as `{{ field_name }}` in the Twig template file. See for example `template_preprocess_node()` and node.html.twig: What the function sets as `$variables['node']` is available as `{{ node }}` in the template file.

Be sure to use the correct filename for the template.
> 2 votes

# Answer
I think this is the problem, you are trying to get the node from the route, only, you are not on a node route, you are on an entity\_print route, so node is not available.

As a side note, you should always check that the field exists before trying to get the value. Before you try something like this:

```
$vars['field_name'] = $entity->get('field_name')->getValue();

```

You should do something like this:

```
if ($node->hasField('field_name') && !$node->field_name->isEmpty()) {
  $vars['field_name'] = $entity->get('field_name')->getValue();
}

```

But in this case, that probably wouldn't even prevent the error, since $node ( or $entity ) isn't even populated here.

What I've resorted to doing for entity\_print preprocess functions is basically parsing the string URL. Your print path is something like /print/pdf/{entity\_type}/{entity\_id}, which contains all of the info you need.

```
/**
 * Implements HOOK_preprocess_entity_print__entity().
 */
function THEME_preprocess_entity_print__node(array &$variables) {
  $route = \Drupal::routeMatch();
  $entity_type = $route->getParameter('entity_type');
  $entity_id = $route->getParameter('entity_id');
  // double check that you are printing a node, not a view or something else.
  if ($entity_type == 'node') {
    $node = \Drupal::entityTypeManager->getStorage('node')->load($entity_id);
    if ($node->hasField('field_name') && !$node->field_name->isEmpty()) {
      $variables['field_name'] = $node->field_name->value;
    }
  }
}

```

Now you can access 'field\_name' in your twig file just using {{ field\_name }}, but once again, check that it's populated before trying to print or you could get another error.

entity-print.html.twig

```
{% if field_name %}
  {{ field_name }}
{% endif %}

```

Of course, this assumes 'field\_name' is a single value field, not an entity\_reference or other sort of complex field.
> 1 votes

---
Tags: theming, files, 8
---


# Question
Title: Change title of certain paragraphs in a form
Please see the attached pictures. In one of my projects I have a taxonomy, which users can edit and add data. It has multiple tabs (see picture one) and each tab has multiple fields in which paragraphs can be added (see picture two).

We have different kinds of paragraphs with each different titles. Our problem is that we want to show each paragraph to the end-user (see the second picture, the button "Meting (decimaal) toevoegen") with a title of "meting" while maintaining the more descriptive titles for the admins and developers.

One option is changing the title for the end-user while maintaining the actual title in the DB. The other one would be changing the actual title in the DB and change it for the admins (setting the system name as the title).

and I've tried all kinds of hooks but can't wrap my head around this problem.

**Solution:** Due to the structure of the site, I couldn't get any hook solutions to work. So I wrote my own module, which attaches the javascript below to the form.

```
(function ($) {
  'use strict';

  Drupal.behaviors.test_form_styles = {
    attach: function (context, settings) {
      var regEx = /(?:meting)/i;
      var paragraphTitles = document.getElementsByClassName("paragraph-type-title");
      Object.keys(paragraphTitles).forEach(function (key) {
        if (regEx.test(paragraphTitles[key].innerHTML)){
          paragraphTitles[key].innerHTML = "Meting";
        }
      });

      var submitButtons = document.getElementsByClassName("field-add-more-submit");
      Object.keys(submitButtons).forEach(function (key) {
        if (regEx.test(submitButtons[key].value)) {
          submitButtons[key].value = "Meting toevoegen";
        }
      });
    }
  }
} (jQuery));

```

# Answer
If you want to change the title of certain paragraphs in the form:

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'foo') {
    // insert more conditions
    $element['top']['paragraph_type_title']['info']['#markup'] = t('New title for paragraph type Foo');
  }
}

```
> 1 votes

---
Tags: 8, paragraphs
---


# Question
Title: Get taxonomy term ID from standard URL and then pass it to a View as a contextual filter
is a simple question, I whant get the term ID (tid) from standard drupal taxonomy url taxonomy/term/167 ou 167 is my tid and use as argument on views.

I found this code to get the tid:

```
$term_path=drupal_get_normal_path('position/'.arg(1));
$tid = basename($term_url);
$$here_is_my_tid = taxonomy_term_load($tid);

```

How to get taxonomy by URL alias?

I try also :

```
$here_is_my_tid = drupal_lookup_path('source', 'taxonomy/term/'.$tid);

$here_is_my_tid = drupal_get_path_alias('taxonomy/term/' . $tid);

```

But I try many combination without success.

Here is my views with the tid from url I try to pass "$here\_is\_my\_tid"

```
$view1 = views_embed_view('mavue','page',$here_is_my_tid);

 if(arg(0) == 'taxonomy' && arg(1) == 'term') {
            $tid = (int)arg(2);
            $term = taxonomy_term_load($tid);

      }
    $view1 = views_embed_view('mavue','page',$term);

```

By advance thanks

# Answer
**You do not have to write any code to achieve that.**

Just go to the views edit page, add a contextual filter named as **Has taxonomy term ID** and select **Provide default value**, see screenshot for more options

**However, you can also do it pragmatically**

```
function HOOK_views_query_alter($view, $query) {
   $term = menu_get_object('taxonomy_term', 2);
   if ($term && $term->vocabulary_machine_name == 'VOCABULARY_NAME') {
     if ($view->name=='VIEWS_MACHINE_NAME') {
       $view->query->where['0']['conditions']['0']['value']= $term->tid;
     }
   }
}

```

I hope it helps.
> 2 votes

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


title: Contextual filter in URL via Twig

text:
# Question
Title: Contextual filter in URL via Twig
Does somebody of you know how to build a link as described in **#9** in https://www.drupal.org/project/views\_contextual\_filter\_query/issues/2686467#comment-10983075

I tried it this way

```
<a href="node/{{ nid }}?{{ nothing_1 }}">[title]</a>

```

but the output ends with a "?" ... like me :-) The link to the node works, but the query/argument/contextual filter is missing in the url. How can I fix this?

# Answer
Drupal offers a helper function for building URLs in Twig templates.

```
{{ url('entity.node.canonical', {node: nid}, {query: {foo: 'bar'}}) }}

```
> 3 votes

---
Tags: 8, theming
---


# Question
Title: Should I share the same image style as much as possible or create different styles for each size?
I have an image field displayed in slightly different sizes.

Let's say :

100px X 100px as a view field format
120px X 120px as another view field format
150px X 150px as a node view format

My question is :

Which is the best practice ?

1. Creating three different image styles for each size.

2. Creating just one image style and share it (Fixing the size accordingly by CSS) For example, create just the image style of 150px and then make it smaller for 100px and 120px by CSS

Why I wonder is :

1 obviously creates more files but 2 uses unnecessary bigger files for 120px and 150px

# Answer
> 1 votes
I would zoom out the thinking and try to get two things into perspective:

* user interaction "paths" and which images they "touch"
* graphics design decision for the image sizes

## What is the likeliest user scenario for downloading each image size?

What is the path your users take through the site that would trigger downloading those image sizes? Will the user see many of the 100px images in a list, then click through to only one that would display the 120px one, and then clicking on that one so 150px is displayed in a lightbox?

## Aim to reduce downloaded data bandwidth

Diagram some likely user paths (if you have some analytics on your site you probably already know this, better to get data instead of making assumptions) and calculate how many Kb/Mb of image data users would most often download under those paths.

Compare if the data load is larger with 1, 2 or 3 sizes for those "user paths".

If you have a lot of mobile visitors the data size is super important. Your goal should be to provide meaningful content and experience while keeping the data exchange to a minimum.

If users click through a lot and you end up serving the largest 150px size very often, it may not be useful to have the smaller sizes, better use 150px and size down with CSS.

If your images are such that with the change in pixel size the file sizes also vary greatly (if the 100px image is disproportionately smaller in file size than the 150px one) then it may be useful to have a smaller size, especially if users mostly view "list pages" with smaller images and don't click through, so they rarely see the larger image.

## Don't forget server resources and requests

The downloaded data size isn't the only criteria, reusing the same size pulls it out of cache, so saved bandwidth again, fewer server requests.

If you upload a lot of images and have a lot of image styles, server processing power is being used for that and can get congested in extreme cases. You also end up with a lot of data on the disk so storage is also important, as mentioned in comments.

## Graphics design refinement

Having so many close-but-not-identical style elements *might* be a sign you could improve your graphics design by making different design elements more consistent. How justified is it to display some image type in that many different sizes, is there a need for it?

---

Taking a blind guess I don't expect a lot of difference between 100px, 120px and 150px so I would try and see whether I'd need 100px and 120px at all, maybe 120px and 150px would be enough? 3 sizes do seem excessive here, 3 sizes are usually used when there is a much larger difference between them (100px, 500px, hero).

I have a real-world example where I disabled image sizes completely because the uploaded originals were so well optimized that the smaller versions made by Image styles were *bigger* in file size than the large pixel original, even after using custom imagemagick rules!

# Answer
> 0 votes
Generally, as @Prestosaurus mentioned, you want to load the smallest image necessary, however there are a couple things to consider

* Whether the same image is loaded via all the styles or if any individual image would only be loaded once. If you have a single page loading the same image with all 3 styles, that's not as good as just displaying the image with the largest style in all 3 places. I'd probably opt to use individual styles if a single page won't show the same image via multiple styles.
* The additional server space need to store the additional styles.

---
Tags: 7, media
---


# Question
Title: Creating a view by comparing two fields of two different content types using the same taxonomy
I'm trying to create a view to desplay contents based on shared taxonomy terms.

More concretely, I have two content types:

* Offers (with field "Category")
* Needs (with field "Category")

This contents share the same vocabulary "Category". Indeed, the "Category" fields of the content types "Offers" and "Needs" are refered to the same vacabulary (taxonomy) with terms:

* electronic
* chemistry
* mathematics
* science

Each user can define their offers and needs through 2 differents forms.

To put it simply, let's take the case of 3 users who created their offers and needs using this forms. Here is a table of a concrete example:

==\> Case 1: current user (logged in user) = user 1

Imagine that I am user 1 (current user). The view page will have to desplay to me a list of the contents "Needs" of other users (user 2, user 3) and that have the peculiarity of having a "Category" field equivalent to the "Category" field of my contents "Offers".

In other words:

1) My content "Offers" are "Offer 1" and "Offer 2" with fields category ("electronic","science")

2) The contents "Needs" of other users are "Need 2", "Need 3","Need 4","Need 5" and "Need 6"

3) Comparing fields category between my contents "Offers" and contents "Needs" of other users:

* Field Category of "Need 2" = chemistry. The value of this field is different from the values ("electronic","science"), that are the values category of my offers ==\> **The view will not display the content "Need 2"**
* Field Category of "Need 3" = electronic. The value of this field is equivalent to the value category of my Offer 1 ==\> **The view will display the content "Need 3"**
* Field Category of "Need 4" = mathematics. The value of this field is different from the values ("electronic","science"), that are the values category of my offers ==\> **The view will not display the content "Need 4"**
* Field Category of "Need 5" = science. The value of this field is equivalent to the value category of my Offer 2 ==\> **The view will display the content "Need 5"**
* Field Category of "Need 6" = electronic. The value of this field is equivalent to the value category of my Offer 1 ==\> **The view will display the content "Need 6"**

4) It means that the view page should display this list of Needs:

* Need 3 (electronic)
* Need 5 (science)
* Need 6 (electronic)

In other words, Offer 1 and Offer 2 (that are my Offers) match with Need 3, Need 5 and Need 6 (that are needs of the other users covered by my Offers). And this because they have the same categories "electronic" and "science"

==\> Case 2: current user = user 2

Using the same logic, if the current user is user 2, the view page is going to desplay this list of Needs:

* Need 5

==\> Case 3: current user = user 3

And for the user 3, this list of Needs:

* Need 1
* Need 2
* Need 4

**Question : How can I create this view with view UI ? Any other suggestion is welcome.**

# Answer
> 1 votes
This types of matching (list Taxonomy siblings) is usually done through `Has Taxonomy term ID` Contextual filter, but your case is a bit more indirect.

You're not showing related content on other node pages. You want to list some content on User pages, but the matching is not done between the listed content and the user (because you don't have Taxonomy on users), it is one step more removed, you're matching content through the user "bridge" to other content.

You need to go "the entity reference" way to achieve all the necessary matching and contextual filtering.

First we list the user Offer nodes because they give context, they tell us which categories to look for. Once we have that we pull into Views Needs nodes that share the same category field values as those offers, and we additionally filter out that user Needs, in case they have any, because they're only interested in seeing other people's matching Needs.

1. Create Page Display Views listing Offers! (filter Content type)
2. Change `Path` to `user/%user/related-needs`
3. Add Menu Tab (it will show on user profiles)
4. Add Relationship `Taxonomy term referenced from field_category` from the `Content` Category, you can require it since they will all have it filled in
5. Add a new Relationship `Content using field_category` from the `Taxonomy term` Category.

This Relationship automatically uses the first Relationship. This is where the matching is done from all Offers nodes category back to all the nodes on the system using that same category.

You have the Title field showing Offer nodes at this point. You can keep it this way just to test, but that field isn't our target since we want to see the list of *Needs* related to the Offers. Or if you don't need it: modify it according to the following step:
6. Add another `Title` Field and make it use the second Relationship (it will be the only one available). This will show the nodes that share the same category taxonomy as the Offer node in that same views row.

From now on, for every field you add, if you're not using a Relationship it will show Offer node data, and if you use the second Relationship it will show the data from nodes that share the same category as the Offer node from that row. This includes the Needs node we are after.
7. Add Contextual filter `Authored by` from the Content Category and configure it:
**Do not use a relationship**
`When the filter value is NOT available`
**Provide default value**
**User ID from route context**
`When the filter value IS available or a default is provided`
**Override title**
`Needs matching user {{ arguments.uid }} Offerings` (check your argument token under `Replacement patterns`)
**Specify validation criteria**
**User ID**

This Contextual filters out Offer nodes authored by the user whose profile is being viewed.
8. Add another Contextual filter `Authored by` from the Content Category and configure it:
**Relationship `field_category`** (the second one)
`When the filter value is NOT available`
**Provide default value**
**Raw value from URL**
**2**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**User ID**
`More`
**Exclude**

This Contextual filter excludes Needs nodes authored by the currently viewed user since it doesn't make sense to show these. This step isn't necessary if your users will never have Needs nodes that share the same category with their Offer nodes.
9. Since you'll probably have duplicates in your results you can sort it out by turning **Aggregation** on. If you have Needs fields other than Title you may need to change their Aggregation settings from `Entity ID` to `Target_id`.

Make sure you have all Sort Criteria removed since it interferes with Aggregation.

Visit the user profile page and find the tab, and check that the results are as you'd expect. It seems like a complicated procedure but it makes sense once you understand what is happening in each step.

---
Tags: 8, views
---


# Question
Title: RewriteBase /folder issues on IIS for broken images
I have a Drupal 7 site hosted under a subdirectory say http://example.com/drupal. I am using IIS and SQLSRV. But all the images could not be loaded on the site as these images pointing to http://example.com/sites/default/files... I have added $base\_url in settings.php but .htaccess could not be recognised by IIS. When I try to import rules from .htaccess, it does not allow RewriteBase /drupal rule as it is not supported by IIS.

Please help me out in this scenario. What could be the equivalent rule of RewriteBase /drupal?

# Answer
> 1 votes
Okay, so problem is IIS does not understand our .htaccess file and has its own set of rewrite rules. If someone's facing broken images problem, best is to create an outbound rule which will add your subdirectory into the URL. something like "/sites/all/..." to be rewritten to "/drupal/sites/all/...".

---
Tags: media, .htaccess
---


title: Render a custom block programmatically

text:
# Question
Title: Render a custom block programmatically
How do I render a custom block type (block\_content) programmatically with a specific display view?

# Answer
> 4 votes
In `hook_preprocess_page()` add the following code.

```
$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
if ($block_view) {
    $variables['page']['my_block'] = $block_view;
}

```

In your Twig template, print the block with the following code.

```
{% if page.my_block %}
  {{ page.my_block }}
{% endif %}

```

# Answer
> 4 votes
If your block is custom, this worked for me:

```
$customblock = \Drupal::service('plugin.manager.block')->createInstance('{id of block here}', []);

```

Then you could print it from your preprocess like so:

```
if(isset($customblock) && !empty($customblock)) {
  $variables['logo'] = $customblock->build();
}

```

When you created your block, you would have set the ID here:

```
/**
  * Provides a 'Logo' Block.
  *
  * @Block(
  *   id = "logo",
  *   admin_label = @Translation("Logo"),
  *   category = @Translation("Header"),
  * )
  */

```

However, this method stops contextual links from displaying. To work around this you can do the following:

```
$Block = \Drupal\block\Entity\Block::load($id);
if(isset($Block) && !empty($Block)) {
  $Block =  \Drupal::entityTypeManager()->getViewBuilder('block')->view($Block);
}

```

Please note: the block needs to be placed in a region in the block layout page (but can be set to Disabled) and the $id is equal to the instance of that block, NOT what you defined in the .php file. This can be found by hovering on any of the block links in block layout.

# Answer
> 0 votes
If you've created the block as a View you can use views\_embed\_view in your template\_preprocess\_page function, something like:

`$variables['my_block'] = views_embed_view('view_machine_name', 'block_machine_name');`

Sub in the View and block machine names. View name visible at admin/structure/views and the block machine name on the specific block's Advanced settings (defaults to 'block\_1').

---
Tags: 8, blocks
---


# Question
Title: Is it necessary to export features with a version number?
By default, modules generated with features are created with a version string in the \*.info file.

I think the convention is to increase this version number when the feature changes.

In a distributed development work flow with a lot of merging, a linear version increment is not a useful model or metaphor.

Is the version number, and incrementing it, useful or necessary for anything?

I work in a project where until now almost none of the features has version number. But recently a colleague reported problems reverting the features on deployment, if they don't have a version. Of this could be pure concidence, and caused by something other than the missing version number.

# Answer
> 1 votes
It's metadata for keeping track of a Feature release. In D7, the use of Features has two cross purposes:

* Bundling Drupal configuration up as a part of a released feature that can be deployed to any site (e.g. a bunch of re-usable content types).
* Snapshoting config as code which is useful for capturing config that D7 didn't normally have (and has been supplanted by D8's config management system).

In the first case, the use of version tagging is more useful when you're a vendor of some project leveraging Features. A tag gives you an identifiable way to know what will be rolled back if you force a Feature back to its original state.

If you're using Features solely as config as code, versioning is not really important. Especially, if it's part of a large project that is already leveraging some release tagging.

---
Tags: 7, features
---


title: How to query paragraphs content?

text:
# Question
Title: How to query paragraphs content?
Does any one have an example how I can query the paragraph entity type of a given node ?

Let's say I have a node that contains a field 'field\_paragraph' that is linked to the paragraph module . How do I query all that data ?

Thanks, Yaron

# Answer
There are different ways to *query* (output? render?) paragraph field values. If the idea is to print the value in a template, you may find some clues in this page: https://www.drupal.org/node/2532824

```
<?php print render($content['field_paragraph']); ?>

```

But that will also depend on the theme you are using and how do you use it
> 0 votes

---
Tags: 7, paragraphs
---


# Question
Title: Some basic questions about creating a webform handler from the module webform_example_handler
I'm "cutting my teeth" in Drupal 8 on the Webform module so these are going to be rather naive questions.

I need to programmatically fill a URL field in the form with an XML file that I generate from the other data in the form and do it just before the submit so that the form is complete. To do so I figured using a webform handler is the way to go and I have been using `webform_example_handler` as my template.

Now for my ridiculous naivety, just a few basic questions:

In `webform_example_handler.schema.yml` the first line is: `"webform.handler.example"`. Is this a standard Drupal construct of `<webform>.<handler>.<my_module>`, or something specific that must be followed set by the webform module or am I completely off base on how this is derived?

I would guess that for my module the line would be: `webform.handler.dis_doc_gen`?

The `"webform.webform.webform_example_handler.yml"` file: could someone explain the parts? In my module would it be: `webform.webform.dis_doc_gen.yml` ?

Last: I have built my webform through the interface so I assume that I don't need the file `"webform.webform.webform_example_handler.yml"` as that would only be for creating a webform from a yml file upon installing the module as far as I can tell. However, is there something in my webform that I need to set so that it knows about my `".../dis_doc_gen/src/Plugin/WebformHandler/DISDocGenWebformHandler.php"` handler?

Could someone please tell me what key thing(s) I need to do to make that connection or is that all automatic as long as you clear the Plugin cache? (I just discovered that cache through the "Admin Toolbar" module).

I realize this could be done through one of the webform hooks but I would rather use a handler as part of getting familiar with Drupal 8 in general.

# Answer
> 1 votes
> Could someone please tell me what key thing(s) I need to do to make that connection

There are 4 ways that you can tell Drupal that your plugin exists.

You can read about the other 3 at D8 Plugin discovery

In this case Webform uses:

> **AnnotatedClassDiscovery**
>
> The AnnotatedClassDiscovery class uses name of the annotations that contains the plugin definition, e.g., `@Plugin`, `@EntityType`, in plugin docblocks to discover plugins, minimizing memory usage during the discovery phase. The AnnotatedClassDiscovery class takes an argument in its constructor, `$subdir`, which specifies the sub-directory/sub-namespace for this plugin type. The AnnotatedClassDiscovery class scans PSR-4 classes inside those sub-directories of Plugin folders to find plugins (see a "Annotations-based plugins").

Side Note: Entities and blocks also use this "annotation" method.

This "annotation" is seen in webform\_example\_handler/src/Plugin/WebformHandler/ExampleWebformHandler.php

Yes, this info is inside a comment block, weird, but that's just how it works.

---

> In webform\_example\_handler.schema.yml the first line is: `webform.handler.example`. Is this a standard Drupal construct of `<webform>.<handler>.<my_module>`, or something specific that must be followed set by the webform module or am I completely off base on how this is derived?

Wrong, otherwise it would've been named webform.handler.webform\_example\_handler.

It's actually `webform.handler.<WebformHandler_id>` (The ID you use in the annotation).

This is because your module can have multiple plugins, so it makes no sense to use the module's name here.

---

The webform.webform.webform\_example\_handler.yml file: could someone explain the parts? In my module would it be: *webform.webform.dis\_doc\_gen.yml* ?

Assuming your module is named `dis_doc_gen`, correct.

---

> Last: I have built my webform through the interface so I assume that I don't need the file webform.webform.webform\_example\_handler.yml as that would only be for creating a webform from a yml file upon installing the module as far as I can tell

Correct, anything inside the `/install` folder, runs on install and that file is creating a form. Since you created one via the UI, you don't need this in your use case.

---
Tags: 8, webforms
---