# Question
Title: How can I display the time passed since a comment was created instead of the creation date?
how to personalize my comments ?

* I want to display since when the comment was created instead of the date.
* I want to display the comment ID with the link "permalink".

Can you help me ? Thank you

`comment--field-article-commentaire.html.twig` :

```
<article{{ attributes.addClass('js-comment comment--field-article-commentaire') }}>
  <div class="row card rounded-lg mt-4">
    <div class="card-header p-2 m-0 h6">
      <div class="media">
        <div class="timeline-icon mt-1 mr-3 mb-1 ml-1 float-left">
          {{ drupal_entity('user', comment.uid.target_id, 'comment') }}
        </div>
        <div class="media-body">
          <div class="mb-2">
            {{ permalink }}
          </div>
          <div class="mb-2">
            {{ author }}
          </div>
          <div class="mb-0">
            le {{ created }}
          </div>
        </div>
      </div>
    </div>
    <div class="card-body p-2">
      {{ content.field_article_commentaire }}
    </div>
    <div class="card-footer d-flex flex-wrap justify-content-start pt-0">
      <div class="mt-3 mr-3">
        {{ content.flag_report_comment }}
      </div>
      <div class="mt-3 mr-3">
        {{ content.links }}
      </div>
    </div>
  </div>
</article>

```

Here is the current view of my comments :

https://ibb.co/QF051yV

I would like to display the date like this :

https://ibb.co/QCQbmG2

# Answer
Twig's date extension does exactly what you ask:

```
{{ created | time_diff }}

```

However, this extension isn't in Drupal by default, assuming you're using Composer you need to add this extension to your project by running:

```
composer require twig/extensions

```
> 2 votes

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


title: Disable field on hook_form_alter

text:
# Question
Title: Disable field on hook_form_alter
I have a form that I want to render with a disabled field.

I've already tried:

```
$form_element['#node']->field_assoc_cnpj[0]['#attributes'] = array('disabled' => 'disabled');

```

And also to use it directly into the `form` array:

```
$form['#node']->field_assoc_cnpj[0]['#attributes'] = array('disabled' => 'disabled');

```

Nothing seems to work.

How can I do that?

# Answer
> 3 votes
In simple terms, CCK is yet another module that alters the forms. When your form\_alter function is used, even if you disable the field, it will not work. That's because the CCK forms are built after those form alter functions. Note that this limitation is only for Drupal 6. In Drupal 7, it should work with regular form\_alter functions.

I had to do this on a client site. This page from Drupal docs helped me a lot.

See Clive's answer. It's how we do it on regular forms. But don't forget that you always can use field permissions which is much more robust than form alters.

Also, note that setting the field's disabled attribute means this field will not be submitted by browser. If you want to get the value back to your site, use read only attribute with some fancy css to make it look like disabled (browser will take care to not allow editing). Chuck Norris can hack the page using Firebug or something to change the content though.

# Answer
> 3 votes
You can use the `#disabled` FAPI property:

```
$form_element['#node']->field_assoc_cnpj[0]['#disabled'] = TRUE;

```

> Disables (greys out) a form input element. Note that disabling a form field doesn't necessarily prevent someone from submitting a value through DOM manipulation. It just tells the browser not to accept input.

# Answer
> 0 votes
In D7 you can use this:

```
/*
 * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'registration_form':
      if(isset($form['email_field'])) {
        $form['email_field']['#required'] = TRUE;
      }
      if(isset($form['count'])) {
        $form['count']['#disabled'] = TRUE;
      }
      $form['#validate'][] = 'YOUR_MODULE_registration_form_validate';
      break;
  }
}

```

---
Tags: 6, forms
---


title: Template preview not working properly

text:
# Question
Title: Template preview not working properly
I've got a huge problem with my template preview. For all of my post (page, article and so on), I have not the good region in my page.

My theme is extended Classy.

If I go to see the page (not from the preview), I have the good page. But if I want to see the preview of this page, I've got some missing region (I guess this is a region).

See my **page--post-type.html.twig**

```
        {% include '@theme/layout/header.html.twig' %}
    {% include '@theme/includes/page-head.html.twig' %}
    {% include '@theme/includes/page-breadcrumb.html.twig' %}
    {% include '@theme/includes/page-entry.html.twig' %}

    <section id="page-content">
      <div class="container">
        <div class="row"> {{ some displayed data }}
    </div></div></section>
{% include '@theme/layout/footer.html.twig' %}

```

My included files a working (for both preview and view), but the preview isn't in this page is guess.

The last included block is this for the preview :

> BEGIN OUTPUT from 'themes/theme/templates/block/block.html.twig'

And for some reason, after I have this :

> BEGIN OUTPUT from 'core/themes/classy/templates/content/node.html.twig'

if it helps, my .theme file :

```
    /**
 * Implements hook_theme_suggestions_page_alter().
 */
function theme_theme_suggestions_page_alter(&$suggestions, $variables) {
//    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node = \Drupal::routeMatch()->getParameter('node_preview')){
        $node = \Drupal::routeMatch()->getParameter('node_preview');
//        if ($node instanceof \Drupal\node\NodeInterface) {
//            $suggestions[] = 'page__' . $node->bundle() . '_preview';
//            $suggestions[] = 'page__node_' . $node->bundle() . '_preview';
//        }

    } else {
        $node = \Drupal::routeMatch()->getParameter('node');
        if ($node instanceof \Drupal\node\NodeInterface) {
            $suggestions[] = 'page__' . $node->bundle();
            $suggestions[] = 'page__node_' . $node->bundle();
        }
    }

//    dump($suggestions);

}

```

And I have also this function **alstef\_preprocess\_node()** which I took from this : Place block region in node template

I've been stuck for hours, any help you be appreciated.

PS : I'm working on drupal 8 with a custom Theme (here called 'theme').

**EDIT :** I've just made a dump of my node, and the node is null is i'm on my page--post-type.html.twig or page--post-type-preview.html.twig with the preview (change thanks to suggestions)

# Answer
While previewing a node, the node parameter is not "upcasted" from an integer to a node object. But you can easily do this yourself in the preprocess function, just add those lines before:

```
  $router = \Drupal::routeMatch();
  $node = $router->getParameter('node');
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }
  //now you always have "real" node object (instanceOf Drupal\node\NodeInterface -> true),
  //no matter if preview or normal viewing

```
> 1 votes

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


# Question
Title: What is the purpose of using node_submit() before node_save()?
I am creating a node programmatically , In the code given in the link http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7 after creating a node, the code goes as follows :

```
 $node = node_submit($node); // Prepare node for a submit
    node_save($node); // After this call we'll get a nid

```

# Answer
`node_submit()` is a small helper function that makes sure the uid/author and creation date is set. Its main purpose is to map -\>name to uid and -\>date to created. Those two are used in the node edit/create form.

So if you set these two properties yourself anyway (and the validated flag but I haven't found anything that cares about it, likely some sort of left-over from earlier code), there is no need to call it.
> 13 votes

# Answer
you should also use node\_object\_prepare($node) which helps in doing the following: Provides the default values for the status, promote, sticky, and revision flags. These values are type specific if $node-\>type is defined, and can be modified as required.
> 2 votes

# Answer
Why node\_submit() is overriding the uid based on $node-\>name ($form\_state\['values'\]\['name'\]) ?

```
if ($account = user_load_by_name($node->name)) {
  $node->uid = $account->uid;
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: How to determine if loading a form or submitting a form in hook_form_alter?
I am trying to put a simple message at the top of a node edit form when a user is creating a new node.
I added a `\Drupal::messenger()->addMessage()` inside a my `form_alter` hook but this prints when I open the edit form (good!) but also on the view of the node after the node is saved (bad!).

Looking in debugger I can see that the hook is run twice (load and submit); but I don't see any way of determining which version is being run.

The only thing apparent to me is that `$form_state->requestMethod` is different in both cases; but this is a protected property; so no access to it.

code shouldn't be required for this question, but:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  \Drupal::messenger()->addMessage(t('some msg'), 'warning');
  return;
}

```

# Answer
> 4 votes
You can get the request method from `\Drupal::requestStack()`, like this:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  $request_method = \Drupal::requestStack()->getCurrentRequest()->getMethod();
  if ($request_method == 'GET') {
    // Add/Edit form.
  }
  elseif ($request_method == 'POST') {
    // Form is being saved.
  }
}

```

# Answer
> 6 votes
When there is no user input the form is loading for the first time and it is not submitting.

Additionally you can check the entity whether it is new, if you don't want this condition to be true when the form is loading for an existing node:

```
if (!$form_state->getUserInput() && $form_state->getFormObject()->getEntity()->isNew()) {
  // first load of the form
}

```

# Answer
> 2 votes
You can check using @4k4's answer. I think that's probably the best way if you want to trigger against any new node.

However, if you're trying to do this for just one type, node forms have two different form ids whether they're being created or edited. The form ids match a pattern like:

* New node: `node_TYPE_form`
* Existing node (editing): `node_TYPE_edit_form`

For example, you can act on the initial load of the Basic Page create form like:

```
/**
 * Add message to node:page create form.
 *
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_page_form_alter(&$form, $formState) {
  // Check if this is the initial load of the form.
  if (empty($formState->getUserInput()) {
    // Do stuff on node create form initial load.
    \Drupal::messenger()->addMessage(t('You're creating a Basic Page node.'), 'info');
  }
}

```

---
Tags: 8, forms
---


# Question
Title: Using group and rules modules to automatically create group for new user
I am using the Group (not OG ...) and rules modules for this task. I created group type, `Applications Support`. Then I created a rule, `After saving a new user`.
Under the rule, I used the following configuration, but it did not create a group.

My previous question was related to the OG module, this one is for the Group module. So I think it is a different question.

# Answer
> 0 votes
You didn't mention any errors, but for starters your group name should be:

`test group {{ user.uid }}`

---
Tags: 8, rules, group
---


# Question
Title: How to delete all revisions of given content type except the current revision?
I am having a very large website which have around 400000 nodes of story content type. And these nodes have around 2000000 revisions. How can I delete all the revisions except the current revision so i can reduce the size of my database.

I have tried node node revison delete module with no success. Page is getting time out.

# Answer
The time out page is happening cause the modules is not using Drupal batch operation.

Did you try to use drush command that comes with the same module? you need to install Drush Help module to do so. If it didn't work, please post it here so I can provide you with a batch code.
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Setting the default front page setting to be translatable
I've enabled the following multilingual modules:

* Configuration Translation
* Content Translation
* Interface Translation
* Language

Configuration translation enables me to translate the site title and slogan, but how can I translate the default front page setting to have a different front page per language?

I can see the setting in `system.site.yml`:

```
page:
  403: ''
  404: ''
  front: /node

```

but overriding it in `language/de/system.site.yml` doesn't seem to help.

Is there anyway I can activate the setting for translation?

# Answer
> 1 votes
I created a proof of concept Drupal (latest - 8.3.5) instance on simplytest.me earlier today to check if this is actually something you cannot override in language//system.site.yml. I had **no problem** to differentiate frontpage for default (english) language and additional language.

Just remember that `front` property is nested under `page` key.

# Answer
> 0 votes
I just ran into the same situation and like described by @zaporylie, the workaround to set the value directly in the translated configuration works perfectly. Did the author perhaps forget to import the changed configuration?

I now opened an issue to expose these values in UI. Please help to contribute: https://www.drupal.org/project/drupal/issues/3097497

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


# Question
Title: How to Restrict views Date popup to only year/month
I want to have views exposed filter on node `created` field with popup. I've installed date\_popup, the popup appears but I'm looking for a way to restrict it to only year and month.

I tried the following solutions but no success.

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

  if( $form['#id'] == 'views-exposed-form-news-page-1') {
    $form['created']['#date_format'] = 'm-Y';
    $form['created']['#date_date_format'] = 'm-Y';
    $form['created']['value']['#date_format'] = 'm-Y';
    $form['created']['value']['#date_date_format'] = 'm-Y';
    $form['date_needed'] = [
      '#type' => 'date',
      '#title' => 'test',
      '#date_date_format' => 'm/Y',
      '#date_format' => 'm/Y',
    ];
  }
  return $form;
}

```

# Answer
> 1 votes
You'll need a external library to do that. Something like jQuery UI Month Picker Plugin and you'll probably will need to use a `textfield` rather than `date`.

OR

Use the Month Year module

> This module provides a month year field type.

---
Tags: 8, datetime
---


title: Database deadlock detected

text:
# Question
Title: Database deadlock detected
On Drupal 8 we're getting a few deadlock conditions - most connected with the cache. There are quite a few answers to this issue but not so much for D8 (which has very different caching mechanism). Is there any way to resolve/mitigate?

```
Drupal\Core\Entity\EntityStorageException: SQLSTATE[40P01]: Deadlock detected: 7 ERROR: deadlock detected DETAIL:
Process 9131 waits for ShareRowExclusiveLock on relation 8341492 of database 8341380; blocked by process 9130.
Process 9130 waits for ShareRowExclusiveLock on relation 8341562 of database 8341380; blocked by process 9131.
HINT: See server log for query details.: LOCK TABLE {cache_bootstrap} IN SHARE ROW EXCLUSIVE MODE;
Array ( ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save()
    (line 847 of /var/xxx/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

```

# Answer
You can try and add the following lines to your settings.php file :

```
$databases['default']['default']['init_commands'] = array(
  'isolation' => "SET SESSION tx_isolation='READ-COMMITTED'"
);

```

https://support.acquia.com/hc/en-us/articles/360005253954-Fixing-database-deadlocks
> 1 votes

# Answer
You can enable alternative cache implementation (with cache bootstrap) memcache or redis. Read more about deadlocks: https://support.acquia.com/hc/en-us/articles/360005253954-Fixing-database-deadlocks
> 0 votes

# Answer
i had this bug a while ago , and i found this fixing dead locks in drupal

```
ALTER TABLE semaphore ENGINE = MEMORY;
ALTER TABLE semaphore DROP PRIMARY KEY;
ALTER TABLE semaphore ADD PRIMARY KEY (name, value) USING BTREE;
ALTER TABLE semaphore ADD UNIQUE name (name) USING BTREE;
ALTER TABLE semaphore DROP INDEX value;
ALTER TABLE semaphore ADD INDEX value (value) USING BTREE;
ALTER TABLE semaphore DROP INDEX expire;
ALTER TABLE semaphore ADD INDEX expire (expire) USING BTREE;

```

I hope this helps , it worked for me .
> 0 votes

---
Tags: 8, caching
---


# Question
Title: Is it possible to override/replace an event subscriber?
I would like to replace an event subscriber.

Can I write a class that implements `EventSubscriberInterface` which replaces another event subscriber?

# Answer
Since an event subscriber is a service, you can achieve it by creating a class that implements `ServiceModifierInterface`.

Drupal doesn't have a class that alters an event subscriber (which isn't a class used in tests). Changing the class associated to an even subscriber isn't different from changing the class associated with a generic service, which is what the following code used from the `CoreServiceProvider` class does, in its `alter()` method.

```
$uuid_service = $container->getDefinition('uuid');

// Debian/Ubuntu uses the (broken) OSSP extension as their UUID
// implementation. The OSSP implementation is not compatible with the
// PECL functions.
if (function_exists('uuid_create') && !function_exists('uuid_make')) {
  $uuid_service->setClass('Drupal\\Component\\Uuid\\Pecl');
}
elseif (function_exists('com_create_guid')) {
  $uuid_service->setClass('Drupal\\Component\\Uuid\\Com');
}

```

`$container->getDefinition()` returns a `Definition` instance.
> 6 votes

---
Tags: 8, event-subscribers
---


# Question
Title: How to display the number of elements of a view with twig?
How to display the number of elements of a view with twig?

I created a view of 50 products with a pagination (12 products per page).

If I type the following code:

```
{{ drupal_view_result('boutique_page_produit', 'block_2')|length }}

```

This displays the number of items in the view's page (12). I want the total element number of my element (50).

How to do this ?

One solution would be to create a second view without pagination, but is there another solution ?

# Answer
The total items is available in views.view.html.twig like:

```
{{ view.total_rows }}

```
> 0 votes

# Answer
You also can use the views query and execute a `->count()` on it :

```
$total_rows = $view->query->query()->countQuery()->execute()->fetchField();

```
> 0 votes

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


# Question
Title: Create new node and assign it to user after they have been registered
I have one user role on d8 and have few additional fields on user account so when people are registering they can leave additional data. What I would like to achieve is that when user registers - new content of that specific type would be automatically created (node), assigned to him and the fields on that new content would be populated from those fields on user account which he filled during the registration process. I was thinking that this is maybe achievable with the Rules but since couldn't find proper documentation for Rules in d8 not sure is this is doable that way.

# Answer
> 1 votes
This is very easy to do in D8 Rules. Here is an export of a Rule which does what you asked - when a new user is created, it creates a new node (of type article, as an example). It then sets the node author to be the new user. It then sets a field of the new node (the body field, in this case) to a value take from the user (the user's email address, in this case). As you can see, Rules are stored in YAML files, and are imported/exported like any other configuration in D8. So you can just import this and you will immediately have a working example which you can then modify to use the specific fields you've defined on your user entity and node type. This Rule additionally displays a system message, which is a very useful way to debug Rules.

```
langcode: en
status: true
dependencies: {  }
id: create_a_node_for_each_new_user
label: 'Create a node for each new user'
events:
  -
    event_name: 'rules_entity_insert:user'
description: 'Node fields will be populated from values entered on the user form.'
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: c9428f2d-c0b9-47bf-a7e5-3f2cc8af9f54
  conditions:
    id: rules_and
    uuid: 47b8d622-ed38-4977-8e58-4cca6d89260a
    conditions: {  }
  actions:
    id: rules_action_set
    uuid: d96fd6b5-1638-4b15-adde-5f5d7673fb8f
    actions:
      -
        id: rules_action
        uuid: e09cd52d-76fe-4682-91de-bfed58a651ab
        context_values:
          message: 'Node created using information entered by <em>{{ user.name }}</em> when registering'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: fe2acb55-9234-4754-9d2b-3d1889d1775c
        context_values:
          type: article
          title: 'Article created by Rules for {{ user.name }}'
        context_mapping: {  }
        context_processors:
          type:
            rules_tokens: {  }
          title:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: 'rules_entity_create:node'
      -
        id: rules_action
        uuid: 743be03f-d1b7-4251-a1ac-80b17aa5c86e
        context_values:
          value: '{{ user.mail.value }}'
        context_mapping:
          data: entity.body
        context_processors:
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_data_set
      -
        id: rules_action
        uuid: 91f3c8f2-eb47-46e6-a9dd-2affc90e15d2
        context_values: {  }
        context_mapping:
          data: entity.uid.target_id
          value: user.uid.value
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set

```

# Answer
> 0 votes
I achieved it this way, with custom module and just those few lines in .module file. as @4k4 user suggested in the comment.

```
<?php
use Drupal\node\Entity\Node;

  function provider_module_user_insert(\Drupal\user\UserInterface $user) {
    if (($user->get('field_company_type')->value) == 'Provider') {
      $tid = 12;
    }
    elseif (($user->get('field_company_type')->value) == 'Charity') {
      $tid = 13;
    }
    elseif (($user->get('field_company_type')->value) == 'Club') {
      $tid = 14;
    }
    \Drupal\node\Entity\Node::create([
      'type' => 'providers_charities',
      'field_company_name' =>  $user->get('field_company')->value,
      'field_email_address' =>  $user->mail,
      'uid' => $user->id(),
      'field_company_type' => [['target_id' => $tid]],
      'field_website' =>  $user->get('field_website')->value,
      'field_phone_number' =>  $user->get('field_phone_number')->value,

    ])->save();
  }

```

---
Tags: 8, rules
---


# Question
Title: Show metatags on node add/edit pages on custom theme
I have a user role which can add/edit metatags (Metatag module) and when I allow overlay and admin theme access for that user role - everything is OK. But if they are editing/adding node from my custom theme for some reason they cannot see fields for metatags, only tab with the label "Meta tags". Same thing is with the URL alias, only tab. I'm not sure what can be the cause or am I missing something. Thanks

# Answer
> 0 votes
Actually it was related to Bootstrap custom theme and vertical tabs. So fields where only hidden in my theme and it was a style issue. Nothing to do with privileges.

---
Tags: meta-tags
---


# Question
Title: Is there a way to selectively export specific relevant configuration into custom modules?
I'm learning D8 and gaining familiarity with the configuration management aspects of drush.

All my configuration is exported into my **config/sync** directory and I cherry picked the relevant files and moved them into a **config/install** under my custom modules.

However, I'm having trouble when I had to rebuild my site due to some vagrant issues and I came across the following type of errors:

> Unable to install Questions due to unmet dependencies: field.field.node.quiz.field\_questions (node.type.quiz), views.view.quizes (node.type.quiz, rest, serialization)

**Is there a way to selectively export specific relevant configuration into my custom modules directly?**

# Answer
> 1 votes
I would use the awesome features module as a base to export complex configurations that contain multiple dependencies as a base of my new module and then start building my custom functionality. All major distributions are using features module as it saves a lot of time and it is very reliable.

---
Tags: 8, configuration
---


# Question
Title: Displaying multiple fields in referenced webform option?
First I have a content type **Quiz option** which represents one option (answer) for a webform question (field).

Then I have a (entity reference) view which is collecting specific number of nodes in this type. I got one argument to that view, which represents question id and when passed I'm getting all possible answers for that question.

And then I got a webform, where I have field of **entity checkbox** type where all options are referenced with that view. So webform field options are set like:

```
Type of item to reference: Content
Reference method: Views: Filter by an entity reference view
View used to select the entities: my view
View arguments: that question id

```

And all this works well - I'm getting the possible options from that view and as option titles node titles are displayed.

Basically if I create new node in "Quiz option" and select for it question id i.e. 1 then view referencing those node will also display it when question id 1 is passed and since question in my webform is using that view new option will appear as a new option under that option.

Now what I need is to display another field (image field) beside that title as part of an webform option. I've added image field to my content type. Then I adjusted my view so it also displays the image. But problem is that webform is still displaying only node title. New image field is ignored. Checked on "Display options" of my content type, but image field is not hidden there. So must be that webform module is responsible - it's displaying only referenced node title no matter what used view is returning.

Is there a way do configure my webform field to display this extra field for field options instead of only node titles?

# Answer
> 0 votes
The issue is coming from Drupal core and is fixed in Drupal 8.8.

@see Issue #2174633: View output is not used for entityreference options

---
Tags: views, 8, webforms
---


title: Why is my db_query not working?

text:
# Question
Title: Why is my db_query not working?
i am trying to display my content types and their info in a table format. First thing i want to do is make sure i am connected to the database. It seems i cant connect to the database. Please assist.

Thanks in advance

# Answer
> 0 votes
You've passed your query result into a variable named `$results`, then in the next line, checked a non-existent variable `$result` (no 's'). So your `if()` condition will never be entered.

---
Tags: nodes
---


# Question
Title: Programmatically create new Schedule Updates Entity Reference on Node
I’m attempting to populate an entity referenced field created by the Scheduled Updates module within a content type, Event. Within Event I have two Scheduled Updates fields to check and uncheck the Sticky at top of list option.

I also have a product, Promote Event, in which the user is required to add a Begin Promoting Date, an Entity Reference to an Event, and a Quantity. Once a user purchases the Promote Event, I’d like to populate the Scheduled Updates fields within the Event content type with the data used in the purchase.

I can’t seem to figure out how to programmatically populate the Scheduled Update fields within the Event content type after the purchase of Promote Event.

Within my custom module I have:

```
public function orderCompleteHandler(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();

  // Order items in the cart.
  $items = $order->getItems();
  if($order->bundle() == 'promoted_event'){
    $beginPromo = $items[0]->get('field_begin_promotion')->getValue();
    $beginPromo = $beginPromo[0]['value'];
    $quantity = $items[0]->get('quantity')->getValue();
    $quantity = str_replace('.00', '', $quantity[0]['value']);
    $eventId = $items[0]->get('field_event_to_promote')->getValue();
    $eventId = $eventId[0]['target_id'];
    $endPromo = date('Y-m-d', strtotime($beginPromo. ' + '. $quantity .' days'));

    $node = Node::load($eventId);
    // Get the promote_event Entity Reference
    $promoteEvent = $node->get('promote_event')->first();
    // Get unPromoteEvent
    $unPromoteEvent = $node->get('unpromote_event_')->first();
    if($promoteEvent){

    } else {
      $dateTime = new DrupalDateTime($beginPromo, 'UTC');
      $timestamp = $dateTime->getTimestamp();
      $node->promote_event[] = [
        'user_id' => 1,
         'type' => 'node__sticky',
         'update_timestamp' => $timestamp
       ];
       $node->save();
     }
   }
 }

```

# Answer
> 0 votes
Here is one example of how to add a ScheduledUpdate to your 'host' entity, in your case a node.

```
$scheduled_update = ScheduledUpdate::create([
  'type' => 'node__sticky',
  'status' => ScheduledUpdateInterface::STATUS_UNRUN,
  'sticky' => NodeInterface::STICKY,
  'update_timestamp' => $timestamp,
  'entity_ids' => [$eventId],
]);
$scheduled_update->save();
$node->promote_event = $scheduled_update->id();
$node->save();

```

Good luck!

---
Tags: entities, commerce
---


# Question
Title: How can I prevent "Log in to post comments" from displaying for anonymous users?
How do I remove the "Log in to post comments" from the bottom of my content in **Drupal 8** while keeping old comments visible to all and allowing existing registered users to still comment? Basically, I don't want anonymous users to find my login page, ever. *These means no CSS hide or Javascript solutions (bots will still follow the link).*

## So, if comments exist on a node:

I want **anonymous users** to:

1. See the comments as usual
2. NOT see any sort of "add comment" link
3. NOT see any sort of "login/register" link either

I want **authenticated users** to:

1. See the comments as usual
2. See "add/reply" comment links as usual

## If comments DO NOT exist on a node:

I want **anonymous users** to:

1. See NOTHING at the bottom of the node

I want **authenticated users** to:

1. See "add comment" link as usual

# Answer
You can do it using hook\_preprocess\_HOOK
The following hooks should be placed in `YOURTHEME.theme` file:

1. Remove comment links from node for Anonymous user:

```

    /**
     * Implements hook_preprocess_HOOK().
     */
    function YOURTHEME_preprocess_links__node(&$variables) {
      if (\Drupal::currentUser()->isAnonymous()) {
        unset($variables['links']['comment-forbidden']);
      }
    }

```
2. Remove links from the comments for Anonymous user:

```

/**
 * Implements hook_preprocess_HOOK().
 */
function YOURTHEME_preprocess_links__comment(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($variables['links']['comment-forbidden']);
  }
}

```
> 2 votes

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


# Question
Title: Could not find package with stability dev in a version installable using your PHP version
When I want to install Drupal Commerce using Composer via Git Bash terminal and using the following command:

```
$ composer create-project drupalcommerce/project-base mystore --stability dev

```

I get the following error:

> \[InvalidArgumentException\] Could not find package drupalcommerce/project-base with stability dev in a version installable using your PHP version 5.6.40.
>
> create-project \[-s|--stability STABILITY\] \[--prefer-source\] \[--prefer-dist\] \[--repository REPOSITORY\] \[--repository-url REPOSITORY-URL\] \[--dev\] \[--no-dev\] \[--no-custom-installers\] \[--no-scripts\] \[--no-progress\] \[--no-secure-http\] \[--keep-vcs\] \[--remove-vcs\] \[--no-install\] \[--ignore-platform-reqs\] \[--\] \[\] \[\] \[\]

So what can I do?

# Answer
> 5 votes
The package that triggers the error is drupalcommerce/project-base. If you check the composer information for that package you see:

```
  "require": {
        "php": ">=7.0.8",
        "ext-curl": "*",
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6.5",
        [...]

```

As you see, it requires PHP 7.0.8 or higher. You have PHP 5.6.40. You should upgrade your PHP, not only because this package but also because PHP 7.x is much faster and PHP 5.6 is not recommended anymore, not to forget that PHP 5.6 end of life was hit a year ago, on the beginning of 2019.

---
Tags: commerce, composer
---


# Question
Title: How can I specify background color and image for a block or node?
My web page consists of vertically aligned blocks. Each of these blocks/nodes may have a custom background color or image. I am entering the background color/image within the specific block. How can i then apply these CSS attributes on that specific block? I would like to simply render the block as

```
<section id="dlazdice" style="background: {{ field.bgr_color }} url('{{ field.bgr_image }}')">
[...]
</section>

```

I played with block template but was not able to persuade the color or image attribute to appear where i needed them, both the values were wrapped in the useless

```
<div class="field".../>

```

markup.

# Answer
> 0 votes
You can do it with this module: https://www.drupal.org/project/bg\_image\_formatter

Just upload image as background field and set the class in the field settings for which element you want to display image as bgd. It works with Views as well. So, for example, you can use Views conditional module and create a block and test if bdg field is empty and then create different styles with bgd color in that case.

---
Tags: 8, theming
---


# Question
Title: Views: Filter if Value of a field equals logged in user display name?
How to do I create a filter on my view that filters based on the value of one field being equal to the name of the currently logged in user? The field is static.

# Answer
You can use contextual filter, as suggested by DRUPWAY in his comment.

1. Add a new contextual filter
2. Select the field to use
3. For *When the filter value is NOT in the URL*, select *Provide value*, and then *PHP code* for *Type*
4. In *PHP contextual filter code*, enter the following code
```
global $user;
return $user->name;

```

>

For the user ID, it would be simpler: In step 3, you would select *User ID from logged in user*.

>
> 2 votes

# Answer
In view Relationships add "author" then in FILTER CRITERIA Add (User: Current) and select (yes) in "Is the logged in user"..
> 1 votes

# Answer
In Drupal 8 you can just use the module:

https://www.drupal.org/project/user\_field\_value
> 0 votes

---
Tags: 7, views
---


# Question
Title: Can I use the Migrate module to sync a site database with a Filemaker Pro database?
Is it possible to get data from a Filemaker Pro database and insert it into the database for a Drupal site?

Ideally, I'd like to set this up so that Drupal would periodically check the Filemaker database and import any new (or updated) data into its database.

# Answer
> 0 votes
Yes, it's possible.

You can use the Migrate module from Drupal 8. This module allows you to import data from an SQL source. You have to create a custom module to configure the migration. In that module, you should create a migrate source plugin class extending the abstract SqlBase class provided by the core Migrate module.

The SQL source plugin must implement three methods:

* query(): Returns the query that selects the data from the source database.
* fields(): Returns available fields on the source.
* getIds(): Defines the source fields uniquely identifying a source row.

Plus, you'll have to declare the connection to the source database in the settings.php or settings.local.php file. So, you'll have the Drupal 8 connection configuration and your migrate source database:

```
$databases['migrate']['default'] = array (
  'database'  => 'source-database-name',
  'username'  => 'source-database-username',
  'password'  => 'source-database-password',
  'host'      => 'source-database-server',
  'port'      => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'    => 'mysql',
);

```

Finally, you need you define the migration that uses your created plugin and the database:

```
id: filemakerpro
label: 'Filemaker Pro'
source:
  plugin: filemakerpro
  key: migrate
process:
  title: title
  field_datetime: datetime
  field_place: place
destination:
  plugin: 'entity:node'
  default_bundle: yourbundle

```

Once you have done this, you need to execute the migration. You can execute it periodically and migrate will add the content.

You can have more information in the Migrating data from a SQL source (the info I posted here is a briefing from that link).

---
Tags: 8, database
---


# Question
Title: How can I programmatically deactivate multiple user accounts?
I have tried the following code, but something doesn't work, could you please help. I need to deactivate several accounts at once, if they satisfy the conditions:

```
$ids = \Drupal::entityQuery('user')
  ->condition('roles', 'student')
  ->condition('field_school_id', $node_id)
  ->execute();
$users = User::loadMultiple($ids);

$storage_handler = \Drupal::entityTypeManager()->getStorage("user");

foreach($users as $user){
  $entity = $storage_handler->load($user->id());
  $entity->set("status", 0);
  $storage_handler->save($entity); // THE PROBLEM IS IN THIS LINE
}

```

# Answer
> 0 votes
The problem is that you load the users two times. In the foreach loop you already have the loaded entity available in `$user`.

Change your foreach loop to look like this and it should work:

```
foreach ($users as $user) {
  $user->set("status", 0);
  $user->save();
}

```

You can also remove the `$storageHandler` since you don't use that any more.

---
Tags: 8, users
---


# Question
Title: What's the purpose of subfolders inside a theme's templates folder?
What is the purpose of folders inside the templates folder in a theme? Where is specified that when rendering a page the template should be taken from `layout/page.html.twig`? Or a single node template from `content/node.html.twig`?

I could see content, block, field, form etc. in the `/templates` folder. I am referring to the Zymphonies theme. When I check Twig Template naming conventions I could see there are naming conventions for Twig templates. But what is the difference in giving Twig plain twig templates inside the templates folder and by giving specific twig templates in specific folders inside templates folder?

# Answer
> 4 votes
These folders are arbitrary. As long as the template is in the `[THEME ROOT]/templates` folder, it will be picked up. Using folders is simply the developer being well organized.

# Answer
> 1 votes
by default the `[MY_THEME]/templates` folder holding `twig` files is flattened, have a look at this folder `/core/modules/system/templates`. So, it's seen as a good practice to bring such organization to this folder and it's up to you to determine what logic suits your case. The `twig` engine is smart enough to pick up the right `twig` file.

Just to draw your attention when it comes to override an existing template, let say you want to override the default `search form` which uses this `twig` template `/templates/forms/form.html.twig` then you `should` create the template following this path `/templates/forms/form--search-form.html.twig` just to keep certain logic, but this doesn't prevent you to locate that file in an other folder or simply under `/templates`

you can also tell Drupal 8 where to find your new template using `MY_THEME_theme` hook :

```
function MY_THEME_theme($existing, $type, $theme, $path) {
  return [
    'search_form' => [
      'render element' => 'form',
      'template' => 'form/form--search-form',
    ],
  ];
}

```

don't forget to clear and rebuild cache to force twig engine to take in consideration your new `twig` file.

---
Tags: 8, theming
---


# Question
Title: How to set and inherit variables within different twig templates?
I'd like to set a variable in my `node.html.twig` template:

```
{% set title = label %}
{{ content }}

```

The content consists of one field visible only, which has it's own template:

`file-link.html.twig`

How can I access the `title` variable of the node template in the file template? I am not sure if importing or extending is the right way since that might cause infinite recursion?

Edit

The file template looks like this (from the bootstrap theme):

```
{% spaceless %}
  {%
    set classes = [
      icon_only ? 'icon-only',
      not icon_only ? 'icon-' ~ icon_position|clean_class
    ]
  %}
  <span{{ attributes.addClass(classes) }}>
    {% if icon_only %}
      <span class="file-icon">{{ icon }}</span>
      <span class="sr-only">
        <span class="file-link">{{ link }}</span>
        <span class="file-size">{{ file_size }}</span>
      </span>
    {% else %}
      {% if icon_position == 'after' %}
        <span class="file-link">{{ link }}</span><span class="file-size">{{ file_size }}</span><span class="file-icon">{{ icon }}</span>
      {% else %}
        <span class="file-icon">{{ icon }}</span><span class="file-link">{{ link }}</span><span class="file-size">{{ file_size }}</span>
      {% endif %}
    {% endif %}
  </span>
{% endspaceless %}

```

Within that template I'd like to print the title of the respective node:

```
<span class="file-link">{{ link }}</span>
<span class="file-node-title">{{ title }}</span> {# << #}
<span class="file-size">{{ file_size }}</span>

```

# Answer
> 0 votes
**EDIT**

You could write a theme hook in your "mytheme.theme", modifiy the "variables" array and add title to the specific field AND then move the template file (in the original post) to your own theme template directory, make the changes using your new variable (called maybe title) which was provided from theme hook.

---

**OLD:**

First of all, "node.html.twig" is TOO general to claim that it's content in the future will consist only one field (file-link).

At least rename it to "node--my-content-type.html.twig". In the file-link.html.twig you won't able to reach the "title" variable (label) of the node.

You have the following work around: {{ content|without('field\_file\_link') }} {% include directory ~ '/templates/my-custom-twig.html.twig' with {'title': title} %}

Which means: 1. exclude your field from content. 2. create your own twig template 3. Pass any variable from the caller template you would like to pass.

Twig syntax / semantics is still changing, maybe my twig codes of lines can lead to error, but at least it will give you a hint / clue how to achieve this.

# Answer
> -1 votes
What about `hook_preprocess_HOOK` with a relevant HOOK\_ID (page, node, view ...) and declare your variables into it ?

In the youtheme.theme file

```
function MYTHEME_preprocess_page(&$variables) {
  $variables['foo'] = "bar";
}

```

In the twig one,

```
The content of Foo var is : {{ foo }}

```

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


# Question
Title: How to make Localization update believe that the translation of a local .po-file is not up to date?
I use a *local* development branch of a contributed project on several sites. The strings that need translation does not exist on https://localize.drupal.org/ (yet), so I cannot use it to translate the project.

Checking l10n update status produces:

```
$ drush l10n-update-status
…
my_project (7.x-1.x)   Up to date
…

```

Now, how do I convince **Localization update** that the translation of this file is *not* up to date?

So far I've tried:

* Editing and saving (i.e. changing the last updated timestamp).
* Editing the embedded timestamps `POT-Creation-Date` and `PO-Revision-Date`.
* Clearing the cache.

But no joy. **Localization update** keeps insisting that translations from this file is up to date.

# Answer
> 1 votes
Figured it out!

*After* changing the last updated timestamp for, you need to refresh the information. The following sequence of commands works:

```
$ touch my_project.7.x-1.x.nb.po
$ drush l10n-update-refresh
$ drush l10n-update-status
…
my_project (7.x-1.x)   Local update available
…

```

Editing the embedded timestamps `POT-Creation-Date` and `PO-Revision-Date` is not required and have no effect.

---
Tags: i18n-l10n
---


# Question
Title: How to update locale after editing a .po file?
I edited a .po file in profiles/l10n\_install/translations/ but after this the pages of the site are not updated.

How to update the site after editing a .po file?

# Answer
Just Import your file from config menu then translate interface import admin/config/regional/translate/import and then import your file
> 2 votes

# Answer
The answer by *Ahmed* tells you to use the "Import" tab provided by the Administration GUI to download the file and (re-)import after editing it.

As an alternative, you may use the CLI and the following sequence of *Drush* commands:

```
$ drush l10n-update-refresh
$ drush l10n-update-status
$ drush l10n-update

```

This is quicker if you are comfortable with the GUI and *Drush*.
> 0 votes

---
Tags: caching, i18n-l10n
---


# Question
Title: How can I save two logos for a custom theme?
I need to save two custom logos in a custom theme and use them on the site. Can I somehow create a custom field in theme settings or maybe save the path to another logo in one of the .yml theme files?

# Answer
Created theme-settings.php in custom theme root, there created new function, it renders new fieldset and a `managed_file` field

```
function theme_name_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {
  $form['options_settings'] = [
    '#type' => 'fieldset',
    '#title' => t('Theme Specific Settings'),
  ];

  $form['options_settings']['add_logo'] = [
    '#type' => 'managed_file',
    '#title' => t('Additional logo'),
    '#upload_location' => 'public://logo/',
    '#default_value' => theme_get_setting('add_logo'),
    '#states' => [
      'visible' => [
        ':input[name="File_type"]' => ['value' => t('Upload Your File')],
      ],
    ],
  ];
}

```
> 2 votes

---
Tags: 8, forms
---


title: Running Drush returns an error

text:
# Question
Title: Running Drush returns an error
I am running Drush version 6.2.0 and the latest Drupal 8 beta on Dreamhosters. When I run `drush cc all` within the sites directory, I receive the following error immediately after executing the command:

> Fatal error: Class 'Drupal\Core\Session\AccountInterface' not found in /home/mywebsite/mywebsite.com/core/includes/bootstrap.inc on line 63 Drush command terminated abnormally due to an unrecoverable error.

> Error: Class 'Drupal\Core\Session\AccountInterface' not found in /home/mywebsite/mywebsite.com/core/includes/bootstrap.inc, line 63

Why does it happen? How can I fix this?

# Answer
> 12 votes
Drush 6 does not support Drupal 8. You must use drush 7.0-rc1 with Drupal 8 beta 9, or drush master head with Drupal 8 head.

**UPDATE**: Drush 7 no longer supports Drupal 8; now, use Drush 8 with Drupal 8.

# Answer
> 9 votes
If you are using Drush 8 with Drupal 8 and still getting this error... Please make sure path is correct. For me it worked after setting path variable as:-

```
export PATH="$HOME/.composer/vendor/bin:$PATH"

```

# Answer
> 0 votes
As for Drupal 8, `drush cc all` is no longer the way to clear cache, use `drush cr` instead:

```
`cache-clear all` is deprecated for Drupal 8 and later. Please use the `cache-rebuild` command instead.                                                                  [error]

```

# Answer
> 0 votes
I ran into the same error using Drush 5.10.0 from a previous Drupal 7 project. If you have composer installed globally you can upgrade Drush to the latest version using:

```
$ composer global require drush/drush:dev-master

```

---
Tags: drush, 8
---


# Question
Title: if current_node is in menu, do something in theme.inc
I'm trying to check if the current node (of a specific content type) has been added to a menu (using the "**Provide a menu link**" in the node edit GUI).

if it has, I need to set a variable in *.theme.inc*, using `THEME_preprocess_page`.

I've been digging through drupal.org docs and found those two questions find Menu Settings of node, given URL alias (or node ID) and Get menu item of a node seem relevant but not quite right.

# Answer
> 1 votes
To set if the node has menu link you can use menu\_ui\_get\_menu\_link\_defaults function from menu\_ui.module something like:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function YOUMODULE_preprocess_page(&$vars) {
  /** @var \Drupal\node\Entity\Node $node */
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    // Get the default menu link.
    $defaults = menu_ui_get_menu_link_defaults($node);
    if ($defaults['id']) {
      // It has a menu
     // set your variable here.
    }
    else {
      // It has no menu link
      // It mean Provide a menu link not checked
    }
  }
  }

```

---
Tags: 8, navigation
---


title: Add a product image to the cart form

text:
# Question
Title: Add a product image to the cart form
Is there a way of hooking into the commerce cart form and adding a custom field which so happens to be the product image that I want to display?

I've tried via the view itself but I have no idea on how to when there is only the Order or Order Item objects available in the commerce cart form itself.

I've also tried the following hooks:

* theme\_views\_pre\_render
* theme\_preprocess\_views\_view
* theme\_views\_data\_alter
* theme\_commerce\_cart\_form\_views\_pre\_render
* theme\_form\_alter

I had no luck.

Can anyone suggest a solution? It's only temporary as I should imagine it will eventually be entwined with the Drupal Commerce module.

# Answer
> 5 votes
This can be accomplished from the front end by simply editing your **commerce\_cart\_form** view and using relationships to "relate" your way backwards from the order item to the product display.

Edit your **cart form** view and click **Advanced** on the right side of the screen. Then under **Relationships** click "Add" then add and apply the following relationships **in this order**.

1. **Product variation** \- Order item - "*The purchased product variation.*" This will give access to add any of the fields under the Product Variation you are relating. it will also give you access to add the product type relationship in step 2.
2. **Product** \- Product variation - "*The parent product.*" This will give access to add any of the fields that you have in the Product Type you are relating, (including the image field from your product display). This will also give you access to add a content relationship as seen in step 3.

Once you have added those relationships, you will be able to access and add any of the fields you want from both the product variation, and the product type under **Fields**.

**If you are displaying with nodes** and/or need fields that are in content types that have product references, you will also need to add the following relationship:

3. **Content using field\_YOUR\_PRODUCT\_REFERENCE** \- Product - "*Relate each Content with a field\_YOUR\_PRODUCT\_REFERENCE set to the product.*" This will bring in all the fields for the display node.

No custom code required. :)

# Answer
> 0 votes
You can do it with views. Just use relationship (example: productvariation)

Then you can choose the field you want to show in your cart-form.

---
Tags: 8, commerce
---


# Question
Title: Adding Field To Bundle-less Entity On Installation Not Working
I have several fields that I'd like to attach to a custom entity upon installation. I am trying to follow the suggestions here to attach fields to my custom entity (which, by the way, has no bundles). I know the instructions are for content types, but I am trying to take what's there and apply it to custom entities.

I am attempting to do this through having some field config files in the config/install directory of my module. When I install the module, the fields are created, but they are not attached to the custom entity. When I create and save an instance of my custom entity, and then attempt to see the fields that are attached to my custom entity using a `ksm()` print, it only shows the base fields defined in my entity. I am trying to add these other fields through config files instead of hard coding them through the base field definitions as these additional fields are meant to be configurable, and according to this the base fields definitions should only be used to define non-configurable fields. The link talks about adding configurable fields through some hooks, but I'd prefer to do it through this configuration solution I am trying, it seems like it should be possible...

So my question is: Is the way that I'm going about doing this possible for a bundle-less entity, and I'm just missing something? Or do I just have to declare all my fields in the base field definitions? Here is the relevant code:

**QuestionnaireResult.php**

```
<?php

namespace Drupal\questionnaire\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Defines the QuestionnaireResult entity.
 *
 * @ContentEntityType(
 *   id = "questionnaire_result",
 *   label = @Translation("Questionnaire Result"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\Core\Entity\EntityListBuilder",
 *     "views_data" = "Drupal\views\EnitityViewsData",
 *     "form" = {
 *       "default" = "Drupal\Core\Entity\ContentEntityForm",
 *       "add" = "Drupal\Core\Entity\ContentEntityForm",
 *       "edit" = "Drupal\Core\Entity\ContentEntityForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *     },
 *     "inline_form" = "Drupal\inline_entity_form\Form\EntityInlineForm",
 *     "route_provider" = {
 *       "default" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "questionnaire_result",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 *   links = {
 *     "canonical" =
 *      "/admin/structure/questionnaire/result/{questionnaire_result}",
 *     "collection" = "/admin/structure/questionnaire/result/overview",
 *   },
 * )
 */
class QuestionnaireResult extends ContentEntityBase
  implements QuestionnaireResultInterface {

  public function getMessage() {

    \Drupal::logger('questionnaire')->notify('What?!?');

  }

  /**
   * Meant for declaring non-configurable fields only.
   */
  public static function baseFieldDefinitions(EntityTypeInterface
    $entity_type) {

    // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Questionnaire Result entity.'))
      ->setReadOnly(TRUE);

    // Standard field, unique outside of the scope of the current project.
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Questionnaire Result entity.'))
      ->setReadOnly(TRUE);

    return $fields;
  }

}

```

**field.field.questionnaire\_result.default.field\_q\_quiz\_result\_passed.yml**

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.questionnaire_result.field_q_quiz_result_passed
id: questionnaire_result.default.field_q_quiz_result_passed
field_name: field_q_quiz_result_passed
entity_type: questionnaire_result
bundle: default
label: Passed
description: 'Boolean value for whether the user passed the quiz on this attempt or not.'
required: false
translatable: false
default_value:
  -
    value: 0
default_value_callback: ''
settings:
  on_label: 'True'
  off_label: 'False'
field_type: boolean

```

**field.storage.questionnaire\_result.field\_q\_quiz\_result\_passed.yml**

```
langcode: en
status: true
dependencies:
  module:
    - questionnaire
id: questionnaire_result.field_q_quiz_result_passed
field_name: field_q_quiz_result_passed
entity_type: questionnaire_result
type: boolean
settings: {  }
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

# Answer
I implemented the suggestion that 4k4 had given, which was to rename my field assignment config from **field.field.questionnaire\_result.default.field\_q\_quiz\_result\_passed.yml** to **field.field.questionnaire\_result.questionnaire\_result.field\_q\_quiz\_result\_passed.yml**. This worked because I was assuming the default bundle's name on a bundle-less entity was 'default', but instead it is the name of the entity itself. I then changed any `bundle: default` assignment I had to `bundle: questionnaire_result`.

Once I printed the field definitions after these changes, the field\_q\_quiz\_result\_passed was attached to my custom entity.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Select all checkboxes of an entity reference field on creating a node
Drupal 8.7.x

For one of my content types I have an entity reference field referencing a taxonomy vocabulary. I have a lot of terms in this vocabulary which makes it tedious to check all the checkboxes if you practically need all of them checked. I would like to integrate a single checkbox at the top of the field in the node creation form that allows you to check/uncheck all the terms at once.

I found a few modules that do this in drupal 7 but so far I had no luck finding anything related to drupal 8.

How would I go about integrating this functionality myself ?

At the moment I have a jquery function in my theme that adds a checkbox at the top of the fields like so:

```
(function ($, Drupal) {

  /**
   * Check all checkboxes.
   */
  Drupal.behaviors.initFootnotes = {

    attach: function (context, settings) {

      $(".form-checkboxes").prepend($('<input type="checkbox" class="form-checkbox shield-select-all" /><label class="option shield-select-all-label"> Select / Deselect all </label>'));

      let selector = $(".shield-select-all");
      selector.on('click', function (event) {

        console.log("the checkbox is clicked");
        let $options = $('.form-type-checkbox');

        $(".form-checkboxes").closest().find($options).each(
        console.log("I'm an option"),

        $(this).find("input[type=checkbox]").click(),

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

```

The select all checkbox is added but the checkboxes aren't changing their state when the select all checkbox is checked. I noly get "I'm an option" once in the console.

Thanks in advance, Geordi

# Answer
> 1 votes
Ended up resolving this issue with the following code:

```
(function ($, Drupal) {

  /**
   * Check/Uncheck all checkboxes.
   */
  Drupal.behaviors.selectAll = {
    attach: function (context, settings) {
      $(".form-checkboxes").prepend($('<input type="checkbox" class="form-checkbox shield-select-all"/><label class="option shield-select-all-label"> Select / Deselect all </label>'));
      $(".shield-select-all").on('click', function () {
        let $isChecked = (!$(this).attr('checked'));
        $(this).parent().find('.form-type-checkbox input[type=checkbox]').attr('checked', $isChecked);
        $(this).attr('checked', $isChecked)
      })
    }
  };

})(jQuery, Drupal);

```

# Answer
> 0 votes
The contributed module checkboxesjs will do this for you out of the box.

---
Tags: 8, nodes, forms, javascript
---


# Question
Title: Problem setting user specific cache tags on custom block with user context
I have a simple custom block with a user cache context and a specific user specific cache tag:

```
/**
 * Provides a 'User example' block.
 *
 * @Block(
 *   id = "user_example_block",
 *   admin_label = @Translation("User example block"),
 *   category = @Translation("Blocks")
 * )
 */
class UserExampleBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => '<span>Current User ID: ' . \Drupal::currentUser()->id() . '</span>',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return Cache::mergeTags(parent::getCacheTags(), ['example_user:' . \Drupal::currentUser()->id()]);
  }
}

```

The block output varies correctly by the logged in user but the user specific cache tag is not set correctly.

It seems the cache tag is only set once for users with the same role or permissions.

Here is how to reproduce it:

1. Rebuild cache (drush cr)
2. Login with User 100 -\> The block output is correct. The correct cache tag is set (example\_user:100).
3. Logout
4. Login with User 101 (same role as User 100) -\> The output of the block is correct, but the cache tag was not changed, it still is example\_user:100. In fact the getCacheTags, getCacheContexts methods were not even called.

What works is when I put the cacheability meta data in the build method (with the "#cache" element in the render array).

What could be the reason for this?

Thanks for any help.

# Answer
> 2 votes
To sum up the comments: As a general rule, if you render the current user, then always add the correct cache metadata to the render element:

```
 public function build() {
    return [
      '#markup' => '<span>Current User ID: ' . \Drupal::currentUser()->id() . '</span>',
      '#cache' => [
        'contexts' => ['user'],
        'tags' => ['user:' . \Drupal::currentUser()->id()],
      ],
    ];
  }

```

If you have a block, which doesn't return a cacheable render result in all cases, you can add additional cache metadata in the block plugins cacheable dependencies methods. It doesn't harm when you declare a cache tag or context twice.

---
Tags: blocks, caching
---


# Question
Title: How do I get the current path and add a condition in page.html.twig?
I have the view page called "location/all" which contain all the map details.

I changed some CSS styles.

```
<!--<div role="main" class="main-container {{ container }} js-quickedit-main-content">!-->
{% if 'location/all' in url %}
  <div role="main" class="main-container js-quickedit-main-content">
{% else %}
 <div role="main" class="main-container {{ container }} js-quickedit-main-content">
{% endif %}

```

I tried this code to check the condition, but every time it executes the `else` part.

# Answer
> 7 votes
GOt the Answer

```
{% set url = url('<current>') %}
{% if 'location/all' in url|render|render %}
<div role="main" class="main-container js-quickedit-main-content">
{% else %}
<div role="main" class="main-container {{ container }} js-quickedit-main-content">
{% endif %}

```

Thanks for your support

# Answer
> 7 votes
Try this

```
{% if 'location/all' in url('<current>')|render|render %}

```

**Alternative solution** would be to add the following to your `THEMENAME.theme`

```
function THEMENAME_preprocess_page(&$vars) {
  $vars['path'] = \Drupal::service('path.current')->getPath();
}

```

and use this in your `page.html.twig`

```
{% if 'location/all' in path %}

```

# Answer
> -1 votes
Try with this code.

```
<!--<div role="main" class="main-container {{ container }} js-quickedit-main-content">!-->
{% if '/location/all' == url('<current>') %}
  <div role="main" class="main-container js-quickedit-main-content">
{% else %}
 <div role="main" class="main-container {{ container }} js-quickedit-main-content">
{% endif %}

```

# Answer
> -2 votes
Try with this code

{% set current\_url = url('') %} {% if 'location/all' in current\_url|render|render %} {% else %} {% endif %}

---
Tags: 8, theming
---


# Question
Title: How to show a date in the correct timezone?
I have a Datetime Range field (field\_date) in a content type. Once I create my content type I set the Start Date as:

2017-02-27 19:30:01

Now I want to get the value and show the date in other format, so try to use the following code:

```
// Loading the node.
$node = Node::load(2100);
// Getting the start date value.
$date = $node->field_date->value;
// Printing to see what is the output.
dpm($node->field_date->value);
$date = strtotime($date);
// Printing my timezone.
dpm(drupal_get_user_timezone());
// Applying my custom format.
$date = \Drupal::service('date.formatter')->format($date, 'custom', 'Y-m-d H:i:s', drupal_get_user_timezone());
// Printing to see the output.
dpm($date);

```

This is my output:

```
// It's fine.
2017-02-28T00:30:01
// Its fine.
America/New_York
// This is not what I waiting for. I'm waiting here: 2017-02-27 19:30:01
2017-02-28 00:30:01

```

So, how to show a date in the correct timezone?

# Answer
> 33 votes
I suspect the problem has to do with some of the nuances of `strtotime()`.

`strtotime()` can take just about any string, and convert it into a Unix timestamp. The problem is that when the string doesn't contain an explicit timezone, it will use what is set by `date_default_timezone_get()`. That should be set from the current user, though (it is set by the account proxy). However, the string that you are pulling out of `$node->field_date->value` is implicitly in UTC. In other words, I think the string is being parsed by `strtotime()` is being interpreted as in 'America/New\_York' and not 'UTC'.

The good news is that you can simplify your situation a lot. The field item for a date range consists of four parts

* 'value' is the start date as a string in UTC
* 'start\_date' is a DrupalDateTime object representing 'value'
* 'end\_value' is the end date as a string in UTC
* 'end\_date' is a DrupalDateTime object representing 'end\_value'

For a plain date time field they are

* 'value' is the date as a string in UTC
* 'date' is a DrupalDateTime object representing 'value'

So, you can work with the `DrupalDateTime()` object directly. In addition, that `date.formatter` service should pull in the proper timezone in use by the user viewing the page by default (in addition to using the user's active language).

I suspect something like this will work

```
$node = Node::load(2100);
$start_date = $node->field_date->start_date;
$formatted = \Drupal::service('date.formatter')->format(
  $start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s P'
);

```

Note I added the 'P' format placeholder in there so you can see what what timezone the system thinks is in use.

Make sure you have the proper timezone set up on admin/config/regional/settings, and that your user timezone is what you are expecting. Also ensure that you have the proper timezone set in your php.ini (it's the `date.timezone` setting); weird things happen when this isn't set (And off the top of my head, I don't recall if that causes a warning in the installer or on the status report when not set. I remember the issue, but not whether it got committed).

# Answer
> 9 votes
Based in Handling timezone conversion with PHP DateTime I modified my code to this:

```
$node = Node::load(2100);
$userTimezone = new DateTimeZone(date_default_timezone_get());
$gmtTimezone = new DateTimeZone('GMT');
$myDateTime = new DateTime($node->field_date->value, $gmtTimezone);
$offset = $userTimezone->getOffset($myDateTime);
$myInterval = DateInterval::createFromDateString((string)$offset . 'seconds');
$myDateTime->add($myInterval);
$result = $myDateTime->format('Y-m-d H:i:s');
dpm($result);

```

And now my output date it's fine:

```
2017-02-27 19:30:01

```

This works. But I'm sure that there is a way to do this using the Drupal API.

# Answer
> 4 votes
I usually solve it this way.:

```
node = Node::load(1);
$date_original= new DrupalDateTime( $node->field_date->value , 'UTC' );
$result = \Drupal::service('date.formatter')->format( $date_original->getTimestamp(), 'custom', 'Y-m-d H:i:s'  );
dpm( $result );

```

# Answer
> 3 votes
This worked for me:

```
// Take the timestamp.
$timestamp = $form_state->getValue($form_field)->getTimestamp();
// Convert to UTC - the way its saved in database.
$date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
// Add on the current entity.
$this->entity->{$db_field}->value = $date->format("Y-m-d\TH:i:s");

```

# Answer
> 1 votes
This code is working for me.

```
// set use timezone
userTimezone = new DateTimeZone(drupal_get_user_timezone());
// set gmt timezone
$gmtTimezone = new DateTimeZone('GMT');
// Take the timestamp.
$start_date = $val['field_start_time_value'];
$startDateTime = new DateTime($start_date, $gmtTimezone);
$offset = $userTimezone->getOffset($startDateTime);
$startInterval = DateInterval::createFromDateString((string)$offset . 'seconds');
$startDateTime->add($startInterval);
$result = $startDateTime->format('Y-m-d H:i:s');

```

# Answer
> 0 votes
None of these other answers worked for me. This is what I finally ended up with:

```
$range_start = DrupalDatetime::createFromTimestamp((int)$start_date); // unix timestamp
$range_start->setTimezone(new \Datetimezone('EST'));
$node->field_date_range->value = format_date(
  $range_start->getTimestamp() , 'custom', 'Y-m-d\TH:i:s', 'EST');

```

# Answer
> 0 votes
I use this snippet to work with dates :

```
<?php
class MyApp extends ControllerBase
{
    public function output()
    {
        $dtime = DateTime::createFromFormat("d/m/Y - H:I:s", "22/12/1999 - 22:55:12", $this->getDateTimeZone());
        $time = $dtime->format('r');
        // My code goes here
    }

    private function getDateTimeZone()
    {
        return new DateTimeZone(drupal_get_user_timezone());
    }
}

```

You can get more informations about the Datetime object here

---
Tags: 8, datetime
---


# Question
Title: How to get all users with a specific permission
Is there a way to retrieve all users with a specific permission (eg "Post comments"). I only found the possibility to get them by their role:

```
Drupal::entityQuery('user')
->condition('status', 1)
->condition('roles', 'administrator')
->execute();

```

or

```
Drupal::service('entity_type.manager')
->getStorage('user')
->loadByProperties(['roles' => 'administrator']);

```

# Answer
I had to get the roles that had a given permission to get users with a permission, example:

```
$roles = user_role_names(FALSE, 'example_permission');
$rids = array_keys($roles);

$uids = Drupal::service('entity_type.manager')->getStorage('user')->getQuery()
  ->condition('roles', $rids, 'IN')
  ->execute();

```

Apparently thats what Drupal core does in the permission filter for views, see: \Drupal\user\Plugin\views\filter\Permissions

Hope that helps some!
> 5 votes

---
Tags: 8, users
---


# Question
Title: How do I fix a ReflectionException error (class doesn't exist)?
I'm new to drupal 8. I would like to extend the user login form by deleting the username field and adding the email field. So I created a custom module, I implemented an Event Subscriber and declared it as a service :

```
services:
    mdmuser.route_subscriber:
        class: Drupal\mdm_user\Routing\RouteSubscriber
        tags:
             - {name: event_subscriber }

```

And here's my class RouteSubscriber

```
 <?php

 /**
 * @file
 * Contains \Drupal\mdm_user\Routing\RouteSubscriber.
 */

 namespace Drupal\mdm_user\Routing;

 use Drupal\Core\Routing\RouteSubscriberBase;
 use Symfony\Component\Routing\RouteCollection;

 /**
 * Listens to the dynamic route events.
 */
 class RouteSubscriber extends RouteSubscriberBase {

 protected function alterRoutes(RouteCollection $collection) {

     if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\mdm_user\Form\UserLoginForm');
      $collection->add('user.login', $route);
    }
  }
}

```

I have this error when I want to install my new module :

```
ReflectionException: Class Drupal\mdm_user\Routing\RouteSubscriber does not exist in ReflectionClass->__construct() (line 31 of core/lib/Drupal/Core/DependencyInjection/Compiler/RegisterEventSubscribersPass.php).

```

Any idea is appreciated !

Thanks

# Answer
> 2 votes
It has to be the file structure. Check again that it's at /modules/custom/mdm\_user/src/Routing/RouteSubscriber.php

Also, in your class, you don't need to add the route again, it's passed by reference.

You can remove

```
$collection->add('user.login', $route);

```

# Answer
> 1 votes
If you are getting above error message then I suggests following things to check for,

1. Check if there are any spelling mistakes in the routing file, that is may be the name you have written is something and the file name is something else.
2. Check the class name defined in the controller file matches the file name
3. Folder structure is something like '\Drupal\module\_name\src\Controller\exampleConfig.php' but the routing file will have something like this "\Drupal\module\_name\Controller\exampleConfig" don't worry about the "src" folder
4. Check your namespace if it exists or not and if properly written or not
5. Check for unnecessary extra lines in \*.routing.yml of your module.
6. Add 'Controller' to end of file with your Controller Class and to end of Class Name of Controller.

I have the approach of issue with below:

Try command in bash near web/ dir of drupal 'drupal gcon', see also

Hope this helps.

Happy Coding....

# Answer
> 0 votes
Ran into the same issue. It ended up being stupid mistake in my namespace in my RouteSubscriper.php file. I had:

```
namespace Drupal\my_module\Routing\RouteSubscriber;

```

When it should have been:

```
namespace Drupal\my_module\Routing;

```

---
Tags: 8, event-subscribers
---


# Question
Title: Automatically creating an organic group for each new user
I would like to automatically create an organic group for each newly registered user. I checked all its settings, no such option with organic groups module, then I checked the rules module but no luck there too.

# Answer
The Rules module will allow you create new OG node after saving a new user account. Just do the following:

* Create your rule and add an "After saving new user account" event to it
* In the action section, select create a new entity
* In the value section, select node
* In the Content type, select the "your group"
* Fill the title as you need; you can do this using the token
* Fill the author

Hope this will help.
> 0 votes

# Answer
Ok so here is another way to do it, if you dont want to do it with rules;

```
    <?php
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters the user registration form by adding a custom submit handler.
 */
function custom_user_insert(&$edit, $account, $category) {
  if (isset($account->is_new) && !empty($account->is_new)) {
        //print '<pre>';print_r($account);die;
        $groupnode = new stdClass();
        $groupnode->type = 'group'; // Group node type
        $groupnode->status = 1;
        //$groupnode->language ='de';
        $groupnode->uid =  $account->uid;
        $groupnode->title = 'group name comes here';
        //here I save the uid from the activated user
                $groupnode->field_group_user['und'][0]['value'] = $account->uid;
        //$groupnode->{OG_GROUP_FIELD}['und'][0]['value'] = '1';

        node_save($groupnode);
        $nid = $groupnode->nid;
        og_group('node',$nid, array(
        //"entity type"       => 'user', // defaults to user
        "entity"        => $account->uid,
        'field_name' => 'og_user_node',
        'state' => 1,//OG_STATE_ACTIVE
        'force_reload' => TRUE
        ));
        //drupal_set_message('Do it!');
        // Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
        og_role_grant('node',$nid, $account->uid, 12);

        $assign_grp_userid=loadusers_by_role('coaching expert');

         og_group('node',$nid, array(
        //"entity type"       => 'user', // defaults to user
        "entity"        => $assign_grp_userid,
        'field_name' => 'og_user_node',
        'state' => 1,//OG_STATE_ACTIVE
        'force_reload' => TRUE
        ));
        //drupal_set_message('Do it!');
        // Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
        og_role_grant('node',$nid, $account->uid, 11);
  }
}

```
> 0 votes

---
Tags: 7, rules, organic-groups
---


title: How to redirect a user on login?

text:
# Question
Title: How to redirect a user on login?
I have a registration form, when submitted, the user gets logged in automatically.

I want to redirect the users to a specific page on login. Whether they are logged in using the login form or through the registration form.

I used the following code first,

```
function yourmodule_user_login($account) {
  // We want to redirect user on login.
  $response = new RedirectResponse("yourpath");
  $response->send();
  return;
}

```

This is not working because it's called before submit handlers so this would prevent them from being called.

Then I added a custom submit handler to the login form and redirect the users in that submit handler.

```
$form_state->setRedirect('mymodule.mypage');

```

This works fine only when the user logged in using the login form but not working for the registration form. When I use a custom submit handler for the registration and redirect the user there, I think at that time the user is not logged when the redirection occure.

Is there any other method to redirect the users on login through code?

# Answer
> 1 votes
One way to do this without programming is to use Rules.

The advantage of using Rules for this is that if you want to modify the functionality - change the redirect page, put conditions on which users get redirected, etc. - those changes can be made with a few clicks rather than rewriting module code. This allows the site functionality to be modified and maintained without programming, much as Views and Workflow etc. all allow the site administrator to develop site functionality and content without direct programming. If you're building a site to hand off to a client, for instance, this is a very important point to take into account.

Rules automatically exposes core Drupal hooks as Symfony events and allows you to listen for these event and conditionally execute actions when those events happen. Redirecting on login is one of the classic use cases. Here is a Rule export from the rules\_examples module - it is a configuration file so all you have to do is import it and it will work. You can edit it through the Rules UI or manually to suit your specific situation.

```
langcode: en
status: false
dependencies: {  }
id: redirect_on_login
label: 'Redirect users on Login'
events:
  -
    event_name: rules_user_login
description: 'Issue #2858817-8: Redirect users to /special-page on login.'
tags:
  - login
  - redirect
  - rules_examples
config_version: '3'
expression:
  id: rules_rule
  uuid: 7263942c-3847-460d-af3f-6c78f80fbcc1
  conditions:
    id: rules_and
    uuid: a8c1bb95-b783-4238-a7e1-9b4b9fb96ca4
    conditions: {  }
  actions:
    id: rules_action_set
    uuid: d17285ef-4de4-498a-8b78-654cf79566ee
    actions:
      -
        id: rules_action
        uuid: a529b090-e6f3-4421-aede-75489267d888
        context_values:
          url: /special-page
        context_mapping: {  }
        context_processors:
          url:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_page_redirect

```

# Answer
> 0 votes
Subscribe to the UserLogin event like below:

in yourmodule/src/Event/UserLoginEvent:

```
<?php

namespace Drupal\yourmodule\Event;

use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * Event that is fired when a user logs in.
 */
class UserLoginEvent extends Event {

  const EVENT_NAME = 'yourmodule_user_login';

  /**
   * The user account.
   *
   * @var \Drupal\user\UserInterface
   */
  public $account;

  /**
   * Constructs the object.
   *
   * @param \Drupal\user\UserInterface $account
   *   The account of the user logged in.
   */
  public function __construct(UserInterface $account) {
    $this->account = $account;
  }

}

```

in yourmodule/src/UserLoginSubscriber.php:

```
<?php

namespace Drupal\yourmodule\EventSubscriber;

use Drupal\yourmodule\Event\UserLoginEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class UserLoginSubscriber.
 *
 * @package Drupal\yourmodule\EventSubscriber
 */
class UserLoginSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      // Static class constant => method on this class.
      UserLoginEvent::EVENT_NAME => 'onUserLogin',
    ];
  }

  /**
   * React to the user login event dispatched.
   *
   * @param \Drupal\yourmodule\Event\UserLoginEvent $event
   *   Dat event object yo.
   */
  public function onUserLogin(UserLoginEvent $event) {
    $response = new RedirectResponse("yourpath");
    $response->send();
    return;
  }

}

```

# Answer
> 0 votes
include this code at the top

```
use Symfony\Component\HttpFoundation\RedirectResponse;

```

then code this for redirection

```
$response = new RedirectResponse('YOURPATH');
$response->send();
return;

```

---
Tags: 8, users, redirection
---


# Question
Title: How to upgrade to Drupal 8 from 7 with clean install?
I currently have a Drupal 7 site that I want to install Drupal 8, but do a clean install. This means wiping away everything and starting with a new Drupal 8 instance. I have seen many articles on how to upgrade where the content types, fields, code, and other parts are migrated. However, I just want to upgrade to Drupal 8 without any migration of the content type, files, databases, and remove old directories that are not needed for Drupal 8.

How can I upgrade to Drupal 8 without any migration for a clean instance?

# Answer
If I'm understanding your situation correctly in that you just want a new Drupal 8 website without any of the content from your existing Drupal 7 website then you would just simply install Drupal 8 from scratch, as if you didn't even have an old site.

Once the new Drupal 8 website is installed you can then create/re-create any content that you'd like.
> 1 votes

---
Tags: 8, migrations, composer, upgrading
---


title: Post form to external URL

text:
# Question
Title: Post form to external URL
I need to POST the data in a form to an external URL.

In Drupal 7, you would use

```
$form['#action'] = url('http://example.com', array('external' => true));

```

Or maybe this was for GET. Anyway... in Drupal 8, this does not work. I have tried editing the submitForm method:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new TrustedRedirectResponse('http://example.com');
    $response->send();
}

```

This works, however I have not found a way to submit the values of the form along with the request. I looked at the httpClient class, but it seems that is for sending/requesting data only and does not redirect the user.

Hope someone can help me out. If it comes down to it I am fine with using GET instead.

# Answer
> 3 votes
`$form['#action']` works the same, Drupal 7 or Drupal 8. It needs a string, which is what `url()` returns in Drupal 7. The reason why `url()` is normally used is because the code has a relative path for a routing item, such as in `url('comment/reply/'. $edit['nid'])`.

In Drupal 8, for example, the Comment module uses the following code.

```
$form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));

```

`UrlGeneratorTrait::url()`, the method called in that code, still returns a string, not an object. Also in this case, `UrlGeneratorTrait::url()` is used because the code has a route name (comment.reply) and it wants to get the URL for that route.

The following code works for Drupal 7 and Drupal 8.

```
$form['#action'] = 'http://example.com';

```

# Answer
> 1 votes
OK I figured it out. It turns out that the Drupal 7 method works, however there is no longer a need to submit a URL object, just a string containing the URL. So

`$form['#action'] = url('http://example.com', array('external' => true));`

becomes simply

`$form['#action'] = 'http://example.com';`

# Answer
> 0 votes
your sample code would work just fine for simple redirection.

However for posting data to external URL, this should work i believe,

```
$response = \Drupal::httpClient()->post($host, [
        'form_params' => $fields,
        'headers' => [
          'Content-type' => 'application/x-www-form-urlencoded',
        ],
    ]);

```

Answered Similar Question in https://drupal.stackexchange.com/a/288929/18756

---
Tags: forms, 8, uri, redirection
---


# Question
Title: How to build a simple data comparison rule?
I am working on Drupal 8.7.10 and I have installed a fresh Rules 8.x-3.0-alpha5.

Could someone help me to start a very simple rule? I am still struggling with the "new" Rules.

All I need is to send an email to a specific role when a specific field has changed.

"Rulesly" speaking, after a node has been updated, if the unchanged field value is different from the changed field value, then send an email to the manager, with a link to the updated node.

P.S. : I have also started to work with Business Rules so if someone can build this with this module, that sounds good too!

# Answer
OK, I would then recommend Business Rules to build that kind of data comparison rule.

1- Create a first Variable "Value from Entity field" to store the original value of your field.

2- Create a second Variable "Value from Entity field" to store the current value of your field (i.e. the saved value after updating node)

3- Create an Action "Send an email"

4- Create a Condition "Variable data comparison" to compare the two variables you built in 1 and 2. Available variables are listed, use {{your\_variable\_name}}. Use the right operator, here I needed != (different from).

5- Inside your Condition, add the Action "Send an email" (in section "Items to execute if condition succeed")

6- Create a Rule based on an event "After updating Entity", define the context (entity type and bundle, here content and content type) and insert the Condition you built in 4. You should see a nice flowchart with your Rule label (white), then your Condition label (blue) and if YES, your Action label (green).

That's a start.

Hope this helps.
> 1 votes

---
Tags: 8, rules
---


# Question
Title: How can I get the Register form on the front page?
I've managed to create a new theme, customize the front page pretty much how I wanted it, and I've encountered a problem.

I need to get the register form (create new account) in a pop-up on the front page.

After following the instructions from Form API in Drupal 8:

```
    <?php

/**
* @file
* Functions to support theming in the themename theme.
*/

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

/**
* Implements hook_preprocess_HOOK() for HTML document templates.
*/

function themename_preprocess_html(&$variables) {

$form = \Drupal::formBuilder()->getForm('Drupal\user\register');

return $form;
}

```

I can't figure out what I'm doing wrong, because I get an error saying that is not a valid form. I have also tried using the form id as a parameter, still no valid form.

Could anyone please help? I could use a working example.

# Answer
> 1 votes
The correct form id shoud be `Drupal\user\RegisterForm`. However, because the register form is attached to an entity, you can't use `getForm` directly. You need to create an entity and then get the register form for that entity.

The role of the preprocess function is to add / modify / delete template variables via the `$variables` parameter, so you need to add the form to that array rather than return it.

Something like this should work:

```
function themename_preprocess_page(&$variables) {
  $entity = \Drupal::entityManager()
    ->getStorage('user')
    ->create(array());

  $formObject = \Drupal::entityManager()
    ->getFormObject('user', 'register')
    ->setEntity($entity);

  $form = \Drupal::formBuilder()->getForm($formObject);
  $variables['register_form'] = $form;
}

```

Now you should be able to print the form via `{{ login_form }}` in the `page.html.twig` template.

# Answer
> 0 votes
Alternatively, use the module FormBlock (https://www.drupal.org/project/formblock) to make the registration form available as a block, and then add a "popup" region to your theme, and using the blocks UI place the block in that region just for the front page.

# Answer
> 0 votes
This is working well for me at the moment:

```
$formBuilder = \Drupal::service('entity.form_builder');
$form = $formBuilder->getForm(User::create(array()), 'register', array());

```

# Answer
> 0 votes
A shorter answer, mixing the previous one would be to use the entity.form\_builder service for the register form. The answer of @joekers is good on that, it's not necessary to load the entityManager just to display a form.

```
// Load the service renderer
$render = Drupal::service('renderer');

// User login form
$login_form = Drupal::formBuilder()->getForm('Drupal\user\Form\UserLoginForm');
$variables['login_form'] = $render->renderPlain($login_form);

// User registration form
$register_form = \Drupal::service('entity.form_builder')->getForm(\Drupal\user\Entity\User::create([]), 'register', []);
$variables['register_form'] = $render->renderPlain($register_form);

```

As we can see, the method to render Register and Login forms are different, because Register is link to the User entity.

---
Tags: forms, theming, hooks, 8
---


# Question
Title: Add value to a custom composite element in webform via hook_update_N
Testing out some bits with webform. I have created a webform via my module. In it I have a number of elements including a custom composite. Inside the custom composite I have several elements, one is a **select** element with a list of options (i.e. allowed values).

Now comes time I need to do some updates. That is run hook\_update\_N on an existing module/set-up. I have updates for all other fields (not webform) working correctly. Rough code shown below:

```
/**
  * Update for mymodule to add more options to the paragraph and webform custom composite.
  */
 function mymodule_update_8001() {
   // Updates the paragraph allowed field
   $fields = \Drupal::entityTypeManager()->getStorage('field_storage_config')->loadByProperties(array('field_name' => 'myfield'));

   foreach ($fields as $field) {
     $allowed = $field->getSetting('allowed_values');

     // New value(s) to add here.
     $allowed['test'] = 'bob was here...';
     $field->setSetting('allowed_values', $allowed);
     $field->save();
   }

   // Code to update the custom composite element to go here.

 }

```

I know it is rough code, ignoring that, still getting my head around the changes to Webform too. I know the **\Drupal::entityTypeManager()-\>getStorage** method doesn't work for webform composite custom elements and can't see any update function in the composite example module.

So the question is how to I get the options (allowed values) of a select in a custom composite from the webform so I can edit, add, update, etc... when I do other updates to my module?

The method noted in How do I programmatically update the allowed values of a list field? works for basic fields but with for dynamic options. It will not cover what I need here as (a) it is not performing an update of existing fields and (b) doesn't appear to work with custom composite in WebForm, or at least I cannot get it to work, with a select.

# Answer
> 0 votes
After trawling through the Webform source think I have an answer.

```
/**
 * Update using hook_update_N for mymodule to add more options to a webform custom composite.
 */

function mymodule_update_8001() {

    . . .

    // Update a composite element in a webform
    $webform = \Drupal::entityTypeManager()->getStorage('webform')->load('webform_id');
    $elements = $webform->getElementsDecodedAndFlattened();

    // Add new options here.
    $elements['my_composite_id']['#element']['my_composite_element_id']['#options']['my_new_option'] = 'My new option text';

    $webform->setElements($elements);
    $webform->save();

    . . .

}

```

Please let me know if there is a better way.

---
Tags: webforms
---


# Question
Title: How to prevent a user from deleting an entity referenced node before deleting the referencing (child) node first?
I have a Content Type called `ItemRequest`, and another Content Type called `ItemOrder`. One of the fields in `ItemOrder` is "Related Item Request" that is an Entity Reference to `ItemRequest`. Each `ItemOrder` has at least one Related Item Request.

How do I ensure that a parent `ItemRequest` node can only be deleted if it does not have any `ItemOrder` nodes relating to it? What hook can I use that can test for the existence of these child nodes and call form\_set\_error to abandon node deletion?

# Answer
> 1 votes
You can use hook\_node\_access:

> Modules may implement this hook if they want to have a say in whether or not a given user has access to perform a given operation on a node.

The second parameter for this hook is $op:

> $op: The operation to be performed. Possible values:
>
> "create" "delete" "update" "view"

And the return values are:

* NODE\_ACCESS\_ALLOW: if the operation is to be allowed.
* NODE\_ACCESS\_DENY: if the operation is to be denied.
* NODE\_ACCESS\_IGNORE: to not affect this operation at all.

So, you should implement that hook, check if the node being deleted is of type `ItemRequest` and if yes collect all the ItemOrder that point to it. If none are collected you can return `NODE_ACCESS_IGNORE`, if there're `ItemOrder` pointing to the `ItemRequest` return `NODE_ACCESS_DENY`.

While you can hook into the node form and add a custom validator that doesn't prevent user to delete the node using other means (admin content view, for example). This method can prevent any action trying to delete a node.

---
Tags: 7
---


# Question
Title: Where is the temporary directory defined in the code?
I wonder where the tmp dir is set in the code of Drupal 8. Indeed the upload\_tmp\_dir value is not set in the php.ini and I have no access to change it.

Where in the code the value is defined and change it?

# Answer
> 3 votes
The logic for finding the proper OS temp directory is in `FileSystem::getOsTemporaryDirectory`. This will try to use `upload_tmp_dir`, otherwise default back to an OS value, like `/tmp`.

This get used in `file_directory_temp()`. If you read this function, you will see that the config value gets read first, and then it will try to get the OS default.

Personally, I set the filesystem paths in my settings.local.php file, so I can have a different value per environment, eg

```
$config['system.file']['path']['temporary'] = '/var/www/staging/tmp';

```

You also need to ensure that the file is writable by the webserver. Securing file permissions and ownership is the canonical reference on this, but in short something like

```
sudo chown -R www-data:www-data /var/www/staging/tmp
sudo find /var/www/staging/tmp -type f -exec chmod 664 {} \;
sudo find /var/www/staging/tmp -type d -exec chmod 2775 {} \;

```

will work.

# Answer
> 2 votes
You can find the setting in /admin/config/media/file-system. If you need that in php, you can use code like

```
Drupal::configFactory()->get('system.file');

```

The correct config for your tmp dir is `system.file.path.temporary`. Check it in the UI with config-sync of simple config "system.file". Check `class FileUploadResource` for an example.

# Answer
> 1 votes
You are wanting to hack the core. Which is evil. You simply can set another temporary directory on https://example.com/admin/config/media/file-system.

---

Via Drush.

```
$ drush -y config:set system.file path.temporary /Users/norman/Sites/temp

```

---

Alternatively but also quite evil is overriding PHP config from your settings.php. But note that some server setups may block PHP script files containing `ini_set()` calls, resulting in a WSOD.

`ini_set('upload_tmp_dir', '/tmp');`

---
Tags: 8, configuration
---