# Question
Title: How do I make twig variables available in node.html.twig accessible in my html.html.twig?
I have a boolean field on my Content Type called 'field\_bootstrap'. I have some twig logic in my node.html.twig file that, if the field is set to true, includes Bootstrap via HTML inclusion.

What I need is the ability to use my {{ node.field\_bootstrap }} logic in the html.html.twig template, instead of the node-level template. This would allow me to reference Bootstrap's CDNs properly in my document's head, rather than its current position in the middle of body.

I assume I need to build a preprocess in mytheme.theme to make something like {{ custom\_twig\_variable }} available for use in html.html.twig but I'm a little lost on how to complete this :)

Thanks everyone!

# Answer
Kevin is right, creating a library and then attaching it is the better approach for this.

**theme-name.theme**

```
THEME_NAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->field_bootstrap->value) { // checks boolean is true
     $variables['#attached']['library'][] = 'theme-name/bootstrap-files';
  }
}

```

**theme-name.libraries.yml**

```
bootstrap-files:
  version: 1.x
  css:
    theme:
      css/boostrap.css: {}
  js:
    js/boostrap.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

```

and you'll have to put the bootstrap css and js files inside the /css and /js folders of your theme.

---

## Better Yet

Install Bootstrap Library module.

**theme-name.theme**

```
THEME_NAME_preprocess_node(&$variables) {
  if (\Drupal::moduleHandler()->moduleExists('bootstrap_library')) {
    $node = $variables['node'];
    if ($node->field_bootstrap->value) { // checks boolean is true
       $variables['#attached']['library'][] = 'bootstrap_library/bootstrap-cdn';
    }
  }
}

```
> 3 votes

---
Tags: 8, theming, entities
---


# Question
Title: How to display webform results under the webform with contextual filters?
I created a view listing webform fields New View » Webform Submissions » Unformatted list of Rendered submissions

It gives me all the submitted data of all the webforms of the website.

I'm looking for a way to have under each webform its results.

So when i visit : `website.com/webform/id678`
under the form, i would like to have a block showing the previously submitted data i'll be using a pager to only display the 5 latest submissions and be able to browse through submissions if i want to.

This is possible with the contextual filter of Views but i can't seem to figure out how to configure it correctly

thanks

I'm using Drupal 7.56 and webform 4.16

# Answer
> 1 votes
## 1. create a `views block display` of your view

configure the view as you wish but you have to add contextual filter by `content:nid` as shown below with setting: `raw value from URL, path compoment 2`

We have to specify validation criteria `content: webform` as shown below

## 2. add the views block in a block region

Now if you visit a webform will show under it the relevant submissions

---
Tags: 7
---


# Question
Title: Notice: Undefined index: #ajax in ajax_form_callback() (line 395
Drupal 7.54

Content type with 30 fields and every time a click add more field values nothing happens. I get this in my log file -

Notice: Undefined index: #ajax in ajax\_form\_callback() (line 395 of /home/yourcare/public\_html/includes/ajax.inc).

It is driving me nuts it all use to work just fine! Please help.

# Answer
Got the same error with "Add another item" button on a taxonomy field with unlimited values recently:

```
Notice: Undefined index: #ajax in ajax_form_callback() (line 395 of /www/includes/ajax.inc)

```

Found out that it's an issue with jQuery Update module. Relevant discussion: https://www.drupal.org/node/2860158

The lastest version of jQuery Update 7.x-3.x-dev fixed the issue for me.
> 0 votes

# Answer
Go into your php.ini and set max\_input\_vars = something high.
> 0 votes

---
Tags: nodes, ajax
---


# Question
Title: Add custom class to views row depending on field value
I'm using views to show different fields of an entity. If the uid of the entity is the current user I would like to add a custom class to the entire row (not only to the field).

I wrote the following preprocess function that works fine if I use the entity in views, but I don't know how to change it when I use fields instead:

```
function my_module_preprocess_views_view_unformatted(&$variables) {

  $view = $variables['view'];

  if ($view->id() == 'my_view' && $view->current_display == 'page_1') {

    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {

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

      $owner = $row['content']['uid']['#object']->get('uid')->getString();

      $class = ($uid == $owner) ? 'own' : 'other';

      $custom_row_class = 'views-row-' . $class;
      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }

  }
}

```

# Answer
> 9 votes
Can you please try the following code snippet. I swapped the line to retrieve the author's user ID.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_views_view_unformatted(&$variables) {

  $view = $variables['view'];
  if ($view->id() == 'MY_VIEW' && $view->current_display == 'MY_DISPLAY') {

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

    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {

      // Get user ID.
      $owner = $row['content']['#row']->_entity->get('uid')->target_id;

      $class = ($uid == $owner) ? 'own' : 'other';
      $custom_row_class = 'views-row-' . $class;

      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }
  }
}

```

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


# Question
Title: How to get translated field using Twig tweak?
I use twig tweak for rendering username on site this way:

username.html.twig:

```
{#
/**
 * @file
 * Theme override for displaying a username.
 *
 * Available variables:
 * - account: The full account information for the user.
 * - uid: The user ID, or zero if not a user. As used in anonymous comments.
 * - name: The user's name, sanitized, and optionally truncated.
 * - name_raw: The user's name, un-truncated.
 * - truncated: Whether the user's name was truncated.
 * - extra: Additional text to append to the user's name, sanitized.
 * - profile_access: Whether the current user has permission to access this
     users profile page.
 * - link_path: The path or URL of the user's profile page, home page,
 *   or other desired page to link to for more information about the user.
 * - homepage: (optional) The home page of the account, only set for non users.
 * - link_options: Options to set on the \Drupal\Core\Url object if linking the
 *   user's name to the user's page.
 * - attributes: HTML attributes for the containing element.
 *
 * @see template_preprocess_username()
 */
#}
{% if link_path -%}
  <a{{ attributes }}>{{ drupal_field('field_name', 'user', uid) }}{{ extra }}</a>
{%- else -%}
  <span{{ attributes }}>{{ drupal_field('field_name', 'user', uid) }}{{ extra }}</span>
{%- endif -%}

```

But this doesn't work with translation. How to get translated field?

4k4 answer this way:

```
{{ drupal_field('field_name', 'user', uid, user.langcode.value) }}

```

But I don't need language from session/url, not from user settings

# Answer
> 1 votes
Try the language parameter:

```
{{ drupal_field('field_name', 'user', uid, user.langcode.value) }}

```

This was added to drupal\_field() in this issue Support drupal\_field translatability.

For this to work the `user` entity needs to be available in your template.

# Answer
> 0 votes
tried with: `{{ drupal_field('field_name', 'user', uid) | transliterate }}` ?

---
Tags: 8, theming
---


# Question
Title: How to use the same URL alias for all translations of a node?
I want to use the same URL alias for all nodes regardless of language.

On my site, the primary language is English. Translation is enabled for nodes of type **basic page**.

At `/admin/config/regional/content-language`, content translation is enabled for the **Title** and **Body** fields.

With this configuration, on the node edit page, it shows "URL alias (all languages"). I set a URL alias manually for each English node.

However, when I add a translation in another language, even though I see my alias on the translation edit page, this alias is not applied for that language. In other words, if the alias is *myfolder/mypage* in English, if I go to the Japanese translation at `/ja/myfolder/mypage`, I get a "page not found" error. Instead, the page is available at `/node/5` or whatever the NID is. But, on the "edit node" page for the Japanese translation, it does show the English alias with the text "all languages."

**Workaround**

I can go to `/admin/config/regional/content-language` and enable translation of **URL alias** and then manually set each additional language alias to the English alias, but this seems like a lot of extra work to keep the same alias.

# Answer
As pointed out by @Rockabelly, this is a bug with Drupal core. For now, there is a patch to fix the issue.
> 1 votes

# Answer
The Neutral Paths module should work in this situation. From the project page:

> A module for multi-language web sites, allowing users to access content in languages other than the current one by using path aliases.
> -1 votes

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


# Question
Title: Adding markup inside first list item of main-menu
I need to add some custom markup inside the first list-item of the main-menu as you can see here:

```
<div id="block-system-main-menu">
    <div class="block-inner clearfix">
        <div class="content clearfix">
            <ul class="menu">
                <li class="first leaf"><a href="/de/t1">Item 1</a>
                    <div class="my-custom-markup>
                        …
                        …
                    </div>
                </li>
                <li class="leaf"><a href="/de/t2">Item 2</a></li>
                <li class="last leaf"><a href="/de/t3">Item 2</a></li>
            </ul>
        </div>
    </div>
</div>

```

With the following code, I can insert the markup:

```
function mytheme_preprocess_menu_link(&$variables) {
  $variables['element']['#below']['#markup'] = ' <div class="my-custom-markup">...</div>';
}

```

But this code adds the markup to every list-item, not just the first one. Do I use the appropriate function and how can I add the markup only at the first item of main menu?

# Answer
> 0 votes
I managed to apply the code only to the item in the main-menu by introducing a condition of menu-name and #href:

```
function mymodule_preprocess_menu_link(&$vars) {
  $element = &$vars['element'];
  $my_view = views_embed_view('view_name', 'display_id');
  if(strpos($element['#href'], 'home') !== false && $element['#original_link']['menu_name'] == 'main-menu')
  {
    $element['#below']['#markup'] = $my_view;
  }
}

```

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


# Question
Title: How to check in a Rules Condition if an Ubercart product is out of order?
There isn't a good support for "out of order" in Ubercart for Drupal. I'm trying to fix that with the Rules module.

I'm trying to add a rule that disables the product after the stock is updated, using Rules event *After updating existing content of type Product*. I want to disable the product that is sold out (stock = 0).

Here is an export of the rule I have so far:

```
{ "rules_product_sold_out_check" : {
    "LABEL" : "Product sold out check",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update--product" : { "bundle" : "product" } },
    "DO" : []
  }
}

```

But the stock isn't a field of the node. How can I select that field within a Rules Condition? I have no idea how to use that in the Rules module as a data selector.

> The data to be compared, specified by using a data selector, e.g. "node:author:name".

I'm using the stock also in a view. This is what I use there (export-code-view to show the fieldnames / structure).

```
$handler->display->display_options['fields']['stock']['id'] = 'stock';
$handler->display->display_options['fields']['stock']['table'] = 'uc_product_stock';
$handler->display->display_options['fields']['stock']['field'] = 'stock';

```

I use **Ubercart 7.x-3.10** (with Stock 7.x-3.10), **Drupal 7**, **Rules 7.x-2.10**

# Answer
As per the UC issue about "Stock transaction should be more flexible through Rules" (from 6 years ago, status "needs work" ...), it seems that at this time trying to use the Rules module for such "out of order" situations may not be a good idea.

You may want to try to use the Ubercart Out of stock Notification module instead. Some details about it (from its project page):

> Out of stock notification for Ubercart.
>
> It uses ajax and jquery and asks the server for available stock and replaces the 'Add to cart' button with some configurable HTML.
>
> ...
>
> It also provides server-side validation so this module can prevent the addition of out of stock items even if JS is disabled or if the user clicks on an "Add to cart" button too quickly.
> 0 votes

---
Tags: 7, rules, ubercart
---


title: page not rendered from module

text:
# Question
Title: page not rendered from module
i would show a page not themed by drupal from a specific path from my custom module.

I'm using drupal7.

Here is the example module:

file: custom\_example.module

```
<?php
/*
 * Implementation of hook_menu()
 */
function custom_example_menu(){
  $items['foo/bar'] = array(
    'title' => 'Page Title',
    'description' => 'Simple custom hook_menu() implementation.',
    'page callback' => 'my_page_function',
    'access arguments' => array('access content'),
  );
  return $items;
}

/*
 * Returns custom content to Drupal
 */
function my_page_function(){
   return theme('my_custom_template');
}

/*
 * Implementation of hook_theme().
 */
function custom_example_theme(){
  return array(
    'my_custom_template' => array(
      'template' => 'custom-page',
    ),
  );
}

```

file:custom-page.tpl.php

```
<html>
<body>
<p>hello</p>
</body>
</html>

```

This works fine to show the page at mysite.com/foo/bar link but the page is themed with all drupal stuffs (header footer sidebar) that i don't want.

Thanks all

# Answer
> 0 votes
You would need to do something like this in your my\_page\_function

```
$output = '<html>
<body>
<p>hello</p>
</body>
</html>';

print $output;
die;

```

So don't return anything. It's not great and avoids everything drupal related really but it sounds like what you want to do. As using anything to do with drupal's theme functions will always be wrapped in the site of the site content

---
Tags: 7
---


# Question
Title: Javascript file in theme does not get loaded
I just added a script `scroll.js`, but it does not get loaded.

My theme is called `test`. I put the script in the `js` directory within the theme directory.

Permissions on the script are `644` (like on all other scripts in other themes) and permissions on the js directory are `755`.

I added a line `scripts[]= js/scroll.js` to `test.info`.

Sorry for forgetting to mention the version of Drupal. I'm using Drupal 7. I flushed all caches and did a hard refresh in the browser (tried both Firefox and Chromium).

After it looking like nothing was being loaded, I added a line `window.alert("sometext");` to the script just to be sure. Still nothing.

In Firefox and Chrome the file is neither listed as being loaded nor as failing to load or permissions error.

It seems to me that the change to the `.info` file is being ignored, but I might well be wrong. How do I force Drupal to not ignore the new script file?

# Answer
In drupal 8 my theme uses the file main.js. If my theme was called test I would add the file in this order.

File location:

```
test/js/main.js

```

In test.info.yml:

```
libraries:
  - test/global-js
  - test/global-css

```

In libraries.yml:

```
global-js:
  js:
    js/main.js: {}
global-css:
  css:
    theme:
      css/styles.css: {}

```

Remember your spacing in the .yml files (2 spaces).
also read adding stylesheets and javascript to a drupal 8 theme and
Creating a drupal 8 sub-theme, or sub-theme of sub-theme

Happy Drupaling
> 0 votes

---
Tags: 7, theming, javascript
---


title: How to run PHPUnit tests?

text:
# Question
Title: How to run PHPUnit tests?
Drupal 8 is supplementing the testing framework based on Simpletest with PHPUnit, and Simpletest could be removed in Drupal 9.

I'm not upgrading yet to Drupal 8, but I was wondering how I can write existing tests in PHPUnit (to follow-up with the trend) for Drupal 7, instead in Simpletest?

Is there any method or module for integrating PHPUnit with Drupal 7?

There are few like phpunit or drunit, but they're not for Drupal 7.

# Answer
You can get PHPUnit tests to run by bootstrapping Drupal within each of your test files. It's not ideal, but it does work.

```
define('DRUPAL_ROOT', 'your/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';

// Bootstrap Drupal.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Proceed with PHPUnit tests as usual from here.
class MyTest extends \PHPUnit_Framework_TestCase {
  ...

```
> 11 votes

# Answer
PHPUnit provides a nice API for building the objects whereas the Drupal's simpletest doesn't. There is one library available in gist for integrating PHPUnit with Drupal 7.
To execute those scripts you need to checkout this gist-repository. To execute Unit-Tests in the command-line simply go to a Drupal site (ie. `<DRUPAL_ROOT>/sites/default`) and use **dphpunit.bash** just as you would use the phpunit command.

The script consists of 3 files:

1. **dphpunit.bash** \- which simply invokes drun-dphpunit.php with a few extra parameters. It's needed because PHP is incapable of dealing with symlinks correctly.
2. **drun-dphpunit.php** \- which is basically the same as the upstream phpunit runner, except that it handles the extra parameter.
3. **bootstrap.inc.php** \- which makes a Drupal bootstrap very similar to drush.

Source: http://devblog.more-onion.com/content/writing-unit-tests-drupal-7

---

### `bootstrap.inc.php`

```
<?php

$path = CWD;

$site_dir = NULL;
$dpl_dir = NULL;

while ($path != '/') {
    if (file_exists($path . '/settings.php')) {
        $site_dir = $path;
    }
    if (file_exists($path . '/index.php') && file_exists($path . '/includes/bootstrap.inc')) {
        $dpl_dir = $path;
        break;
    }
    $path = dirname($path);
}

if (!$dpl_dir) {
    echo "No drupal directory found in or above current working directory. Aborting. \n";
    exit(1);
}
if (!$site_dir) {
    $site_dir = $dpl_dir . '/sites/default';
    if (!file_exists($site_dir . '/settings.php')) {
        echo "No configured site found. Aborting.\n";
        exit(1);
    }
}

$_SERVER['HTTP_HOST'] = basename($site_dir);
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';

define('DRUPAL_ROOT', $dpl_dir);
set_include_path($dpl_dir . PATH_SEPARATOR . get_include_path());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

### `dphpunit.bash`

```
#!/bin/bash

# get dirname of the script
DIR="$(dirname $(readlink "$0"))"

# assume the boostrap script is stored in the same directory
php "$DIR/drun-phpunit.php" "$(pwd)" --bootstrap "$DIR/bootstrap.inc.php" "$@"

```

### `drun-phpunit.php`

```
<?php
require_once 'PHP/CodeCoverage/Filter.php';
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'PHPUNIT');

if (extension_loaded('xdebug')) {
  xdebug_disable();
}

if (strpos('/usr/bin/php', '@php_bin') === 0) {
  set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());
}

require_once 'PHPUnit/Autoload.php';
define('PHPUnit_MAIN_METHOD', 'PHPUnit_TextUI_Command::main');
define('CWD', $_SERVER['argv'][1]);
unset($_SERVER['argv'][1]);

$command = new PHPUnit_TextUI_Command;
$command->run($_SERVER['argv']);

```

---

There is one more library available for integration PHPUnit with Drupal 7: https://github.com/sebastianbergmann/phpunit

More information about this scripts can be checked here: http://thomaslattimore.com/blog/using-phpunit-with-drupal-7
> 3 votes

# Answer
# There is workaround with configuration file.

1. Create **phpunit.xml.dist** file in your drupal project root. Got to contain this

> ```
> <?xml version="1.0" encoding="UTF-8"?>
> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>          xsi:noNamespaceSchemaLocation="phpunit.xsd"
>          bootstrap="drupal_phpunit_bootstrap.php"
>          verbose="true">
>
> </phpunit>
>
> ```

2. Phpunit has to bootstrap our drupal instance. Create drupal phpunit bootstrap file. I prefer to name it **drupal\_phpunit\_bootstrap.php**

> ```
> <?php
>
> $_SERVER['HTTP_HOST'] = 'your.url';
> $_SERVER['SCRIPT_NAME'] = '/index.php';
> $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
> $_SERVER['REQUEST_METHOD'] = 'GET';
> $_SERVER['SERVER_NAME'] = NULL;
> $_SERVER['SERVER_SOFTWARE'] = NULL;
> $_SERVER['HTTP_USER_AGENT'] = NULL;
> // Fix for behat drupal instantiation.
> define('DRUPAL_ROOT', dirname(realpath(__FILE__)));
> require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
> drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
>
> ```

Gist: https://gist.github.com/permanovd/cb9c02920c49a29c97653f4f697147b1

**Thats all. Now you can start your tests in several ways.**

### 1. CLI

phpunit -c phpunit.xml.dist QuestionValidationValueOptionsInputTest /yoursite.dir/public\_html/profiles/standard/modules/some\_module/tests/QuestionValidationTest.php

where:

* **-c**: Defines configuration file.
* **QuestionValidationValueOptionsInputTest and path**: Defines test class name and path to it.

### 2. IDE (phpstorm)

You have to add test running configuration

And no need to include drupal bootstrap code into every test.

## Note

You may have problems with tests because of wrong php version of your environment.

## Further reading:

https://phpunit.de/manual/current/en/organizing-tests.html
> 1 votes

---
Tags: 7, testing
---


# Question
Title: Custom field type: make only one specific property translateable
Is it possible to mark only a single property of a field as translateable?

E.g. I have a custom field type `RoomRates` with 2 properties `uri` and `price_mode`.

```
/**
 * Plugin implementation of the 'kognitiv_room_rate' field type.
 *
 * @FieldType(
 *   id = "kognitiv_room_rate",
 *   label = @Translation("Kognitiv room rate"),
 *   description = @Translation("Stores an URL to retrieve price and availability data for a room"),
 *   default_widget = "kognitiv_room_rate",
 *   default_formatter = "kognitiv_room_rate",
 *   cardinality = 1,
 *   column_groups = {
 *     "uri" = {
 *       "label" = @Translation("URI"),
 *       "translatable" = TRUE
 *     },
 *     "price_mode" = {
 *       "label" = @Translation("Show prices as")
 *     }
 *   }
 * )
 */
class RoomRate extends FieldItemBase implements LinkItemInterface {

  const PRICE_MODE_PERSON = 'PERSON';
  const PRICE_MODE_DAY = 'DAY';

  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['uri'] = DataDefinition::create('uri')
      ->setLabel(t('URI'))
      ->setRequired(TRUE);

    $properties['price_mode'] = DataDefinition::create('string')
      ->setLabel(t('Show prices as'))
      ->setRequired(TRUE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'uri' => [
          'description' => 'The URI of the JSON API endpoint.',
          'type' => 'varchar',
          'length' => 2048,
        ],
        'price_mode' => [
          'description' => 'Show prices as price per day or price per person in std occupancy',
          'type' => 'varchar',
          'length' => 10,
        ],
      ],
      'indexes' => [],
      'foreign keys' => [],
    ];
  }

```

The `uri` property should be translateable (if the site builder enables translation for this field), while the `price_mode` property should never be translateable/always be the same accross all languages (no matter if the site builder enabled field translation or not).

# Answer
content\_translation has a feature that synchronizes certain property between translations, see how the \Drupal\image\Plugin\Field\FieldType\ImageItem field type uses that:

```
 *   column_groups = {
 *     "file" = {
 *       "label" = @Translation("File"),
 *       "columns" = {
 *         "target_id", "width", "height"
 *       },
 *       "require_all_groups_for_translation" = TRUE
 *     },
 *     "alt" = {
 *       "label" = @Translation("Alt"),
 *       "translatable" = TRUE
 *     },
 *     "title" = {
 *       "label" = @Translation("Title"),
 *       "translatable" = TRUE
 *     },
 *   },

```

By not setting translatable = TRUE, the UI by default suggests to keep that value across translations, although it can be configured differently.
> 2 votes

---
Tags: 8
---


# Question
Title: Do not show errors including database error to users in D7
I have disabled displaying errors to the user in my D7 website. See below the screenshot of the configuration-

However, I (without admin login) still see a database related error such as following-

How do I disable the above error display to a normal user (but making sure admin can see)? It would be better if these errors can be logged but not displayed to a normal user. By saying a normal user, I am referring to all non-logged users.

# Answer
> 1 votes
You should be able to add the following to your settings.php to hide all errors (It will mean the admin screen you mentioned will no longer be used so any changes to this setting will need to be done via settings.php

```
$conf['error_level'] = ERROR_REPORTING_HIDE;

```

---
Tags: 7, log-messages
---


# Question
Title: How can I get the email address of a user who has just registered?
I need to add a hash key to users on register, generated from their email address and the current time, I added the field 'field\_subscription\_key' to user's fields and I hooked into

> custom\_newsletter\_mail\_user\_insert(&$edit, $account, $category)

in module's .module file, I have no idea how can I get the email address and time the user was created from these above parameters.

Also, I don't know how to get the user entity, so I would insert the hash key.

# Answer
The docs on the core entities are really good. Here are the docs on the User class.

You should be able to get the email with:

```
$email = $account->getEmail();

```

And the created time with:

```
$created = $account->getCreatedTime();

```
> 2 votes

---
Tags: 8
---


# Question
Title: How to check in Rules if a text field has changed?
Not sure why this condition is ALWAYS evaluating to true. Trying to check to see if the value in a long text field has been changed.

The first field in the condition node-unchanged:field-security-audit (field type is Long Text) is always evaluating as true. The second field node-unchanged:field-security-audit-status-pubf (field type is term reference)is evaluating properly.

Any help would be greatly appreciated.

Here is the rule export:

```
{ "rules_security_audit_status_updated" : {
"LABEL" : "Security Audit Status Updated",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "security" ],
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--api_publishing_form" : { "bundle" : "api_publishing_form" } },
"IF" : [
  { "OR" : [
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-security-audit" ],
          "value" : "node:field-sucurity-audit"
        }
      },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-security-audit-status-pubf" ],
          "value" : [ "node:field-security-audit-status-pubf" ]
        }
      }
    ]
  }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-security-audit-timestamp" ],
      "value" : [ "site:current-date" ]
    }
  },
  { "mail" : { //send mail
    }
  }
 ]
}
}

```

# Answer
> 1 votes
First things first: your `node:field-sucurity-audit` token *might* contain a typo ... It could well be that you intended to use `node:field-security-audit` instead (see the difference?). If that is not the solution (yet), just keep reading ...

Also make sure to *always* (repeat: *always*) add an `Entity has field` condition BEFORE any other Rules Conditions in which you might want to refer to some field. So in your case you should add 2 such extra Rules Conditions (since you're checking the value of 2 different fields). That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says:

> *The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*.

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

PS: I'm assuming this is about D7 ...

---
Tags: rules
---


# Question
Title: Creating redirects for files (images) on Pantheon
What is the best way to create 301 redirects on Pantheon for file? I can create redirects for paths by placing rules in my settings.php:

```
switch ($_SERVER['REQUEST_URI']) {
  case '/my-path':
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: http://mydoamin/my-new-path');
   exit();
}

```

This is the redirect I want to create:

`a/b/c/document.pdf` and `e/f/g/document2.pdf`both should be redirected to `/new/folder/document3.pdf`.

Unfortunately, this won't work with files.

Here is how I test:

1. Create file `test.txt` in sites/default/files
2. Access sites/default/files/test.txt and verify it works
3. Update settings.php and add `die($_SERVER['REQUEST_URI']);` and verify you the get uri.

Instead of getting URI I get 404.

# Answer
Thanks to Sarah at Pantheon for walking me through this.

File redirects aren't really possible using the same logic used to do PHP redirects for URLs. Requests to files are managed by the server and don't run through settings.php (Drupal) or wp-config.php (WP). It is not possible to intercept those like a URL served by the application.

If you were running your own nginx server you could manage this in a .conf file, but on Pantheon the nginx.conf isn't editable on a per-site basis since it's set platform-wide (https://pantheon.io/docs/platform-considerations/#nginxconf)

A workaround could be to utilize a third-party CDN like Cloudflare to create nginx-like redirects before you hit the server.
> 1 votes

---
Tags: redirection
---


# Question
Title: Custom breadcrumbs from a breadcrumb builder disappear until I clear Varnish cache
Unrelated to this question, which is about how to properly inject breadcrumbs as a renderable item into a node template.. I have a custom breadcrumb builder for certain node types with the same sort of cache clearing issue.

After I deploy code to production, and clear the Drupal cache, about 50% of the time anonymous users stop seeing breadcrumbs on these 3 node types. I find that I have to clear cache again, then clear the Varnish cache on the server, and then they appear again for anonymous users. Am I missing something in the build method?

```
<?php

declare(strict_types = 1);

namespace Drupal\harlib_breadcrumbs;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Routing\AdminContext;
use Drupal\node\NodeInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;

/**
 * Class ContentTypeBasedBreadcrumbBuilder.
 *
 * @package Drupal\harlib_breadcrumbs
 */
class ContentTypeBasedBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * The AdminContext service.
   *
   * @var \Drupal\Core\Routing\AdminContext
   */
  protected $adminContext;

  /**
   * The AliasManager service.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * The EntityTypeManager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    AdminContext $admin_context,
    AliasManagerInterface $alias_manager,
    EntityTypeManagerInterface $entity_type_manager
  ) {
    $this->adminContext = $admin_context;
    $this->aliasManager = $alias_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) : bool {
    if (!$this->adminContext->isAdminRoute()) {
      $parameters = $route_match->getParameters()->all();

      if (isset($parameters['node']) && $parameters['node'] instanceof NodeInterface) {
        $types = ['story', 'press_release', 'news_mention'];
        $type = $parameters['node']->getType();
        return in_array($type, $types);
      }
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) : Breadcrumb {
    $node = $route_match->getParameter('node');
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    if ($url = $this->getNodeUrlByAlias('/about')) {
      $breadcrumb->addLink(Link::fromTextAndUrl($this->t('About'), $url));
    }

    if ($url = $this->getNodeUrlByAlias('/about/news')) {
      $breadcrumb->addLink(Link::fromTextAndUrl($this->t('News'), $url));
    }

    $breadcrumb->addCacheContexts(['url.path']);
    $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);
    return $breadcrumb;
  }

  /**
   * Create a Url object if the alias matches a node object path.
   *
   * @param string $alias
   *   The node alias.
   *
   * @return bool|\Drupal\Core\Url
   *   A Url object, or FALSE if no result found.
   */
  protected function getNodeUrlByAlias(string $alias) {
    $path = $this->aliasManager->getPathByAlias($alias);

    if (preg_match('/node\/(\d+)/', $path, $matches)) {
      $id = $matches[1];
      return Url::fromRoute('entity.node.canonical', ['node' => $id]);
    }

    return FALSE;
  }

}

```

# Answer
Pretty sure I found the root cause. I found some errant code here in the `else` condition.

```
/**
 * Implements hook_preprocess_block().
 */
function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'system_breadcrumb_block') {
    if (...) {
      $variables['attributes']['class'][] = 'hl__breadcrumb--light';
    }
    else {
      if (!empty($variables['content']['#links'])) {
        if (count($variables['content']['#links']) == 1) {
          $variables['content'] = [];
          $variables['elements']['content'] = $variables['content'];
        }
      }
    }
  }
}

```

Deleting the entire `else` block seems to have corrected the issue, unable to replicate it now.
> 0 votes

---
Tags: 8, caching, breadcrumbs
---


# Question
Title: Drupal won't load properly named custom twig template
I am currently trying to override views default grid template for a front page block view but drupal seems to be refusing to use it. I followed twig's debug suggested name, cleared the cache, etc...

I tried several suggestions, at the moment my template's name is "views-view-grid--events-front--block.html.twig" I am kinda lost, hopefully one of you guys will know what the hell is going on!

# Answer
> 0 votes
Are you relying on the patch from https://www.drupal.org/project/drupal/issues/2923634?

That patch is unfinished and might result in that. The length of the suggestion is not relevant, the first in the list matches, and as @Kevin said, the first entry is the same as the last.

You do not need that core patch, views template suggestions work fine in HEAD, they're just not shown in twig debug mode.

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


# Question
Title: How can I pass variables from a view template to a node template?
I have a view showing the nodes of a content type which has reference entity fields to another content type.

I am trying to iterate through this view with templates.

If I choose to show nodes for my format, I can easily access the referenced entities and its fields, but I cannot track in which row.content I am.
If I switch to show fields, I can use the global view results count and I have an effective counter. However, I cannot access the referenced entities to get the values of the fields.

So far I have not found anything that actually addresses this particular problem. I am using the *views-view-unformatted* template which in turn calls the *node--view* template. I am unable to "pass" along the row index from the unformatted views template to node view template.

I already know that this is doable when using fields, but fields is out of the question because of the inability to access referenced entities.

These are possible solutions to this issue:

* Show content and somehow track the row.content index between twig templates
* Show fields to be able to actually access the fields of referenced entities

Does anyone have any suggestion?

# Answer
> 0 votes
Ok, so I finally solved my problem. I went with 'solution #1' in the original question. I created a single view showing content with unformatted list format and then triplicated that. Here's the template set up I followed:

```
page.html.twig
views-view--page.html.twig
views-view-unformatted.html.twig
node--view.html.twig

```

`page--page-url.html.twig` contained the main html layout template. Within this page, I used twig\_tweak's `drupal_view('viewname', 'viewmode', parameter)` where I wanted the specially formatted view to appear. I had three different view formats. So, in page--page-url.html.twig, it looked something like this:

```
drupal_view('beta', 'page_1', parameter) << node--view--beta--page_1.html.twig
<html code>
drupal_view('beta', 'page_2', parameter) << node--view--beta--page_2.html.twig
<more html code>
drupal_view('beta', 'page_3', parameter) << node--view--beta--page_3.html.twig
<rest of html code>

```

The `node--view--beta--page_1.html.twig` is where the view html was formatted per row.

To handle the row\_index, I used the preprocess function to find it for me. In Drupal 8, row\_index is not available in the view itself (it should be, but it is null). So, each time node--view is called, the corresponding preprocessor is executed and it iterates through the view nodes to find the matching nid and hence, the row index:

```
function theme_name_preprocess_node__view__beta(&$vars) {
    $view = $vars['view'];
    $node = $vars['node'];
    foreach($view->result as $key => $row){
        if($row->nid == $node->id()){
            $vars['row_index'] = $row->index;
        }
    }
}

```

In the html.twig, I simply used `{{ row_index }}` where needed.

Hope this helps anyone else in similar situation.

# Answer
> -1 votes
Possibly use **devel** and **kint** modules.

Once both modules are enabled add `{{ kint(fields) }}` or `{{ kint(content) }}` to see what your options are for displaying your view's data. If the view wrks successfully then you should be able to display it using twig e.g. if you find field\_name in kint and it output's the correct data then add `<p>{{ fields.field_name }}</p>` to your template

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


# Question
Title: How can I pass the loop.index from a view template to a node template?
In a views template (views-view-unformatted.twig.html), I have

```
{% for row in rows %}
    {% set row_index = loop.index0 %}
    {{ row.content }}
{% endfor %}

```

where each row is processed in a `node--view.twig.html`. How can I pass in `row_index` to the `node--view.twig.html`? This is used simply to create an index.

# Answer
This can be done using the preprocess function in `my_theme.theme`. In the case above, the row was formatted in `node--view--pagename.html.twig`, so the preprocessor function name is `mytheme_preprocess_node__view__pagename`. In the function, the view is iterated until the node matches the current node that is being processed, at that point, the row\_index is determined and set and accessible in `node--view--pagename.html.twig` as `{{ row_index }}`.

```
function fu_preprocess_node__view__pagename(&$vars) {
    $view = $vars['view'];
    $node = $vars['node'];
    foreach($view->result as $key => $row){
        if($row->nid == $node->id()){
            $vars['row_index'] = $row->index;
        }
    }
}

```
> 2 votes

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


# Question
Title: How to add html signature to node(article)?
I want to add a specific html signature in the body of article if a condition is met otherwise it should not be displayed. the specific html is:

```
<div style="width: 165px; height: 50px; background-color: white; font-family: Roboto; font-size: 12px; border: 1px solid #CDCDCD; border-radius: 4px; box-shadow: 0 2px 0 0 #F0F0F0;">
    <div style="color: #35393E; text-decoration: none; display: flex; flex-direction: row;  height: 50px">
        <img src="/media/plg_content_poet/quill.svg"
             style=" width: 31px; height: 31px; margin-top: 8px; margin-left: 8px; margin-right: 8px; color: #35393E; font-family: Roboto;">
        <div>
            <p title="<?php echo $workId; ?>" style="padding-top: 10px; line-height: 15px; margin: 0; font-size: 10pt; font-weight: bold; text-align: left;"></p>
        </div>
    </div>
</div>

```

I want to make it part of the node body. I am new to drupal and I want to know how to achieve this. I have read about twig templates and views but I can't find any example of this kind of work.

The specific action should take place when a node is published that is why I am using `hook_node_insert()`

```
function poet_plugin_node_insert(Node $node){
    if($node->field_workid !=''){
        //adding html to node goes here
    }
}

```

# Answer
If you can't override the node template in the theme for whatever reason, you can just append another item to the content array and change the weight of elements until everything flows as you need.

`hook_ENTITY_TYPE_view` is as reasonable a place as any to make the change, something like this:

```
function MODULE_node_view(array &$build, \Drupal\node\Entity\Node $node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($node->field_workid->value != '') {
    $build['signature'] = [
      '#theme' => 'MODULE_signature',
      '#work_id' => $node->field_workid->value,
      '#weight' => 10,
    ];

    $build['body']['#weight'] = 9;
  }
}

function MODULE_theme() {
  return [
    'MODULE_signature' => [
      'variables' => ['work_id' => NULL],
    ],
  ];
}

```

And the template file at MODULE/templates/MODULE-signature.html.twig:

```
<div style="width: 165px; height: 50px; background-color: white; font-family: Roboto; font-size: 12px; border: 1px solid #CDCDCD; border-radius: 4px; box-shadow: 0 2px 0 0 #F0F0F0;">
    <div style="color: #35393E; text-decoration: none; display: flex; flex-direction: row;  height: 50px">
        <img src="/media/plg_content_poet/quill.svg"
             style=" width: 31px; height: 31px; margin-top: 8px; margin-left: 8px; margin-right: 8px; color: #35393E; font-family: Roboto;">
        <div>
            <p title="{{ work_id }}" style="padding-top: 10px; line-height: 15px; margin: 0; font-size: 10pt; font-weight: bold; text-align: left;"></p>
        </div>
    </div>
</div>

```
> 2 votes

# Answer
In Drupal 8, you can just add it to the twig template for that content type.

Copy `node.html.twig` in your active theme to `node--(node-type)--full.html.twig` and add something like this:

```
// code...
<div class="node-body">
  {{ content|without('field_workid') }}
  {% if node.field_workid.value %}
<div style="width: 165px; height: 50px; background-color: white; font-family: Roboto; font-size: 12px; border: 1px solid #CDCDCD; border-radius: 4px; box-shadow: 0 2px 0 0 #F0F0F0;">
    <div style="color: #35393E; text-decoration: none; display: flex; flex-direction: row;  height: 50px">
        <img src="/media/plg_content_poet/quill.svg"
             style=" width: 31px; height: 31px; margin-top: 8px; margin-left: 8px; margin-right: 8px; color: #35393E; font-family: Roboto;">
        <div>
            <p title="{{ content.field_workid }}" style="padding-top: 10px; line-height: 15px; margin: 0; font-size: 10pt; font-weight: bold; text-align: left;"></p>
        </div>
    </div>
</div>
  {% endif %}
</div>
// code...

```

I would also create a `field--field-workid.html.twig` template too and nullify any field markup so its just the field value:

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

The line in the template, `{{ content|without('field_workid') }}` renders all of the fields on that content type except for work id. You can also break it out and print each field individually in your template for more control:

```
{{ content.body }}
{% if node.field_workid.value %}
  // signature markup
{% endif %}

{{ content.field_some_other_fieldname }}

```
> 2 votes

---
Tags: 8, nodes
---


# Question
Title: Problem with using ksm($entity) in hook_entity_insert()
As the title states, I've encountered a weird problem with hook\_entity\_insert():

```
Array ( [:db_update_placeholder_0] => 1 [:db_update_placeholder_1] => 127.0.0.1 [:db_update_placeholder_2] =>

```

I get a error screen, and this is what's displayed when I attempt to use ksm($entity).

I also checked the logs:

```
Warning: Error while sending QUERY packet. PID=18801 in Drupal\Core\Database\Statement->execute()....

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: CREATE TABLE {cache_config}....

```

This is troubling, as the custom module I'm developing heavily relies on nodes.

I thought maybe this was an issue with the DB, and so I used a new one, but the problem persist. I'll be attempting to create a new Drupal project using the same modules.

Therefore I'm asking if anyone else have encountered anything similar to this and found a solution?

# Answer
> 3 votes
Found another post that provides a solution to my problem: How to preserve kint output upon form submit redirection?

In my case, while

```
ksm($entity)

```

would display nothing, or show errors,

```
ksm($entity->toArray())

```

seems to display correctly.

I'm a bit baffled myself why this happens, and will continue to investigate.

---
Tags: 8, nodes, hooks
---


# Question
Title: Accessing a selected value instead of key in drupal 8
I need to access values instead of keys from a custom form select field. To get the keys, I am using `$form_state->getValue()` but I don't know how to access the values. Kindly help.

# Answer
> 5 votes
Assuming that code is in a submit/validate method, you have the original form array available, so you can grab the options straight from the element definition:

```
$key = $form_state->getValue('foo');
$val = $form['foo']['#options'][$key];

```

---
Tags: forms
---


# Question
Title: Get the select list current value not key
For example, There is a field with 3 options in allowed values, like option1, option2, option3.Is there any function which receive the field name and returns selected values not a keys ?

With this just return key of selected opinion

```
  print ($node->field_opinion['und'][0]['value'])

```

**Update :**

I have create select list field and with this field user can answer and select own value like this

```
1|Stars
2|Nights
3|Awesome
4|Days

```

With above code just return the keys field and i want to return values like "Stars"

# Answer
> 2 votes
Try this code:

```

$key = $node->field_opinion['und'][0]['value'];
$label = list_allowed_values(field_info_field('field_opinion'))[$key];

```

# Answer
> 1 votes
You need the `field_info_field()` and `list_allowed_values()` functions to get an array representation of the values you entered in the field's configuration.

The following:

```
$field_opinion_info = field_info_field('field_opinion');
$opinion_values= list_allowed_values($field_opinion_info);

```

should give you access to an array that looks like this stored in `$opinion_values`:

```
Array
(
    [1] => Stars
    [2] => Nights
    [3] => Awesome
    [4] => Days
)

```

And from that, you can get the needed value like this:

```
$selected_option = $node->field_opinion[LANGUAGE_NONE][0]['value'];
$selected_value = isset($opinion_values[$selected_option]) ?
  field_filter_xss($opinion_values[$selected_option]) :
 t('Not a valid option');

```

Note the use of `field_filter_xss()`; according to the documentation of `list_allowed_values()`:

> The strings are not safe for output. Keys and values of the array should be sanitized through field\_filter\_xss() before being displayed.

Hope this helps!

---
Tags: 7
---


# Question
Title: Facet API: grouping indexed values into several drop-down facets
I have an indexed field which contains values in such a form:

CPU: Intel Core i5 CPU: Intel Core i7 ... Memory: 4 GB Memory: 8 GB ... Video card type: Integrated Video card type: Nvidia ...

I would like to display these as several drop-down lists, e.g:

Title: CPU with values: Intel Core i5, Intel Core i7, ... Title: Memory with values: 4 GB, 8 GB, ... Title: Video card type with values: Integrated, Nvidia, ...

Any suggestions would be welcome on how to implement this. Thank you very much in advance.

Best regards, Laszlo

# Answer
If possible, I'd use a vocabulary for each of the facets ('dropdowns'). Add a term referenece field to your node for each of those as well. Then add these fields to your search index and add the facets for them.

E.g., Vocabulary: CPU

Terms: Core i5 Core i7 ...

Vocabulary: Memory

Terms: 4 GB 8 GB ..
> 0 votes

---
Tags: theming, search
---


# Question
Title: How to show a field in a view taken as input in a different content type?
I made a form Company Information, which contains standard fields like Name, Address, Rating etc.

Now I am taking Rating from a different content type "Company Reviews", under Rating Field.

What I want to display various fields from Company Information and Company Reviews in a single view. I tried using the machine name in twig but somehow the view is showing values from Company Information but not from Company Reviews.

Does this sound familiar? I am sure it can be done but I am missing out something. Any help or even a direction is much appreciated, thanks.

---

\[ UPDATE 1\]

So, I was researching this for a while and just after posting the question I stumbled upon "Entity Reference", but it seems that this is not available for drupal 8 can we do this in drupal 8 somehow https://www.ostraining.com/blog/drupal/entity-reference-views/

---

\[ UPDATE 2\] The entity reference was suppose to show up in Add Relation under Advance Tab

And I am getting a few fields, but not the ones I want. neither the view is showing following entity relation

instead, I am having this on my dashboard,

so I went ahead and added Review content filter anyway, as a result, the Listing View started showing the reviews as companies, which was not the desired result, using review title as company title.

Do I require a module or should something have be-be done at content types Company Profile and Review?

\[ UPDATE 3 \] The Answer is correct, Here is how did it, if anyone is interested.

It was rather simple,

Suppose you have Content-Type A, and Content-Type B, and a result View C

In Content Type A, you add a field, that is actually a Reference to Content-Type B, let's call it ref-AB. Similarly, Add add a field, that is actually a Reference to Content-Type A, say ref\_BA. Now fields of A & B Content-Type are related, and you can show them in the view.

To Show them in a view, you need to add "reference to the content" as a relation in view ( Go to view\> your-view \> advance \> add relation). Suppose, you added ref\_BA to your view, then all fields of content type B, will be available in your view.

In your view, add the field you want to show, making relation to ref\_BA.

# Answer
Entity Reference is now included in Drupal 8 core. To use it, simply add a field "Reference-Content" and you may use your Company Reviews content type. Then, following the tutorial from your link, you should be able to add any field from Company Reviews in a view showing content of type Company Information.
> 0 votes

---
Tags: views, nodes, entities
---


# Question
Title: Inserting in user's field on creating the user?
I need to add subscription key field to user as a hash of his email and time created so I did this in a custom module

```
function custom_newsletter_mail_entity_presave($entity, $type) {

    if($type == 'user') {
        if(empty($entity->get('field_subscription_key')->getValue()[0]['value'])) {
            $hash_input = $entity->getEmail() . $entity->getCreatedTime();
            $key = hash ('sha256' , $hash_input , FALSE);
            $entity->set('field_subscription_key',$key);
            // $entity->save();
        }
    }
}

```

This is not working for some reason, note that I tried this outside of module on all users array and it worked. for some reason, the subscription key field is still empty, the second if condition is there to prevent the field from being overwritten.

# Answer
If you're using Drupal 8, See This one.

**Update a node:**

**Example 1 :** Update title

```
$node = \Drupal\node\Entity\Node::load($nid);
$node->setTitle('The new Title')
$node->save();

```

**Example 2 :** Update a field ('body' and 'field\_name')

```
$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->save();

```

To make changes after click on save / edit button, you can use the hook\_entity\_presave. **hook\_entity\_presave(Drupal\Core\Entity\EntityInterface $entity);**

**Example:**

```
function CUSTOM_MODULE_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('Edited Title');
  $node->set('body', 'this is the bew body');
  //CAUTION : Do not save here, because it's automatic.
}

```

> Note : Do not re save inside of hook\_entity\_presave().

Using **HOOK\_entity\_presave**()

```
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.
  }
}

```

Source : drupal8.ovh
> 1 votes

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


title: Unable to show the block title in D8

text:
# Question
Title: Unable to show the block title in D8
I want to show the D8-based blocks in the block.html.twig file with the html tag only. However, when I entered this special split file, I created a special branch file for each block area (eg region - sagblok.html.twig), block title and content css, html codes. Unfortunately, the block titles did not appear. My code is below:

```
<div class="BlockTitle col-sm-text-center">{{ title_prefix }}</div>
{%if label %}
  <h5{{ title_attributes }}>{{ label }}</h5>
{% endif %}
{{ title_suffix }}</div>
{% block content }}
<div class="col-sm BlockRight">
  {{ content }}
</div>
{% endblock %}

```

Editor screenshot

Sorry for my English.

I have debugged the theme, I am cleaning the cache with the "drush cr" command continually. I have copied the style files of the blocks to the folder of the theme I am developing "core / templates / stable / templates / block / block.html.twig".

The content of the "block.html.twig" file looks like this:

```
<div{{ attributes }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}
</div>

```

I changed the codes in this file like this:

```
  {% block content %}
  <aside>
    {{ content }}
  </aside>
  {% endblock %}

```

then I created a twig file called "region--sagblok.html.twig" belonging to the block region, codes:

```
<div class="BlockTitle col-sm text-center">{{ title_prefix }}
  {% if label %}
    <h5{{ title_attributes }}>{{ label }}</h5>
  {% endif %}
  {{ title_suffix }}</div>
  {% block content %}
  <div class="col-sm BlockRight">
    {{ content }}
  </div>
  {% endblock %}

```

unfortunately block names do not appear in this way. but when I looked at the source code, I realized that the html codes came, but the block names did not.

# Answer
> 1 votes
You are supposed to put your templates into a `/templates` subfolder of your theme.

I'd recommend you find out how to **enable debugging** for Twig templates during development. Here is a how-to on DO: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

By that you'll get template suggestions printed as HTML comments directly inside the markup of your page. It will suggest you certain file namings which then must be placed inside the `/templates` subdirectory of your theme.

And last but not least: Flush caches as often as possible. And find out how to **disable caches** completely during development. Here is another how-to on DO: https://www.drupal.org/node/2598914

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


# Question
Title: Views: How to sort in Table format naturally
1. Create view.
2. Select `Format: Table`.
3. Under the Table Settings toggle `Sortable` on.
4. Fields gets arranged/sorted unnaturally 1 2 3 4 40 5 50 51 6 60, etc. both ways ascending and descending.

The module `Views Natural Sort` does not solve the problem, it works only with fields under `Sort criteria` settings. And it's pretty broken in overall, the option to sort doesn't even appear in my Views.

We want to sort in normal natural way 1 2 3 4 5 6 7 8 9 10

# Answer
Try to install Views\_bootstrap module.

Then in **views/Format** select **Bootstrap Table**

> Don't forget the Settings
> 0 votes

---
Tags: 7, views
---


# Question
Title: Views Contextual Filter Match criteria with contains instead of equal to
When setting up contextual filters, its fixed setting is if the argument **equals** the result. I want to be able to choose if my result **contains** my argument string. How can this be done?

# Answer
> 3 votes
Try using Views Argument Substitutions

> Contextual Filters allow a View to be filtered based on arguments passed via URL or other embedded method (e.g. the View Reference module), **but contextual filters are inflexible compared with normal filters (which allow for "contains," "begins with," "ends with," etc.).**
>
> **This module allows contextual filter arguments to be used as replacement tokens in filters** and table arguments, so that passed-in arguments (such as from URLs or View Reference fields) can be used as values in normal View filters.

---
Tags: 7, views
---


# Question
Title: Compute price based on order item fields
Is it possible to get the order items fields in a price resolver using Drupal 8 and Commerce 2.x?

Indeed, the resolve method in a price resolver only allow to access the purchased entity, quantity and context.

```
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $contex) {}

```

I would like to:

* Define some custom fields in an "Order Item Type" (In my case the fields are dates.)
* Expose those fields in the add-to-cart form
* Define product variation and product that uses that custom order item type, to have my custom add-to-cart form
* Compute the purchased product price (in a custom Price resolver) according to field values provided in the add-to-cart form

I could use product attributes to achieve that, but unfortunately the values entered in the order item fields are not finite.

### Notes

How do I implement this in Commerce 2.x? Did I misunderstand something?

thanks in advance

# Answer
> 11 votes
The short answer: No

**Why:**

In the Drupal Commerce Slack Channel, I asked whether it would be possible to add Order Item to the Context class. This was the response:

> price resolvers are also called by regular price formatters the whole point of the context is to provide known information when the order item is missing
>
> so changing that would be a big API change if you need order item data, for now use an order processor instead

**How to solve the issue:**

Replace YOURMODULE with the name of your custom module. The Priority value is used to prioritize what order processors get called first. You need to look at other order processors and figure out when yours should be called and set the priority value appropriately.

In YOURMODULE.services.yml

```
services:
    YOURMODULE.order_processor:
    class: Drupal\YOURMODULE\OrderProcessor
    arguments: []
    tags:
      - { name: commerce_order.order_processor, priority: 110 }

```

In YOURMODULE\src\OrderProcessor.php

```
<?php

namespace Drupal\YOURMODULE;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\Entity\OrderItemInterface;
use Drupal\commerce_order\OrderProcessorInterface;

class OrderProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {
    $order_items = $order->getItems();
    foreach ($order_items as $order_item) {
      if ($order_item->bundle() == 'YOURCUSTOMBUNDLE') {
        // YOUR LOGIC TO FIGURE OUT $calculated_price
        $price = new Price($calculated_price, $currency)
        // Set to TRUE if you want to override unit price.
        $order_item->setUnitPrice($price, FALSE);
      }
    }
  }

```

Hope this helps!

---
Tags: commerce
---


# Question
Title: How to set cache meta data on drupalSettings?
I use drupalSettings to send config data to javascript. But when I edit my config, the javascript object is not modified, I have to clear all cache to get the update. The cache metadata in http headers show me that the page is linked to my 'config:my\_module.settings' tag but the inline drupalSettings declaration is left unchanged.

What's the way to add cache metadata to:

```
$attachments['#attached']['drupalSettings']['example']['foo']
//or in hook_preprocess_hook ()
$variables['#attached']['drupalSettings']['example']['foo']

```

Or is there a function that could rebuild drupalSettings ?

# Answer
When you add attachments you can add cache data as well:

```
$attachments['#cache']['tags'][] = 'config:my_module.settings';

```

BTW `#attached` and `#cache` are the only data you are allowed to add in hook\_page\_attachments() or hook\_page\_attachments\_alter().
> 6 votes

---
Tags: 8, javascript, caching
---


# Question
Title: How to place content/user field value inside of a rules action?
I'm trying to grab the contents of a field in my node of custom Content Type 'Messages'. The field is called 'targetuser'. I successfully grab the content of this field, and place it inside a field on my User profile called '**last\_user\_messaged**' with the rule 'set a data value'. Hooray...

I then fetch the entity type User (see second action), and the field/property **last\_user\_messaged** (site:current-user:field-last-user-messaged), which *in theory*, should now return the data I'd set there with my first action.

That said, when I try and set my third action 'Send a push notification to a user account' with the data selector \[last-messaged:1\], upon execution, my logs tell me that it's empty. Technically, shouldn't **last-messaged:0** return the first value inside field last\_user\_messaged? And last-messaged:1 return the second value? Or am I reading this wrong?

**In short:** I want my push notification to send to the integer (a uid) that is placed in last\_user\_messaged field.

I hope this makes sense.

# Answer
> 1 votes
Have a look at issue # 430274, which somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...). From the limited details provided in the question, it could well be that this also explains what causes your issue.

A possible compromise to avoid these kind of issues, is to transform relevant parts of what you're trying to do in your Rules Action(s) in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Save of the entity" for sure completed, and updates will have been applied as expected.

PS: as an alternative, add an extra "save entity", after your first Rules Action (possibly that might be sufficent also).

---
Tags: 7, rules
---


# Question
Title: How to programmatically set Webform field value with custom submit?
I try to update an hidden field value with my custom submit, but it doesn't work, my new value are not saved.

With : `$form_state->setValue('token_uid', $token_uid);`

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

    if ($form_id == 'webform_submission_creation_compte_add_form' || $form_id == 'webform_submission_creation_compte_test_form') {

      foreach (array_keys($form['actions']) as $action) {
        //attention en multi step : wizard_next
        if ($action != 'wizard_next' && $action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_MODULE_creation_compte_submit';
        }
      }
      if (isset($form['#validate'])) {
        $form['#validate'][]  =  '_MODULE_creation_compte_validate';
      }
    }
  }

```

My custom submit function :

```
function _MODULE_creation_compte_submit(array &$form, FormStateInterface $form_state) {
    global $base_url;
    $data               = array();
    $user_id_created    = null;

    //Info account
    $account_name       = $form_state->getValue('nom');
    $account_username   = $form_state->getValue('username');
    $account_first_name = $form_state->getValue('prenom');
    $account_mail       = $form_state->getValue('email');
    $account_password   = $form_state->getValue('mot_de_passe');
    $account_phone      = $form_state->getValue('telephone');

    if (!empty($account_username) && !empty($account_password) && !empty($account_mail)) {

        $account_username   = strtolower(str_replace(' ', '', $account_username)).'_'.rand(0,1000);

        $user_created       = User::create([
          'name'                  => $account_username,
          'pass'                  => $account_password,
          'mail'                  => $account_mail,
          'field_user_nom'        => $account_name,
          'field_user_prenom'     => $account_first_name,
          'field_user_telephone'  => $account_phone['phone'],
          'status'                => 0,
          'init'                  => $account_mail,
          'created'               => time(),
          'changed'               => time(),
          'login'                 => 0,
          'access'                => 0,
        ]);
        $user_created->save();
        $user_id_created = $user_created->id();
        $token_uid       =  $base_url . '/user/' . $user_id_created;

       //==> Value is not saved after submit
        $form_state->setValue('token_uid', $token_uid);

    }
}

```

# Answer
> 1 votes
**The solution with `hook_ENTITY_TYPE_presave`** :

```
use Drupal\webform\WebformSubmissionInterface;

 function MODULE_webform_submission_presave(WebformSubmissionInterface $webform_submission){
    global $base_url;
    $user_id_created    = null;

    //Info account
    $account_name       = $webform_submission->getElementData('nom');
    $account_username   = $webform_submission->getElementData('username');
    $account_first_name = $webform_submission->getElementData('prenom');
    $account_mail       = $webform_submission->getElementData('email');
    $account_password   = $webform_submission->getElementData('mot_de_passe');
    $account_phone      = $webform_submission->getElementData('telephone');

    if (!empty($account_username) && !empty($account_password) && !empty($account_mail)) {

      $account_username   = strtolower(str_replace(' ', '', $account_username)).'_'.rand(0,1000);

      $user_created       = User::create([
        'name'                  => $account_username,
        'pass'                  => $account_password,
        'mail'                  => $account_mail,
        'field_user_nom'        => $account_name,
        'field_user_prenom'     => $account_first_name,
        'field_user_telephone'  => $account_phone['phone'],
        'status'                => 0,
        'init'                  => $account_mail,
        'created'               => time(),
        'changed'               => time(),
        'login'                 => 0,
        'access'                => 0,
      ]);
      $user_created->save();
      $user_id_created = $user_created->id();
      $token_uid       =  $base_url .'/user/' . $user_id_created;
      $webform_submission->setElementData('token_uid', $token_uid);
    }
  }

```

---
Tags: 8, webforms
---


# Question
Title: Field values sometimes do not show up in grid view or node view for non admin users
I have a view that is sorted by the number of times a user visits a node and clicks the play button (the play button is a menu item of the node). Every time the play button has pressed the value of an integer field inside the node is incremented and this value is used to sort my view. I also display the value "Times Played" both in the view and the node. When I look at the view as admin everything looks good, like this:

But when I look at the view as a normal user the view is still sorted correctly but some of the nodes don't show the value for "Times Played", here is that screenshot:

Also, when I view the actual node page as an admin I see always see the correct value for "Times Played" but when I visited it as a normal user I get the same behavior I see in the view. Any idea what could be going on here? Is this some strange permissions issue?

# Answer
> 1 votes
Did you try to embed view in your template file? `$embed = views_embed_view('name_of_view','display_id');` . You need also to check permissions

# Answer
> 0 votes
In the query options of the view disable SQL rewriting and see what happens. If your fields appear again for all the users then you have some kind of restriction at field level.

---
Tags: 7, views, nodes, users
---


title: Export configuration translation

text:
# Question
Title: Export configuration translation
Using Drupal 8, I need to create several content types. They'll be used in a multilingual site, so I installed the *Configuration Translation* module from the core to translate the field labels. I can succesfully do that, but I need to create a feature (using *Features* module from the core) to export the content types and import them easily in the production site.

The problem is that the *Features* module doesn't export the configuration translation, even including the languages in the feature.

Is there any way to export the content types with their configuration translation and import them seamlessly into another site?

Exporting the entire site with the *Configuration Synchronization* seems to do the trick, but is more difficult to import because requires a clone site, and I only want the content types.

# Answer
Anyway. You can back up the database with the back up and migrate module and import to your live site. The other tool can be `drush cex` for exporting configuration and `drush cim` for importing it.
> 1 votes

# Answer
Here's something you should consider trying:

* Export configuration from the source site.
* In the directory where you exported the configuration, select the YML files you want to import into the second site.
* Move / copy the files into a separate directory.
* Now, you will have to manipulate the UUID for the configs so that they become compatible with the destination site.
* Once you change the UUIDs to match those of the destination site, you should be able to import them to the destination site.

Hope it helps.
> 0 votes

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


# Question
Title: How to emulate all the AJAX functionality when the form is rendered after an AJAX callback?
I have a Drupal form, but I am adding it to the page as the result of an AJAX callback.

I need this form to trigger a new callback. My code below:

```
      $form['#suffix'] = '<div id="form-return-message-box">this is the return box</div>';
  $form['#attached']['js'] = array('misc/ajax.js');

  $form['markup'] = array(
    '#type' => 'markup',
    '#markup' => '<h2>This is a form</h2>'
  );

  $form['button'] = array(
    '#type' => 'button',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'module_myform_callback',
      'wrapper' => 'form-return-message-box',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $replace_layer = '#somelayer';

  $commands = array();
  $commands[] = ajax_command_replace($replace_layer, drupal_render($form));
  $page = array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );

  ajax_deliver($page);

```

So this is what happens: this form is being added into a container called 'somelayer' that already exists on the page (I didn't add that part of the code because I thought it would be unnecessary). It was called from a link with the class 'use-ajax'.

So the form renders on the page as desired after an AJAX callback triggered by the link. This part works allright.

But here is the (very) tricky part: I would also like to preserve the new form AJAX functionality (check the '#ajax' part of the array), which doesn't occur. After the form is rendered, the button won't trigger any AJAX code. By clicking on it, the page will refresh, not triggering the callback function (not added here to preserve space).

By looking into source code of a regular form page with AJAX, you will see code like this that enables the AJAX functionality:

```
"ajax":{"edit-something":{"callback":"module_formname_callback","wrapper":"wrapper-name","method":"replaceWith","effect":"fade","event":"change","url":"\/spabear\/system\/ajax" ...

```

By looking at the source code of the form added into my page, I can see there is no piece of `<script></script>` code that would trigger the AJAX callback in my dynamically loaded form. How can I emulate all the AJAX functionality when the form is rendered after an AJAX callback?

# Answer
The #ajax\['wrapper'\] property includes the HTML ID of a page section that should be replaced (or altered in some other way). The #ajax\['callback'\] tells the Form system what callback should be called after the Ajax call happens and the form is rebuilt.

https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7
> 2 votes

# Answer
Try adding a 'prevent' =\> 'click' to your #ajax. This will prevent the form from submitting and refreshing the page. After that, it should be a little easier to debug the problem.

```
    $form['button'] = array(
      '#type' => 'button',
      '#value' => t('Submit'),
      '#ajax' => array(
        'callback' => 'module_myform_callback',
        'wrapper' => 'form-return-message-box',
        'method' => 'replace',
        'effect' => 'fade',
        ***'prevent' => 'click',***
      ),
    );

```
> 0 votes

# Answer
Check that your your form has the proper library attached. So when it is being loaded into a page, it will ensure those libraries are avaibable for its defined behaviors.

I assume according to your original question that your are on D7 :

```
  $form['#attached']['library'][] = array('system', 'drupal.ajax');
  $form['#attached']['library'][] = array('system', 'jquery.form');

```

Im not sure with your code example, but you should also try as much as possible to decompose responsibilities. You should have one function to generate your form, one function to submit your form, one function to load and send your form through ajax, etc...
> 0 votes

---
Tags: ajax, forms
---


# Question
Title: D8 - show view in comments depending on user role
how i have to set up a view with Drupal 8 to show a field in the comments when the user\_role is NOT "admin".

im not sure what kind of relationship and contextfilter i need to to this?

background: i want to show a label under the user\_image of the comments Thanks for help!

# Answer
> 1 votes
There is many ways to do it, but the simplest way is to check if user is admin or has exact role..

`global $user;
 if ( !in_array('administrator', $user->roles) ) {
 ... do something ...
 }`

OR

```
if( $user->uid !== 1 ){
  ... do something ...
}

```

OR

`path_is_admin(current_path())`

# Answer
> 0 votes
I don't have all of the answer. However I think you need to create a user view instead of a content view. That might be the key to solving it.

---
Tags: views, users, comments
---


# Question
Title: Spammers apply for an account, how to disable other users from applying for an account on my website
I am using drupal 7 and get messages like these several times a day:

Account details for sizemutter at "my Website Name" (pending admin approval)

sizemutter has applied for an account.

I am afraid that I may approve one of these by mistake. Is there a way to make it for them impossible to apply and to stop spamming me?

Thank you!

# Answer
There are several options. In addition to disallowing vistor registration (Navigate to *Administration → Configuration → People → Account settings* and select "Administrators only" under "Who can register accounts?", you may you one of several contributed modules that is designed to prevent spammer and spambots from registration.

My personal favourite is **Mother May I**. It adds a field to the registration form where the registrant must type in a "secret word". If the registrant gets this wrong, no new account is created. This is perfect for invitation only sites, where the invitation reveals the "secret word". However, I find it works pretty well on other sites as well, where the "secret word" may be the answer to some a "riddle" that is solvable by humans but not by 'bots.

As an alternative to the above, there are are several contributed modules that let you add various types of CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) challenges to forms, including the user registration form. These block spam robots, but do not block human spam registrations. However, blocking 'bots take care of about 99 % of spam registratons, so doing this helps a lot. The most popular module providing a CAPTCHA is named **CAPTCHA**. It comes with a built-in challenge, but is really a framework that to manage a set of CAPTCHA plugin modules, letting you experiment with these to find one CAPTCHA method that is effective for your site.

There are also contributed modules that provides a Drupal interface to some external third party anti-spam service. The most effective of these is **http:BL**. an interface to the project Honeypot blacklist. I've found that this module provides efficient blacklist lookups and blocks malicious visitors effectively. (There a few false positives tho', in particular if your site attracts visitors that connects through TOR.)
> 3 votes

# Answer
Go to `admin/config/people/accounts` and select "Administrators only" under "Who can register accounts?"
> 1 votes

# Answer
If your spam signups are from bots, do all the things other people have suggested (honeypot, captcha).

You might still have spammers manually getting past the Captcha, or maybe you don't like to use a Captcha because it drives away legitimate traffic. Your next step will be to block the IP addresses that the spammers use: Drupal's admin/config/people/ip-blocking blocks will report a 403 error to any connection made from one of the blacklisted IPs.

This can get tedious when spammers have a dynamic IP that keeps changing, or access to multiple internet connections. Use the ip\_ranges module to block entire IP ranges that your spammers are coming from. It's much more powerful than the built-in IP block, which only blocks a single address at a time.

If you only expect traffic from a small geographical area, and your spammers are from other parts of the world, then there are GeoIP-based blocking modules that can also help.

At this point, the persistent spammers will start using Tor or other anonymous proxies to gain access to even more IP addresses, faster than you can block them. This is difficult to detect: What you need now is a service that tells you whether a remote IP is an anonymous proxy or a Tor exit node. That's where the proxy\_rules module comes in. Disclosure: I'm the author of this module.

The idea behind it goes like this:

* Set "Who can register accounts?" to "Visitors", allowing everyone who passed the earlier checks (IP blocks, Captcha, etc) to register an account without approval.
* Add a rule (you can do this in a hook\_user\_presave or with the rules module, which is great for this) to check the client IP when a new user is created, and block the new account if it matches a list of known anonymous proxies.
* Now administrators can review those signups and activate or delete them.

Or, if you don't want that hassle, just reject all connections from these proxies, the same way that the ip\_rules module does it (I think it implements a hook\_boot).

The module can identify Google Proxies by HTTP headers, and Tor nodes through a free DNS lookup service from the Tor project.

However, the list of anonymous HTTP proxies changes all the time. I do not know of any free data sources to implement, but the module supports external APIs and local databases (from udger.com and ip2location.com) that charge a monthly fee for their use.
> 1 votes

---
Tags: users, advertising
---


title: Drupal 8 rewrite a hook

text:
# Question
Title: Drupal 8 rewrite a hook
I want to rewrite a hook `comment_node_links_alter`. How can I do it? I created a file `THEME.theme` in my theme, placed there `THEME_comment_node_links_alter` but it is not called. I cannot find any distinct information how to rewrite hooks. I observed `bartik.theme` and saw that all hooks are prepended with a theme name. I did the same. Did clear the cache. My funciton is included, I checked with xdebug. But it is never called.

# Answer
> 2 votes
I think you're getting confused about how Drupal hooks work. You don't overwrite the existing function you instead create your own function that is called when the relevant part of the site is loaded. (So in this case node links)

So there is no THEME\_comment\_node\_links\_alter hook. There is HOOK\_node\_links\_alter. So I'm guessing you looked in the comment module and saw comment\_node\_links\_alter which is actually the comment module implementing HOOK\_node\_links\_alter

In your theme/module you'd want to replicate what the comment module is doing so something like

```
THEME_node_links_alter(

```

With THEME being your theme machine name. THen that will mean your function is called and you can amend the variables

https://api.drupal.org/api/drupal/core%21modules%21node%21node.api.php/function/hook\_node\_links\_alter/8.4.x

---
Tags: 8, hooks
---


title: Altering block to include another block

text:
# Question
Title: Altering block to include another block
I am using the following code for a block.

```
  public function build() {
    $current_client = \Drupal::service('user.private_tempstore')->get('epensions');
    $build = [];
    $build['client'] = array(
      '#markup' => $current_client->get('scheme_name').' : '. $current_client->get('sponsor_name'),
    );

    $build['change_link'] = array(
      '#title' => $this->t('Change'),
      '#prefix' => '<br>',
      '#type' => 'link',
      '#url' => Url::fromRoute('epensions.sponsor.selector')
    );

    $build['#cache']['max-age'] = 0;

  return $build;

  }

```

I want the results to appear to the right of the account details in Bootstrap and show the same way "My account" & "Log Out" appears.

>

Kindly help.

# Answer
There are multiple ways you could approach this. Rather than create a new block, one way would be to add the 'change\_link' item to the User Account menu, and then use hook\_link\_alter to add the sponsor\_name text in front of the new link.

Another way would be to use the Block Layout settings (admin/structure/block) to position your block in the desired region (wherever the account details are positioned) and give it the desired weight within that region. Then use CSS to float it to the right of the account details.

If you really want to position block output within another block, you could use hook\_block\_view\_alter.
> 0 votes

---
Tags: blocks
---


title: drush updatedb for a single module

text:
# Question
Title: drush updatedb for a single module
Is it possible to perform a single module's update function via drush? I can see `drush updatedb` which does not take an modulename as argument and runs all available updates. Then there is `drush pm-update` wich also checks for new files. the documentation says:

> (same as pm-updatecode + updatedb)

Does this mean if I run `drush pm-update` every available (newer update\_function exits) update will be perfomed? Is there a way to only (db)update exactly one module?

# Answer
> 10 votes
No, you can't.

If you want to update each module on their own, only update the files of a single module and then run updatedb.

# Answer
> 21 votes
On Drush 5.7 you can run the command `drush pm-update --no-core module-name`. Drush will automatically backup the current module, download the new version and prompt you to update the database.

# Answer
> 11 votes
If you want to run just one update, you can run `drush eval foo_update_33()`, for example. In practice, it is a little more complex than that as you have to load the .install file but not much.

You can also try @macaleaa solution :

`drush php-eval 'module_load_install('my_module');my_module_update_7XXX();'`

# Answer
> 5 votes
neither `drush up someproject`, nor `drush upc someproject` seem seem to update only the `someproject` module. A different way to that what you want is through :

```
drush dl someproject #use --select option to be prompted for a module version
                     #this will overwrite your exising module's files
                     #backup your modules files with --backup, yourself, use a VCS to revert
drush updb           #run available database update scripts

```

Here is discussion a similar topic on Drupal.org. Take care !

# Answer
> 3 votes
I'm using Drush 5.9, & can update a single module successfully with this command:

```
drush dl *project*

```

So, for example, to update the 'devel' module:

```
drush up devel

```

# Answer
> 0 votes
I had a situation in which a table created by an update function (`MYMODULE_update_7101`), but that table was being accessed in code somewhere in every cache clear and almost every drush call (it was basically getting the names of entity types for all the menus and whatever else). Running `drush updatedb` was running `MYMODULE_update_7101` third instead of first.

I tried the solution suggested by @macaleaa and @moshe weitzman of running:

```
drush php-eval 'module_load_install('MYMODULE');MYMODULE_update_7101();'

```

before running `drush updatedb`, but this didn't help - the drush run failed because `updatedb` tried again to run `MYMODULE_update_7101()` and errored out, saying the table already existed. Basically, the above code had run the update, but not left its mark on the system that the update had been run. Presumably there is a whole bunch of other stuff `update.php` has to do after running each update to store the latest version number for the module in the db, etc.

I went through `update.php` to see how it actually runs each update function and what it does after, looking for a function to call that would call the update function and also do all the other stuff. I ended up getting to this:

```
include_once DRUPAL_ROOT . "/includes/update.inc";
$c["results"]["#abort"] = array();
update_do_one("MYMODULE", 7101, array(), $c);

```

Which I actually ran with drush:

```
drush eval 'include_once DRUPAL_ROOT . "/includes/update.inc"; $c["results"]["#abort"] = array(); update_do_one("MYMODULE", 7101, array(), $c);'

```

It ran the update, no problem, but then MYMODULE version 7101 still showed up in the updates list when I ran `updatedb`, ALTHOUGH it ran without erroring out and everything looked good on inspection of the site.

A bit hacky and 6 years late, but all's well that ends well?

---
Tags: 7, drush, updating
---


# Question
Title: Output node creation date between two fields
I want to print the creation date of nodes of type article between two fields. I know you can do this with Display Suite, but I don't want to install the module only for this functionality. My only idea is to put an `if` condition into the `for` loop of field.html.twig to print the date after a certain field occurs, but I wonder if there is a better solution.

# Answer
> 1 votes
Yes, you would need a module like Display Suite only if you want to do this in UI. For a solution in code you can add extra information to the render array `$variables['content']` in a preprocess hook:

*mytheme.theme:*

```
/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];

  if ($node->getType() == 'article') {
    $variables['content']['created'] = [
      '#markup' => t('<p>Node created: @created</p>', [
        '@created' => format_date($node->getCreatedTime(), 'medium'),
      ]),
      '#weight' => '5',
    ];
  }

}

```

Adjust weight to position it between the two fields.

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


# Question
Title: Enforce URL rules when posting content types
so I created a content type "Regions" - This includes the 13 provinces in Canada listed as individual terms.

When creating a new post with the content type "Regions", you have to choose which term to post into. Let's say I would like to post a page "TEST POST ONTARIO", I post it in the term "Ontario"

I would like the URL from this post to be automatically changed to www.website.com/region/on/testpost by default, it posts to www.website.com/testpost

Is there a way to automate the url for when this content type is created? or would you have to manually change the url alias every post?

# Answer
> 0 votes
You want to use the PathAuto module. This lets you create default patterns on a per content type basis that can use information from fields on the node to create a URL.

---
Tags: taxonomy-terms, uri
---


# Question
Title: What is the $user array consists of for Drupal 7?
I couldn't find a good reference to what the $user object consists of. I know $user-\>uid provides to uid. What else?

# Answer
The Drupal 7 $user object consists of the following when doing an output of dsm($user):

If your wanted the name, you would do: $user-\>name or roles would be: $user-\>roles\[2\]
> 0 votes

---
Tags: 7, users
---


title: How do I add classes to blocks?

text:
# Question
Title: How do I add classes to blocks?
I am using Drupal 8 Panels and it is working fine. The problem currently I have is, that I want to add classes to individual blocks on the panel layout page. Is there a way to add classes to blocks on panel pages?something like the Drupal 7 version of CSS properties on panel panes?

# Answer
For custom blocks it's pretty easy to add classes without any module. Simply add a text (plain) field - or whatever fit's your needs best, get the value in the block.html.twig (maybe use Twigs |clean\_class filter) and add it to the classes.
> 0 votes

---
Tags: blocks, 8, panels
---


title: How to get node object from node ID

text:
# Question
Title: How to get node object from node ID
in a drupal 8 custom module, how do I get a node object if I have the node id? I tried :

```
$node = new Node($nid);
$node->save();`

```

but got this error:

> Argument 1 passed to Drupal\Core\Entity\ContentEntityBase::\__construct() must be of the type array, string given,

# Answer
There are a few ways.

If your context allows for Dependency injection, inject the `entity_type.manager` service and use it like so:

```
$node = $this->entityTypeManager->getStorage('node')->load($nid);

```

If not you can still use the `entity_type.manager` service:

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

```

If you prefer, you can use the `Node` class directly:

```
$node = \Drupal\node\Entity\Node::load($nid);

```
> 35 votes

# Answer
You never use `new` to create an entity, whenever you need to load it from the database or create it without loading it from the database.

In the case you want to create a node, you use `Node::create()`, as in the following example code.

```
  use Drupal\node\Entity\Node;

  $settings = [
    'body' => [
      [
        'value' => 'The node body is here.',
        'format' => filter_default_format(),
      ],
    ],
    'title' => 'The node title',
    'type' => 'page',
    'uid' => \Drupal::currentUser()->id(),
  ];
  $node = Node::create($settings);

```

If you need to simply load a node from the database knowing its node ID, the code is much simpler.

```
  use Drupal\node\Entity\Node;

  $node = Node::load($nid);

```

If then you need to load a node from the database knowing any other properties, but not the node ID, you can use the following code.

```
  use Drupal\node\Entity\Node;

  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties($values);

```

`$nodes` is an array containing zero or more nodes, and `$values` is an array describing the properties you know.
> 7 votes

---
Tags: 8, nodes
---