# Question
Title: How do I grant to roles dynamically created permissions?
In my module, I am dynamically creating user permissions for vocabularies. I would like to also grant all roles the view permission, but I cannot figure out a proper way where to do it.

I cannot use a config yml, because these are dynamic permissions created within permission callback and both the hook\_install and hook\_modules\_installed are run before the permission callback, so the roles don't pick up the permissions.

This is how I tried to grant the permissions in `hook_install()` and `hook_modules_installed()`.

```
$vocabularies = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_vocabulary')
  ->loadMultiple();

if (!empty($vocabularies)) {
  foreach ($vocabularies as $vocabulary) {
    $permission = 'view name defined in the callback ' . $vocabulary->id();
    $anonymous_rid = RoleInterface::ANONYMOUS_ID;
    $authenticated_rid = RoleInterface::AUTHENTICATED_ID;

    if ($anonymous_role = Role::load($anonymous_rid)) {
      $anonymous_role->grantPermission($permission);
    }
    if ($authenticated_role = Role::load($authenticated_rid)) {
      $authenticated_role->grantPermission($permission);
    }
  }
}

```

Where should I grant these permissions within my module?

# Answer
> 2 votes
After granting the permissions, you should call the `save()` method to make the code work.

```
if ($anonymous_role = Role::load($anonymous_rid)) {
  $anonymous_role->grantPermission($permission);
  $anonymous_role->save();
}

```

---
Tags: 8, users
---


title: views_get_current_view returns null

text:
# Question
Title: views_get_current_view returns null
I have placed the following function in my .module file to get the information of current view. But it returns null

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $record = array();
    $view = views_get_current_view();
}

```

I have added `use Drupal\views\Views;` in the top.

What could be the reason to return null. Am i missing anything?

# Answer
`views_get_current_view()` seems to be from the early days of procedural code and I don't know how this can be used in connection with form building in D8.

You can get the current view from the current route, if this is what you are looking for:

```
use Drupal\views\Entity\View;

  $view_id = \Drupal::routeMatch()->getParameter('view_id');
  if ($view_id) {
    $view = View::load($view_id);
  }

```
> 0 votes

---
Tags: 8
---


# Question
Title: How do I remove the trailing time zeros after the Date
I'm using Drupal 8.4 Webform Module. I selected the Date element (not Date/time). In the Webform Date Settings, I'm using date picker, Medium date - D, m/d/Y (Mon, 11/27/17). (I also tried Custom, D, M j, Y.

I'm using this field in a View, Format = Default medium date and this is what I get, Thu, 12/14/2017 - 00:009:00 AMFri, 12/15/2017 - 00:005:00 PM . How do I remove the trailing zeros?

# Answer
> 0 votes
Go to '**yoursite/admin/config/regional/date-time**' and click the button, '**\+ Add Format**' to add a new date format.

Enter a name for this new format and add your date format in the Format string box.

Example: **D, M j, Y** will output **Fri, Dec 22, 2017**. Click **Add Format**

Go to your Webform \> build and select the date element you want format with your new date format. In the Advanced tab, select your new date format in the SUBMISSION DISPLAY \> SINGLE ITEM \> ITEM FORMAT box and save.

You should also be able to select the new date format in Views.

Its best to clear the cache at **yoursite/admin/config/development/performance**

---
Tags: views, webforms
---


# Question
Title: How do I use an absolute URL to set as breadcrumb link?
I would like to use absolute URL instead of relative URL as the breadcrumb link on my website. Right now, I am using Drupal 7 and Path Breadcrumb 7.x-3.0 Module. All my breadcrumbs are set by Module.

This is a sample of my breadcrumb right now.

```
<div id="breadcrumbs">
      <h2 class="element-invisible">You are here</h2>
      <div class="breadcrumb">
                <a href="/">Home</a> »
                <a href="/category.html">Category</a>
      </div>
      <span class="delimiter"> > </span>
      <strong>Dimmer</strong>
</div>

```

How can I make the breadcrumbs like these?

```
<div id="breadcrumbs">
      <h2 class="element-invisible">You are here</h2>
      <div class="breadcrumb">
                <a href="http://mywebsite.com">Home</a> »
                <a href="http://mywebsite.com/category.html">Category</a>
      </div>
      <span class="delimiter"> > </span>
      <strong>Dimmer</strong>
</div>

```

**EDIT**

My breadcrumb code is generated by `print $breadcrumb;` in the page.tpl.php file. How can I convert the breadcrumb link from Relative to Absolute in this case?

# Answer
> 0 votes
Using PHP code you can build absolute urls with the url function.

Example:

```
$url = url('/category.html', ['absolute' => TRUE]);

```

# Answer
> 0 votes
You shall put your html in a template and create a preprocess function where you create a variable like this:

```
$vars['url'] = url('/category.html', ['absolute' => TRUE]);

```

Then you have a variable called `$url` that you can use in your tamplate.

Hope it works

---
Tags: 7, breadcrumbs
---


title: Custom form "Data too long for column"

text:
# Question
Title: Custom form "Data too long for column"
I create a custom entity (pool) with a custom form.

In my custom form, i have a field (start\_date)

```
$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => new DrupalDateTime()
];

```

When i want to save, i have the follow error :

"Data too long for column"

In the log, the value is : 2017-12-21 18:06:29 Europe/Paris Instead of 2017-12-21T17:06:29

What i'm doing wrong ?

# Answer
Drupal's DateTime field isn't ISO 8601 compliant, (doesn't save datetime values in the standard format you're expecting 2017-12-21T17:06:29). You need to convert the value to UTC format for storage. One approach is to initialize a date variable, convert it, and then pass as the value in your form field.

```
$currentDate = new DrupalDateTime();
if ($currentDate instanceOf DrupalDateTime && !$currentDate->hasErrors()) {
  $currentDate->setTimezone(new \DateTimeZone('UTC');
  $db_friendly_value = $currentDate->format('Y-m-d\TH:i:s');
}

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => $db_friendly_value
];

```

Specific notes about working with the DateTime API in D8 can be found in this *"New DateTime API"* post.

This specific formatting issue was reported for the datetime module here.

Comment  shows the recommended approach to converting the date into the proper format for saving.
> 2 votes

# Answer
So with your advices, i found a solution :

```
      public function buildForm(array $form, FormStateInterface $form_state) {
        $form = parent::buildForm($form, $form_state);
        $entity = $this->entity;

        $currentDate = new DrupalDateTime();
           $form['start_date'] = [
           '#type' => 'datetime',
           '#title' => t('Start Date'),
           '#default_value' => $currentDate
        ];

```

I add the function validateForm and setValueForElement

```
public function validateForm(array &$form, FormStateInterface $form_state)
{
$entity = $this->getEntity();
$currentDate = $form_state->getValues()['start_date'];
if ($currentDate instanceOf DrupalDateTime && !$currentDate->hasErrors()) {
  $currentDate->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
  $db_friendly_value = $currentDate->format(DATETIME_DATETIME_STORAGE_FORMAT);
}

$element[] = $db_friendly_value;

$element['#parents'] = ['start_date'];
$form_state->setValueForElement($element, $db_friendly_value);
$form_state->setTemporaryValue('entity_validated', TRUE);

```

}

And now it's ok in the db
> 0 votes

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


# Question
Title: How do I correctly setup caching for my custom block showing content depending on the current node?
I have this very basic block which just shows the current node's ID.

```
<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Block\ExampleEmptyBlock.
 */

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;

/**
 * @Block(
 *   id = "example_empty",
 *   admin_label = @Translation("Example: empty block")
 * )
 */
class ExampleEmptyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    $build = array();

    if ($node) {
      $config = \Drupal::config('system.site');

      $build = array(
        '#type' => 'markup',
        '#markup' => '<p>' . $node->id() . '<p>',
        '#cache' => array(
          'tags' => $this->getCacheTags(),
          'contexts' => $this->getCacheContexts(),
        ),
      );
    }

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $node = \Drupal::routeMatch()->getParameter('node');
    return Cache::mergeTags(parent::getCacheTags(), ["node:{$node->id()}"]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['user.node_grants:view']);
  }

}

```

But once cached, the block stays the same, regardless which node I visit. How do I correctly cache the result per node ID?

# Answer
This is full working code with comments.

```
namespace Drupal\module_name\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;

/**
 * Provides a Node cached block that display node's ID.
 *
 * @Block(
 *   id = "node_cached_block",
 *   admin_label = @Translation("Node Cached")
 * )
 */
class NodeCachedBlock extends BlockBase {
  public function build() {
    $build = array();
    //if node is found from routeMatch create a markup with node ID's.
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $build['node_id'] = array(
        '#markup' => '<p>' . $node->id() . '<p>',
      );
    }
    return $build;
  }

  public function getCacheTags() {
    //With this when your node change your block will rebuild
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      //if there is node add its cachetag
      return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
    } else {
      //Return default tags instead.
      return parent::getCacheTags();
    }
  }

  public function getCacheContexts() {
    //if you depends on \Drupal::routeMatch()
    //you must set context of this block with 'route' context tag.
    //Every new route this block will rebuild
    return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
  }
}

```

I tested it; it works.

Just put the code in a file named NodeCachedBlock.php in your module folder, change its namespace {module\_name}, clear the cache and use it.
> 51 votes

# Answer
The by far easiest way to do this is to rely on the plugin/block context system.

See my answer for How do I make a block that pulls the current node content?

You just have to put a node context definition in your block annotation like this:

```
*   context_definitions = {
*     "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
*   }

```

And then use it like this: `$this->getContextValue('node')`

The nice thing about this is that Drupal will then take care of caching for you. Automatically. Because it knows that the default (and as far as core goes only) node context is the current node. And that knows where it is coming from, so the cache context and cache tags are added automatically.

Through `\Drupal\Core\Plugin\ContextAwarePluginBase::getCacheContexts()` and the corresponding `getCacheTags()` methods, BlockBase/your block class extends from that and inherits those methods.
> 18 votes

# Answer
If you derive the class of your block plugin from `Drupal\Core\Block\BlockBase`, you will have two methods to set cache tags and contexts.

* `getCacheTags()`
* `getCacheContexts()`

For example, the Book module block implements those methods as follows.

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

```

The Forum module block uses the following code.

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

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return Cache::mergeTags(parent::getCacheTags(), ['node_list']);
  }

```

In your case, I would use the following code.

```
  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $node = \Drupal::routeMatch()->getParameter('node');
    return Cache::mergeTags(parent::getCacheTags(), ["node:{$node->id()}"]);
  }

```

You could also use the following method, to make the block uncacheable at all (even if I would avoid it). It could be useful in other cases, maybe.

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

```

Remember to add `use Drupal\Core\Cache\Cache;` on the top of the file, if you are going to use the `Cache` class.
> 9 votes

# Answer
When you build a render array, always attach the correct metadata:

```
use Drupal\Core\Cache\Cache;

$build['node_id'] = [
  '#markup' => '<p>' . $node->id() . '<p>',
  '#cache' => [
    'tags' => $node->getCacheTags(),
    // add a context if the node is dependent on the route match
    'contexts' => ['route'],
  ],
];

```

This is not block specific and the block plugins cache dependency methods getCacheTags(), getCacheContext() and getCacheMaxAge() are not a replacement. They should only be used for additional cache metadata, which can't be delivered through the render array.

See the documentation:

> "It is of the utmost importance that you inform the Render API of the cacheability of a render array."

https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

See this example how Drupal expects a render array to provide the necessary cache metadata when optimizing caching through auto-placeholdering and lazy-building Problem setting user specific cache tags on custom block with user context
> 8 votes

# Answer
The problem here is that the cache contexts are not declare at the right place in the build function:

```
class ExampleEmptyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
   $node = \Drupal::routeMatch()->getParameter('node');
   $build = array();

   if ($node) {
    $config = \Drupal::config('system.site');

    $build = array(
    '#type' => 'markup',
    '#markup' => '<p>' . $node->id() . '<p>',
    '#cache' => array(
      'tags' => $this->getCacheTags(),
      'contexts' => $this->getCacheContexts(),
    ),
   );
 }
 return $build;
 }
}

```

If you call that block on a non node, the build function return an empty array, so there is no cache context for this block and that behaviour will be cached by drupal: the display of this block will not properly invalidate or be rendered.

Solution is just to initialise the $build with the cache contexts everytime:

```
class ExampleEmptyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
   $node = \Drupal::routeMatch()->getParameter('node');

    $build = array(
    '#cache' => array(
      'tags' => $this->getCacheTags(),
      'contexts' => $this->getCacheContexts(),
    ),
   );

   if ($node) {
    $config = \Drupal::config('system.site');

    $build['#markup'] = '<p>' . $node->id() . '<p>';
    $build['#type'] = 'markup';
    }
 return $build;
 }
}

```
> 3 votes

# Answer
Have you tried implementing `hook_block_view_BASE_BLOCK_ID_alter`?

```
function hook_block_view_BASE_BLOCK_ID_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#cache']['max-age'] = 0;
}

```
> 3 votes

# Answer
I realize that I'm late to this conversation, but the below code worked for me:

```
class ExampleBlock extends BlockBase
{

  public function build()
  {
    $lcContent = '';

    $loNode = \Drupal::routeMatch()->getParameter('node');

    if (!$loNode)
    {
      return (array(
        '#type' => 'markup',
        '#cache' => array('max-age' => 0),
        '#markup' => $lcContent,
      ));
    }

    $lcContent .= "<div id='example_block' style='overflow: hidden; clear: both;'>\n";
    $lcContent .= $loNode->id();
    $lcContent .= "</div>\n";

    return (array(
      '#type' => 'markup',
      '#cache' => array('max-age' => 0),
      '#markup' => $lcContent,
    ));
  }
}

```
> 2 votes

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


# Question
Title: How to render the textfield from custom advanced theme setting?
I'm working on a custom theme with message field(textfield) in custom advanced theme setting.

In "theme-settings.php", I added a "***textfield***" for "***message***" field

```
<?php
function MYTHEME_form_system_theme_settings_alter(&$form, $form_state) {
    $form['message_value'] = array(
        '#type'     => 'textfield',
        '#size' => 12,
        '#maxlength' => 100,
        '#default_value' => theme_get_setting('message_value'),
        '#description' => t('Some text here'),
    );
}
?>

```

In "***template.php***", I added "***theme\_get\_setting***"

```
<?php
  function MYTHEME_preprocess_page(&$vars) {
    $message = theme_get_setting('message_value');
  }

```

And in my "***page.tpl.php***", I render the "***message***" if it is not empty

```
<?php if(!empty($message)) echo $message; ?>

```

The problem is, it does not render anything and has no error.

It works if I put the theme\_get\_setting in page.tpl.php

```
<?php $message = theme_get_setting('message_value'); ?>

```

How to make it work if I want to put that in ***"template.php"***?

# Answer
In your template.php preprocess function, you need to pass the message back as a key/value in the variables array. (I set the variable key as "custom\_msg" as "message" may be too generic and be accidentally confused with any system message variables"

```
function MYTHEME_preprocess_page(&$vars) {
    $message = theme_get_setting('message_value');
    $vars['custom_msg'] = $message;
}

```

Then, in your page.tpl.php, the variable would be accessible as $custom\_msg (or whatever custom key you set in the preprocess function) and can be included in your page template as:

```
<?php if(!empty($custom_msg)) echo $custom_msg; ?>

```

More information about this can be found on this Drupal.org page: *Setting up variables for use in a template (preprocess and process functions)*
> 5 votes

# Answer
Your code in template.php needs modification

instead of $message, you need to mention `$vars['message']`. If you need to send a variable from template.php file to a tpl file, then the variable has to be mentioned in `$vars['variable_name']` or `$variables['variable_name']`, depending upon the argument set in the preprocess method.

So here goes the modification to your code:

`function MYTHEME_preprocess_page(&$vars) {
$vars['message'] = theme_get_setting('message_value');
}`

And then in you tpl file, you will be able to render the 'message' variable.

```
if(!empty($message)) echo $message;

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: How do I invalidate cache for a block for anonymous users on a schedule?
At the top of every page of page of my organization's site resides the current hours of operation and current "now open"/"now closed" status, using Views block and Office Hours module).

At this time of night on a Wednesday when logged in, I correctly see that the hours are reflecting tomorrow's hours and that the organization is now closed:

However when logged out, I see that the current day's hours (now over) and "NOW OPEN". It's six hours after closing time and the 5 minute page cache time in performance settings does not seem to be respected for anonymous page views:

What can I do to force an anonymous cache clear (overkill?) or invalidation of a block for anonymous users, perhaps on a schedule? I'm aware that the built-in Page Cache module may be caching full rendered pages for anonymous users while Dynamic Page Cache module makes it usable for logged in users. Shouldn't Page Cache respect the page cache maximum age set in the Performance settings page? Most people viewing the current hours at the top of every page are anonymous users.

For now I'll manually clear the cache, making the status update properly (not ideal).

# Answer
> 5 votes
At the top of the issue queue of Office Hours is this issue:

Fix javascript in D8-version of office\_hours module

The problem is, you need this issue resolved, because for anonymous users javascript has to work.

If you want to build your own module, follow @oknate advice and use a lazy builder in a custom block plugin and install BigPipe to get the javascript part for ~~anonymous~~ logged-in users.

**Updated question:**

For anonymous users you can instead of disabling the Internal Page Cache set an expires header to the response as suggested by @Berdir's comment. See https://drupal.stackexchange.com/a/196557/47547

# Answer
> 2 votes
A quick and dirty solution would be to use the Cleaner module to force the cache to clear when cron runs. You could schedule cron runs to occur at open/close times. It's not an ideal solution because Cleaner clears the entire cache, resulting in slower performance. But it's a quick fix until you have time to develop the lazy builder/bigpipe solution mentioned above.

# Answer
> 1 votes
Try setting "`cache max-age`" in your block definition. As per short description provided on Cache API Page for **max-age**:

> For time-sensitive caching, i.e. time dependencies

For example of how to use/set cache in block check Drupal 8 Block Cache.

Hope this helps.

# Answer
> 1 votes
Have you tried implementing `hook_block_view_BASE_BLOCK_ID_alter`?

Here is the code to exclude from cache.

```
function hook_block_view_BASE_BLOCK_ID_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#cache']['max-age'] = 0;
}

```

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


# Question
Title: Render variables printed by {{ dump(user) }} in a template?
I have the following code in node.html.twig.

```
{{ dump(user) }}

```

I get this output.

```
object(Drupal\Core\Session\AccountProxy)#523 (4) {
["account":protected]=>
object(Drupal\Core\Session\UserSession)#91 (16) {
["uid":protected]=>
string(1) "1"
["roles":protected]=>
array(2) {
  [0]=>
  string(13) "authenticated"
  [1]=>
  string(13) "administrator"
}
["access":protected]=>
string(10) "1513942493"
["name"]=>
string(5) "admin"
["preferred_langcode":protected]=>
string(2) "en"
["preferred_admin_langcode":protected]=>
NULL
["mail":protected]=>
string(18) "noreply@imi.org.uk"
["timezone":protected]=>
string(13) "Europe/Berlin"
["langcode"]=>
string(2) "en"
["pass"]=>
string(55) "$S$E7IRVipuFHHectBpj8GkGZGPHlFWNQKG9ydDoRpwBDcCbzklpVaj"
["status"]=>
string(1) "1"
["created"]=>
string(10) "1513920795"

```

I want to render value of `["created"]=>string(10) "1513920795"` and `["uid":protected]=>string(1) "1"`. What is the syntax or code to output them from the template?

# Answer
> 1 votes
You can just get the user ID and when the account was created respectively with `{{ user.id }}` and `{{ user.created }}`. With `{{ user.created | date("d F Y") }}` you print the timestamp with the date format you specify.

Consider `user` as an object. You can access all the values the same way.

See also the Twig documentation.

---
Tags: 8, theming
---


# Question
Title: How to get the $form_state in hook form submit?
I need to create a node when a comment is submitted in nodes. There are two content types `image` and `memory` and I need to get node ID of the node that a user is inserting comment in it.

Here is my code

```
function THEME_form_submit(&$form_state, $form_id){
    if($form_id == "comment_node_memory_form" || $form_id == "comment_node_image_form"){
        kpr($form_state);
        //Insert new node
    }
}

```

Clearly this code won't display the `$form_state` but I need to some how get the node ID and the ID of the user who inserting the comment. I guess these information are in `$form_state` but I really have no idea how to get them.

Thanks

# Answer
If you can see it, it is not mean that your submit hook not run,
you can use `dpm`( it is useful dpm function in devel module ) or use something like below line in your submit or validate functions,

`drupal_set_message("<pre>" . print_r($form, 1) . "</pre>");`

```
  function THEME_form_submit(&$form_state, $form_id){
if($form_id == "comment_node_memory_form" || $form_id == "comment_node_image_form"){
drupal_set_message("<pre>" . print_r($form_state, 1) . "</pre>");
}

```

}

after it you sure that your function run and you can see exists variable there.

**first try this, if not work try other solution(creating module )** instead `THEME_form_submit(&$form_state, $form_id){` write `THEME_form_submit($form, &$form_state){`

**update part**

I suggest you put this code in your custom module

```
function mycmodule_form_submit(&$form,&$form_state, $form_id){
    if(in_array($form_id,array("comment_node_memory_form","comment_node_image_form"))){
           $form['actions']['submit']['#submit'][] = '_mycmodule_custom_sumbmit_handler';
        //ym($form);
       }
    }

function _mycmodule_custom_sumbmit_handler($form,&$form_state){
        /// every sumibted data provided in $form_state
        /// dsm($form_state);
       drupal_set_message("<pre>" . print_r($form_state, 1) . "</pre>");
  }

```

and if you not have custom module lead you to create it,

first creaate a directory(folder) name it as `mycmodule`

then create two file in it

* `mycumodule.module`
* `mycumodule.info`

then put this content in there

in `mycumodule.module`

```
function mycmodule_form_submit(&$form,&$form_state, $form_id){
    if(in_array($form_id,array("comment_node_memory_form","comment_node_image_form"))){
           $form['actions']['submit']['#submit'][] = '_mycmodule_custom_sumbmit_handler';
        //ym($form);
       }
    }

function _mycmodule_custom_sumbmit_handler($form,&$form_state){
        /// every sumibted data provided in $form_state
        /// dsm($form_state);
       drupal_set_message("<pre>" . print_r($form_state, 1) . "</pre>");
  }

```

in`mycmodule.info`

```
name = My custom module
description = custom module provide some devel changes
core = 7.x
package = My Package

```
> 1 votes

# Answer
If you only need nid of node comment is being inserted inside and uid of comment author then use these codes :

nid exist in : `$form_state ['values']['nid']`

you can even load node if you need more info about it using :

```
$node = node_load($form_state ['values']['nid']);

```

to get info about author use : `$form_state ['values']['uid']`

if user is anonymous this returns 0
> 1 votes

# Answer
Comments are an Entity in Drupal.

The comment entity object consists of the Node id on which the comment is attached. Try

```
MYMODULE_entity_insert($entity, $type) {

//Paste your  node creation code here

}

```

See https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_entity\_insert/7 for more details on this hook
> 1 votes

# Answer
In that case use hook\_form\_alter in custom module.

Use dpm($form),check what datas it rendered first.

Store desired datas in a custom table.Then use a custom trigger (pull all stored datas from custom table)to notify users.
> 0 votes

# Answer
```
/**
 * This will give you all nodes of your selected content type
 **/
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', $content_type)
          ->propertyCondition('status', 1);
     $results = $query->execute();
    $node_ids = array_keys($results['node']);
/**
 * This will give you all nodes of that content type
 **/
$compfields = node_load_multiple($node_ids);

/**
 **Now check here, for each node, if it has comments, get the node id. It will check each node, and if there is any comment present, it will reflect node id.**
 **/
foreach($compfields as $keys => $node){
if($node->cid >0){
print $node->nid;
}
}

```
> 0 votes

# Answer
The accepted answer doesn't show how to get the ID of the node for which the comment is being posted. Given the code used to generate the comment form (`comment_form()`), you can use code similar to the following one, in Drupal 7.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "comment_node_memory_form" || $form_id == "comment_node_image_form") {
    if (isset($form_state['comment'])) {
      // Get the node ID from the comment object passed in $form_state.
      $nid = $form_state['comment']->nid;
    }
  }
}

```
> 0 votes

---
Tags: nodes, forms, hooks
---


# Question
Title: How to give an 'editor' role rebuild/clear cache permission?
I'm setting up an "editor" role for a D8 site. I noticed there's no "Flush all caches" in the Tools menu. I don't see any permission setting related to caches. How to enable cache clearing/cache rebuilding for non-admins?

# Answer
> 16 votes
I'd like to mind the following answer to a similar feature request on DO:

> I kind of disagree with this because of the that shouldn't be necessary in the first place. With cache tags, any change that an editor can make should automatically invalidate all relevant caches. Anything else is a bug IMHO.

Nevertheless in real world sometimes it may be necessary to have other roles than the one with `administer site configuration` being able to rebuild caches.

Basically all you need to do is to build a trigger of some kind (button, route etc.) and let it fire `drupal_flush_all_caches()`. Have a look at the Devel module for a great example of this approach.

---

Since I was in need of this myself – which was why I came here in the first place – I finally built a small module and published it on DO. It adds *its own permission* and places a *button on the admin toolbar* from which every user with the new permission is now able to flush all caches:

https://www.drupal.org/project/rebuild\_cache\_access

# Answer
> 8 votes
To access this, they would need the `administer site configuration` permission.

From `system.routing.yml`:

```
system.performance_settings:
  path: '/admin/config/development/performance'
  defaults:
    _form: 'Drupal\system\Form\PerformanceForm'
    _title: 'Performance'
  requirements:
    _permission: 'administer site configuration'

```

---
Tags: 8
---


# Question
Title: Required field not being shown on password reset page
We have a terms and conditions checkbox boolean which is required to create an account. It's created in the Manage Fields section under People. We have set that checkbox to Required, and it works. But when a user goes to reset their password the form cannot be submitted because the field is required but it's hidden from the form. In the manage display for the boolean field it's set to display and shows for the user. Any idea why this field is hidden from users on password reset form but not account creation or their profile page?

# Answer
> 0 votes
Fields setup in the Account profiles only appear on the creation/edit forms for users and not the password reset form.

If you have existing users and just recently added the field, you could set the field for your existing user base with Views Bulk Operations; otherwise they won't be able to edit their accounts/reset passwords until the field has been assigned a value on their user account profiles.

This is also true of content types/nodes, when you add a new field with a default value- the default value will only appear for new nodes and not existing ones; likewise any required fields will prevent edits to the existing content until they are populated.

---
Tags: 7, users
---


# Question
Title: How to disable javascript validation of html5 URL element?
The LinkWidget uses a URL render element, which behaves differently in different browsers. In chrome, there is annoying pop-up, which is out of character with other validation within Drupal where there is an error message at the top of the page and a red border added to the form element.

In order to gain more control over the validation, I'd like to do away with the javascript (i.e. HTML 5) validation. There are various suggestions using javascript or CSS, but they are heavy handed as the most effective method is to set the "novalidate" parameter on the entire form, which loses the benefit of validation on other html 5 elements such as email or dates.

What is a good way to turn this off for link fields that are set to accept external links? (If you also accept internal links, this doesn't happen).

# Answer
One way to do this is to simple not use the URL render element. You can still use its validation, but you replace the URL element with a textfield element.

```
/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getType() == 'link') {
    $settings = $context['items']->getFieldDefinition()->getSettings();
    // If external link, don't use HTML5 URL element, to prevent its annoying
    // pop-ups.  Use a textfield with the backend validation from the URL element.
    if (!empty($settings['link_type']) && $settings['link_type'] == 16) {
      $element['uri']['#type'] = 'textfield';
      array_unshift($element['uri']['#element_validate'], ['Drupal\Core\Render\Element\Url', 'validateUrl']);
    }
  }

```
> 2 votes

---
Tags: 8
---


# Question
Title: Allow special characters in the Search Form
I can't search with any special character in the default search block form or in search API. Commonly used word like *B&W* (black and white) don't seem indexed up well, probably due to some encoding or decoding problem.

>

# Answer
> 1 votes
Drupal's built-in search, as well as Search API, generally search full words. Using Search API, you can further configure the search to match parts of words and consistently ignore special characters in the matching process (as some may reserve other purposes like logical AND / OR).

Based on your use case/example,

* check the minimum character length for search suggestions (it is usually three) (but since it strips away special characters such as the &, your search criteria is only two characters), and
* enable the "Ignore characters" processor and configure it to ignore the ampersand symbol, hyphens, or any others consistently in both the form submission and the search index results as suggested here in this Search API issue post: Special characters are always ignored in searches on DB backend

---

Additional references:

1. Review all the configurable Search API processors to ensure you are indexing your content appropriately: https://www.drupal.org/docs/8/modules/search-api/getting-started/processors
2. Check out this succinct blog post "How to set up search API for partial words in Drupal" that provides a checklist for configuring your Search Index.
3. Consider configuring a search view that reflects a "Single phrase" parse mode to find exact matches with special characters. This *Using Search API, Search API Solr and Facets in Drupal 8* slidedeck provides a good rundown of caveats with Search API for D8.

---
Tags: 8, nodes, forms, search
---


# Question
Title: This works as a module, but think it should go in my .theme file instead
This is some code which we're using to merge together content types into the body of an article:

```
<?php

function remove_p($string) {
  $first_p=substr($string,0,3);
  if($first_p=="<p>") {
    $string=str_replace('<p>','',$string,$temp=1);
  }
  return $string;
}

function custom_press_release_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $node_array = $build['#node']->toArray();
  if ($node_array['type'][0]['target_id'] == 'press_release' || $node_array['type'][0]['target_id'] == 'article') {

    // Get the location entity ID
    $field_name = $entity->get('field_office_location')->getValue();

    $location_id = $field_name[0]['target_id'];

    // Get the location name
    $term_object = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($location_id);

    if(is_object($term_object)) {
      $term_array = $term_object->toArray();
    }

    // Generate output like - December 5, 2017
    $new_time_format = date('F d, Y', strtotime(substr($build['created'][0]['#markup'], 0, -7)));

    // Body text from Drupal
    $old_body = $build['body'][0]['#text'];

    $body = '<p><strong>';
    if (is_array($term_array)) {
      $body .= $term_array['name'][0]['value'] . ', ';
    }
    $body .= $new_time_format . ' – </strong>';
    $body .= remove_p($old_body) . '</p>';

    // Modified body text
    $build['body'][0]['#text'] = $body;

  }

}

```

I think that this would be better done in my theme file, but we weren't able to call the functions we needed within the theme.

Did we just miss something, or is this something that just needs to be done as a separate module?

# Answer
> 2 votes
What you missed is, that you can achieve all that output manipulation by just using the admin UI and view modes. It has the benefit of you being able to adjust the output order and available fields without having to touch any code. And gives you more power and flexibility to administer how content is displayed.

By incident, your solution matches a question answered just recently here: How to modify the value of a taxonomy field of a node using hook\_node\_view()?

Please have a look to my answer there, which describes how to show a field of the the taxonomy terms on the nodes by using the UI.

You can easily adjust the proceedings by e.g. creating a dedicated display mode for your content nodes instead and adding the required fields there.

Additionally, you like to show the formatted created time, which you can either preprocess within a theme's hook\_preprocess\_HOOK() (so for example `yourtheme_preprocess_node()`), but also have already exposed within the template variables as `{{ date }}` in your `node.html.twig` template.

# Answer
> 1 votes
Hooks go in the **.module** file, to my knowledge, the only hooks that can also work in the **.theme** file are preprocess and alter hooks.

---
Tags: nodes
---


# Question
Title: Show comment author e-mail in comment.html.twig
Anonymous users can leave their e-mail when posting a comment but how can I display this e-mail as a plain text value in the comment.html.twig?

# Answer
> 2 votes
> If you have a fresh Drupal 8 standard install, go to: 'People \> Permissions' and Allow anonymous users to 'Post comments' and 'Skip comment approval'. Then go to: 'Structure \> Content Types \> Article \> Manage Fields' and edit the 'Comments' field. Go to 'Anonymous commenting' and select 'Anonymous posters may leave their contact information'. Click 'Save settings'. Now when you go post a comment as an anonymous user you can leave your e-mail.

You can print that e-mail value in plain text like this:

```
{{ content.comment_body['#object'].getAuthorEmail() }}

```

Now, this will print the e-mails of logged in users as well. If you don't want that, then you will need to add a conditional to check if their User ID is 0, which means they are anonymous.

```
{% if attributes.toArray()['data-comment-user-id'] == 0 %}

    {{ content.comment_body['#object'].getAuthorEmail() }}

{% endif %}

```

---
Tags: 8, theming, comments
---


title: Get entities grouped by year

text:
# Question
Title: Get entities grouped by year
Trying to write entity queries with group by condition using `Drupal::entityQueryAggregate`. It works well for simple fields, for example:

```
$query = \Drupal::entityQueryAggregate('node')->condition('status', 1)->condition('type', 'node_type');

$result = $query
      ->groupBy('field_custom_field')
      ->aggregate('nid', 'COUNT')
      ->execute();

```

But now I have to select nodes aggregated by year from custom field and I can't figure out how to do it:

`->groupBy('YEAR(field_custom_date)')` \- doesn't work

`->addExpression('YEAR(field_custom_date)', 'fcd_year')` \- doesn't work

Any ideas how to implement this query?

# Answer
> 2 votes
My final solution, by guidance @CG Monroe:

```
$query = $this->connection->select('node_field_data', 'n');
$query->innerJoin('node__field_date_created', 'fdc', 'fdc.entity_id = n.nid');
$query->addExpression('count(n.nid)', 'nid_count');
$query->addExpression('substring(fdc.field_date_created_value, 1, 4)', 'yr');
$query->condition('n.type', 'my_type');
$query->condition('n.status', 1);
$query->groupBy('yr')->orderBy('yr', 'ASC');
$result = $query->execute()->fetchAll();

```

# Answer
> 0 votes
Drupal has abstracted the DateTime field to a string with an ANSI standard date format. This is part of making Drupal more friendly for non-SQL data storage.

This means the standard SQL date functions will not work.

The date string format is basically YYYY-MM-DDTHH:MM:SS (may vary by granularity).

One solution to using a query to group by year is to add an expression that uses the substring function to get the year from the field and then group by that.

---
Tags: 8, database
---


# Question
Title: how to count results in a Calendar view?
I enable the calendar module, then "Add view from template" on /admin/structure/views/add-template, but I cannot count nodes published at the same day in the month view by following this tutorial. I want events occurred in the same day can be counted like "3 events occurred" other than the original output in the red box, and the counted field can be rewritten.

I tried aggregation feature of views, but no luck.

# Answer
Finally, I get it working. After I turn on View's setting "Show the SQL query", I notice there is an unnecessary GROUP BY field "nid" in the Calendar view, then I unset this field in a hook\_query\_alter(QueryAlterableInterface $query) as below:

```
if ($query->hasTag('views_' . $view_name)) {
    $fields =& $query->getGroupBy();
    unset($fields['nid']);
}

```
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to include task links in twig node template
I have created a custom twig node template. It displays the content in the manner that I want but it is not displaying the task buttons. How do I include the display of the task buttons if the user who is viewing the page has the permission to see them?

I have tried Googling for a solution, but haven't found anything. I figure this should be pretty straight forward to do (at least I would hope it is).

Thanks.

# Answer
> 3 votes
https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-contextual-links The manual says:

Contextual links are stored in title\_suffix. This variable needs to be printed in the html.twig file, such as in this example from block.links.contextual.yml.

```
<div{{ attributes }}>
  {{ title_suffix }}
  ...
</div>

```

---
Tags: 8, theming
---


# Question
Title: Main navigiation layout bugs after adding a cart block
I have a question about some layout problems that I'm having since I installed commerce 2.x on my school project website. I'm using Drupal 8 for this.

You can see that one of the dots between each menu item are gone and another dot is slightly misplaced. Is there a way to restore this or remove all the dots maybe? The domain of my website is designmuseum.vansompel.be

I have been changing some of the css in the most upper sidebar to get the cart block next to the user account menu. Even when I revert these changes, the problem on the main navigation seems to remain. Could it be that my website is doing some automatic layout tweaks because of the new cart block? For example there is also a 10px padding above the cart block that I didn't specify myself and can't seem to find it in the code also.

```
.header-top-highlighted__section .block + .block {
  padding: 10px 0 0 0;
}

```

I'm still pretty nooby at theming so if someone could point me in the right direction, that would be great! Thanks!

# Answer
Looks like those dots are a content on :before of the anchor tag, to remove them you could add this to your CSS files.

```
.header-container ul.menu li a:before {
    display: none;
}

```

This looks like it have been added by Drupal or maybe the theme you are using, i am not really sure, I recommend you read this https://www.w3schools.com/cssref/sel\_before.asp to understand more about the before selector.
> 0 votes

---
Tags: theming
---


title: Custom module access denied

text:
# Question
Title: Custom module access denied
I just have followed two tutorials on Youtube, https://www.youtube.com/watch?v=79zYcIoheCc&t=43s and https://www.youtube.com/watch?v=SAP9clnOf9E&t=8s.

The result was a "You are not authorized to access this page." error.

In the routing file, I have made the correct indentation for both modules.

```
my_module.routing:
  path: '/admin/structure/my_module'
  defaults:
    _title: 'My module'
    _content: '\Drupal\my_module\MyModuleController::test'
  requirements:
    _permisions: 'access administracion pages'

hello_world:
    path: '/hello/world'
    defaults:
        _controller: 'Drupal\hello_world\Controller\HelloWorldController::hello'
    requirements:
        _permisions: 'access content'

```

# Answer
You have a typo in one of the permissions. It should be “administration”. Permissions itself is also spelled incorrectly.

Please refer to the official docs for creating routes and links. YouTube videos may be out of date.
> 1 votes

---
Tags: 8, routes
---


# Question
Title: PHPUnitTest is missing the file_managed table?
My PHPUnit test is throwing an error saying that my `file_managed` test database table does not exist. What module do I need to include for that test table to get created? I would think it should be the `file` module, but I've already got that listed in my $modules array.

This is a Kernel test and I've been trying to fill up the modules array with everything I can think of that might actually get that table created.

```
  public static $modules = [
    'system',
    'path',
    'user',
    'file',
    'file_test',
    'node',
    'field',
    'media_entity',
    'entity',
    'image',
    'graphql',
    'graphql_core',
    'custom_graphql_file_upload',
    'custom_graphql_field'
  ];

```

Here's the error:

```
Invalid GraphQL query. Errors: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'contenta.test87607590file_managed' doesn't exist: INSERT INTO {file_managed} (uuid, langcode, uid, filename, uri, filemime, filesize, status, created, changed) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array

```

I'm trying to test a `graphql` file upload to make sure the file entity gets created as expected. I have a lot more tests I want to write and lot more that needs to be solved with multi-part/form data, etc, but I need to figure this out first I think.

Here's the full test https://github.com/justinlevi/graphql\_custom\_file\_upload/blob/feature/PHPUnitTest\_WIP/tests/src/Kernel/MutationFileUploadTest.php

All other code posted as well on the WIP branch.

# Answer
> 5 votes
Ugh... Forgot to install the entitySchema.

This is how to do it in the setup method

```
  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->installConfig('system');
    $this->installConfig('graphql');
    $this->installConfig('file');
    $this->installConfig('image');
    $this->installConfig('user');
    $this->installEntitySchema('user');
    $this->installEntitySchema('file');

    Role::load(RoleInterface::AUTHENTICATED_ID)
      ->grantPermission('execute graphql requests')
      ->grantPermission('create media')
      ->grantPermission('view media')
      ->grantPermission('access content')
      ->grantPermission('bypass node access')
      ->grantPermission('create url aliases')
      ->save();
  }

```

---
Tags: 8, testing, files
---


title: How do I render the User Login block?

text:
# Question
Title: How do I render the User Login block?
I'm trying with this:

```
$block = module_invoke('user', 'block_view', 'login');

```

It returns an empty array.

# Answer
The `user_block_view()` function has this line in it for the `login` delta:

```
if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

```

If you're logged in, the function will return an empty array, which is probably what's happening in your case.

If that's not the reason (and even if it is) you can get around it by calling the form function directly:

```
$form = drupal_get_form('user_login_block');

```

There doesn't appear to be any extra access checks done in the form function so it should be rendered regardless of whether you're logged in or not.
> 5 votes

# Answer
If you look at the code of user\_block\_view(), the hook you are invoking, you will notice it contains the following code.

```
case 'login':
  // For usability's sake, avoid showing two login forms on one page.
  if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

    $block['subject'] = t('User login');
    $block['content'] = drupal_get_form('user_login_block');

```

The login form is shown only for the anonymous user, and when the user is looking at example.com/user.

Both the restrictions make sense because:

* An authenticated user cannot log in without first log out. In that case, it doesn't make sense to show the log in form when the user could not use it. It would also make the users think they are not logged in when they are.
* example.com/user, for not logged-in users, already shows the login form. It doesn't make sense to show it twice.
> 3 votes

# Answer
If above answer did not solved your problem somehow, try this:

```
if (user_is_logged_in()) {
echo "not logged in";
}
else{

echo drupal_render(drupal_get_form('user_login'));
}

```
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: hierarchical select in user registration form
I have a vocabulary "school" which has these fields.

School Name:

School Type:(male/female)(term reference)

School City:(term reference)

Now, I need to add the school term reference in the registration process. I used profile2 and added the below vocabularies as a select list.

-School Type

-School City

-School Name

I need to filter the school name based on type and city.

```
show schools in the select list where type= female and city = xyz

```

Something like hierarchical select but how this all be applied in above case?

# Answer
> 0 votes
Your taxonomy architecture is not hierarchical as city and type are in same term as school name is. if you want to use hierarchical select you need to define you vocabulary as follows :

* Male
    + city\_1
        - school\_1
        - school\_2
    + city\_2
        - school\_3
* Female
    + city\_1
        - school\_4
    + city\_2
        - school\_5

but if you prefer the current structure you can create a view (entity reference view mode) which takes two argument and filter school taxonomies and then in your form use Dynamic Dependent Fields so you can pass city and type as argument to your view and view will do the rest job for you.

---
Tags: users, taxonomy-terms
---


title: User registration email translation

text:
# Question
Title: User registration email translation
I am working on an English/Arabic website, the user can switch between the two languages using the language switch block, I wanted to translate the email sent to the user after registration. So after some digging, I figured out I could do this using the account setting (translate tab), I added the Arabic translation of the email; then, after testing, I found out that the registration email is still sent in English.

Shouldn't a user registered in the Arabic language get an Arabic registration email?

I also found out that the user's preferred language is English, even after registering in the Arabic language.

These are my language detection settings.

>

# Answer
> 1 votes
As you said you have configured the translations correctly. On the account settings page you will be able to see the **Translate Settings** tab here `/admin/config/people/accounts`

After clicking on the link here you will find the enabled languages with options in front of them

Click on edit and then you will be able to see all the Account settings to be translated including mail where you can `write / modify` the text in mail like in following screenshot.

---
Tags: 8
---


# Question
Title: Migrate existing dev desktop site from PC to Mac without existing db dump
I have a PC with dev desktop on it where I had a local install of a drupal 7 site. I needed to reinstall windows on the PC and it wiped out my local install except I kept the old windows files, so I have access to the original site files.

What I don't have is a database dump of the local install.

With the old files, is there a way I can find the database table data? I can see in the old install of dev desktop the mysql/data content for the site, but I think I need additional files to complete the database tables, etc.

Thanks.

# Answer
> 0 votes
DevDesktop stores the mysql databases in its application installation folder. Assuming, you installed to the default location, in your PC backups, navigate to ***C:\Program Files (x86)\DevDesktop\mysql\data*** This folder contains a copy of the MySQL databases.

* **Restoring to PC for use or export:**

1. On the PC (assuming you haven't installed any other devdesktop sites), copy all the files and folders from the mysql/data backup directory into a fresh install's MySQL's data directory.
    2. For export: Start MySQL and export a copy for backup purposes/importing elsewhere as needed.
    3. For immediate use/development on PC: Start MySQL and your DevDesktop to confirm the site is running; resume normal dev desktop development on PC
* **Loading directly to a fresh install of DevDesktop, MAMP, Vagrant, or other MySQL service on Mac**

1. You could also copy the contents of that backup folder directly to the corresponding mysql/data backup directory on your Mac. NOTE: copying the entire directory will wipe all existing databases/user accounts in MySQL on your Mac's MySQL server, be sure to back it up first if you have existing data). If it's a fresh install of DevDesktop (or other) on the Mac, copy all the files and folders from the mysql/data backup directory of the PC to the corresponding folder on the Mac.
    2. Start DevDesktop or other local webserver app to confirm the site is running; resume normal dev desktop development on Mac
* **Merging with existing mySQL data, hosting database along side others on existing install of DevDesktop, MAMP, Vagrant, or other mySQL service on Mac**

1. If you do have existing MySQL data on the Mac (be it MAMP, DevDesktop, Vagrant instance or other), backup the corresponding /mysql/data folder from that application.
    2. Replace with the backup folder from the PC
    3. Start MySQL and export the database.
    4. Then swap the original Mac MySQL data back into place.
    5. Restart MySQL and import the database backup you just exported.
    6. Now you have both your PC devDesktop database and Mac databases available on the Mac.

---
Tags: migrations
---


# Question
Title: How do I remove the page title only from the front page?
I have created a basic page and assigned it to the front page. Now I would like to remove the title shown in the front page.

>

How can I achieve this?

# Answer
> 2 votes
The Title is a Block now in Drupal 8. You can edit the Page Title Block and set it to show on all paths except for `<front>` to hide it from the front page.

---
Tags: 8
---


# Question
Title: Failure to add content (/node/add/recipe) instead says "This page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500"
I am trying to add a node (/node/add/recipe), but it doesn't get saved. Instead, I get the following error message.

> This page isn't working
> localhost is currently unable to handle this request.
> HTTP ERROR 500

I get no log messages associated to this attempt to add content. I went into `node_save()` to see how far it went, and it appears to stop near the beginning at `$transaction = db_transaction();`.

I have output `$node` to look for any clue.

Any suggestions on things I could try would be appreciated.

# Answer
> 1 votes
A few things you could try to debug the issue, as it appears limited to just this one "recipe" content type on your site (presuming you have a local running copy of the site):

1. Enable php error logging in your site's settings.php as described here https://www.drupal.org/docs/7/creating-custom-modules/show-all-errors-while-developing
2. Flush your Drupal cache, then try adding a recipe node.
3. Upon saving, you should see php errors output to the browser, and you can `tail` the apache logs. This should help you further narrow down the cause of the error.

More than likely, one of the following is the culprit on saving your content:

* There's a reference type/entity/field whose dependency has been accidentally deleted or modified (sometimes a machine name change, or settings change to a field widget can cause this, especially if there was data already present in that field)
* A database field table has been corrupted/accidentally changed or deleted. This can happen if you installed some updated modules/Drupal core code without properly running updates from the *"Run Updates"* menu link or via `drush updatedb`
* If you're uploading image(s) as part of the content, make sure they are optimized for the web and not gigantic in dimensions. Overly large images can freeze up/lock up on image cache generation due to limited memory.

---
Tags: nodes
---


# Question
Title: How to allow users to edit the profile of users in the same department?
Department is a term reference or a list (text) field of the user entity. I want to let managers edit the profiles of users in the same department as the manager.

I know I should define a custom permission, but in which hook should I check this custom permission?

# Answer
> 3 votes
In Drupal 7 if you want to change the access check for any path you need to use hook\_menu\_alter.

After you change the access callback you can write your own code which does the check you want.

You just need to be careful so you don't override access callback with a bad check.

What I suggest here is to keep the original function which does the access callback user\_edit\_access check in your custom callback function.

I wrote sample code which gives you an idea which direction to go:

```
/**
 * Implements hook_permission().
 */
function example_permission() {
  return array(
    'edit own department users' => array(
      'title' => t('Edit own department users'),
      'description' => t('Allowed department manager to edit own department users.'),
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function example_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'example_custom_user_edit_access';
}

/**
 * Custom access callback for user account editing.
 */
function example_custom_user_edit_access($account) {
  if (user_access('edit own department users')) {
    // We perform our check only for user with edit own department permissions.
    global $user;

    // Load user ( Department manager) via entity api.
    $user_wrapper = entity_metadata_wrapper('user', $user);

    // Get array of managed department terms id.
    $user_departments = $user_wrapper->field_user_department_managed->value();

    // Load user (Editor) via entity api.
    $account_wrapper = entity_metadata_wrapper('user', $account);
    // Get array of department belongs to terms id.
    $account_departments = $account_wrapper->field_user_department_belongs->value();

    // Check any common term id.
    $common_departments = array_intersect($user_departments, $account_departments);

    return !empty($common_departments);
  }
  // For other user we perform default check.
  return user_edit_access($account);
}

```

---
Tags: 7, users
---


# Question
Title: Moving drush installed directory to production site?
I am installing Open Social on Drupal 8 on my own Ubuntu Linux instance with Nginx, MySQL and PHP 7. Got the "Quick install" instructions using composer and drush completed successfully.

As a relative n00b to Drupal, there is a small gap in the documentation. You can complete an installation on a server using `drush` and you get a "site built" message - with everything in a directory in my user account. I'm looking at that, and looking at `/var/www/html` (which is where my public facing web server successfully serves traffic) and I think - eh - what now? The documentation does an exit stage left right there.

Same in the standard Drupal docs. The main clue is where you get vectored off to the procedure to create a dev site from a running production one (ie: the wrong way around). Which sort of suggests that you put the whole tree in the `/var/www/html` directory into an `html/` subdirectory, but then hand edit `settings.php` to match the database credentials on your newly restored db backup.

So, to get the site running internet facing, is it as simple as moving the whole tree in my local directory under `html/` to `/var/www/html` recursively, and then dragging a `settings.php` file up to the top level from `./sites/default/settings.php`, then editing in the database credentials?

If I do move the website wholesale, nginx just http 500's the web site. Just working through some of the directory assumptions that composer uses... getting `autoload.php` failing to find a file at line 17.

# Answer
The answer is that you have to copy the `html/` and `vendor/` directory trees from your project under `var/www`, and in theory it works. Except for me that it doesn't, as it just steps onto the next error where the stylesheet doesn't load properly (error in MIME types)... but that's the next story!
> 0 votes

---
Tags: 8, drush, installation
---


title: Pass variable to drupalSettings

text:
# Question
Title: Pass variable to drupalSettings
I'm using Drupal 8.

What I'm trying to do is:

* Access the active node
* From the node get the value of `field_test` and assign it to a variable
* Pass the variable to the drupalSettings function and subsequently to a custom module 'mycustommodule' that triggers an alert

In my content type, I created a `field_test` field, which is the field I reference in my code. The block is placed on a page of this content type.

This is the code I am using.

### mycustomblock.libraries.yml

```
custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

### MyCustomBlock.php

```
<?php
/**
 * @file
 *
 */

namespace Drupal\mycustomblock\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Creates a 'Foobar' Block
 *
 * @Block(
 * id = "block_mycustomblock",
 * admin_label = @Translation("MyCustomBlock"),
 * category = @Translation("Blocks")
 * )
 */
class MyCustomBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */

  public function build() {

  // get the variable from field_test
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $test = $node->field_test->value;
      $variables['#attached']['library'][] = 'mycustomblock/custom';
      $build['#attached']['drupalSettings']['mycustomblock']['test'] = $test;
    }
}

```

### custom.js

```
(function ($, Drupal, drupalSettings) {
  var testMe = Drupal.settings.mycustomblock.test;
  alert(testMe);
)(jQuery, drupalSettings);

```

How can I tell if the JavaScript file is being loaded from the block? I checked in the inspector, and do not see it being loaded when the page with the block on it loads.

Furthermore, how can I properly access the field value and pass it to JavaScript?

# Answer
The code doesn't work because the `build()` method doesn't return anything, which for PHP is like returning `NULL`. (In other words, you are telling Drupal not to render anything.)
If you fix that, then you would also have to add the library to the render array returned from `build()` (`$build['#attached']` in the following code).

```
public function build() {
  $build = [];
  // get the variable from field_test
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $build['#attached']['library'][] = 'mycustomblock/custom';
    $build['#attached']['drupalSettings']['mycustomblock']['test'] = $node->field_test->value;
  }

  return $build;
}

```

As a side note, class names that follow the Drupal coding standards should use the UpperCamel naming, a.k.a. PascalCase.

For the JavaScript code, take node.js as guide.

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.nodeDetailsSummaries = {
    attach: function attach(context) {
      var $context = $(context);

      $context.find('.node-form-author').drupalSetSummary(function (context) {
        var $authorContext = $(context);
        var name = $authorContext.find('.field--name-uid input').val();
        var date = $authorContext.find('.field--name-created input').val();

        if (name && date) {
          return Drupal.t('By @name on @date', { '@name': name, '@date': date });
        } else if (name) {
          return Drupal.t('By @name', { '@name': name });
        } else if (date) {
          return Drupal.t('Authored on @date', { '@date': date });
        }
      });

      $context.find('.node-form-options').drupalSetSummary(function (context) {
        var $optionsContext = $(context);
        var vals = [];

        if ($optionsContext.find('input').is(':checked')) {
          $optionsContext.find('input:checked').next('label').each(function () {
            vals.push(Drupal.checkPlain($.trim($(this).text())));
          });
          return vals.join(', ');
        }

        return Drupal.t('Not promoted');
      });
    }
  };
})(jQuery, Drupal, drupalSettings);

```

Drupal modules should use behaviors.

See the first and the last line of the code I quoted. Your JavaScript code should use the same lines, and access the settings with `drupalSettings.mycustomblock.test`.
> 16 votes

---
Tags: 8, javascript, blocks
---


title: Add body class if a block is present

text:
# Question
Title: Add body class if a block is present
I need to add a body class if a block or menu is present on the current page on Drupal 8. Probably this should be done on `template_preprocess_page()` or `template_preprocess_html()`.

# Answer
A block is visible in a page depending on two conditions:

* None of the condition plugins associated to the block marks the block as not visible
* The current user has the permission to see the block

Assuming the block is visible at a specific path is wrong because the current user could simply not have the permission to view it. Adding to that the fact that any third-party modules could define new condition plugins, the only way to avoid duplicating in code the block settings done from the user interface is using code similar to the following one.

```
function mymodule_preprocess_html(&$variables) {
  // Replace 'block_id' with the ID of your block.
  $block = Block::load('block_id');
  if ($block && $block->access('view')) {
    // The block is visible to the current user.
    // Replace 'the-class-to-add' with your CSS class.
    $variables['attributes']['class'][] = 'the-class-to-add';
  }
}

```

Remember to add the correct `use` statements on the top of the file containing that code (e.g. `use Drupal\block\Entity\Block;` to be able to access the block entity class).
> 6 votes

# Answer
You can only add classes to the body tag in template\_preprocess\_html() hooks. Blocks are only built in page.html.twig, so they are not yet visible here. But blocks have visibility condition, and you should use that condition here, for example the path.

```
function THEMENAME_preprocess_html(&$vars) {
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path == 'path/where/block/appears') {
    $vars['attributes']['class'][] = 'class-name';
  }
}

```
> 2 votes

# Answer
Thanks, both answers are right, but while I was trying @kiamlaluno suggestion I realized the block didn't had any condition setup since it was a menu block, so it's always enabled.

I ended up checking if the current page is a children of the menu block I want to target.

```
$menu_tree = Drupal::menuTree();
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters('main');
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

foreach ($main_menu_top_level as $sub_tree) {
  if($sub_tree->inActiveTrail){
    $vars['attributes']['class'][] = 'your-class-here';
  }
}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to retrieve data from custom table in database?
I created a custom table in my modules .install file and I am asking for some form input in a custom made configuration file. I am unable to retrieve that data and print it out in a custom callback page that i created for testing. I'm not quite sure what i am doing wrong.

```
<?php
/* mymodule.install */
function mymodule_schema(){
  $schema['mymodule'] = array(
    'description' => 'Table for testing',
    'fields' => array(
      'pmid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'field_one' => array(
        'description' => 'Field 1',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => ''
      ),
      'primary key' => array('pmid'),
      'unique keys' => array(
        'pmid' => array('pmid'),
      ),
     ),
   );

/* mymodule.module */
function mymodule_form_submit($form, &$form_state){
  db_insert('mymodule')
  ->fields(array(
    'field_one' => $form_state['values']['field_one'],
    'pmid' => 1,
  ))->execute();
}

function mymodule_print_table(){
$result = db_select('mymodule', 'mm')
       ->fields('field_one')
       ->execute()
       ->fetchAll();
var_dump($result);
}

```

This prints an empty array for me.

EDIT:

I incorrectly assumed form\_submit was a hook and didn't add it to my form.

```
function mymodule_form($form, &$form_state){
$form['field_one'] = array(
    '#type' => 'textfield',
    '#title' => t('Field One'),
    '#default_value' => '',
    '#description' => t('Field One Test'),
    '#required' => true,
  );
//This was missing
$form['#submit'][] = 'mymodule_form_submit';

return system_settings_form($form);
}

```

# Answer
> 3 votes
The `fields` method takes a table name/alias as its first arg, and an array of field names as its second:

```
$result = db_select('mymodule', 'mm')
   ->fields('mm', ['field_one'])
   ->execute()
   ->fetchAll();

```

---
Tags: 7, database
---


# Question
Title: Drupal Behaviors uncaught reference error
I'm using Drupal 8.

What I'm trying to do is:

* Access the active node
* From the node get the value of `field_test` and assign it to a variable
* Pass the variable to the drupalSettings function and subsequently to a custom module 'mycustommodule' that triggers an alert

In my content type, I created a `field_test` field, which is the field I reference in my code. The block is placed on a page of this content type.

This is the JavaScript code I am using.

### mycustomblock.libraries.yml

```
custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

### custom.js

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.mycustomblock = {
    attach: function (context, settings) {
      var testMe = drupalSettings.mycustomblock.test;
      alert(testMe);

  }
};
})(jQuery, Drupal, drupalSettings);

```

The error I get from the JavaScript console is this.

The error message is referring to this line.

Why is the instance of Drupal in the closing parenthesis throwing this error?

# Answer
You will have to add the core library `core/drupal` to your library dependencies. This assures, that the Drupal core JavaScript is loaded before your custom module's JavaScript will be executed.

So your **mycustomblock.libraries.yml** should look like:

```
custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```
> 6 votes

---
Tags: 8, javascript, blocks
---


# Question
Title: Passing taxonomy term through drupal_html_class() and use it as row class name
In a view I would like to use a excluded term reference field as source for the the row classname. But the values need to be sanitized by putting the term names through `drupal_html_class()`, otherwise the resulting classnames are not valid in every case.

How can I sanitize the values using a preprocess function?

# Answer
> 0 votes
I got it working by using this preprocess function:

```
function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'field_category') {
      $tid = $variables['row']->_entity->field_category->target_id;
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->getName();
      $variables['output'] = \Drupal\Component\Utility\Html::cleanCssIdentifier($name);
    }
  }
}

```

An alternative would be using `mytheme_views_pre_render`.

---
Tags: views, hooks
---


# Question
Title: how to display/hide block on homepage depending the value in user profile field?
I'm currently displaying a block on my D7 site' homepage.

Now I've a requirement to display that block only if the logged in user has a specific value in their profile.

I know it can be done using php evaluation by navigating to the bottom of the block and then click (Pages \> Pages on which this PHP code returns TRUE ) but have no experience in writing php scripts.

```
global $user;

If($user->your_profile_field_value == 'requiredvalue')
{
// display the block
// display the block only on 'homepage' }
Else { // don't display the block }

```

I'm new to php can someone please help me fill in the blanks in above code snippet.

thanks

# Answer
> 0 votes
I would use the PHP visibility settings to display the block if user has requiredvalue. Once you've created the block that you want to display (or not display) add the following code to the "Page specific visibility settings" in the block configuration menu:

```
 <?php
    global $user;

    If($user->your_profile_field_value == 'requiredvalue' && drupal_is_front_page()) {
    return TRUE;
    }

    return FALSE;

    ?>

```

# Answer
> 0 votes
you can create custom module and implement this code

```
 /**Implementation of hook_preprocess_HOOK().  */

 function mymodule_preprocess_page(&$variables)
 {
  global $user;
  if($user->your_profile_field_value == 'requiredvalue')
  {
     if (drupal_is_front_page()) {
         return TRUE;
        // for front page only condition
     }
    // your code
  }
 }

```

you can also add this in your current enable theme by just replace

`mymodule` to your `themename`

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


title: Colorbox after ajax load

text:
# Question
Title: Colorbox after ajax load
I've created a custom module that updates content in my page via an ajax call. I tried it do it with only views but it was too complex because I was loading multiple content types based on organic groups.

So I have a view that I'm rendering from code and in that view I have a colorbox trigger. The ajax works and the view gets rendered but I cannot figure out how to properly process the inline-colorbox. Right now it seems to create the colorbox but fills it with default content from the frontpage so I'm not sure what I'm missing.

I re-init the colorbox after the ajax is loaded in the success and it does process the field.

JS Code

```
(function ($) {
Drupal.behaviors.forums_dashboard = {
attach: function (context) {

  // If changing the select field
  $('#cohort-select-value', context).change(function () {
        var cohort = $(this).val();
        var dataString = "cohort=" + cohort;

        $.ajax({
          url: '/ajax/coaching_summary',
          type: "POST",
          data: {cohort_id: cohort},
          success: function (response) {
            $('#coaching_summary_ajax').html(response);

            //reinit the colorbox
            $('.colorbox-inline').colorbox();
          }
        });
      }
  );
}
}
})(jQuery);

```

Ajax code in my module:

```
function forums_dashboard_menu() {
// Ajax callback
 $items['ajax/coaching_summary'] = [
  'title' => 'Update Coaching Summary',
  'page callback' => 'forums_dashboard_update_coaching',
  'access arguments' => ['access content'],
  'type' => MENU_CALLBACK,
 ];
 return $items;
}

```

function used to print the view is:

```
print views_embed_view('cohort_user_list','default',$args);
drupal_exit();

```

here is the html i get after ajax is called

```
<div class="views-field views-field-colorbox">
 <span class="field-content">
  <a href="/?width=400px&height=400px&inline=true#colorbox-inline-549561640" class="colorbox-inline cboxElement" rel="">

  </a>
  <div style="display: none;">
   <div id="colorbox-inline-549561640">
    <div class="contact_box"></div>
   </div>
  </div>
 </span>
</div>

```

Edit: I forgot to add versions Drupal 7.56 Colorbox 7.x-2.13 Views 7.x-3.18

Update: I decided to use a separate page view for the content to load instead of trying to do it inline. Here is the new cleaned up jquery

```
(function ($) {
Drupal.behaviors.forums_dashboard = {
attach: function (context, settings) {

  // If changing the select field
  $('#cohort-select-value', context).change(function () {
    var cohort = $(this).val();

    $.ajax({
      url: '/ajax/coaching_summary',
      type: "POST",
      data: {cohort_id: cohort},
      success: function (response) {
        $('#coaching_summary_ajax').html(response);
        $('a',context).colorbox();
      }
    });
  });
}}}(jQuery));

```

The ajax now returns it as follows to create the URL for a colorbox-node link instead which links to the page with the UID as a parameter:

```
<a href="/user_popup/95?width=400&height=400" class="colorbox-node cboxElement"><div class="left">Test User 1</div><div class="right">100 Hours</div></a>

```

My problem now is that the first time I click the link it displays the entire page with header/footer instead of just the node content which colorbox-node should be doing. If I close the colorbox and click the link a second time it displays only the node content as expected. The colorbox URL gets updated when its clicked the first time. I'm not sure how to replicate this colorbox process so that it works the first time as expected. Here is the new link after its clicked a first time.

```
<a href="/user_popup/95?width=400&height=400" class="colorbox-node cboxElement init-colorbox-node-processed-processed"><div class="left">Test User 1</div><div class="right">100 Hours</div></a>

```

# Answer
Here is the updated jquery code that renders the colorbox properly the first time:

```
success: function (response) {
        $('#coaching_summary_ajax').html(response);
        $('.colorbox-node',context).once('init-colorbox-node-processed',function () {
          $(this).colorboxNode({'launch': false});
        });
        $('.colorbox-node',context).colorbox();

      }

```
> 0 votes

---
Tags: views, javascript, ajax
---


# Question
Title: Access to the url of a node from another one
I'm a bit stuck there ! here what i do :

I have two content types : Ad Lock, Ad complete. When a user create a node Ad Lock, i use rules to clone it and then convert the original in Ad complete.

So now i have two nodes in two different content types.

Now i need to copy the url of Ad complete to fill a field in Ad Lock. Is this possible ?

Thanks in advance guys !

# Answer
> 0 votes
Ok so my mistake was : that i used a module called "url field" and it was not recognise by rule. With a normal text field i can copy the link i want

---
Tags: nodes, rules
---


# Question
Title: Aliases stop working after composer install
We have added some drush aliases for a multi-site project, the aliases were converted from the previous syntax to the Drush 9 syntax (.yml files).

I went over the documentation, and also saw the previous issues, notes and changes on this GitHub issue.

For some reason the aliases didn't work inside `$ROOT/../drush/sites` as documented, but did work inside `$ROOT/drush/sites`, and I also had to use the format of `[site].alias.yml` and not `[site].site.yml` as on the documentation.

Another thing is that @greg-1-anderson wrote on his comment that

> Only ~/.drush/sites et. al. are searched now.

So now I am really lost between the documentation, the comments, and the aliases that **worked last week** and were broken now after composer install.

Can someone please tell me what am I missing here?

\** I've also tried to place the aliases in `~/.drush/sites/` (which didn't work).

# Answer
> 8 votes
Drush has undergone some change in behavior to simplify the implementation and increase maintainability ahead of the stable release.

* Rename `[site].alias.yml aliases` to `[site].site.yml`
* Spit apart `[sites].aliases.yml` (no longer supported) into multiple `[site].site.yml` files
* Run `drush init` if you would like to maintain global alias files.

If `$ROOT/../drush/sites` is not working, perhaps you do not have a Composer-managed site. The actual supported locations for aliases is `__DRUPAL_ROOT__/drush/sites` and `__PROJECT_ROOT__/drush/sites`. The project root is where the composer.json file is located, which is usually at `$ROOT/..`. It might be clearer if the documentation were updated to describe the supported locations in terms of the Drupal root and Project root, as this is now the basis for finding these directories.

---
Tags: drush
---


title: Set views exposed filter using url

text:
# Question
Title: Set views exposed filter using url
In a view an exposed filter of type taxonomy reference exists, the referenced taxonomy vocabulary contains about 15 terms, the functionality I'm trying to get is to allow user call view with a default value for filter, so if user enter the path `sitename/view-name/term-name` the view would be load with entities of term `term1`.

I used contextual filter for limiting entities to those having specific `term-name` but the problem is, if user selects another term name, rather than the one specified in contextual filter, the view returns no result (term reference in node accepts only one value).

So I wanted to know if there is a solution to set the exposed filter default value based on url?

# Answer
Well after some research I could found the answer. Actually drupal itself do provide such functionality and there is no need to code or ...

When exposing a field as filter to user, in filter settings window a filter identifier can be set (this can't be empty and is filled with field name by default), this is shown in image below :

in above example the identifier is set as `cat`, in this situation the path `sitename/view-address/?cat=term-1` will load the view with my exposed filter assigned as term-1 and corespond entities.
> 1 votes

---
Tags: 8, views, path-aliases
---


# Question
Title: How do I add tabledrag with 'weight' to admin form
I have built a fairly basic module but i'm struggling with the UX of the admin form. Essentially I need a list of items that have several values; a textfield, checkbox, select list and a button to delete them.

I've built all of the functionality (including the "add one more" using the example in the drupal ajax examples module) and its working great, except now I need to be able to reorder the items and the webmin style up/down buttons are not good UX. I've been hacking to no avail at numerous examples like: http://www.urbaninsight.com/2012/09/11/creating-table-with-draggable-weights-in-drupal-7

It doesn't appear that `theme_hook_form` is being called so I can't inject the weight javascript, styles or markup.

I added this to the .module file:

```
function module_cache_theme() {
  dpm("themehook");
  return array(
    'theme_module_settings_form' => array(
      'file' => 'module_form.inc',
      'arguments' => array('form' => NULL),
    ),
  );
}

```

The menu item is in the hook\_menu:

```
  $items['admin/config/development/module'] = array(
    'title' => 'module',
    'description' =>'',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_settings_form'),
    'access arguments' => array('administer site configuration'),
    'file' => 'module_form.inc',
  );

```

When the cache is regenerated I get a dpm message but the method `theme_module_settings_form` is never being triggered.

Ideas?

# Answer
At the risk of oversimplifying, have you tried using or integrating Draggable Views?

If the items you are sorting are nodes (I'm not clear on this) it is a great option for achieving drag-and-drop sorting as you can assign as many fields to an entity as you'd like and set different sort priorities depending on the circumstances. That as apposed to 'weight' which is a one size fits all number.
> 0 votes

# Answer
Have a look at how Sharerich is implementing it. The example is a CTools integration but it can be applied to any form.
> 0 votes

---
Tags: 7, forms, users
---


title: How do I get $node->body $node->teaser?

text:
# Question
Title: How do I get $node->body $node->teaser?
I'm migrating a large custom module and theme from Drupal 6 and can't work out how to convert references to `$node->body` and `$node->teaser` since they are no longer fields in the node object, right?

# Answer
Use this code in a preprocess hook:

```
$node = \Drupal::entityManager()->getStorage('node')->load($nid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$variables['node_full'] = $view_builder->view($node, 'full');
$variables['node_teaser'] = $view_builder->view($node, 'teaser');
$variables['body_full'] = $node->body->view('full');
$variables['body_teaser'] = $node->body->view('teaser');

```

And in twig

```
{{ node_full }}
{{ node_teaser }}
{{ body_full }}
{{ body_teaser }}

```

Use the rendered node and configure the view modes full, teaser or a custom view mode. The single rendered field does not work well with other code.
> 10 votes

# Answer
I've made some progress. It seems that

```
{{ node.body.value|raw }}  ** unsafe! **

```

works well but I guess it skipping input filters, and

```
{{ node.body.value }}

```

shows the markup. Not quite sure how to get the body with input filters but not escape the markup.

**Safety notice:**

Don't use the raw filter if you cannot guarantee that the value is safe from unwanted user input!
> 0 votes

# Answer
You can get the body in twig via:

```
{{ content }}

```

After adding this to your THEME.theme file:

```
function THEME_preprocess_node(&$variables) {
  $node = &$variables['node'];
  $node_array = $node->toArray();
  $variables['node_teaser'] = $node_array['body'][0]['summary'];
}

```

You can pull it up in templates/node.html.twig with:

```
{{ node_teaser }}

```
> 0 votes

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


# Question
Title: How do I parse application/vnd.surveymonkey.response.v1+json?
I recently asked a question about setting up SurveyMonkey webhooks here: https://drupal.stackexchange.com/questions/252571/surveymonkey-v3-webhook-callback

After laborious troubleshooting, I've determined that the issue is that I need to be able to parse the request as application/vnd.surveymonkey.response.v1+json.

How do I do that?

There's no option to add this type of parser, or a custom parser, in the REST server config. Googling for a few hours has come up with nothing. In a Drupal REST endpoint, how can I use this parser type?

# Answer
So the answer is to use hook\_rest\_server\_request\_parsers\_alter(). This way, the `application/vnd.surveymonkey.response.v1` Content-Type can be mapped to the standard JSON parser.

```
function MY_MODULE_rest_server_request_parsers_alter(&$parsers) {
  $parsers['application/vnd.surveymonkey.response.v1+json'] =  'ServicesParserJSON';
}

```
> 0 votes

---
Tags: 7, services
---


# Question
Title: How to add more image styles to an image element in a content type
I have a image field in my content type. In that field the images should be saved in two image sizes. As an example when I uploaded a photo it should save as two photos. One for 200x200 px and one for 360x360 px.

When I change the `function settingsForm(array $form, FormStateInterface $form_state)` in **ImageWidget.php** as below it applies to the all image tags in content types.

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

    $element = parent::settingsForm($form, $form_state);

    $element['preview_image_style'] = [
      '#title' => t('Preview image style'),
      '#type' => 'select',
      '#options' => image_style_options(FALSE),
      '#empty_option' => '<' . t('no preview') . '>',
      '#default_value' => $this->getSetting('preview_image_style'),
      '#description' => t('The preview image will be shown while editing the content.'),
      '#weight' => 15,
    ];

    $element['main_image_style'] = [
      '#title' => t('Main image style'),
      '#type' => 'select',
      '#options' => image_style_options(FALSE),
      '#empty_option' => '<' . t('no preview') . '>',
      '#default_value' => $this->getSetting('main_image_style'),
      '#description' => t('The main image will be shown when opening the popup.'),
      '#weight' => 14,
    ];

    return $element;
}

```

I need to do this only for a selected content types selected image field. Is there a way to do this?

# Answer
Instead of altering the default field widget of the image fields, you should create an own custom field widget.

You may either extend the existing widget, or create it from the scratch by copying the image field widget's code to your own widget.

Then you will be able to just select that widget for your images that require two image styles to be selected, while other image fields can still use the default widget.

Edit:

For defining the different image styles for output to the end user (within your slider), you will be better off to creating a custom field formatter with according settings and output and choosing this formatter in "Manage display" of your content type. A good starting point once again is the existing field formatter.
> 1 votes

---
Tags: 8, nodes, media
---


# Question
Title: How do I add local tasks menu to a views page display
I have created a views page display that has the path /node/%node/sessions, contextually filtering by content ID. It also creates a "menu tab" called "Sessions".

Therefore when I got to node/12 I see a local tasks menu: "View / Edit / Sessions" etc.

When I go to /node/12/sessions I see my view, filtered correctly by 12, but WITHOUT any local tasks tabs.

How should I make a local tasks menu appear on the view page node/12/sessions, (with the local tasks the same as the node/12 but with the sessions tab as active)?

Using this entry in my\_module.links.task.yml succeeds in adding an entry to the node local tasks (still present if 'no menu' is selected in view UI). But it doesn't add the node local tasks to the views page.

```
view.event_sessions.page_1:
  title: Sessions
  route_name: view.event_sessions.page_1
  base_route: entity.node.canonical

```

Using views.view.event\_sessions.page1 as the route throws a route not found error (although that is usually the correct route for a views page, so that's weird).

# Answer
@Eyal was right. Some information:

* Find the current route : `/devel/routes` gives you all the registered routes.
* Or better : use the **devel** module & **web profiler** submodule to display the Symfony2 toolbar, you will have a lot of useful information, especially the **current route**.

> You should find a route name as `view.my_page.page_1` for example.
* Create a `modulename.links.action.yml` (or `modulename.links.local.yml`) with this content:

```
view.my_page.page_1:
  route_name: view.my_page.page_1
  title: My button title
  appears_on:
    - view.my_page.page_1

```
> 1 votes

# Answer
I created a view at `/node/%node/authors` that just lists the author of the node. I did not create a menu link in the views ui.

In `MODULE.links.task.yml`, I have:

```
view.authors.page_1:
  title: Authors
  route_name: view.authors.page_1
  base_route: entity.node.canonical

```

After clearing the cache, I have an Authors tab on the node, and when I'm on the views page, I have the usual view, edit, etc tabs.
> -1 votes

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


# Question
Title: Is it better to create a taxonomy term using the 'create' method of the base Entity class or the entity storage manager?
I've seen multiple ways to programmatically create entities.

In this case I'm creating a taxonomy term. One is using this method

```
$term = \Drupal\taxonomy\Entity\Term::create([
  'name' => $name,
  'vid' => $vocabulary,
])->save();

```

Where I'm using the base entity class's public static create function. Another way to perform the action is using an entity storage manager. Like so:

```
$term = [
  'name'     => $name,
  'vid'      => $vocabulary,
];

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term);

```

I looked up the 'create' function of the base Entity class and it seems to just be implementing what appears in the second example I provided. Is there a better practice between the two? Or does it not matter?

UPDATE: Also is there a difference between what the two return? Unless I'm doing things wrong I noticed that the top method returned an int which I'm assuming is the term id.

# Answer
> 2 votes
Actually, there is a difference between the two shown snippets: The first will end up containing, in `$term`, either `SAVED_NEW` or `SAVED_UPDATED` because that is the value returned from `Entity::save()` (and from `EntityStorageInterface::save()`, indirectly used from the first).

So, also for the second snippet, writing it as follows would be an error.

```
$values = [ /* values to set for the taxonomy term */ ];
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($values)->save();

```

The correct code to use in the first case would be the following one, especially if `$term` is later used (e.g. passed to a function).

```
$term = Term::create([
  'name' => $name,
  'vid' => $vocabulary,
]);

$term->save();

```

(Don't forget to add the right `use` statement, which should always go on the top of the file containing the code.)

As for using one or the other snippet, you will often find Drupal code using `Node::create()`, `Term::create()`, or `Vocabulary::create()` in tests, which is (IMO) preferable than using the other snippet you are showing because at least it doesn't directly use the `\Drupal` class. (Just run `grep -rnwI ./ -e Term::create` from Bash in the directory containing Drupal core code, and you will see how many times it is used.)

Probably, after \[meta\] Replace \Drupal with injected services where appropriate in core is marked as fixed, there will be no reason to avoid using methods like `Term::create()`, which has still the pro to be clearer and shorter.
In any case, if the service I want to use is already available in a class property, or I can inject the service I need in the class I am using, I would rather use that property or inject the service, instead of using a static/global property, directly or indirectly. (Dependency injection is preferable to global properties.)

# Answer
> 3 votes
In procedural code it doesn't matter, because both do the same. The static `create()` is a shortcut for the second example. (The different result is because the first saves the term and the second does not, if you want the term as result then save in a separate step)

In OOP code a better way is dependency injection. The second example points in the right direction. Inject the entity type manager, store it in a class property and use it:

```
$term = $this->entityTypeManager->getStorage('taxonomy_term')->create($term);

```

How to inject a service depends on which class you want to use it in.

A lot of base classes include services already and if you are lucky such a common service like this is one of them. Sometimes, for example in a controller, there is a method to retrieve the service. Then add to the code above parentheses:

```
$term = $this->entityTypeManager()->getStorage('taxonomy_term')->create($term);

```

See ControllerBase::entityTypeManager().

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