# Question
Title: Commerce 2 how to set to live paypal signature API Credentials
I have set up a sandbox account and I can take TEST payments without issue but there is nowhere for the live account details.

If I set the app you can create to live it gives different account API settings but no signature.

It seems Paypal has changed the layout and the PayPal module in D8 commerce 2 and has no help docs as of yet for this just help documents for the old D7 version.

# Answer
Ok I sussed this out quicker than I expected. So for anyone else having this issue do this..

1. Login to the merchant account NOT the developer account.
2. Menu on Top right *Click Profile \> Profile and settings*
3. *My selling preferences \> API access \> update*
4. Under *Pre-built payment solution \> Manage API permission*
5. Under *Option 2 \> View API Signature*
6. Under *View or Remove API Signature* expose the fields to show the Credential API Signature, API Username, API Password.

Add these to your PayPal settings in the commerce payment making sure you set this to live.
> 2 votes

---
Tags: 8, commerce, payment-gateways
---


title: How to add dynamic css for each node?

text:
# Question
Title: How to add dynamic css for each node?
I need to apply dynamic css for each node. I have stored the css into the database for each row of the page.

I have generating css like `node_57002-en.css` here, 57002 is a node-id with language code for each responsive layout. For eg. If I select width for desktop layout for `node-id-57002` then `node_57002-en.css` generated with below code.

`@media only screen and (max-width:991px) {}@media only screen and (max-width:767px){}`

I have to find out the better solution becouse, everytime generated the new css for each node. Below is the code which I used,

```
$styles = $nodeProcessor->getStyles();
$rowCss = $styles->getDesktop() . "@media only screen and (max-width:991px) {" . $styles->getTablet() . "}" . "@media only screen and (max-width:767px) {" . $styles->getMobile() . "}";
$cssPath = $modulePath . '/resources/css/rows/node_' . $this->_nid . '-' . $this->_langCode . ".css";
$cssPath .= '?' . filemtime($cssPath);

```

I have some questions on this,

1. How to get that css from db and how to apply on front-page in drupal manner.
2. How to cache the library css and how to clear the cache when css updated?
3. If not then what is the alternative option.

I referred Dynamically generated CSS and JS document but it is only for dynamic js. I really appreciate if anybody helps me. Thanks in advance.

# Answer
> 1 votes
I think you're over-engineering things here.

If your CSS is per-node-specific and stored in the DB anyways, then why not just use a text field to store the CSS? You just need to create a field template to output the raw content of the field in a `<style scoped>` tag.

---
Tags: theming, 8
---


# Question
Title: How to find the cause of 'The following module has moved within the system'?
I can't get rid of this message whenever I install a module, it shows:

> User warning: The following module has moved within the file system: \[modulename\]. In order to fix this, clear caches or put the module back in its original location. For more information, see the documentation page. in \_drupal\_trigger\_error\_with\_delayed\_logging() (line 1138 of /data/all/000/core/drupal-7.54.2/includes/bootstrap.inc).

I read the documentation mentioned, but cannot find a module that could cause this.

What would be the right way to find the cause?

# Answer
It might be tough to find the module that causes your error message.

However, you may want to have a look at 'How to fix "The following module is missing from the file system..." warning messages' which describes a few possible causes and corresponding solutions, such as:

* You removed a module from the file system without disabling and uninstalling it.
* You moved the module inside your Drupal installation.
* Leftover fields or other configuration entries.
* Obsolete modules existed from a previous Drupal version.
* There is a bug in a module installed on your site.

The one I ever used in the past (to get rid of that message) is to use the module 'Module Missing Message Fixer' (also mentioned on that same page).
> 2 votes

---
Tags: 7
---


title: Simpletest for Sending Mail

text:
# Question
Title: Simpletest for Sending Mail
I've written the following testcase to send an email. In test results output it says

> "1 e-mail was sent during this test."

but acutally it's not.

I tried another way, I put the function in menu callback (test-mail) it's sending mail when I access the URL. But if I access the URL in simple testcase like `$this->drupalGet('test-mail');` the result still says the same "1 e-mail was sent during this test." but was not.

So is it by design? Is there any other way to send mail?

```
 public function testSendMail() {
  $this->sendmail();
 }

function sendmail() {
  $from = 'fromaddress@gmail.com';
  $to = 'toaddress@gmail.com';
  $message = 'testcase mail';
  $language = 'en';
  $module = "test_mails";
  $key = "notification_mail";
  $send = TRUE;
  $subject = t("subject line goes here", array(NULL),array('langcode'=>'en'));
  $params = array(
    'body' => 'hello from krishna',
    'subject' => $subject
  );
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  return 'Mail sent succesfully';

  }

 function test_mails_mail($key, &$message, $params) {
 switch ($key) {
   case 'notification_mail' :
     $message['subject'] = $params['subject'];
     //the email body is here, inside the $message array
     $message['body'][] = $params['body'];
     break;
 }
}

```

# Answer
You need three functions.

1) module\_submit. 2) Create a function to send the mail. 3) create hook\_mail.

a complete example: file sendmailtest.info

```
name = sendmailtest
description = sendmailtest
core = 7.x

```

file sendmailtest.module

```
<?php

function sendmailtest_menu() {
 $items['sendmailtest'] = array(
   'title' => 'send mail test',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('sendmailtest'),
   'access callback' => TRUE
 );
 return $items;
}

function sendmailtest($form, &$form_state){

 $form['submit'] = array(
  '#value' => 'Send Mail Test',
  '#type' => 'submit',
 );
 //Fundamental devolver el objeto-array form
 return $form;
}

function sendmailtest_submit($form, &$form_state){

 drupal_set_message('Test ok');

 sendmailtest_send($form_state['values']);

}

function sendmailtest_send($form_values) {
  // All system mails need to specify the module and template key (mirrored from
  // hook_mail()) that the message they want to send comes from.
  $module = 'sendmailtest';
  $key = 'sendmailtest';

  // Specify 'to' and 'from' addresses.
  //$to = $form_values['email'];
  $to = 'jeremiselxi@gmail.com';
  $from = variable_get('site_mail', 'admin@example.com');

  // "params" loads in additional context for email content completion in
  // hook_mail(). In this case, we want to pass in the values the user entered
  // into the form, which include the message body in $form_values['message'].
  $params = $form_values;

  // The language of the e-mail. This will one of three values:
  // - user_preferred_language(): Used for sending mail to a particular website
  //   user, so that the mail appears in their preferred language.
  // - global $language: Used when sending a mail back to the user currently
  //   viewing the site. This will send it in the language they're currently
  //   using.
  // - language_default(): Used when sending mail to a pre-existing, 'neutral'
  //   address, such as the system e-mail address, or when you're unsure of the
  //   language preferences of the intended recipient.
  //
  // Since in our case, we are sending a message to a random e-mail address that
  // is not necessarily tied to a user account, we will use the site's default
  // language.
  $language = language_default();

  // Whether or not to automatically send the mail when drupal_mail() is
  // called. This defaults to TRUE, and is normally what you want unless you
  // need to do additional processing before drupal_mail_send() is called.
  $send = TRUE;
  // Send the mail, and check for success. Note that this does not guarantee
  // message delivery; only that there were no PHP-related issues encountered
  // while sending.
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  if ($result['result'] == TRUE) {
    drupal_set_message(t('Your message has been sent.'));
  }
  else {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }

}

function sendmailtest_mail($key, &$message, $params) {
  switch ($key) {
    // Send a simple message from the contact form.
    case 'sendmailtest':

      $message['subject'] = 'Test subject';

      $body= 'Test Body';
      $message['body'][] = check_plain($body);
      break;
  }
}

```
> -1 votes

---
Tags: 7, testing
---


# Question
Title: Cannot format date for date field in a Views_Database_Connector view
I am using the Views Database Connector module in drupal 8 to display the data from an external mssql database. I am running into issues with the date field. When I am asked to configure this field in the view, I am asked to choose a format for the date. However, when I go to view the page, I get this error (and stacktrace):

InvalidArgumentException: The timestamp must be numeric. in Drupal\Component\Datetime\DateTimePlus::createFromTimestamp() (line 172 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).

Drupal\Core\Datetime\DateFormatter-\>format('2009-03-02', 'html\_year', '', 'UTC', 'en') (Line: 323)

format\_date('2009-03-02', 'html\_year', '', NULL) (Line: 177)

Drupal\views\Plugin\views\field\Date-\>render(Object) (Line: 1144) Drupal\views\Plugin\views\field\FieldPluginBase-\>advancedRender(Object) (Line: 224) template\_preprocess\_views\_view\_field(Array, 'views\_view\_field', Array) (Line: 287) Drupal\Core\Theme\ThemeManager-\>render('views\_view\_field', Array) (Line: 435) Drupal\Core\Render\Renderer-\>doRender(Array, ) (Line: 195)

I have not been able to figure out how to get the date to be converted to a timestamp so it can be formatted. I have tried a preprocessor but the template\_preprocess\_view\_view\_field always occurs first and the exception occurs before it gets to my preprocess function. Is there something particular about the date data type in mssql? Any suggestions how to get the date to not generate the exception?

# Answer
> 0 votes
Took me a while but I figured out what I needed to do - create a custom module with a plugin to override the Date.php plugin (which actually overrides the FieldPluginBase.php). Using the LastTimestamp.php plugin (which overrides the Date.php) from drupal's core comment module as a reference, I was able to piece together what I needed to do.

First step is when reading in the data from the tables (via the Views\_Database\_Connector module), I gave the drupal date field a different id rather than the default 'date' (eg "date\_to\_display"). This is the id used to trigger the call to the custom plugin rather than the Date.php plugin. While the VDC was the first step, actually giving the date field a different id was the final piece of the puzzle to make this work.

Next step was to create the custom module and then create the plugin to override Date.php and use the id in the annotation (this is important): @ViewsField("date\_to\_display"). You can read about this in Drupal's doc Annotations-Based Plugins in Views. In the custom plugin, override the render function. In my particular case, I simply just checked to see if the date field value was numeric (which seems to be required for this to not throw an exception), and if not, convert it to timestamp (new value = strtotime(value)). For me that did the trick. The top part of the created plugin looks like this:

```
<?php

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\Date;
use Drupal\views\ResultRow;

/**
 * A handler to provide proper displays for dates.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("date_to_display")
 */
    class ViewsDateField extends Date {

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {

```

---
Tags: views, datetime
---


title: How to index field as single value?

text:
# Question
Title: How to index field as single value?
I use `Search API`, `Search API Database` and `FacetAPI`to create custom search. And there are mistakes in facets when it displays field with hyphens. For example, there is a text field "city" with value of "Rostov-na-Donu" (the name of the city in Russia). Facets show me three values: Rostov, na, Donu. But I want only one value for this field and it should be entire field content.

Please help.

# Answer
The solution was to index the field as "string", not "fulltext".
> 0 votes

---
Tags: 7, database, search
---


# Question
Title: How can I override date field validation?
I'm overriding the date field to hide the "day" part with this code:

```
function MYMODULE_form_MYFORM_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#after_build'][] = 'MYMODULE_date_remove_day_after_build';
}

function MYMODULE_date_remove_day_after_build($form, &$form_state) {
  $form['field_MYFIELD']['widget'][0]['value']['day']['#value'] = '15';
  $form['field_MYFIELD']['widget'][0]['value']['day']['#attributes']['class'][] = 'element-hidden';
  return $form;
}

```

This hides the day and allows the user to input the month and year. If the field is required, everything is fine.

However, if the field is not required, and the user does not input any value on the form, then the form validation fails because the **day** of the date field has been set to **15**, and the date module validation only accepts "every part (year + month + day) filled out" or "no part filled out."

So, on this specific field in my content type, I want to disable the date module's validation for the "day" alone-- or, I just want to disable validation for the entire date field. How can I do that?

# Answer
You can achieve this by prepending your own custom #element\_validate function before Datelist::validateDatelist().

As in your question, you have to add an after\_build function to access the individual parts (year, month, day) of the form element:

```
function MYMODULE_form_MYFORM_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#after_build'][] = 'MYMODULE_date_remove_day_after_build';
}

```

You can make the form element disappear by setting '#access' to FALSE. Then prepend your custom #element\_validate function to the array #element\_validate on the element.

```
function MYMODULE_date_remove_day_after_build($form, &$form_state) {
  $form['field_MYFIELD']['widget'][0]['value']['day']['#access'] = FALSE;
  array_unshift($form['field_MYFIELD']['widget'][0]['value']['#element_validate'], 'mymodule_date_set_day');
  return $form;
}

```

Then in your custom element validate function, unset everything if Year or Month are unset, otherwise, set the day. Notice you have to create the object before passing it to Datelist::validateDatelist().

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Datetime\DrupalDateTime;

function mymodule_date_set_day(&$element, FormStateInterface $form_state, &$complete_form) {

  $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

  if (empty($input['year']) || empty($input['month'])) {
    $form_state->setValueForElement($element, []);
  }
  else {
    $input['day'] = "15";
    $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
    $input['object'] = DrupalDateTime::createFromArray($input, $timezone);
    $form_state->setValueForElement($element, $input);
  }
}

```
> 3 votes

# Answer
Add an additional validation handler that runs before the default one:

```
array_unshift($form['#validate'], 'MYMODULE_MYFORM_validate');

```

In this validation handler check if only the day is set, and if so unset it. Something like:

```
function MYMODULE_MYFORM_validate($form, FormStateInterface $form_state) {
    $field_value = $form_state->getValue('field_MYFIELD');
    if(empty($field_value['month']) && empty($field_value['year'])) {
        $form_state->setValue('field_MYFIELD', []);
    }
}

```

I'm totally guessing at some of that syntax. But you should get the idea.
> 0 votes

# Answer
I found that when unsetting a field its easier to set it to the default value of the field.

For example, a select box tends to have the default value of "- Select a Value -". Instead of setting the select boxes value to \[\] or NULL, Set it to "- Select a Value -". You should take a look at what Drupal would normally set the value of the day field when it is empty and set the field to that value in the form validation. It may be an empty or filled in string, number, bool, array, etc...
> 0 votes

---
Tags: 8, forms, datetime
---


# Question
Title: Error messages aren't displayed when submitting the form
I want to display an error message when I submit a form. I added an AJAX callback to the form, and the error message appears after I refreshed the page.

I first tried the following code, but it doesn't work.

```
$response = new \Drupal\Core\Ajax\AjaxResponse();
$message = drupal_get_messages();
$output = $response->addCommand(new \Drupal\Core\Ajax\PrependCommand(".region-highlighted",$message));
return $output;

```

I also tried the following code.

```
$status_messages = array('#type' => 'status_messages');
$text = \Drupal::service('renderer')->render($status_messages);
return $text;

```

# Answer
You should retrieve the errors with `$form_state->getErrors()`.

So, you should have something like:

```
/**
   * Ajax submit handler.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   */
  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    drupal_get_messages();
    $response = new AjaxResponse();
    if ($form_state->getErrors()) {
      unset($form['#prefix']);
      unset($form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response->addCommand(new ReplaceCommand('#my-id', $form));
    }

    return $response;
  }

```

Check Examples for Developers for more details.
> 1 votes

# Answer
this works for form messages (in a regular ajax form callback):

```
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
    $response->addCommand(new ReplaceCommand('#yourFormWrapperElement', $form));

```

but using drupal\_get\_messages() screw's things somehow up .... sometimes. plus you need enable showing messages here: */admin/config/development/logging*

So - your second try should also work !

```
$status_messages = array('#type' => 'status_messages');
$text = \Drupal::service('renderer')->render($status_messages);
return $text;

```

Maybe the mentioned settings are needed ..
> 0 votes

---
Tags: 8, ajax, status-messages
---


# Question
Title: Check Content Type in Paragraph Preprocess
I've written a paragraph preprocess function that is working perfectly. The only issue is that I need it to only work when that paragraph is embedded in a certain content type.

```
function mytheme_preprocess_paragraph__paragraph_type(&$variables) {
   // Do things here if content type == 'specified_type'
}

```

I'm unsure of how to check the content type, though. How can I accomplish this?

# Answer
> 16 votes
The correct way of getting the entity data referencing to your paragraph is to use Paragraph's entity API.

```
/**
 * Implements template_preprocess_paragraph().
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - paragraph: The paragraph object.
 *   - view_mode: View mode; e.g., 'full', 'teaser'...
 */

function mytheme_preprocess_paragraph(&$variables) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];
  // Get the parent bundle.
  $parentBundle = $paragraph->getParentEntity()->bundle();
}

```

# Answer
> -1 votes
There is another post with either the same or similar answer here. https://stackoverflow.com/questions/31116325/how-to-programmatically-get-content-type-name-in-drupal-8

The poster Jose points out you can use

$node = \Drupal::request()-\>attributes-\>get('node');

to get the content type.

---
Tags: 8, paragraphs
---


title: Solution to migrate a field collection

text:
# Question
Title: Solution to migrate a field collection
My requirement is to migrate content nodes in xml format to drupal 7 content type fields.The xml contains a node which has to be field collection in drupal.I know how to migrate field which are enity references and term references.But i am new to field collection migration.I am using drupal migrate contrib module for migration. The field collection node in my xml file.

```
<myphotos_grid grid="true"><![CDATA[<rows>
  <row rowID="1">
    <rowAttribute>
      <theName>photo-name</theName>
      <value>photname1</value>
    </rowAttribute>
    <rowAttribute>
      <theName>photo-credit</theName>
      <value>my credit</value>
    </rowAttribute>
    <rowAttribute>
      <theName>photo</theName>
      <value>
      <attachment id="1009343343"/>
      </value>
    </rowAttribute>
  </row>
  <row rowID="2">
    <rowAttribute>
      <theName>photo-name</theName>
      <value/>
    </rowAttribute>
    <rowAttribute>
      <theName>photo-credit</theName>
      <value/>
    </rowAttribute>
    <rowAttribute>
      <theName>photo</theName>
      <value>
      <attachment id="4432434344"/>
      </value>
    </rowAttribute>
  </row>
</rows>]]></myphotos_grid>

```

I am writing a base class for my content types migration by extending XMLMigration class and it defines the migration source files and destination.Also i am writing corresponding classes for each content type which defines the field mapping by extending base class.

Above xml grid node in xml which has to be migrated to to field collection in my content type X in drupal 7 site.

My queries

Whether i need to write a seperate class for field collection extending my custom content type X migration class or adding the field mappings for field collection in the custom content type X migration class? Whcih is the best standard to migrate field collection in drupal?

I am new to this field collection migration,please help,Also very sorry for my english.

# Answer
I think you're on the right track. If I'm understanding your question, you won't need to add an extra class. Instead, you'll want to use your existing Migration class's complete() method, which is called after the node has been created. Within complete(), you can then use entity\_create to create your field collection and entity\_metadata\_wrapper around your newly migrated node to set a reference to your field collection entity.

In psuedocode,

```
public function complete($entity, stdClass $row) {
  fc_entity = entity_create(...)
  $ewrapper = entity_metadata_wrapper('node', $entity);
  $ewrapper->fc_ref_field->set( $fc_entity->nid );
  $ewrapper->save();
}

```

Or something thereabouts. When in doubt, "whatever works" is the correct standard for migration code. Hope that helps get you started!
> 0 votes

# Answer
Did you check Migrate Field Collections

> Field collections are separate entities, which are linked to host entities. That is why we have to create separate migration classes for every field collection field.
> 0 votes

---
Tags: migrations, entities
---


# Question
Title: When I change a node title and hit save, I get 'page not found'
I have a site which behaves strangely, whenever I change the node title, it give a page not found error. I think it has to do with Drupal trying to find the node by path alias, but why? It should find it by node ID?

I have even installed the module Global Redirect, but that does not help.

Suggestions are welcome!

# Answer
When you change the title of a node when URL auto-alias is turned on, you will need to fix your links to that node or do the options below. You are getting the page not found error, because it's trying to go back to the view version of the node that now has a different URL. You have the following options:

Install redirect. Then set up a redirect to the old URL. If you install this first, it will automatically track the changes of the URL moving forward.

Alternatively, you can go to the node and uncheck the auto-alias option and hand-assign the URL back to what it was before you changed the title. I recommend the redirect module though.
> 2 votes

---
Tags: 7, nodes
---


title: How do I get the uid of a node?

text:
# Question
Title: How do I get the uid of a node?
I am trying to get the user ID associated with a node using this code in Drupal 7, without any luck:

```
$uid =  $node->uid;
echo "uid: " . $uid;

```

`$uid` doesn't have any value in it.

I want to get it so that I can count the number of my members' posts.

```
$node = node_load('NID');
$uid = $node->uid;
$sql = "SELECT nid FROM {node} WHERE uid = $uid";
$result = db_query($sql);

$number_of_rows = $result->rowCount();
echo "uid: " . $uid;
print "<p>$node->name has submitted <em><strong>$number_of_rows</strong></em> source code / articles.</p>";'

```

I tried putting it in a display suite module under fields. I also tried putting in a page content type.

# Answer
for **Drupal 8** you can use

```
$uid = $node->getOwnerId();

```
> 8 votes

# Answer
That should work. Try making sure that you have a properly loaded node object.

```
$node = node_load('NID');
echo $node->uid;

```

It is possible that if the node was created by an anonymous user that the $uid would be zero and thus wouldn't print.
> 5 votes

# Answer
I think you need with this message print "

$node-\>name has submitted ***$number\_of\_rows*** source code / articles.

";'

To print the number of nodes by each user after submit(add) a new node You have to add drupal\_set\_message in hook\_node\_save using this sql

```
 global $user;
 $sql = "SELECT count(nid) FROM {node} WHERE uid = $user->uid";

```
> 0 votes

# Answer
Use Views. See this other question for some clarity.

If you want to attach this information to a node, you can use Viewfield.

Also: There's a better query you could use, instead of SELECTing all the content and then counting the results. You could use COUNT and let the DB server do it. `COUNT nid FROM {node} WHERE uid = $uid` This is essentially what Views is doing for you.
> -1 votes

# Answer
You can only get the author id of a node by using the following code. FYI it will work only in the node template.

```
<?php echo $uid; ?>

```

If you want to use the user id in any other template or in any custom module you can use the following code.

```
<?php $node = node_load(NID); $uid = $node->uid;?>

```
> -2 votes

---
Tags: 7, nodes
---


title: How to get the user_picture styled

text:
# Question
Title: How to get the user_picture styled
I have a $user and what to get the style image as a URL

originally found this answer How do I access a user image?

but it was not what I was looking for

# Answer
> 2 votes
I have found this to work

```
Use Drupal\image\Entity\ImageStyle;
$file_uri = $user->get('user_picture')->entity->getFileUri();
$styled_image_url = ImageStyle::load("large")->buildUrl($file_uri);

```

---
Tags: 8, users, entities, media
---


# Question
Title: How to prohibit some words and letters to use as a Drupal password?
I need to prohibit a user from using a few words as a password. E.g I don't want to use these words as a password. Drupal, 123456, Microsoft. When a user submits the registration form with the above terms in the password field then they get a message about the prohibited password.

# Answer
This module should work. I have never used it before, but it should definitely have the feature to prohibit certain password strings. Password Policy Module
> 4 votes

# Answer
You may also want to consider the Password Strength module. Some details about it (from its project page):

> ... provides realistic password strength measurement and server-side enforcement for Drupal sites using pattern-matching and entropy calculation. Almost any type of password can be allowed so long as the password proves to be of high enough entropy. For inspiration see the XKCD comic on password strength.

PS: Here is how the linked comic looks like:
> 1 votes

---
Tags: forms
---


title: How to handle tokens in Rules field?

text:
# Question
Title: How to handle tokens in Rules field?
I have duplicated Drupal Commerce module "Cash on delivery", from which I am trying to make custom module, where if customer choose as payment method my new payment, it will simply print out text with tokens inside. (This is because client needs to be able to pair orders with payments sent by credit card directly to his account, he will pair them with commerce order number)

I have successfully made a textarea in rules UI even with token field under this area, now I have to print them.

Working code for making textarea:

```
function bankovy_prevod_settings_form($settings = NULL) {

  $settings = (array) $settings + array(
    'information' => '',
    'var_symbol' => ''
  );

  $form = array();

  $form['information'] = array(
    '#type' => 'textarea',
    '#title' => t('Information'),
    '#description' => t('Informácie, ktoré chcete zobraziť zákazníkom, keď si navolia túto možnosť platby.'),
    '#default_value' => $settings['information']
  );

  $form['var_symbol'] = array(
    '#type' => 'textarea',
    '#title' => t('Variabilný symbol'),
    '#description' => t('Sem vložte token, na základe ktorého sa bude generovať variabilný symbol.'),
    '#default_value' => $settings['var_symbol']
  );

    if (module_exists('token')) {
      $form['token_help'] = array(
        '#theme' => 'token_tree',
        '#token_types' => array('commerce-order'),
      );
    }

  return $form;
}

```

Code for displaying the output on commerce order:

```
function bankovy_prevod_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
  $form = array();

  $var_symbol = "";
  if (!empty($payment_method['settings']['var_symbol'])) {
      $var_symbol = token_replace($payment_method['settings']['var_symbol'], array('node' => $form['commerce_checkout_form']));
  }

  if (!empty($payment_method['settings']['information'])) {
    $form['grafeon_bankovy_prevod_description'] = array(
      '#markup' => $payment_method['settings']['information'] . "<br/>" . $var_symbol
    );
  }

  // Need to create a dummy value to solve http://drupal.org/node/1230666
  // Probably an issue in the main commerce module
  $form['dummy'] = array(
    '#type' => 'hidden',
    '#value' => 'dummy'
  );

  return $form;
}

```

Now I have to somehow replace tokens, trying to use function token\_replace, but it does not seem to work with "node" as checkout is not node, so I tried various different "commerce\_checkout\_form" strings but neither of them worked. Can anyone please help me out to solve this?

Thats the part I have problem with:

```
$var_symbol = token_replace($payment_method['settings']['var_symbol'], array('node' => $form['commerce_checkout_form']));

```

Any advice would be greatly appreciated.

# Answer
> 0 votes
Just needed to replace this one field with this:

```
$var_symbol = token_replace($payment_method['settings']['var_symbol'], array('commerce-order' => $order));

```

Now it works perfectly.

---
Tags: commerce, tokens, payment-gateways
---


title: Creating booking system for items

text:
# Question
Title: Creating booking system for items
I am thinking of the best approach for a small website selling only two products - two sets of coin printings - one gold, and one silver. **There are only 100 products of each set made, all gold are the same price, all silver too.**

I need to create a system of 10 x 10 table (100 items) containing numbers, each one cell can be clicked and "reserved" (by ordering) - then administrator will ship the product and mark the cell as "sold", so each number can be bought only one time.

Now I was thinking of several methods to achieve this:

1. **Using Drupal Commerce**, which is quite robust for only two products. And I do not really want to have 200 same products on site differing only by ID and cell number. Maybe having only two products, adding some kind of field in this product with data of which numbers were already sold and then providing this field in product display would do the trick.
2. **Using Webform**, products can be nodes, there is no need for checkout, webform components should contain things like shipping and billing information and product nodes can have the same field with table as specified upper. Order mails can also be provided by webform.
3. Some other already made system for things like this, I was thinking about booking systems, but most of them are locked on dates I guess.
4. Other ideas?

Also the only payment method will be paying directly to bank account, nothing else. Back account creditials will be mailed to customer, they only need to contain order number or something because if all the orders are mostly the same amount, it would be hard to recognize which payment belongs to which order. Shipping method will again be only one, customer only need to be informed.

Thanks in advance.

# Answer
> 0 votes
Assuming this is about D7, here is a blueprint of just another idea (as in your bullet item "4"):

* Create a single node for each number, of content type (say "Golden Coin"), so 10x10 = 100 of such nodes.
* Use the Views module to display a 10x10 grid of those 100 nodes, and link each of them to there corresponding node.
* Use the Flag module for authorized users to "flag" such nodes, to indicate "reserve this one".
* Use the Rules module to make the remaining magic happen, using Rules Events such as "When such node is flagged", with Rules Actions such as "Create appropriate notifications (eg towards the admin)".
* Repeat the above for "Silver Coin", or add an extra field to the Flag you'll be using, to select between "Silver" and "Gold".

---
Tags: nodes, commerce, webforms, bookings
---


title: Reusable images question

text:
# Question
Title: Reusable images question
I want to have reusable images in my new Drupal 8 blog.

I followed this guide that uses the *Media Entity* and *Media Entity Image* modules, but I have a problem every time I want to use an existing image. I get the following error.

> The referenced entity (media: 206) does not exist.

So far, I used the default field\_image field in the articles, but now I want to use the new field\_reusable\_image that uses existing images.

Will the already uploaded images in field\_image be available to be added in field\_reusable\_image?

# Answer
The problem was that I created a field in media bundles that didn't match with the one in the content type. The guide that I followed was not so clear so in the media bundle I created a field\_image and I was trying to reference it with content.field\_reusable\_image in content type, which apparently didn't work.
> 0 votes

---
Tags: entities, media
---


# Question
Title: 8 How to configure add-on products in Commerce 2.x
What is the best way in Commerce 2.x to allow the shopper to check boxes to add optional accessories to a product before he adds the product to the cart. In addition, the product price should be updated.

Sounds like this module would do it in D7: Commerce Product Add-on.

This question asks the same question, but it's tagged with 7. Can a VBO form be integrated with the Commerce Add-to-Cart form to allow adding optional add-on products with checkboxes?

# Answer
Commerce Product Add-on now has a beta release for D8.
> 1 votes

---
Tags: 8, commerce
---


title: How to make menu block item show up?

text:
# Question
Title: How to make menu block item show up?
I have a menu block composed of menu items with submenu items. Each menu item is displayed separately in a block.

They are all set to appear on every page, no restrictions. However if I were to access one of the submenu items, the entire menu item (including the submenu items) belonging to it does no longer appear.

I have checked in variables from `template_preprocess_page`, the region where the menu item block should appear is showing as empty.

How can I make it show up?

# Answer
I have found the issue, "Make the starting level follow the active menu item." needs to be unticked.
> 0 votes

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


# Question
Title: Render image or entity in a custom block!
I want to render product content type in a custom block with a custom view mode. I have a field product\_teaser in my article content type that reference the product that is I want to render in the custom block using advert view mode

**The content type to be rendered:** "product"

**The view mode to be rendered with:** "advert"

The product teaser only contains an image and a buy=now button I can easily place using twig. So placing only the image in the render of the custom block should be enough for this to work But I have been trying to render the image for a while and I could not do it.

---

**This is my first approach to do this, Rendering the whole product advert.**

```
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $view_mode = 'advert';
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
      $pre_render = $view_builder->view($product, $view_mode);
      $render_output = render($pre_render);
      return $render_output;
    }
    return [];
  }

```

Render output is an empty string for some reason. $pre\_render has got view mode and node array having all the product fields, everything looks good except that render($pre\_render) return an empty spaces string. This is the error being output from this approach "Argument 1 passed to Drupal\Core\Render\Element::isEmpty() must be of the type array, object given"

---

**My second approach was to get the image URI of the product advert and render it manually**

```
$build= array();
    //Gets current node to check for which product to be displayed.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $product_advert_url = $product->field_teaser->entity->url();
    }

    $build['image'] = [
      '#theme' => 'image_style',
      '#style_name' => 'thumbnail',
      '#uri' => $product_advert_url
    ];

    return $build;

```

This is the error being output from this approach "Class name must be a valid object or a string in Drupal\image\Entity\ImageStyle-\>buildUri()"

---

How to fix these errors ??, I prefer the first method because it will be easier if I needed to add anything to the product teaser later.

# Answer
> 2 votes
You can do this in a View block. Add a contextual filter for the content id and configure it to provide the default value "Content ID from URL":

The view mode *Teaser* would be in your case a custom view mode (for the content type "article") only containing the product teaser field, configured to render the target entity in a second view mode "advert" (now for the content type "product").

---

If you want to do this in code, then get the node from a context plugin (see this great answer from @Berdir https://drupal.stackexchange.com/a/188629/47547) and build the render array (if you use the view modes mentioned above you only need one line of code). Very important, never render in Drupal 8, always return unrendered arrays.

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


title: Feeds - importing from 2 csv

text:
# Question
Title: Feeds - importing from 2 csv
i'm having issue with Feeds module, i already imported my csv but the images are in a different csv file, (the images are urls from old site) in the first csv i have and ID for every gallery and ofc this ID is inside the csv where are the images. Is it possible somehow to update and attach these images to my node ? I guess i need to work with that ID somehow. Thank you

# Answer
If you add a unique identifier/primary key column to both csv's, you can map that column as the GUID (under Processor \> Mapping tab of the specific feed importer config) and set the Feeds importer to update the nodes

You may need to use the Feeds Tamper module to properly parse out the subfields of data for the images/files (such as alt text), downloading them from your legacy site, and uploading to the new site.
> 0 votes

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


# Question
Title: Adding a class to a region: how is the class correctly added?
In the book Definite guide in Drupal I found the code below for adding a class to specific regions. I just don't understand how Drupal knows which regions should use the CSS class. There is only an `if` statemente which checks that the regions "sidebar" etc exist, but I can't see how Drupal adds the class to the specific regions. Did I misunderstand the code?

```
/**
 * Implements template_preprocess_region().
 */
function dgd7_preprocess_region(&$variables) {
  $region = $variables['region'];

  // Sidebars and content area need a good class to style against. You should
  // not be using id's like #main or #main-wrapper to style contents.

  if (in_array($region, array('sidebar_first', 'sidebar_second', 'content')) {
    $variables['classes_array'][] = 'main';
  }
}

```

# Answer
The code is not checking if those regions exist, but for which region the function is being invoked. `hook_preprocess_region()` (of which `dgd7_preprocess_region(&$variables)` is an implementation) is invoked once for each region the page contains.

The fact `$variables['region']` contains the name of the region being handled is clearer in the documentation for `template_preprocess_region()` which says:

> Prepares the values passed to the theme\_region function to be passed into a pluggable template engine. **Uses the region name to generate a template file suggestions.**

Since the code the function uses is the following one, `$variables['region']` contains the region name.

```
$variables['theme_hook_suggestions'][] = 'region__' . $variables['region'];

```
> 0 votes

---
Tags: theming
---


title: form's submit function does not execute

text:
# Question
Title: form's submit function does not execute
My problem is that when i click the form submit the page reloads but do nothing. whithin the submit function i have a statement where i dump the $form variable. as nothing happens i figured that the process does not reach the submit function at all and it must be stopping at the validation phase.

below you find my form structure (LoginForm).

## LoginForm.php

```
class LoginForm extends FormBase{
/**
* {@inheritdoc}
*/
public function getFormId(){
    return 'login_form';
}

/*
 * {@inheritdoc}
 */

public function buildForm(array $form, FormStateInterface $form_state){
    //$theme_dir = $GLOBALS["base_url"].'/'.drupal_get_path('theme', 'epw');
    $form = array();

    //$form['#attributes']['class'][] = 'login';

    $form['user_email'] = array(
        '#type' => 'email',
        //'#title' => $this->t('E-mail'),
        '#prefix' => '<div  class="db f5 dark-gray text textinp">E-mail</div >',
        '#default_value' => '',
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'mail',
            'name' => 'mail',
            'class' => array('b', 'pa3', 'input-reset', 'ba', 'bg-transparent', 'hover-bg-moon-gray', 'hover-black', 'w-100'),
        ),
    );

    $form['user_pass'] = array(
        '#type' => 'password',
        //'#title' => $this->t('Mot de passe :'),
        '#prefix' => '<div  class="db f5 dark-gray text textinp textinp2">Mot de passe :</div >',
        '#size' => 8,
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'password',
            'name' => 'password',
            'class' => array('b', 'pa3', 'input-reset', 'ba', 'bg-transparent', 'hover-bg-moon-gray', 'hover-black', 'w-100'),
        ),
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('SE CONNECTER'),
        '#button_type' => 'primary',
        '#prefix' => '<div class="tr mpoub">
                        <a href="index_mpoublier.php" class="tr f6 dark-gray ">Mot de passe oublié ? </a>
                      </div>
                      <div class="subhold tc">',
        '#suffix' => '</div>',
        '#attributes' => array(
            'name' => 'checklogin',
            'class' => array('f6', 'ttu', 'link', 'dim', 'ba', 'ph3', 'pv3', 'dib', 'white', 'bg-green', 'btn'),
        ),
    );

    return $form;
}

/**
* {@inheritdoc}
*/
public  function submitForm(array &$form, FormStateInterface $form_state){
    $email_value = $form_state->getValue('user_email');
    $msg = 'Votre email a bien etè envoyè. Vous avez recu une confirmation à ' . $email_value;
    drupal_set_message($msg);
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $formState){}
}

```

Any ideas on the source of the problem? Am i missing something?

# Answer
So i did found the culprit; and it was the attribute "name". it seems that it ovverides the actual name so when i call $form\_state-\>getValue('user\_email'); it does not know what i'm talking about but even with $form\_state-\>getValue('mail'); it does not work (don't know why at the moment). and because i made both field required the validation does not success and therefore it does not reach the submit function. so i just remove the attribute name :D
> 0 votes

---
Tags: forms, blocks
---


title: Make all user profile pictures round

text:
# Question
Title: Make all user profile pictures round
I am trying to figure out how to apply a class to user profile pictures in Drupal 8 to make the pictures round.

Since I am using Bootstrap 3 I can just apply image-round class in this case, but I am not sure how to add the class to the profile image.

I tried adding a class with the *Field Class* module, but it didn't work.

# Answer
In your file of your theme: **"MYTHEME.theme"**

Create ***hook\_preprocess\_image***

```
/**
 * Implements hook_preprocess_image() to add classes to the search form.
 */
function MYTHEME_preprocess_image(&$variables) {
  ksm ($variables);
    if ($variables['style_name'] == 'thumbnail') {
        $variables['attributes']['class'][] = 'image-rounded';
    }
}

```
> 1 votes

---
Tags: theming, bootstrap-theme
---


# Question
Title: drupal_view or views_embed_view doesn't show translated content
I have a block view on a multi-language website. Rendering Language is set to `Content language selected for page` and the translated content is displayed correctly in the admin page.

I embed this view like `{{ drupal_view('ipa_projects_map') }}` inside twig but at that page the content in original language is displayed, ignoring the content language selected for page setting.

Any ideas why?

PS: `drupal_view` is provided by "Twig Tweak" module and utilizes `views_embed_view`

# Answer
I found the problem. The view is configured to be a "block" and the "rendering language" setting belongs to the "block" definition I guess. So I added the block id and now it renders in the correct language:

```
{{ drupal_view('ipa_projects_map', 'block_1') }}

```
> 1 votes

---
Tags: views, 8
---


# Question
Title: How do I get all view fields in a preprocess hook?
In a view, I have an image field. I would like to get all the fields and process the image field.

```
function template_preprocess_views_view(array &$variables) {
  $view = $variables['view'];
}

```

How can I get those fields?

# Answer
If your use case allows for this, I would use rendered content (maybe a new view mode if the others are used somewhere else) in the view and do all the preprocessing on the node level (if needed). Usually, twig is enough to properly format the output of the node.
> 1 votes

---
Tags: views, 8
---


# Question
Title: Can a Event Service be coupled to a route
I have created a custom service and have hooked into the "event\_subscriber" via tags in my custom service.yml

```
  demo_api.exception_handler_subscriber:
      class: Drupal\demo_api\Response\Handler
      tags:
          - { name: 'event_subscriber' }

```

With in this custom service I'm listening into KernelEvents::RESPONSE

```
public static function getSubscribedEvents()
{
    // For this example I am using KernelEvents constants (see below a full list).
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
}

```

The problem is I have some API request and I'm modifying the response for these request and returning a modified json format.

```
public function onResponse(FilterResponseEvent $event)
{
    $response = $event->getResponse();
    $apiFormatter = new ApiFormatter();
    $response->setContent(
        json_encode(
            $apiFormatter
            ->wrapResult(
                json_decode(
                    $response->getContent()
                )
            )
        )
    );
}

```

This is causing any web pages to respond as json.

I would like to limit this service to these API calls only and not be called on each request.

Any advice would be grateful.

# Answer
If you want to restrict the event subscriber to a route then check for the route name:

```
public function onResponse(FilterResponseEvent $event) {

  $route_name = $event->getRequest()->attributes->get('_route');
  if ($route_name !== 'my.route.name') {
    return;
  }

  ...

}

```

Although in Drupal it might be best practice to get the route name from the `current_route_match` service:

```
$route_name = $this->routeMatch->getRouteName();

```

which you then need to inject in the event subscriber.
> 2 votes

---
Tags: 8, routes, symfony-services
---


# Question
Title: How can I clone all field values when creating a node translation (entity_translation) programmatically?
I use `entity_translation` and have an `en` node currently without translations. Assume it has fields `field_foo` and `field_bar` so currently they are:

```
$node->field_foo['en'][0]['value'] = 'foo';
$node->field_bar['en'][0]['value'] = 'bar';

```

I want to programmatically add an`fr` translation but only translate `field_foo` so I do:

```
$node->field_foo['fr'][0]['value'] = 'foo FR';

entity_translation_get_handler('node', $node)->setTranslation(array(
  'translate' => 0,
  'language' => 'fr',
  'source' => 'en'
), $node);
field_attach_update('node', $node);

```

This works but now if I edit (or devel) the `fr` node, `field_bar` is empty. On the frontend it does show "bar" which is the `en` value, but I've noticed that if I create the translation via the Drupal UI then the `field_bar` is not empty and contains a copy of the `en` value.

So, does anyone know of a way that the API will copy all values upon translation creation? Or should I be doing that myself manually via the code?

# Answer
I ended up doing it manually via code:

```
function _populate_translation_values($node, $targetLanguage) {
  $fields = field_info_instances('node', $node->type);
  foreach($fields as $fieldName=>$fieldInstance) {
    $fieldInfo = field_info_field($fieldName);

    // only process translatable fields
    if (!$fieldInfo['translatable']) continue;

    // ignore fields which are complicated to copy - could be fixed in the future
    if (in_array($fieldInfo['type'], array('field_collection'))) continue;

    // skip fields which already have a value in the target language
    if (isset($node->{$fieldName}[$targetLanguage])) continue;

    // skip fields which don't have a value in the source language
    if (!isset($node->{$fieldName}[$node->language])) continue;

    // copy value
    $node->{$fieldName}[$targetLanguage] = $node->{$fieldName}[$node->language];
  }
}

```
> 1 votes

---
Tags: 7, i18n-l10n
---


title: altering the add content type form

text:
# Question
Title: altering the add content type form
I am going to alter the form of `add content type form` and for that I used the `hook_form_FORM_ID_alter()`

Here is my code which implement in the module file, but it is not working.

```
function hc_listings_menu()
{
    $items = array();
    $items['node/add/home-care-popular-search-region']=array(
        'title' => 'Create Home Care Popular Search Region',
        'page callback' => 'drupal_get_form',
        'page arguments'=> array('home_care_popular_search_region_node_form',''),
        'type'=>MENU_NORMAL_ITEM,
    );
    return $items;
}
function hc_listing_home_care_popular_search_region_node_form_alter(&$form, &$form_state, $form_id)
{

    $state_list=['ffff','gggg'];
    $region_list=['1','2','3','4'];
    $form['home_care_popular_search_region']=array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#title' => t('Homeeee Care Popular Search Region'),
        '#description' => t('Home Care Popular Search Region'),
        '#required' => TRUE,

    );
    $form['hc_popular_state']=array(
        '#type' => 'select',
        '#default_value' => $state_list,
        '#title' => t('Popular State'),
        '#description' => t('Home Care Popular State'),
        '#required' => TRUE,
    );
    $form['hc_popular_regions']=array(
        '#type' => 'select',
        '#default_value' => $region_list,
        '#title' => t('Popular Search Region'),
        '#description' => t('Home Care Popular Search Region'),
        '#required' => TRUE,
    );

}

```

**Note**: content type is =\> home\_care\_popular\_search\_region

module is =\> hc\_listing

Should I have to remove the details in `hook_menu` regarding the altering?

# Answer
First, You need to find out the correct form id for this form and then you can use,

`hook_form_FORM_ID_alter` there.

Thanks
> 0 votes

# Answer
Remove the `hook_menu` from the module because there are not need to add this menu item.
> 0 votes

---
Tags: 7, forms, hooks
---


# Question
Title: View filtering, Relationship Vs Contextual filter
I used contextual filters before and I know they are just like the normal filters but more dynamic, now I have this view "Sidebar Product advert block" that needs to show the product advert ( Similar to product teaser! advert is a view mode ) BUT only if the product is referenced in the field\_product\_teaser in the article data type. So to be more clear:

---

Articles have a reference entity (Autocomplete) **field\_product\_teaser.**

Products referenced in this field should appear in the sidebar!

So the condition is **{{ product.Product-id == article.field\_product\_teaser }}**

---

I hope that was clear enough, what should I use in this case ?? contextual filters? relationships? I tried using both with no luck!

# Answer
> 0 votes
You should use the contextual filter to identify the article the block is being displayed on. E.g. content id from URL should work.

Then you should use the relationship option to link the field\_product\_teaser info to products. E.g. Content referenced from field ....

Then in the view, you can select the product fields you want to display and use the reference to tell views what you want displayed. E.g. title w/ product reference relationship = product title.

---
Tags: 8, views
---


# Question
Title: How to add 'add to cart' button in custom content type using Commerce 2?
I have created a new content type with product title, description, price(field\_price), SKU(field\_sku) fields. I just want to add a `Add to cart` button into this content type.

What I tried? I have read many places, it says to add 'Product references'. I have tried to do that using 'Entity reference' field and selected 'Product'. But no luck.

Can someone guide me step by step about how can we add such 'Add to cart' button in custom content type?

# Answer
> 1 votes
Follow below steps to show `Add to cart` button into any content type.

1. Add field with reference as Product and select list of product bundles you want to show in content type.
2. And in field settings select reference as shown in below.
3. Go to content type manage display and select as "Rendered Entity" as shown below.
4. Go to the product type which you selected in content type and click on manage display.
5. See for variations and select as "Add to cart form" as shown in below.

And that's it after adding node with product you will be able to see the `Add to cart` button into node view like below.

---
Tags: 8, commerce
---


# Question
Title: Theme Suggestion for overridding page-title.html.twig file?
Is there a way to override the default page-title template using the theme suggestion. Like we can override node for article type as below,

***For all nodes:*** `node.html.twig`

***For nodes of article type:*** `node--article.html.twig`

same way,

***for all page title:*** `page-title.html.twig`

***for page title on article content type:*** `???`

I tried many things like `page-title--article.twig`, `field--page-title--article.html.twig`, `field--bartik-page-title--article.html.twig`, `node--article--page-title.html.twig` etc.. these are not working. OR it is not possibel to do this with page-title file?

# Answer
> 1 votes
The page-title template is not aware about the context where it is placed and so there is no straightforward solution for a theme hook suggestion on the content type.

But you can override the field template, which is placed inside of page-title. This would be the twig name for the content type `article`:

```
field--node--title--article.html.twig

```

And this is the `field--node--title.html.twig` from core theme stable:

```
{#
/**
 * @file
 * Theme override for the node title field.
 *
 * This is an override of field.html.twig for the node title field. See that
 * template for documentation about its details and overrides.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing span element.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see field.html.twig
 */
#}
<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

```

I would use this field twig to start with, because this is not so cluttered as the standard field template.

# Answer
> 4 votes
You can do this by adding your own suggestion. In your theme's `ThemeName.theme` file add a `hook_theme_suggestions_HOOK_alter()` for the page title:

```
// Add content type suggestions, e.g. page--node--article.html.twig.
function ThemeName_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  // Are we looking at a node?
  $node = \Drupal::routeMatch()->getParameter('node');
  // Object check required, sometimes it's a string, yes, really. Who knew?
  if (!empty($node) && is_object($node)) {
    array_splice($suggestions, 1, 0, 'page_title__' . $node->getType());
  }
}

```

Then create templates per node type, e.g. page-title--article.html.twig, page-title--custom-content-type.html.twig etc.

Edit: rather than the array\_splice you can just push suggestions onto the array, e.g.:

```
  if (!empty($node) && is_object($node)) {
    $suggestions[] = 'page_title__node';
    $suggestions[] = 'page_title__node_' . $node->getType();
  }

```

array\_splice() is just a trick I commonly use to position suggestions in the $suggestions array so I can control when they are picked up and used.

# Answer
> 0 votes
I was struggling with this because for the theme suggestions alter hook for page title, there is jack for data in the `$variables` array, so it's near impossible to come up with any useful logic to create suggestions. You can load the current node and use that data to come up with suggestions, but not much else.

In my case I needed to come up with suggestions based on which block was rendering the page title template. In order to do this, I made use of `drupal_static`.

```
/**
 * Implements hook_preprocess_HOOK() for Block document templates.
 */
function bax_commercial_theme_preprocess_block(array &$variables) {
  $current_rendered_block = &drupal_static(__FUNCTION__);
  $current_rendered_block = $variables['elements']['#id'];
}

/**
 * Implements hook_preprocess_page_title().
 */
function bax_commercial_theme_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  $current_rendered_block = &drupal_static('bax_commercial_theme_preprocess_block');
  if (isset($current_rendered_block)) {
    $suggestions[] = 'page_title__block__' . $current_rendered_block;
  }
}

```

Because of the render order, this is valid and works well for me. It may or may not work for everyone.

# Answer
> -1 votes
Yes. Turn on Twig debugging and view source.

It'll give the name of template suggestion to use.

Twig templates go down to the field level.

---
Tags: theming, 8
---


title: RSS Events Calendar

text:
# Question
Title: RSS Events Calendar
I installed 'Calendar' module in Drupal 7. What I want to know is if it's possible to get an RSS feed and feed that to the Calendar ?

I do realize that the 'Feeds' module will break it down and store it in the database, but was wondering if there is a more direct approach to displaying the RSS on the calendar?

Thank you.

# Answer
* Calendar \- Requires **Views** and the Date API (packaged with the Date module).
* Views - support natively RSS Feeds.

So you need just add Feed display.

For importing events to calendar, you can use Feeds module, on source side there's some date(s) provided.
> 0 votes

# Answer
Just a note that Events aren't really supported well in RSS, i.e. there isn't a place to provide start and end times. There was a draft spec made for RSS events (http://web.resource.org/rss/1.0/modules/event/), but It's not natively supported in Drupal. You would be better off setting up a generic XML or JSON feed that exposes the fields you need.
> 0 votes

---
Tags: feeds
---


# Question
Title: Using Migrate API, is it possible to UPDATE entities on subsequent imports?
I am using Migrate API with Migrate Plus, Tools and Source CSV to create Commerce Products from a CSV file. The CSV file will be updated daily where the product info (prices, stock level, etc) may change. As far as I can tell, Migrate doesn't recognize changes to the source of existing content once it's been imported.

Is there a way to re-import a file and pull changes to the file (source)

# Answer
Got the answer:

add --update to your drush command (drush mi your\_migration --update)
> 1 votes

---
Tags: 8, migrations, importing-exporting
---


title: cannot use some drush commands

text:
# Question
Title: cannot use some drush commands
I am running into some trouble with `drush pm-enable`: I cannot enable the modules I just downloaded. I did some research but none of the solution worked for me, most cases involved switching localhost to 127.0.0.1 in the *settings.php* file, but in my case the database server is located on a Docker container. I am running Drush from the root folder.

This the output I get when I run `drush en module1, module2`.

> Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
> The drush command 'en module1, module2' could not be executed.
> Drush was not able to start (bootstrap) the Drupal database.
> Hint: This may occur when Drush is trying to:
>
> * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
> * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.
>
> Drush was attempting to connect to: Drupal version : 8.4.0
> Site URI : http://default
> Database driver : mysql
> Database hostname : mariadb
> Database port : 3306
> Database username : root
> Database name : drupal
> PHP executable : /usr/local/bin/php
> PHP configuration :
> PHP OS : Linux
> Drush script : /var/www/html/vendor/drush/drush/drush.php
> Drush version : 8.1.15
> Drush temp directory : /tmp
> Drush configuration :
> Drush alias files :
> Drupal root : /var/www/html
> Drupal Settings File : sites/default/settings.php
> Site path : sites/default
> Sync config path : sites/default/files/config\_oL5MBo-2\_ALSPTKnAwZb1o3WVs19lndEmQpb4zfSv42kL9A8F0bp4g\_demvUvf96DBkH3qyYww/sync

This is the output of `drush sql-connect`.

> mysql --user=root --password=root --database=drupal --host=mariadb -- port=3306

# Answer
> 0 votes
I prefer to use drush from drush alias files, so that the magic of Drush figuring out everything from the document root isn't so magical and you can sometimes more easily debug issues from a proper drush alias file.

As others mention it's likely the database connection that's not working. In docker you can use the `--add-host` build option, or the `extra_hosts` docker-compose options to give a name to your database container (docker can use the container name to properly create the /etc/hosts entry at runtime).

See this stackexchange answer https://stackoverflow.com/a/38306666/1491507

By following the above directions in docker-compose an entry such as the following that creates a named hosted in /etc/hosts as `my_resolved_db_service` which is magically resolved to the `mariadb` container.

```
extra_hosts:
  - "my_resolved_db_service:mariadb"

```

Then in a drush alias file, or when installing drupal via drush you would use the /etc/host name created: `drush si --db-url=mysql://root:root@my_resolved_db_service/drupal` as an example.

---
Tags: 8, database, drush
---


# Question
Title: How to prevent duplicate entity reference items from being entered on a field?
How would you prevent a user from being allowed to enter duplicate entity reference items on an entity reference field?

# Answer
Using form alter, you could add an #element\_validate function to the field.

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

  if (isset($form['field_articles'])) {
    if (empty($form['field_articles']['widget']['#element_validate'])) {
      $form['field_articles']['widget']['#element_validate'] = ['mymodule_prevent_duplicate_entity_reference'];
    }
    else {
      $form['field_articles']['widget']['#element_validate'][] = 'mymodule_prevent_duplicate_entity_reference';
    }
  }
}

```

Then in your custom validation function, if there are duplicate entity reference items, set a form error.

```
function mymodule_prevent_duplicate_entity_reference(array &$element, FormStateInterface $form_state, array &$complete_form) {

  $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

  $ids = array_filter(array_column($input, 'target_id'));

  // Check that there aren't duplicate entity_id values.
  if (count($ids) !== count(array_flip($ids))) {
    $form_state->setError($element, 'Field "' . $element['#title'] . '" doesn\'t allow duplicates.');
  }

}

```

If you would like to create a reusable widget, you could extend one of the entity reference widgets, for example, EntityReferenceAutocompleteWidget:

```
namespace Drupal\mymodule\Plugin\Field\FieldWidget;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
use Drupal\Component\Utility\NestedArray;

/**
 * Plugin implementation of the 'entity_reference_autocomplete' widget.
 *
 * @FieldWidget(
 *   id = "no_duplicate_entity_reference_autocomplete",
 *   label = @Translation("Autocomplete - Disallow Duplicates"),
 *   description = @Translation("An autocomplete text field that validates against duplicates."),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class NoDuplicateEntityAutocomplete extends EntityReferenceAutocompleteWidget {

  /**
   * {@inheritdoc}
   */
  public static function afterBuild(array $element, FormStateInterface $form_state) {
    parent::afterBuild($element, $form_state);

    $class = get_class();
    $element['#element_validate'][] = [$class, 'validateNoDuplicates'];

    return $element;
  }

  /**
   * Set a form error if there are duplicate entity ids.
   */
  public static function validateNoDuplicates(array &$element, FormStateInterface $form_state, array &$complete_form) {

    $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

    $ids = array_filter(array_column($input, 'target_id'));

    // Check that there aren't duplicate entity_id values.
    if (count($ids) !== count(array_flip($ids))) {
      $form_state->setError($element, 'Field "' . $element['#title'] . '" doesn\'t allow duplicates.');
    }

  }
}

```
> 3 votes

---
Tags: 8, forms, entities
---


title: Paragraphs + selectlist based bg-color

text:
# Question
Title: Paragraphs + selectlist based bg-color
I have a selectlist-field based bg-colors:

* yellow
* black
* blue

I added this to paragraph bundle called 'Hero'. Now i got selectlist-field on this paragraph bundle. How do I print that yellow to paragraphs-item template? I tried it few times but it always returned 1.

Any ideas?

# Answer
You need to use a preprocess hook to add a class / set a style to the paragraph based on the field content.

Here's some sample code from one of my sites that uses this. The options for bg\_color field are like: "Ghost Gray" =\> "eeeeee" and the like. The paragraph type is colorsection.

```
function my_module_preprocess_paragraph__colorsection(&$variables) {
  if (!$variables['paragraph']->field_bg_color->isEmpty()) {
    $variables['attributes']['style'][] = 'background: #'.$variables['paragraph']->field_bg_color->value.';';
    $variables['attributes']['class'][] = 'bg-'.$variables['paragraph']->field_bg_color->value;
  }
}

```
> 0 votes

---
Tags: theming, paragraphs
---


# Question
Title: Looking for something similar to "Views selective filters", just with "inactive" instead of "removed"
The Views Selective Filter module reduces the filter items in a views exposed filter to only those having actually results.

I'm searching something similar, but I don't want to hide the options with no results, instead I want to make them inactive (shown greyed out).

The exposed filter list I have is just a vocabulary with some category terms.

Is there a module for this somewhere out there? Or how can I achieve that?

# Answer
How are you going to gray out items in a combobox? If using Better Exposed filters module to replace the combox with some other widget, you can easily use Views Selective Filters and some Javascript to do the magic.
> 0 votes

# Answer
# Views Dependent Filters

Consider looking at the Views Dependent Filters module, which might help. Here is a quote from its project page:

> Allows the presence of exposed filters on a view to be controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.
>
> The module is compatible with both the Views basic and the Better Exposed Filters form plugins.

Investigate how the technique of "filters are hidden when not relevant" is implemented and try to someho tweek that if needed to perfectly meet your needs.

Its readme.txt file contains some more information about this module.

# Views Reference Filter

Another module that might help is the Views Reference Filter module. From its project page:

> Imagine you have taxonomy terms in exposed filter widget (drop down select list). But for some reason you want to show just several terms, not all the dictionary. With this module, you can do this by creating a separate view which generates the desired list of terms.
> 0 votes

# Answer
I'd have two filters for the field, one selective and one normal.

I'd hide the normal one with css and use jQuery to loop through it, compare the entries to the selective list, and add any extras + a class to disable them.
> 0 votes

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


# Question
Title: How do I redirect a specific page on my drupal site to an external site?
I have a shop on my drupal website which we have replaced with an updated squarespace page. I need the drupal page to automatically redirect to the new shop and I can only find a help page from circa '07 which says redirects are in the works... Thanks

# Answer
You can use drupal\_goto("external-path");
> 0 votes

# Answer
There are different ways to redirect automatically,

1) Web Server, Apache or nginx: in Apache, you can write rewrite rules()this link will help in .htaccess file which you can place in your document root. In nginx you can follow this link

2) Drupal hooks: hook\_init or hook\_boot, check the page URL using `drupal_get_path_alias(current_path())` and use drupal\_goto

3) javascript or jquery -\> Add js to the respective page which you needs to redirect

Using Jquery: `$(location).attr('href',url);`

Using javascript: `window.location.href="url";`
> 0 votes

---
Tags: redirection
---


# Question
Title: LogicException node save via ResourceBase post()
When i try to create a node via rest api (8.4) I keep getting

> LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\rest\ResourceResponse

The node is created but my app recieves an error.

the end point code is as follows

```
namespace Drupal\transactions\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\node\Entity\Node;

/**
 * Provides a Transactions Resource
 *
 * @RestResource(
 *   id = "transactions",
 *   label = @Translation("Stripe Transactions"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/transactions",
 *     "create" = "/api/v1/transactions",
 *   }
 * )
 */

class TransactionsResource extends ResourceBase{

  public function get() {
    return new ResourceResponse("Implement REST State GET!");
  }

  /**
   * Responds to entity POST requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function post($payload) {
    $recipient = Node::create([
      'type' => 'recipient',
      'field_firstname'=>"name3",
      'field_lastname'=>"name2",
      'field_mobile'=>"3128371973193",
      'field_city'=>"london",
      'field_country_to'=>"UK"
    ]);
    $recipient->save(); //error occurs here

  $response = new ResourceResponse(['nid', $recipient->id()]);
  $response->addCacheableDependency($recipient);

    return $response;
  }

}

```

# Answer
> 0 votes
Responses to a POST request should not be cached. Use an uncacheable response like ModifiedResourceResponse:

```
  $response = new ModifiedResourceResponse(['nid', $recipient->id()]);

```

---
Tags: 8
---


# Question
Title: Add a contextual filter to a view based on taxonomy term programatically?
I have content type called "Article", in this content there is a field called "topic" which is a auto complete field and it is taxonomy term.

There is a taxonomy called "topic" and terms in this taxonomy are "Red 2015","Red 2016","Red 2017","Red 2018".

I created 3 nodes under this "article" content type and selected topic field as "Red 2017"

And the node url is coming like this "www.qwerty.com/top-10-red-2017-18".

I want to create Contextual filters by giving a condition like that if the url contain year 2017 then consider the taxonomy term "Red 2017" content and fetch recent 3 node coming under article content type and node coming under taxonomy term "Red 2017"

# Answer
Doing it by regexing the url is messy and prone to error. You just need to load the node, get the term id and send it to the view.

In your view's contextual filter, instead of "Provide default", select "Hide view". Views has no way of getting the term from the currently viewed node by itself so we'll provide it with a module called `custom_taxonomy`.

**custom\_taxonomy.module**

```
<?php

function custom_taxonomy_views_pre_view(&$view, &$display_id, &$args){
    // Check for view
    if($view->name == 'block_under_article') {
        // Current URL
        $url = explode('/', current_path());
        // Check we have a node ID. This ignores aliases.
        if (isset($url[1]) && is_numeric($url[1])) {
            // Load node to get taxonomy
            $current_node = node_load($url[1]);
            // Check taxonomy is set
            if (isset($current_node->field_topic['und'][0]['tid'])) {
                // Send it to the view
                $args[0] = $current_node->field_topic['und'][0]['tid'];
            }
        }
    }
}

```

Just change the view name and check that the field name is correct. This assumes that there is that the field\_focus contextual filter is at the top of the list. If it isn't, you can use `$args[1] $args[2]` etc.

If your `www.qwerty.com/top-10-red-2017-18` page isn't an article or something you can add that taxonomy field to, then you'd need to do something like below..

```
if (strpos(current_path(), '2017') !== false) {
    $args[0] = 123; // The tid of the 2017 term
}

```
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to load all information Currency properties by currency code?
I used module Currency version 8.x-3.1 . I had currency Code so I looking up function to load all properties currency by currency code , What API or function do it ?

Thanks

# Answer
As a currency is just an entity you can do the following:

```
$currency_code = 'AUD';
$entity_type_manager = \Drupal::service('entity_type.manager');
$currency = $entity_type_manager->getStorage('currency')->load($currency_code);
ksm($currency); //check out what's available

//eg get sign
$sign = $currency->get('sign');

```

Good Luck
> 0 votes

# Answer
You need to load the commerce\_currency entity with entity manager

```
    $entity_manager = \Drupal::entityManager();
    $currency_code = 'USD';
    $currency = $entity_manager->getStorage('commerce_currency')->load($currency_code);
    kint($currency);

```
> 0 votes

---
Tags: 8
---


# Question
Title: How can I programmatically get the custom blocks (objects) placed in header and footer of a view created from the backoffice
I tried this line to get the view.

```
$actualites_view = \Drupal\views\Views::getView("actualites");

```

I also used these lines to get header and footer blocks.

```
$bandeau_entete = (\Drupal\block_content\Entity\BlockContent::load(1));
$bandeau_pied_de_page = (\Drupal\block_content\Entity\BlockContent::load(2));

```

I am using a constant value for the block ID.

How would I programmatically get the block ID from header and footer of the view?

>

# Answer
> 0 votes
You can get header of view like below:

```
$actualites_view =\Drupal::entityTypeManager()->getStorage('view')->load("actualites");
$header_block_id = $actualites_view->get('display')['default']['display_options']['header']['entity_block']['target'];

```

And in same way you can get footer block ID also.

---
Tags: views, blocks
---


# Question
Title: How to redirect programatically using a route with parameters?
I am trying to use the Passwordless module API to redirect the user on login.

I want to redirect the user to a specific node edit page (**node/12/edit**).

In `hook_passwordless_login_redirect()`, the module redirects the user with this code:

`return $this->redirect($redirect);`

So here is my implementation:

```
function MYMODULE_passwordless_login_redirect_alter(&$redirect) {
  // You can use hasPermission() with currentUser, but need to load for hasRole()
  $account = \Drupal\user\Entity\user::load(\Drupal::currentUser()->id());
  $test = \Drupal::service('path.validator')->getUrlIfValid('node/12/edit');
  if (!($account->hasRole('admin'))) {
    $redirect= $test->getRouteName();
  }

```

The problem is that I get this error:

> Some mandatory parameters are missing ("node") to generate a URL for route "entity.node.edit\_form".

The missing route parameter is the node id, which I can get with `$test->getRouteParameters()`. But how do I pass this to the redirect? (How do I call the redirect and give it both the route name and the route parameters?)

# Answer
> 1 votes
As pointed out by @4k4, the problem is that the module did not ask for the route parameters, so I patched it.

Then you can call the redirect like this:

```
  if (!($account->hasRole('admin'))) {
    $routename = $test->getRouteName();
    $routeparameters= $test->getRouteParameters();
  }

```

# Answer
> 0 votes
You can pass parameters like below:

```
$url = \Drupal\Core\Url::fromRoute(
    $test->getRouteName(),
     array(
       'query' => array('query1' => 'YOUR QUERY'),
       'absolute' => TRUE,
     )
);

```

---
Tags: 8, redirection
---


# Question
Title: Field and storage settings on base fields
I am rewriting my config fields (Field API fields) into base fields and I am unsure about one thing: settings.

Base fields have the `setSettings()` method, which I presume is equivalent of field instance settings. Then, there is `getFieldStorageDefinition()->setSettings()`, which I presume is equivalent of storage settings.
When I look at the entity reference item and the user ID field used by the node entity, the user ID field calls `setSetting('target_type', 'user')`, which is storage setting and not instance setting. Do I get these two wrong? What is going on?

`Node::baseFieldDefinitions()` contains the following code.

```
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Authored by'))
  ->setDescription(t('The username of the content author.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'user')

```

`EntityReferenceItem::defaultStorageSettings()` contains the following code.

```
return [
  'target_type' => \Drupal::moduleHandler()->moduleExists('node') ? 'node' : 'user',
] + parent::defaultStorageSettings();

```

# Answer
> 1 votes
The base field definition implements the FieldDefinitionInterface and the FieldStorageDefinitionInterface, so it can act like a form API field, though it's not managed by the field module.

So the base field definition contains the settings of both, which you can see how the default values are set in `BaseFieldDefinition::create()`:

```
  public static function create($type) {
    ...
    $default_settings = $field_type_manager->getDefaultStorageSettings($type) + $field_type_manager->getDefaultFieldSettings($type);
    $field_definition->itemDefinition->setSettings($default_settings);
    return $field_definition;
  }

```

---
Tags: 8, entities
---


# Question
Title: How do I use only a taxonomy term in the path alias?
I have content that is tagged with multiple terms from the same vocabulary. How can I use only the first term the node was tagged with, in the URL structure, e.g. domain.com/first/term/with/depth/node-title?

I am trying to do this with the Pathauto module and Drupal 8, but I can't figure it out. It either grabs all the terms used in that node or none.

# Answer
I gave this a try and the following pattern seems to be working:

\[node:field\_tags:0:entity\]/\[node:title\]
> 1 votes

# Answer
This is what worked. It includes all parents and term of the first entry. If you are using unlimited terms in node, the rest will be ignored.

/\[node:field\_term:0:entity:parents:join-path\]/\[node:field\_term:0:entity\]/\[node:title\]
> 0 votes

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: If a user does not have a role, keep redirecting them to the same form until they complete it?
I have a form/node that I want all users to complete after logging in for the first time. When the user completes the form (saves the node), they are automatically awarded the `completed` role.

If a user does not have the `completed` role, I want to keep redirecting them to the form no matter what links they click.

In Drupal 7, I could do this with Rules (event: content is viewed, condition: user does not have role, action: redirect). However, in Drupal 8, Rules is still in alpha and I can't get it to work without crashing my site. So what hook should I use to do this programmatically? (what's the hook for "user views a node"?)

# Answer
> 1 votes
You can use `hook_entity_view`, this is called when a user views any entity type, also `hook_ENTITY_TYPE_view` can be used if you want to redirect on specific entity type view like node.

# Answer
> 0 votes
Here's a simple way to do this.

1. Find all the blocks that print links (User account menu, Footer, Main navigation, etc.)
2. Configure the display settings for each block to "hide" the block on `/node/*/edit`.

By hiding all the links, the user will have to click "save" before being able to proceed to a different page.

However, this solution removes all the links from all node edit pages, which is a big tradeoff compared to what the question asks for (a way to redirect the user if they click a link-- this solution is just hiding all the links that can be clicked).

---
Tags: 8, redirection
---


# Question
Title: What is the 'System' display option in Views?
Could you tell me what the "System" display in views is? (shown in red)

I suppose it's a presentation which is only available programmatically, but I'm not 100% sure.

Thanks.

# Answer
> -2 votes
The Views System module extends the Views module and allows to create customized lists (pages, blocks) of modules, themes, and theme engines that are or have been installed in Drupal's file system

views system

# Answer
> 2 votes
Today I was in the same situation, so I decided to look and this is what I found:

> So, for anyone stumbling upon this, 'system' displays are only to override core views (which you do through the System Path Settings area in the Advanced section of views) and I should just be using a page display with a path that begins with '/admin/' if I want to make custom admin views.

Here is the link: https://www.drupal.org/node/2539256#comment-10150524

# Answer
> -1 votes
> The answer is that this is a style exposed by the Commerce Backoffice module. It's a heavily-modified version of the "Page" display style option, with the ability to replace existing menu paths with views.

Source: https://www.redbottledesign.com/blog/whats-drupal-views-system-display-style

And indeed when looking in the commerce backoffice module repository we can see the display plugin defined here: http://cgit.drupalcode.org/commerce\_backoffice/tree/includes/views/plugins/commerce\_backoffice\_content\_plugin\_display\_system.inc

---
Tags: views
---


# Question
Title: Indexing image url in search api drupal 8
How to index the absolute image url instead of image uri in search api drupal 8.

Image field formatter renders the image url but there is no option to index the url part.

# Answer
> 2 votes
It looks like that should be available as a field.

If your field name is "field\_image", you would select "field\_image:entity:uri". I think that would give you "public://path-to-file-in-public-directory.jpg"

You could add a custom field to your index in a custom module at src/Plugin/search\_api/processor:

In this way, you can add any sort of custom value that's not available by default in the fields provided.

---
Tags: 8, media, uri, search
---


# Question
Title: How do I create a simple checkbox in a content entity?
I just want a boolean checkbox with a label beside it. How do I do it?

# Answer
> 4 votes
Use type `boolean_checkbox` and `display_label`:

```
$fields[$open] = BaseFieldDefinition::create('boolean')
    ->setLabel(t("My Checkbox Field"))
    ->setDisplayOptions('form', array(
      'type' => 'boolean_checkbox',
      'settings' => array(
        'display_label' => TRUE,
      ),
      'weight' => '0',
    ))
    ->setDisplayConfigurable('form', TRUE);

```

# Answer
> 2 votes
I found this worked. Not sure if it's the best approach though:

```
  $fields[$open] = BaseFieldDefinition::create('boolean')
    ->setLabel(t("My Checkbox Field"))
    ->setSetting('on_label', t("Label that actually shows up on the form"))
    ->setDisplayOptions('form', array(
      'type' => 'boolean',
      'weight' => '0',
    ))
    ->setDisplayConfigurable('form', TRUE);

```

# Answer
> 0 votes
D8 ... Add field \> select field type Boolean and give it a label \> save and continue \> Save settings again ... go to Manage Display and select the options icon to the right of the field you just added \> under Output form dropdown you will have many selections, i.e., On/Off, Yes/No, True/False, Enable/Disable, 1/0, etc. Then go to Manage form display, next to the filed you just added under Widget select Single on/off checkbox.

---
Tags: 8, entities
---


# Question
Title: How is a field's key (rather than value) obtained?
In Drupal 7, I have a page content type that has a field called **group** (so the machine name is **field\_group**). The field is a **List (integer)** field type.

This field might have allowed values as follows:

```
0|Description 1
1|Description 2
2|Description 3

```

If I want to see the *value* of this field for the current page, the following code correctly works:

```
echo render(field_view_field('node', $node, 'field_group'));

```

If the key were set to 1 for this page, the above code would display the value "Description 2."

However, is there a way to instead get the *key* (e.g., 0, 1, 2, etc.)?

# Answer
> 1 votes
You can change the display in your content type "Manage Display" and ask to have the key and not the label :) It's here : /admin/structure/types/manage/\[your type\]/display

Programmatically for a nude value as asked :

```
$items = field_get_items('node', $node, 'field_list');
$key = $items[0]['value'];

```

---
Tags: 7, theming, entities
---