# Question
Title: How to add a display format for the field
I have a field of list type in my custom content type. The display format of list type field has two options default(value) and key. In my case i want third option which will display "key and value". How can i add third option or get the key/value for the field.

# Answer
Here is an example on how to create custom field formatters

https://github.com/npinos/drupal8-field-formatters

You can directly specify the markup like this extending the FormatterBase class:

```
<?php
/**
 * @file
 * Contains Drupal\drupal8_field_formatters\Plugin\Field\FieldFormatter\MainHeadingFormatter.
 */
namespace Drupal\drupal8_field_formatters\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
 * Plugin implementation of the 'main_heading_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "main_heading_formatter",
 *   label = @Translation("Heading 1"),
 *   weight = "10",
 *   field_types = {
 *     "string",
 *     "text",
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class MainHeadingFormatter extends FormatterBase {
  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];
    foreach ($items as $delta => $item) {
      // Render each element as markup.
      $element[$delta] = [
        '#type' => 'markup',
        '#markup' => '<h1>' . $item->value . '</h1>',
      ];
    }
    return $element;
  }
}

```
> 2 votes

# Answer
You will require to write your own custom field formatter to achieve that. There are detailed docs at : https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-formatter

File /modules/custom\_module/src/Plugin/Field/FieldFormatter/KeyValueFormatter.php

```
<?php

namespace Drupal\custom_module\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'key_value' formatter.
 *
 * @FieldFormatter(
 *   id = "key_value_list",
 *   label = @Translation("Key - value"),
 *   field_types = {
 *     "list_string"
 *   }
 * )
 */

```

The `field_types` key determines the type of the field this formatter will be available to. Just override the `viewElements` function in the `KeyValueFormatter` class and let them display key - value.

I would recommend extending `Drupal\options\Plugin\Field\FieldFormatter\OptionsDefaultFormatter` instead of `FormatterBase` as suggested by the docs.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Where does the menu trail get added into the $data parameter in pathauto_tokens()?
I have seen this post: where does $data come from in hook\_tokens?, but that did not help me answer my question, maybe it could've but there's no way for me to interact with that post.

I am working in Drupal 8.5, using pathauto 8.x-1.1.

I am looking at pathauto.tokens.inc, here is the code for pathauto's hook\_tokens():

```
function pathauto_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();

  if ($type == 'array' && !empty($data['array'])) {
    $array = $data['array'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'join-path':
          $values = array();
          foreach (token_element_children($array) as $key) {
            $value = is_array($array[$key]) ? render($array[$key]) : (string) $array[$key];
            $value = \Drupal::service('pathauto.alias_cleaner')->cleanString($value, $options);
            $values[] = $value;
          }
          $replacements[$original] = implode('/', $values);
          break;
      }
    }
  }

  return $replacements;
}

```

I can't seem to find how the menu trail makes it into the $data parameter. I can see the menu trail in $data when I set a breakpoint at array = data\['array'\].

My ultimate goal is to figure out why pages with a menu\_position rule associated with them are not getting the joined-path history in their url alias.

# Answer
Token resolving is recursive. The caller of replace() is responsible for providing the data.

As far as this token is considered, it's not an active trail, it's just an array with strings that is combined together.

Your token probably looks something like `[node:menu-link:parents:join-path]`. If this doesn't receive the right parents then you need to look at where the parents are fetched and passed on, which is in token.module: https://cgit.drupalcode.org/token/tree/token.tokens.inc#n721

And if it is a different token then you need to look up whatever intermediate tokens you are using
> 0 votes

---
Tags: 8, path-aliases, tokens
---


# Question
Title: Does the #cache property for render arrays cache content from a query when used in a controller?
I have a custom page displaying a query result from the database. Before I attempt to cache it myself, I am trying to see if Drupal 8 render arrays support caching in anyway for authenticated users. My use case is a route and a controller on the node entity. Users go to node/id/something that displays a list of entries in a table. I would like to cache this in the controller.

I am using the following code.

```
public function displayContent(NodeInterface $node) {
  // query the DB to generate content.
   $content['#markup'] = $result_of_db_query;

    $content['#cache'] = [
      'keys' => ['entity_view', 'node', $node->id()],
      'tags' => ['node:' . $node->id()],
      'max-age' => Cache::PERMANENT,
    ];
    return $content;
}

```

It doesn't work: The database query is executed on every page request. I am not sure if this is due to the fact this page is an administrative page and users must be authenticated.

# Answer
> 3 votes
Now that the topic is open again I will try to answer the questions:

> Does the #cache property for render arrays cache content from a query when used in a controller?

Yes, it does. The cache metadata will be used to cache the render array if you set cache keys and the metadata bubbles up to page level.

> The database query is executed on every page request. I am not sure if this is due to the fact this page is an administrative page and users must be authenticated.

On page level this is true, as for now it is presumed that admin pages are not cacheable, see Change Dynamic Page Cache's response policy from "deny admin routes" to "deny html admin routes"

> I expect the content to be cached and the query that generate the result to not run on every page request.

See the comments from @Berdir and this blog post how to do this by moving the query to a `#pre_render` callback:

https://dev.acquia.com/blog/drupal-8-performance-render-caching

---
Tags: 8, theming, caching
---


# Question
Title: Why does composer not work with core composer.json file when adding new libraries?
When you download the source from here, and run composer:

```
php composer.phar require facebook/graph-sdk

```

I get:

```
    You are running Composer with SSL/TLS protection disabled.
Using version ^5.6 for facebook/graph-sdk
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.4
9m

  Problem 1
    - Conclusion: don't install symfony/http-kernel v2.8.27
    - ...
    - Conclusion: don't install symfony/http-kernel v2.8.5
    - Conclusion: remove symfony/http-kernel v2.8.4
    - Conclusion: don't install symfony/http-kernel v2.8.4
    - ...
    - Installation request for symfony/http-kernel ~2.8 -> satisfiable by symfony/http-kernel[2.8.x-dev, v2.8.0, v2.8.0-BETA1, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.17, v2.8.18, v2.8.19, v2.8.2, v2.8.20, v2.8.21, v2.8.22, v2.8.23, v2.8.24, v2.8.25, v2.8.26, v2.8.27, v2.8.3, v2.8.4, v2.8.5, v2.8.6, v2.8.7, v2.8.8, v2.8.9].
    - Conclusion: don't install symfony/debug v3.0.9
    - symfony/http-kernel 2.8.x-dev requires symfony/debug ^2.6.2 -> satisfiable by symfony/debug[v2.7.6, 2.6.x-dev, 2.7.x-dev, 2.8.x-dev, v2.6.10, v2.6.11, v2.6.12, v2.6.13, v2.6.2, v2.6.3, v2.6.4, v2.6.5, v2.6.6, v2.6.7, v2.6.8, v2.6.9, v2.7.0, v2.7.0-BETA1, v2.7.0-BETA2, v2.7.1, v2.7.10, v2.7.11, v2.7.12, v2.7.13, v2.7.14, v2.7.15, v2.7.16, v2.7.17, v2.7.18, v2.7.19, v2.7.2, v2.7.20, v2.7.21, v2.7.22, v2.7.23, v2.7.24, v2.7.25, v2.7.26, v2.7.27, v2.7.28, v2.7.29, v2.7.3, v2.7.30, v2.7.31, v2.7.32, v2.7.33, v2.7.34, v2.7.4, v2.7.5, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.0-BETA1, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.17, v2.8.18, v2.8.19, v2.8.2, v2.8.20, v2.8.21, v2.8.22, v2.8.23, v2.8.24, v2.8.25, v2.8.26, v2.8.27, v2.8.3, v2.8.4, v2.8.5, v2.8.6, v2.8.7, v2.8.8, v2.8.9].
    - Can only install one of: symfony/debug[v3.0.9, v2.7.6].
    - ...
    - Can only install one of: symfony/debug[v2.8.9, v3.0.9].
    - Installation request for symfony/debug (locked at v3.0.9) -> satisfiable by symfony/debug[v3.0.9].

Installation failed, reverting ./composer.json to its original content.

```

Surely the core composer file that comes with Drupal can work with the facebook SDK. What am I missing?

# Answer
> 2 votes
Hope it helps someone else. The issue was that I only updated drupal's /core folder, not composer.json. So I had a very old composer file. When I updated it with the composer.json from the latest D8 download, things started working again.

# Answer
> 1 votes
This likely to be not related to `facebook/graph-sdk`, since it doesn't require any symfony related packages as per:

```
composer show facebook/graph-sdk ^5.6

```

The error happens during update of your dependencies where your existing `symfony/debug` package is `locked at v3.0.9` (as per your `composer.lock`) and another package requires `^2.6.2` and you are able to install one branch within same `vendor` dir.

To find out which existing packages requiring `symfony/debug`, run:

```
composer why symfony/debug -t

```

I had similar issue when I've tried to install `drush/drush` `~8@stable` and `drupal/console-core` `1.8.0` in the same folder and it failed due to incompatible dependencies. I've reported this issue at `hechoendrupal/drupal-console-core` (GH-338).

Related posts:

---
Tags: 8, composer
---


title: Get the views field value

text:
# Question
Title: Get the views field value
How to get the views field value and make a condition base on that field. Let say may views field is 'field\_state'

Example below:

```
function my_module_views_pre_render(ViewExecutable $view) {
  //current user id
  $user_id = \Drupal::currentUser()->id();
  //load user data
  $user = \Drupal\user\Entity\User::load($user_id);
   // Get user state
  $state = $user->get('field_state')->getValue()[0]['value'];
  if ($state == Views field_state value) {
        $view->field['field_state']->options['exclude'] = TRUE; // exclude field for only this result ???
  }
  else{
    $view->field['field_state']->options['exclude'] = FALSE; // include field for only this result ???
  }
}

```

Is it possible on views pre-render or I need to use the different hook?

# Answer
You should try `hook_views_post_build()`. I haven't tried this but I was looking at the views api and noticed that hook\_views\_post\_build shows an example of modifying the `exclude` property of a field.
> 0 votes

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


# Question
Title: How to combine block form submit result with on fly created content together in Drupal 8
I write a custom module in Drupal 8.

Have my custom block defined:

```
class MyBlock extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build(){
     $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\myform');
     $markup = bunch of html here;
     $content = data feed from 3rd party;
     return array(
      '#markup' => $form + $markup + $content,
     );
  }
}

```

What I want is, that after block build have both form and feed data in format html way show up. Any suggestions will be appreciated.

# Answer
There are two ways you can do this. You can put the results in the form, or you can put the results in the block. Choosing which one to do will depend upon how the form should work - if you were to use this form in another location, and would want the results to show in that location as well, then you should put the results in the form as follows:

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

  // Note: Form build not shown.

  $results = some_function_that_returns_results();
  $form['results'] = [
    '#prefix' => '<div id="results_wrapper">',
    '#suffix' => '</div>',
  ];
  foreach ($results as $result) {
    $form['results'][] = [
      '#prefix' => '<div class="result">',
      '#suffix' => '</div>',
      '#markup' => $result,
    ];
  }

  return $form;
}

```

If you only want the results to show if the form is in the block, and not in other places where the form would be shown, you add the results to the block as follows:

```
public function build(){
  $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\myform');
  $markup = bunch of html here;
  $content = ‘some data’;

  $block = [
    'form' => $form,
    'markup' => [
      '#markup' => $markup
    ],
    'content' => [
      '#markup' => $content,
    ],
  ];

  $results = some_function_that_returns_results();
  $block['results'] = [
    '#prefix' => '<div id="results_wrapper">',
     '#suffix' => '</div>',
  ];
  foreach ($results as $result) {
    $block['results'][] = [
      '#prefix' => '<div class="result">',
      '#suffix' => '</div>',
      '#markup' => $result,
    ];
  }
}

```
> 1 votes

---
Tags: forms, blocks
---


# Question
Title: How to display the rendered entity of entities flagged with a Search API view?
I created an index view "Search API".

I added the flags to the index.

How to display the rendered entity of entities flagged with a Search API view?

Currently only the title is displayed, I want to display the display mode "Teaser".

# Answer
Have you tried to change the configuration of the **Format** section ?

Instead of "Fields" you might be able to select "Rendered entity" and then under **Settings** link, you will be able to choose a view mode like "Teaser".
> 1 votes

---
Tags: 8, entities, search
---


# Question
Title: delete URLs of all terms for a specific taxonomy vocabulary
Using pathauto module, I know we have a **Delete aliases** tab to delete URLs in bulk but what if we need to delete URLs of all terms for specific vocabulary?

Any idea how to do that?

# Answer
> 2 votes
To **delete** the aliases you will need a custom module or perhaps a custom VBO action based on the `update taxonomy term alias` action. Here is a quick and dirty version of a custom module

**aliases\_delete.info**

```
name = delete aliases
description = will delete vocabulary aliases for specific vocabulary
package = aliases_delete
version = 1
core = 7.x
dependencies[] = pathauto

```

**aliases\_delete.module**

```
<?php

function aliases_delete_menu() {
  $items['aliases_delete/%'] = array(
    'page callback' => 'aliases_delete_delete_vocabulary',
    'page arguments' => array(1),
    'access callback' => 'taxonomy_term_edit_access',
    'access arguments' => array(2),
  );
  return $items;
}

function aliases_delete_delete_vocabulary($vocabulary_name){
  $vocab = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocab->vid));
  foreach ($terms as $term) {
    pathauto_entity_path_delete_all('taxonomy_term', $term, "taxonomy/term/{$term->tid}");
  }
  return 'Deleted aliases of all terms in ' . $vocabulary_name;
}

```

If you enable and install this module you can visit as admin `aliases_delete/tags` to delete all aliases of terms in vocabulary **tags**

To **update** the path aliases of specific taxonomy terms (instead of **deleting**) you can use VBO - views\_bulk\_operations

* install and enable the module
* create a view of taxonomy terms and use appropriate filters for vocabulary
* add field "view bulk operations" and save your view
* go to your view and select all terms that will be updated (VBO can select multiple pages of results)
* choose the `update taxonomy term alias` action and press `execute`
* all terms should be updated according to the new pathauto rules

---
Tags: 7, path-aliases
---


title: Complete project package

text:
# Question
Title: Complete project package
I have been working on a D8 project and been wondering what the best course of action would be in order to produce a complete project package that can be easily set up in a new drupal installation. The theme part is pretty straightforward but what about all the specific content types that accompany a project with a specific theme? Is there a way I can have those being created on theme installation?

# Answer
> 0 votes
The best practice for is to use Configuration import/export.

> Exporting and importing configuration changes between a Drupal installation in different environments, such as Development, Staging, and Production, allows you to make and verify your changes with a comfortable distance from your site's live environment.

# Answer
> 0 votes
You can add the needed configuration files of the content types and fields needed for the site in a folder named config/install in your theme directory. These configuration gets imported when we install it.

for eg: if you want to create a content type test when your theme is installed

**Create a file node.type.test.yml in your\_theme/config/install folder paste the code in it**

```
langcode: en
status: true
dependencies:
  module:
    - menu_ui
third_party_settings:
  menu_ui:
    available_menus:
      - main
    parent: 'main:'
name: test
type: test
description: ''
help: ''
new_revision: true
preview_mode: 1
display_submitted: true

```

**Easy method is to**

* create the content types and fields form backend
* export the configuration
* Take the newly created files from it and remove the line uuid from it
* paste it in your theme folder

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


title: Populating Webform Tables

text:
# Question
Title: Populating Webform Tables
I am new to Drupal and have been working with Webform module to generate a custom form. One of the requirements for the form is to show a table where a user can add upload documents like this:

I created a new webform and started adding fields. As I added the 'table' field, it had option to set table Header (th) but not rows (td). I am not very familiar with the idea of hooks. Can someone please tell me how I can add rows? And if it is not possible to be done via the UI, then in what files the code must be added?

I am using Drupal 8.

# Answer
Composite elements do not support file uploads. If there is a finite amount of documents you could manually build a table. The Table element was recently hidden because it was impossible to document. Here is an example of table layout within a Webform.
> 1 votes

---
Tags: webforms
---


title: Commerce Stripe webhook

text:
# Question
Title: Commerce Stripe webhook
I use the Drupal Commerce Stripe module to create subscription charges in a Drupal web, through the Stripe platform. Everything seems to work well, the clients are created, the charges are produced and appear in Stripe's Dashboard .... I also have a webhook that seems to work too. The problem I have is that I need to implement within the webhook itself the ability to complete certain fields with the response that Stripe sends to that webhook. These data must complete the profile of the user who made the payment. Any idea what this would be like?

I'm talking about Drupal 7

This is my webhook

```
<?php

require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("sk_test_*************");

$input = @file_get_contents("php://input");
$event_json = json_decode($input);

$event_id = $event_json ->id;
$event_type = $event_json -> type;
$customer_email = $event_json -> receipt_email;

if ($event_type == "charge.succeeded") {
  $msg = "test webhook";
  mail($customer_email, "Test suscrip", $msg);

*/*Here I would like to be able to send certain data of the json object to certain fields of the user profile*/*

}

http_response_code(200);

?>

```

# Answer
> 1 votes
It sounds like you want to load the user object from the email address, set some field values, and save it again.

In code that would look something like this:

```
if ( ($account = user_load_by_mail($customer_email) ) {
  $account->field_foo[LANGUAGE_NONE][0]['value'] = $event_json->foo;
  $account->field_bar[LANGUAGE_NONE][0]['value'] = $event_json->bar;

  user_save($account);
}

```

# Answer
> 0 votes
I added this to the webhook, and now it would be like that, but it does not seem to write anything in the given field. Any ideas?

```
<?php

```

define('DRUPAL\_ROOT', '/var/www/html/'); require\_once DRUPAL\_ROOT . '/includes/bootstrap.inc'; drupal\_bootstrap(DRUPAL\_BOOTSTRAP\_FULL);

require\_once('vendor/autoload.php'); \Stripe\Stripe::setApiKey("sk\_test\_\***********");

$input = @file\_get\_contents("php://input"); $event\_json = json\_decode($input);

$event\_id = $event\_json -\>id; $event\_type = $event\_json -\> type; $customer\_email = $event\_json -\> receipt\_email;

if ($event\_type == "charge.succeeded") { $msg = "test webhook"; mail($customer\_email, "Test suscrip", $msg); if ( ($account = user\_load\_by\_mail($customer\_email) ) { $account-\>field\_id\_subscripcion\[UND\]\[0\]\['value'\] = 'test';

user\_save($account); }

}

http\_response\_code(200);

?\>

# Answer
> 0 votes
Thank you very much for your response, I have managed to access the Stripe response, and thanks to its response I have also managed to update the user. I owe you one, thanks

---
Tags: 7, commerce
---


# Question
Title: How to transform select options from views exposed filters to clickable link areas?
I have asked more generally in stack overflow

https://stackoverflow.com/questions/49491094/how-to-transform-select-options-to-clickables-link-areas?noredirect=1#comment85985442\_49491094

How can I make my exposed filters look like this?

```
<select data-drupal-selector="edit-field-video-theme-target-id" id="edit-field-video-theme-target-id" name="field_video_theme_target_id" class="form-select"><option value="All" selected="selected">- Tout -</option><option value="9">A*midex</option><option value="11">Bibliothèque</option><option value="10">Relation entreprise</option><option value="8">Université</option></select>

```

Is it possible to transform select/options to ul/li?

Is it possible to override the template `views-exposed-form--videos.html.twig`?

# Answer
It is possible to override the template, you shall just create it in your theme and then clear the cache.

In your new template you can just change the select list to a ul

The template that you want to override may only contain `{{ form }}`. Then you must find the preprocess function in the module or theme.
> 1 votes

# Answer
There is nothing integrated into drupal at the moment but you can probably use select2Buttons in your theme.

just include it in your theme and in custom javascript you can call

```
$('select[name=simple-select]').select2Buttons();

```
> 1 votes

# Answer
If i understand you correctly you could create a file `views-exposed-form--videos.html.twig`(I am not sure with the name just check it with twig debug) and add the following code in it

```
<# add your styled html with attribute name = "field_video_theme_target_id" #>

<ul name="field_video_theme_target_id" class="form-select">
  <li value="All" selected="selected">- Tout -</li>
  <li value="9">A*midex</li>
  <li value="11">Bibliothèque</li>
  <li value="10">Relation entreprise</li>
  <li value="8">Université</li>
</ul>
{{ form|without('field_video_theme_target_id') }}

```
> 1 votes

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


# Question
Title: views exposed filters : how to trigger the submit on options click
How to trigger the submit on select options click?

This would require for the end-user one click instead of two. The button could be removed or hide.

# Answer
> 1 votes
Check out the Better Exposed Filters module.

Also, this related post: Where is the "auto submit" option?

---
Tags: 8, views
---


# Question
Title: Restrict User Role from Unpublishing Content
I'm attempting to restrict a certain role from being able to unpublish content of a certain content type but I can't get it to work correctly. They need to be able to publish but not unpublish this content.

If "Administer Content" is checked they seem to be given permission to publish/unpublish any content types. If it's unchecked and I attempt to defer to the individual publish/unpublish permissions for that content type they lose the option to use the "Publish" checkbox when editing nodes of that type.

Am I missing something or doing something wrong?

# Answer
> 1 votes
Check out the Publish Content module.

---
Tags: 8, users
---


# Question
Title: Cannot do a `composer install` even though my minimum stability is listed as dev
I am trying to build the master branch in my project after updating to 8.5.0, but am being met with an error from composer (which I did not get on my develop branch):

> The requested package drupal/focal\_point 1.0.0-beta6 is satisfiable by drupal/focal\_point\[1.0.0-beta6\] but these conflict with your requirements or minimum-stability.

In my composer file, I have:

```
"drupal/focal_point": "^1.0",

```

as well as:

```
"minimum-stability": "dev",

```

How can I fix this so TravisCI gets unstuck? It worked fine for the develop branch, and the master is now updated with it.

# Answer
This may be incorrect per information in comments and because it contradicts Installing an alpha dev version with composer.

I think the issue here is that the beta6 is not `^1.0`. If you updated the requirement to be `"drupal/focal_point": "^1.0@beta"`, this would work fine.

Alternatively, you could call `composer require drupal/focal_point` with no version specified and it would install the beta6 version just fine. I believe this is where minimum stability is checked, but that would add a require line in your composer.json different from what is specified in your question.
> 3 votes

---
Tags: 8, composer
---


# Question
Title: Implement javascript inside body, error: jQuery is not defined
In Drupal 7, I had a template containing JavaScript code.

```
<script>
<?php if(isset($content['field_custom_javascript'])) print $content['field_custom_javascript']['#items'][0]['value']; ?>
</script>

```

In Drupal 8, I am trying to achieve the same in a template file.

```
{% if content.field_custom_javascript is not empty %}
  <script>
    {{ content.field_custom_javascript }}
  </script>
{% endif %}

```

When I put this JavaScript code in that field, I get an error about jQuery not being defined.

```
(function ($, Drupal) {
  $(document).ready(function() {
    console.log( "ready!" );
  });
})(jQuery, Drupal);

```

Is this a good way to do it, or do you have any suggestion?

# Answer
In Drupal 8, it's not a good idea at all. You must define a library and put the JavaScript code in a separate file, following what described in Adding assets (CSS, JS) to a Drupal theme via \*.libraries.yml.

If the JavaScript code uses jQuery, core/jquery must be added as library dependency.

If you want to attach a library in a template file, the following code achieves that.

```
{{ attach_library('modulename/libraryname') }}

```
> 1 votes

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


# Question
Title: How to expose the node creation form in the front page?
I created a new content type "project" and I want to create a **view** where every one can add a node (create a content) with my content type.

How to expose the form (to add a new project node) in the front (I do not just want to expose a link to add such node)?

In `admin/people/permissions` I granted the permission for *ANONYMOUS USER* to be able to create a new content.

# Answer
> 1 votes
To display content type form you can use formblock module as it description explains:

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

* Enable the module
* Go to **Project** `admin/structure/types/manage/project`
* On the bottom left vertical tabs there'd be a *Form Block*, check **Enable data entry from a block** and save
* Go to `admin/structure/block` and enable **Project form block**

I hope this'd help you.

---
Tags: 7, nodes
---


# Question
Title: How to do path aliases for views like news/%?
Let's suppose we have a view like news/%. Where news is my content type, and % is tid of term id from vocabulary "categories".

Obviously that urls like news/3, news/5 etc. works great. But how to do the path aliases for this kind of urls, generated from this view?

I want like this:

* news/% -\> company-news/\[term:name\]
* Example: news/3 -\> company-news/accidents

(where \[term:name\] transliterated term name from original title, because my site not on english language)

P.s. the just using pathauto for taxonomy terms, and the view "taxonomy/term/%" does not suit, because one term is used by multiple content types, and therefore in multiple views.

# Answer
That is quite a tricky one.

Two possible solutions:

1) Use page manager, create a context for each content type, and then use this module to generate the aliases): https://www.drupal.org/project/page\_manager\_pathauto (note: no Drupal 8 version)

2) Add/remove/modify the aliases yourself with an update hook. So when a node is updated, you create/update/delete the corresponding path aliases.
> 0 votes

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


# Question
Title: How to get the product id on hook form alter
I am currently working on drupal 8 commerce. I need to form alter some of the expose fields but need to get the product id first so I can get my condition on the product fields. I used this kint($form\_state) on my form alter to show the attached image. But when I try use this $form\['storage'\] im having wsod. Thanks

# Answer
> 3 votes
If You alter 'Add to card form', try this code

```
$form_state->getFormObject()->getEntity()->getPurchasedEntity()->product_id->getString();

```

# Answer
> 1 votes
Right, you can't ever access "protected" items of the data, which you can see is shown in the kint output. As 4x4 said, you'll want to look at the "Available Methods" tab, and use one of those to extract the data you need, so you'd want something like:

```
$product_id = $form_state->getFormObject()->getEntity()->getValue('product_id');

```

I hope this gets you going in the right direction for getting this data you need and understanding a major difference of D7-D8

# Answer
> 0 votes
I figure it out. Since it is a product page I used this code instead $product = \Drupal::routeMatch()-\>getParameter('commerce\_product')) && is\_object($product);

---
Tags: 8, forms
---


# Question
Title: how to get a list of all the boolean fields of a node?
I need to get a list of all the boolean fields of the node

My code

```
 $query = \Drupal::entityQuery('node')
   ->condition('status', NODE_PUBLISHED)
   ->condition('type', 'product')

```

Please help me

# Answer
> 3 votes
You can get a list of an entity's field definitions with EntityFieldManager::getFieldDefinitions(). You should then have a list of fields defined on that entity and should be able to determine which are the boolean fields.

You can access this via a service like:

```
$product_field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'product');

```

---
Tags: 8
---


# Question
Title: Disable menu cache for hook_menu() implementation
There is a way to disable the menu cache ?

**Context**

Drupal 7

I have a custom module that implements hook\_menu(). The link is showing up only if a view have results. It's working.

The problem is that I have to clear the drupal cache each time the view changes the number of results because the condition is not triggered anymore.

```
function gal_custom_menu() {

  $items['exhibitions'] = array(
    'title' => t('Current exhibition'),
    'page callback' => 'gal_exhibition_callback',
    'access arguments' => array('access content'),
  );

  return $items;
}

function gal_exhibition_callback() {

  $x = views_get_view_result('exhibition', 'page');

  if(count($x)) {
  $path = drupal_get_path_alias('node/' . $x[0]->nid);
  drupal_goto($path);
  } else {
  return FALSE;
  }

}

```

Do you have any idea how can I disable the menu cache ? Or is it the Views cache ?

Thanks

# Answer
Good conversation about other things in this code sample, but to make a page loaded through a menu callback skip cache, you can try `drupal_page_is_cacheable(FALSE)`. See: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal\_page\_is\_cacheable/7.x
> 2 votes

---
Tags: 7, routes, caching
---


# Question
Title: How to delete all Drupal content owned by a particular user?
It seems like there should be a drush command to achieve this, but I cannot find one. I am not clever enough to fashion an SQL query that will delete all nodes owned by a user as well as clean up all the field and revision data.

Please let me know if anyone has any solutions (other than deleting the user's account).

Drupal 7

# Answer
A possible alternative to achieve what you're trying to do, is to use a combination of modules Views and Views Bulk Operations (VBO). With these modules in place, you could simply create a view of all the nodes "*owned*" by a user, and simply use the out-of-the-box VBO action to "delete an item" (after adding a VBO field like "Bulk operations: Content"). And by creating a similar VBO view, using the VBO field "Bulk operations: Content revision", you can probably also cleanup up the revision data.

If you need more sophisticated business logic to decide about the criteria related to "*owned by a user*", you could add Rules to such solution also and implement a variation of the solution described in my answer to "How to bulk update select list fields?", i.e.:

* Create a Rules Component with a Rules Condition to checks if the node matches the criteria you're interested in.
* Create a VBO enabled view of all nodes to be checked, whereas you'll use the Rules Component as your custom VBO action.

***Done ...***
> 2 votes

---
Tags: 7, nodes, entities, users
---


title: Upgrade Acquia lightning

text:
# Question
Title: Upgrade Acquia lightning
We have installed Acquia lightning on the website.

We have updated the core only for past 1 year, unfortunately now we see lightning and Drupal not compatible in version point of view.

Now we got struck and we are not sure whether we update the lightning profile alone or downgrade Drupal.

Thanks, Kumaresan.G

# Answer
> we are not sure whether we update the lightning profile alone or downgrade Drupal

Definitely don't downgrade Drupal on account of Lightning. Lightning increments it's minor version when a minor version of core comes out. The most recent version is 3.1.x which is compatible with core 8.5.x. I suspect you have a constraint in your project's composer.json file which is preventing you from getting one of those. Something like the following should resolve your issue:

```
$ composer require drupal/core:~8.5.0 acquia/lightning:~3.1.0 --no-update
$ composer update

```
> 0 votes

---
Tags: 8, composer, acquia-cloud
---


# Question
Title: D8 Views Template Suggestions Being Ignored
I went through other questions/answers on this topic and I am still stumped. My added template suggestion for a Views Exposed form is being ignored.

```
function talon_theme_suggestions_views_exposed_form_alter(array &$suggestions, array $variables) {
      $suggestions[] = $variables[form]['#id']. "__ef";
}

```

Template name in theme: `views-exposed-form-views-programs-block-1--ef.html.twig`

Theme Debug lists suggestion as: `views-exposed-form-views-programs-block-1--ef.html.twig`

# Answer
A template name suggestion has to start with the theme hook and two underscores. You find the theme hook in the twig debug output, in this case `views-exposed-form`:

```
$suggestions[] = 'views_exposed_form__' . $mycustomdata;

```
> 5 votes

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


# Question
Title: Should I translate string inside a Unit test?
I have a Unit test where I need to print a string so I decide to use the t() function to translate it:

```
$this->assertTrue(is_numeric($expected), t('Parameter is numeric.'));

```

But the problem is that in the Unit test the `t()` function is not available. So I decide to check a similar Unit test in core (SortArrayTest) and the test don't translate the string:

```
$this->assertTrue(is_numeric($expected) && is_numeric($result), 'Parameters are numeric.');

```

I know that at this moment Drupal don't have integration with the Unit test from the UI, but this can be possible in future, so:

Should I translate string inside a Unit test? If the answer is Yes, How I can do it?

# Answer
> 3 votes
No, you should not. An assertion message is basically on the same level as a code comment, you're not translating that either.

We used to do that in core, also because it was all Simpletest then and the messages *were* shown in the UI, so an argument could be made that should be translatable. But we did massive patches to get rid of that, it just adds more complexity without any additional benefit.

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


title: How do I modify a Drupal Theme?

text:
# Question
Title: How do I modify a Drupal Theme?
The theme I am using has a slider -- a panel of automatically changing images to display a topic that the user can choose -- but it only shows a few slides. I want to extend it to a dozen slides. I did simple text searches to determine which files in the theme are used code files to provide the functionality to the slider. That was the easy part. I was able to extend the code from the few slides to 12 slides.

Now comes the more difficult and hidden part. As I see it, each slide has two parts that are not hard coded. First, each slide has a caption -- a text description. Secondly, each slide has a URL associated with it that is where the browser goes if the user clicks on the slide. These two things are not hard coded in any of the PHP or other files, as far as I can tell. They can be edited by the admin in the drupal backend admin settings.

So I assumed that these fields are somehow set and retained in the database. But I did a search on a downloaded copy of the database and I did not find this text.

Please advise. What additional work do I need to do to complete this task?

I suppose I could just forge ahead. Obviously this data is being stored somewhere. Maybe they are stored in the database in an encrypted form for security reasons. I could do an ftp upload of the site theme files. But then what? Do I uninstall the theme and then reinstall it? Do I just deactivate it and then reactivate it? How do I make my code changes work?

# Answer
> 0 votes
If I understand your (main) question correctly, you want to show additional images in the slider. In that case you have to narrow down which modules are used to create the slider. Typically a View is used to retrieve all content (stored in your database, normally not encrypted), an overview of all Views can be found at `admin/structure/views`. In the View there is an option to set the number of items that have to be shown in the `Pager` section (setting the number of items to show to 12 would in a typical installation be the thing you want to do).

When this is indeed the set up and you don't see the expected change after altering the value, don't forget to clear the caches (`drush cr` or via `admin/config/development/performance`).

If your environment is different, please provide additional details: which module is used to create the slider, e.g. Flex Slider, is Views used to provide the data (images provided by the user), etc.

---
Tags: theming
---


# Question
Title: Order won't programmatically mark as completed
I am struggling to get an order to be marked as completed in Drupal 7 Commerce.

Customers will go through the checkout process inside of Drupal, gets marked as "Awaiting shipment" (a custom order status), but then a fulfillment team goes through a different program and the order should be getting updated programmatically as "Completed".

However, when I use `commerce_order_status_update` it doesn't seem to want to get marked as completed.

Here is the code I am working with:

```
$order_entity = commerce_order_load($orderId);
commerce_order_status_update($order_entity, 'completed', false, true, 'Order updated via warehouse');
watchdog('warehouse', 'Order status updated %o', array('%o' => $order_entity->status)); //Does not equal 'completed'

```

I know this code is firing because of two reasons:

1. When I set 'completed' to be different status messages, it works
2. I see the revision message "Order updated via warehouse", but the status has not changed.

Is there something I have missed? Am I marking the order as completed in a wrong way?

I have also tried EMW

```
$order_wrapper = entity_metadata_wrapper('commerce_order', commerce_order_load($orderId));
$order_wrapper->status->set('completed');
watchdog('warehouse', 'Order status updated %o', array('%o' => $order_wrapper_status->value())); // Does not update to 'completed'
$order_wrapper->save();

```

**EDIT**
I added the watchdog statements that I have used to echo out of the operation was successful.
It should also be noted that there are no Rules modifying the order status at this point. I have gone through my list of Rules and verified that nothing is modifying it, and the order history shows no new revision created from Rules.
Error logs also show no error happening on save process. The operation is successful if I change 'completed' to any other status.

# Answer
> 1 votes
I figured this issue out.
I had a Rule that was firing "before a commerce order was saved" that reset the order status but did not show any errors or log any thing. Not sure why that rule wsn't working correctly, but now that I have disabled it, the status is updating successfully.

---
Tags: 7, commerce, entities
---


title: Rules data selection tokens

text:
# Question
Title: Rules data selection tokens
I have *\[order:products:0:node:author:uid\]* as rules data selection token. In data selection mode that works perfectly, and adds the exact data right where I need it, but when I add that token into the database table, using *Execute custom PHP code* and the following this code, I get only a blank *destination* field with no value.

```
$nid = db_insert('mytable') ->fields(array(
  'uid' => $uid,
  'username' => $username,
  'addr' => $address,
  'destination' => "[order:products:0:node:author:uid]"
))
  ->execute();

```

All the other fields are filling correctly.

What could the problem be?

# Answer
Yes, that kind of tokens are not being replaced, because god only knows why, but I solved my problem by adding variable to the needed rule, placing it before the executing php code, and selecting user entity by data selection there, and making reference to it in a php code. That is how it worked. Thank you, Jdrupal for your answer, anyway, it is always helpful to learn something new.
> 0 votes

---
Tags: rules, tokens
---


title: Create route that returns XML Feed

text:
# Question
Title: Create route that returns XML Feed
How do I create a page that returns an XML feed?

# Answer
Can you give more details ?

For example for an aggregator RSS :

In your test.routing.yml :

```
test.rss:
  path: '/rss'
  defaults:
    _title: 'rss'
    _controller: '\Drupal\test\Controller\RssController::content'
  requirements:
    _access_test: 'test'

```

And in your controller :

```
<?php

namespace Drupal\test\Controller;

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

class RssController extends ControllerBase
{
    public function content()
    {
        $response = new Response();
        $response->setContent('<?xml> My flux </xml>');
       // kint($response);
        return $response;

    }

}

```

> You need the HttpFoundation\Response component.
> 7 votes

# Answer
Kevin's answer caused my Twig template's `<?xml ...>` tag to be commented out. I had to add to make the page render it as XML.

```
$response->headers->set('Content-Type', 'text/xml');

```

Full example for my module named `custom`.

**custom.routing**

```
# My XML controller
custom.my_xml_feed:
  path: '/xml-feed'
  defaults:
    _controller: '\Drupal\custom\Controller\XMLfeed::content'
  requirements:
    _permission: 'access content'

```

**XMLfeed.php**

```
<?php

namespace Drupal\custom\Controller;

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

class XMLfeed extends ControllerBase {

  public function content() {
    $rows = [];

    $build = [
      '#theme' => 'my_theme_template',
      '#rows' => $rows,
      '#cache' => ['max-age' => 0],
    ];

    $output = \Drupal::service('renderer')->renderRoot($build);

    $response = new Response();
    $response->setContent($output);
    $response->headers->set('Content-Type', 'text/xml');

    return $response;
 }

}

```
> 8 votes

---
Tags: 8, routes, page-controller
---


# Question
Title: How to display a custom block in a view?
I created a custom block "Share". This one is not displayed on any page.

I installed the "Twig Tweak" module.

How to display a custom block in a view ?

# Answer
> 5 votes
If you want to add it to the header or the footer, edit your view, and in the middle column next to header or footer click add and then select Rendered entity - Custom block

When adding the block, just use the block ID (that can be found in the block's URL - in the image you uploaded your block ID would be 103)

Make sure these options are checked / filled in.

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


title: Entity id availability in Custom Field

text:
# Question
Title: Entity id availability in Custom Field
I've created a Custom Field (let's call it 'Reference') whose value requires the Entity Id.

To accomplish that I modify the Field value in the postSave method, like this:

```
if (!$update) {
  $this->get('value')
    ->setValue($this->getCalculatedReferenciaValue());
}

public function getCalculatedReferenciaValue() {
  //...
  $entity = $this->getEntity();
  $id = $entity->id();
  $year = date("Y", $date);
  // default format: 'SWAN%s%08dIMOV'
  $format = $this->getSetting('format');
  return sprintf($format, $year, $id);
}

```

Then, in pathauto, I use that custom created field, as a token, to generate the path.

However, for some reason, when creating a node, my custom field still has the default value.

If I then edit and save the node, the custom field (and the auto path) is updated correctly.

**Q: Is there a way to update the field value so that it becomes available when generating the autopath for the first time?**

# Answer
> 0 votes
For getting the node ID you need to first save the node. For eg:

```
$node = Node::create([
      'type' => 'my_content_type',
      'title' => 'My Title',
      'uid' => \Drupal::currentUser()->id(),
      'status' => 1
]);
$node->save();
    :
    :

$id = $node->id();
$year = date("Y", $date);
// default format: 'SWAN%s%08dIMOV'
$format = $this->getSetting('format');
$node->field_custom->value = sprintf($format, $year, $id);
$node->save();

```

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


# Question
Title: module/theme update on web hosted site question
I am new to drupal and I just installed a fresh site onto Acquia web hosting. How do I install modules and themes since I can't seem to be given direct access to the file manager via the browser? Terminal/console from my desktop? Use Drush? What is the simpliest route?

(please don't ding me for asking what may appear as a subjective question, I just need the most secure way to doing it that is simple!).

# Answer
> 0 votes
Straight from the docs:

> If your application is hosted on Acquia Cloud, the module directories are part of the code repository, which is not directly writable. This means that you can't directly add a module using the Update Manager, drush dl, or SFTP. Instead, you must commit your changes using a version control system (Git).

So you need to commit the modules to git locally, and push them to the repo; Acquia’s platform will take care of the rest.

The same docs explain the various specific implementation options in step-by-step guides.

---
Tags: console
---


# Question
Title: Migrate multilingual Drupal 7 users to Drupal 8
I have Drupal 7 users that uses Profile module and has fields for individual languages i.e. presentation\_sv, presentation\_en that I would like to migrate to a proper Entity translated Drupal 8.

First migration file:

```
id: custom_user
label: "Custom User accounts"
migration_group: custom
migration_tags:
  - Custom D7
class: Drupal\user\Plugin\migrate\User
source:
  plugin: d7_user
process:
  langcode:
    plugin: default_value
    default_value: sv
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  presentation: profile_presentation_sv
destination:
  plugin: entity:user

```

Here is the translations migration file:

```
id: custom_user_translations
label: "Translated Custom User accounts"
migration_group: custom
migration_tags:
  - Custom D7
class: Drupal\user\Plugin\migrate\User
source:
  plugin: d7_user
  translations: true
process:
  uid:
    plugin: migration
    source: uid
    migration: custom_user
  langcode:
    plugin: default_value
    default_value: en
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  presentation: profile_presentation_en
destination:
  plugin: entity:user
  translations: true
migration_dependencies:
  required:
    - custom_user

```

The error I get:

```
Next Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'map.destid2' in 'field list': SELECT map.sourceid1 AS sourceid1, map.destid1 AS destid1, map.destid2 AS destid2
FROM
{migrate_map_custom_user_translations} map
ORDER BY destid1 ASC; Array

```

# Answer
> 3 votes
Looks like your migration configuration needs to be re-installed. When I had that issue I deleted the map table (in your case `migrate_map_custom_user_translations`) and then re-installed the config (I used the `config_devel` module).

---
Tags: 8, migrations
---


# Question
Title: Configuration management with different database and websites
We have a central code base (Git repo). From this code base we deployed several websites already.

* Till now we used features. The websites which are already in production they have a filled database with a lot of content.
* From now we switch over to drupal 8 Configuration management.

In the central code base we have set `$config_directories[CONFIG_SYNC_DIRECTORY] = 'config/base';`. This directory contains all the configuration, from where we deploy our new added configuration, after a `drush cex -y`.

But after I do:

1. *first* a new install off the site with Configuration installer module and import all the existing configuration, everything works fine. I can import and export configuration without problems
2. but then I have to copy the production database (from the site which is already in production) back into this database. After that I am not able to import configuration anymore.

But I need to copy this database back in, because we need all the content from the existing site (which was based on Features)

I get an error the UUID is not matching etc... Is it possible what I want? And how do I get it working?

(I tried already manually copy/paste the correct `uuid:` in `system.site.yml`, but it still didn't work).

**Update:** I use docker for my local Drupal 8 environment

# Answer
> 1 votes
Basically you need to make sure both sites share the same UUID.

Do you have drush? If so:

In the shell of your old site (copying from) get the UUID

```
drush cget system.site uuid

```

(You'll get something like 'system.site:uuid': bfb11978-d1a3-4eda-91fb-45decf134e25 - copy the value)

Then in the shell of your new site (copying to) set the UUID

```
drush cset system.site uuid <your_uuid>

```

EG: `drush cset system.site uuid bfb11978-d1a3-4eda-91fb-45decf134e25`

Then if you get an error something like "placeholder ... These entities need to be deleted before importing." run this command:

```
drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'

```

After all that, `drush cim sync -y` should allow you to sync the settings between your environments.

Source

# Answer
> 0 votes
An easy approach you can do is the uuid of the site will be available in `config/sync/system.site.yml` file. So in your terminal you can use cat (Linux) or type (Windows) to get the uuid displayed in terminal.

```
cat config/sync/system.site.yml | grep uuid

```

Then,

```
// using console
drupal config:override "system.site" uuid "<new-uuid>"
// OR, using drush
drush config-set "system.site" uuid "<new-uuid>"

```

If you get the shortcut set place holder error

```
// using console
drupal entity:delete shortcut_set default
// OR, using drush
drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'

```

Then, `drush cim` **OR** `drupal ci`

---
Tags: 8, database, configuration, installation-profiles, entities
---


title: Content edit links?

text:
# Question
Title: Content edit links?
I'm new to Drupal 8 and can't figure out a way to show the edit contextual links for content displayed through the Views module. This was simple in Drupal 7, but in Drupal 8, a view only shows the links for editing; there are no edit or quickedit links for the content.

It does seem to work with nodes and taxonomy terms, but not custom blocks.

# Answer
> 0 votes
Add show content and teaser/full view like below.

Goto page and it will show links.

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


# Question
Title: Unable to render fields in node.html.twig
I'm trying to get individual fields printed on my node template, but am unable to get anything other than {{ content }} to work.

I'm using 8.5.0 and I'm not seeing any errors in the log. The page renders my markup so I know the template is being called.

Here's my node.html.twig markup:

```
    {%
     set classes = [
    'main-article',
    'main-article-page',
    ]
    %}
    {{ attach_library('classy/node') }}
     <article {{ attributes.addClass(classes) }}>

     <div class="main-article-image">
    {{ content.field_image }}
     </div>

     <div class="main-article-body">
    {{ content.body }}
     </div>

     </article>

```

Perhaps I've missed something in the setup of my theme?

# Answer
This was an issue to do with the Field Layout module. Once that was uninstalled my markup worked as it should.

Field Layout (and also Layout Builder module) moves Drupal towards theming within the UI, so if you're looking to theme with twig files, I'd recommend not installing them.
> 1 votes

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


# Question
Title: How to save webform submissions data in fields using rules module
I used the answer in my last question Override webform module submit to create node after webform submissions.

My webform contains many components like phone, address, responsible and others.

How can I save this data in fields tables?

# Answer
Let's say that my webform contains the components: phone, address, city ..

I created a new content type that contains these fields: phone, address, city ..

Then, for each field I added

```
{ "variable_add" : {
      "USING" : { "type" : "text", "value" : "[data:address-value-raw]" },
      "PROVIDE" : { "variable_added" : { "var_address" : "Address label" } }
    }
  },

```

Where **address** is my **MachineFieldName**

and

```
  { "data_set" : {
      "data" : [ "article-created:field-address" ],
      "value" : [ "var_address" ]
    }
  },

```

To check your data as **\[ "article-created:field-address" \]**

1. go to **admin/config/workflow/rules/reaction/manage/rules\_create\_a\_node\_from\_webform\_data**
2. go to add action and select **set a data value**
3. in the Data selector \*: select **article-created:...(Created article)** Then you will see all your fields..

This answer to How to create a node from a Webform using rules? helped me..

I hope that can help someone..

Thank you
> 1 votes

---
Tags: 7, entities, rules, webforms
---


title: How to add button to header

text:
# Question
Title: How to add button to header
I have a header like this:

I would like to add a button "Buy tickets" that links to a html page. How can I do this in easy way?

# Answer
> 2 votes
There are a couple of ways of achieving this:

First way is to edit your theme's page.tpl.php file and add your custom html into the correct region. This will ensure your button will appear on all pages, unless you have any custom templates (page-front.tpl.php for example) that override specific pages. In this case you would simply add your code to the custom templates also.

Second method (and probably the easiest) is to create a custom block by visiting www.site.com/admin/structure/blocks and slicing on "+add block". You can then create a block with the html you need - you may need to change the input format of the text box in order to allow all your html code.

As you create this custom block you can decide which region the block will be placed into, making sure it's for the correct theme, and which pages it will appear on. Hopefully it should clear how you can achieve this from the UI.

Save your block and it should now appear!

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


title: Webform: Hide the "add more" button

text:
# Question
Title: Webform: Hide the "add more" button
I would like to get rid of the ajax "add more items" button at the bottom of a multiple elements form item.

The D8 webform I'm building has a custom composite element with multiple values allowed. The table form display has nice + and – buttons in each row. The "Add x more items" element below the table is not needed.

In the advanced tab, under "Multiple settings", there is only an option to hide the +/– buttons, not the "Add x more items" element.

**Additional information:**

Webform module version: 8.x-5.0-rc7
YAML Source (excerpt):

```
   fieldset_teilnehmer:
    '#type': fieldset
    '#title': Teilnehmer
    teilnehmer:
      '#type': custom_composite
      '#title': Teilnehmer
      '#required': true
      '#required_error': 'Bitte tragen Sie die Teilnehmer ein.'
      '#multiple__label': Teilnehmer
      '#multiple__labels': Teilnehmer
      '#multiple__min_items': '5'
      '#multiple__empty_items': '5'
      '#multiple__sorting': false
      '#element':
        teilnehmer_name:
          '#type': textfield
          '#title': Name
        teilnehmer_alter:
          '#type': select
          '#options':
            18: ≥18
            17: 17
            16: 16
            15: 15
            14: 14
            13: 13
            12: 12
            11: 11
            10: 10
            9: 9
            8: 8
            7: 7
            6: 6
            5: 5
            4: 4
            3: 3
            2: 2
            1: 1
            0: 0
          '#title': Alter

```

# Answer
If you set the "Minimum amount of items" and "Number of empty items" to the same number the add more won't appear.

Here is a screenshot

Here is the YAML source for basic multiple text field

```
textfield:
  '#type': textfield
  '#title': textfield
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'

```

Here is the YAML source for multiple custom composite

```
custom_composite:
  '#type': custom_composite
  '#title': custom_composite
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'
  '#multiple__sorting': false
  '#multiple__operations': false
  '#element':
    textfield:
      '#type': textfield
      '#title': textfield
    select:
      '#type': select
      '#options': days
      '#title': select

```
> 4 votes

---
Tags: 8, webforms
---


# Question
Title: Restrict core to generate taxonomy terms' URLs
I'm working on very large existing Drupal site that has thousands of nodes, user in it and bunch of Taxonomies as well.

I understand very well that Drupal core generates default URLs `(taxonomy/term/tid)` as we create a taxonomy term but my requirement is not to so is there a way we can control it?

**Updated**

Actually, I'm working on SEO of the site so according to the SEO report there are more than 10K redirections **to** `404 page` **from** the `Location taxonomy term pages` (URL aliases generated by pathauto module and redirected by custom code to 404). So the owners want to reduce 404 redirections.

I was thinking I can achieve this

* By deleting URL aliases of terms so aliases URLs'll not be listed in the google search (would be less SEO friendly) and user'll not try to access, by this way we can reduce 404 redirection.
* By deleting `taxonomy/term/tid`, path to such terms will permanently removed so I'll also help to reduce 404.

What do you suggest?

# Answer
> 0 votes
My approach to this previously has been to ensure that there are no links within the site to taxonomy terms and that they are removed from the XML sitepath (using https://www.drupal.org/project/xmlsitemap) so they don't get into the search engines' database in the first place.

I would also recommend a module such as https://www.drupal.org/project/rabbit\_hole which can force either a redirect, page not found, or access denied for taxonomy pages (and others) automatically.

I don't think there's any sense in trying to remove taxonomy links from the system when you can use the modules above to achieve this automatically for you.

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


# Question
Title: Change module's description from another module
How can I change a description of a module from my custom module or how can I override `hook_process`?

# Answer
You can alter a module's information through `hook_system_info_alter()`. For example to change the description of the Views module:

```
function MYMODULE_system_info_alter(&$info, $file, $type) {
  $info['views']['description'] = 'Something else';
}

```
> 3 votes

---
Tags: 7, hooks
---


title: Unset regions for specific content type

text:
# Question
Title: Unset regions for specific content type
I want to create a special content type that doesn't include the logo and main navigation. I have a helper module and have added the following section before renenabling it but it doesn't seem to be having an affect. What might I be doing wrong?

```
function myhelpermodule_page_alter(&$page) {
  if (current_path() == 'node/add/specialcontenttype') {
    unset($page['header']);
  }
}

```

Just in case I got "header" wrong, I've tried it with 'footer' and other regions to test it out and it seems to be having no affect at all.

# Answer
> 2 votes
Create a hook suggestion in page preprocess and theme that page

for eg:

```
function yourthemename_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

Now clear the caches Duplicate page.tpl.php and rename it as page--specialcontenttype.tpl.php

Then, remove the `<?php print render($page['header']); ?>` etc.. from it

# Answer
> 1 votes
The easiest way I've found to achieve this is to have a custom page.tpl.php file for your particular content type. That way you can remove the regions you don't need from the specific template file.

It's easily done with a few lines of code in your theme's template.php file and creating a new page template file. You'll find lots of tutorials online.

Here's one to get you started: https://www.digett.com/insights/overriding-page-templates-content-type-drupal-7

---
Tags: 7, theming
---


title: How to hide "do something on load"

text:
# Question
Title: How to hide "do something on load"
I am using drupal 7 with custom omega theme. I am developing a site for myself for a year now. I could find a solution to everything until now. Hopefully the answer is easy and simple I just don't see the wood from the tree.

How can I remove or hide the 'Do something on load' message, but keeping those messages what I want to appear?

Thank you for your time to read, and I'm hoping in a quick and good response

Thank you everyone who looked at it. It seems I have found the answer. Yes it really is connected to the Entity Reference field. There is a sub-module called " Entity Reference Behavior Example". All I needed to do is to disable this sub module. I have fallen into that mistake to switch it on without knowing exactly what it is doing. Simply switch it OFF.

# Answer
> 0 votes
I haven't seen that message myself yet, but just came across a suggestion how to avoid that message. I suppose you're using the entityreference module? At least for what I know the message seems to come from there – so hopefully this hint helps you:

> To avoid some status messages like 'Do something on load', you should uncheck "Test behavior" in "Additional behaviors" section.

As far as I know the author is relating to the entityreference settings – here's the source: "how to render a node field of a referenced node on the node form". I hope it helps somehow.

# Answer
> 0 votes
You should simply disable the "Entity Reference Behavior Example" module.

---
Tags: 7, entities, status-messages
---


# Question
Title: The path admin/content/files is missing in Drupal 8.5
I have installed Drupal 8.5 and today I realised that the tab `admin/content/files` is missing. Thanks to my backups I realized that this tab link is already missing since the 14th of March. Prior to the disappearance on the link I did not install any module. How can I solve this issue?

# Answer
By mistake I’ve disabled the View that generates the page, and the only thing I needed was to enable it again, and the tab reappeared. Thanks for the support.
> 1 votes

# Answer
I had the same problem and was because the route that creates the page (view.files.page\_1) was not recognized by Drupal. Why? I don't know, but I reinstalled the Views UI and the Views module and the problem was solved.

You can read about this problem in Add Item for Files under Content Menu and this is why we added in the Admin Toolbar module a validation for the route. The file module can be installed and the route can be missed from the site.
> 1 votes

---
Tags: views, 8, files
---


title: Pass id from URL to next page

text:
# Question
Title: Pass id from URL to next page
I have made a product page overview that displays all the products of my webshop. On the left, I have placed a filter where people can filter the products (e.g. country can be France, Germany...). When a customer selects a country (e.g. France) the URL changes and the id of the choice (France) is added to the URL. Now I want the next thing: when a customer selects a product, I want that the id that was added in the previous URL also is added to the URL of the product detail page.

So when you have www.test.com/products, you select France, you get `www.test.com/products?field=country%1` and when you select a product, you should get `www.test.com/products/product?field=country%1` instead of just `www.test.com/products/product`...

Anyone who can help?

# Answer
> 0 votes
To get the query string use

```
\Drupal::request()->query->all();

```

To further dig into use kint() and debug the `\Drupal::request()`

---
Tags: 8, uri
---


# Question
Title: Using #cache key on a render array generates 2 entries per role, how to change that?
On a page controller I have a method that displays the content via a render array. It also caches the rendered output using the `#cache` key:

```
  public function viewContent(NodeInterface $node) {
    $content = array(
     '#entity' => $node,
     '#sorted' => TRUE,
     '#pre_render' => [[$this, 'buildList']],
     // Cache the render array until the lock history/node is changed.
     '#cache' => [
      'keys' => ['my_module', 'node', $node->id()],
      'tags' => ['my_module:node:' . $node->id()],
     ],
   );
    return $content;
  }

```

But I noticed that drupal is generating 2 cache entries per user role in the cache render table as you can see in the screenshot:

Is it possible to generate only 1 set of entries for all users and manually pick the cid using the builtin render `#cache` properties?

# Answer
Yes, by default cached render arrays are varied by the hashed user permissions. See this container parameter:

*/sites/default/services.yml*

```
parameters:
  renderer.config:
    # Renderer required cache contexts:
    #
    # The Renderer will automatically associate these cache contexts with every
    # render array, hence varying every render array by these cache contexts.
    #
    # @default ['languages:language_interface', 'theme', 'user.permissions']
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

```

Though this should be changed only in rare cases, because caching content with the wrong user permissions can cause security issues.

If you don't want the variations of the render cache, another approach might be to cache the query results directly:

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

  if ($cache = \Drupal::cache()->get($cid)) {
    $data = $cache->data;
  }
  else {
    $data = my_module_query();
    \Drupal::cache()->set($cid, $data, Cache::PERMANENT, $tags);
  }

```

Then you can manually pick a cid. With the cached query results the rendering of the list shouldn't take too much cpu time and so probably you don't need render caching anymore.
> 1 votes

---
Tags: 8, theming, caching
---


# Question
Title: Hide a field in views if it has a certain value
I would like to hide a field when there is a certain value in it like `999`.

.

# Answer
> 0 votes
You could use views\_conditional

With this module you can create a **views conditional field** that checks for the value of your **population** field and if it is a certain value to display your field. You will need to have the **population** field included in the view and **excluded from displaying**

# Answer
> 0 votes
You can achieve this by using views conditional module. According to its explanations:

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> * Equal To
> * Not Equal To
> * Greater Than
> * Less Than
> * Empty Not
> * Empty
>
> Views conditional allows you to output text based on the result of the condition.
>
> How to use Views Conditional in your Views:
>
> 1. Create a view. Add some fields under "FIELDS".
> 2. Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
> 3. Add and configure fields...
> 4. Choose a field to run a condition against, and provide values accordingly.
> 5. Save, views conditional handles the logic and returns as specified.

I hope this will help you.

---
Tags: 7, views
---


title: make taxonomy terms more human friendly

text:
# Question
Title: make taxonomy terms more human friendly
I work on a news site that has hundreds of articles and all the article urls are written by hand. eg. example.com/world-news-today-28-march-2018 The site has various news categories like: business, economy, technology, etc but they are named taxonomy/term/1 and so on. Is it too late now to activate pathauto module on a live production site that has tons of content? All I want to do is change the urls of the news categories and make them more human friendly, so example.com/taxonomy/term/1 becomes example.com/business without touching the article urls which are in each category. Any ideas how can I do this and if it's safe at this stage?

# Answer
> 1 votes
You can use Pathauto module and follow these steps:

* Enable pathauto module
* Go to `admin/config/search/path/patterns` and set the patterns for specific taxonomy using Token module and save the form
* Go to `admin/config/search/path/update_bulk` and generate URLs for taxonomy

Don't worry about the existing URLs (no matter wherever you added it) it will remain same, Pathauto will not effect anything. Now, visitors can access by both URLs (default and newly generated).

I hope this will help you.

---
Tags: path-aliases
---


title: maintenance theme on every page

text:
# Question
Title: maintenance theme on every page
On every page, maintenance theme is getting applied along with the user login boxes below the page after logging in. This is the state of the site which was handed over to me. I think this exists from a long time and no one gave importance to this issue.

This is my body tag obtained from inspect element (Chrome)

```
body class="marinelli html front logged-in no-sidebars page-newmain toolbar toolbar-drawer admin-menu" id="maintenance-page" style="padding-top: 65px;">

```

Please help me with this issue.

**edit: Uncaught TypeError: $ is not a function at marinelli:133** This is the information obtained from inspecting element. It seems to be present in CDATA.. Where can i find CDATA?

```
    //grab all header rows
    $('th').each(function (column) {
        $(this).addClass('sortable').click(function () {
                var findSortKey = function ($cell) {
                    return $cell.find('.sort-key').text().toUpperCase()+ ' ' + $cell.text().toUpperCase();

```

# Answer
> 0 votes
***Debugging is the art of removing all possible reasons why some unexpected/undesired issue arises ...*** so make sure your site is NOT in maintenance mode ...

To do so, navigate to `admin/config/development/maintenance` and ensure that "*Put site into maintenance mode*" is NOT (repeat: NOT) checked.

---
Tags: 7, theming
---


title: How do I list all core templates?

text:
# Question
Title: How do I list all core templates?
Is there a way to list or get all the Drupal 8 core templates which are being used by a site? The list should exclude the templates coming from the theme.

The method I am using is enabling Twig debugging in the services.yml and checking whether a template is from core using a browser's inspector, but this is tedious.

# Answer
> 1 votes
I don't see a way to get a list of all core templates, but if you want to override them here is a perfect guide, Drupal core template naming

---
Tags: 8, theming
---


# Question
Title: Add the view mode to the CSS classes used for the body
Is it possible to add the view mode used for a display into the body class?

At the moment, the view mode is being inserted into one of the region classes, but I would like to add it also to the body class. This would allow me to change the page to full width depending on the view mode.

I am using the Bootstrap theme.

# Answer
> 0 votes
If you are using sub theme of bootstrap theme then you can possibly add class to body tag of the node.

Go to `SubThemeDirectory/`and open `template.php` and add this hook\_preprocess\_html()

```
function THEMENAME_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    $vars['body_attributes_array']['class'][] = 'mode-' . $vars['page']['content']['system_main']['nodes'][$node->nid]['#view_mode']; // Node ID class
  }
}

```

I hope this'll at least give an idea how to add class attribute.

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


title: {{ kint() }} leads to install.php

text:
# Question
Title: {{ kint() }} leads to install.php
Just on certain pages, I'm led instead to /core/install.php...

This has happened to me a great number of times now, in certain twig templates. But, I can't imagine why. Has anyone else had this happen? What causes it? It just doesn't work in some templates. I'm only asking this because I have never seen anyone ask anything like it, and it has happened to a coworker as well.

# Answer
> 6 votes
That will be caused by an overload on resources. `kint()` is very resource intensive. If you are calling **kint** in a `views-view-files.html.twig` template for example then it could get called multiple times and overload the system.

If you check your logs you'll find an error like this:

`General error: 2006 MySQL server has gone away`

The DB has been overloaded and Drupal thinks there's no install, hence ending up on the install page.

Here are three ways of limiting the **kint** maxLevels variable which can help avoid this. Set maxLevels to 3 or 4.

1) In `settings.php`:

```
require_once DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php';
Kint::$maxLevels = 3;

```

2) In `/modules/contrib/devel/kint/kint/` duplicate the `config.default.php` file to `config.php` and modify this line:

```
$_kintSettings['maxLevels'] = 3;

```

3) In a preprocess function, add the following:

```
kint_require();
Kint::$maxLevels = 3;

```

---

You can also filter the kint output so it only shows the KEYS, e.g.

```
{{ kint(_context|keys) }}

```

---

Alternatively, use Symfony var-dumper which is a bit more lightweight:

```
composer require symfony/var-dumper

```

Visit the **devel** settings page and set **Symfony var-dumper** as the **Variables Dumper**.

Example usage:

```
{{ devel_dump() }}
{{ kpr() }}
{{ dpm() }}

```

---
Tags: 8, debugging
---


title: Cron drupal 8 for my module?

text:
# Question
Title: Cron drupal 8 for my module?
I am doing a module in drupal 8, I would like to know how to execute a function automatically every month. I think it's done with Cron, but I only get to do it every week. as I edit it from my function.

# Answer
> 12 votes
A modified example from cron\_example module. This doesn't concern the interval the cron tasks are set in cron.

This is important, as you will probably set another cron tasks sooner or latter with different interval requirements. Also, many system tasks require more frequent cron runs.

```
function cron_example_cron() {
  $interval = 30*24*60*60; // Approx a month of interval

  // We usually don't want to act every time cron runs (which could be every
  // minute) so keep a time for the next run in the site state.
  $next_execution = \Drupal::state()->get('cron_example.next_execution');
  $next_execution = !empty($next_execution) ? $next_execution : 0;
  if (REQUEST_TIME >= $next_execution) {
    // This is a silly example of a cron job.
    // It just makes it obvious that the job has run without
    // making any changes to your database.
    \Drupal::logger('cron_example')->notice('cron_example ran');
    if (\Drupal::state()->get('cron_example_show_status_message')) {
      drupal_set_message(t('cron_example executed at %time', ['%time' => date_iso8601(REQUEST_TIME)]));
      \Drupal::state()->set('cron_example_show_status_message', FALSE);
    }
    \Drupal::state()->set('cron_example.next_execution', REQUEST_TIME + $interval);
  }
}

```

Also, for more fine-tuned approach, you can use the Ultimate Cron module, which provides more fine-grained control for the cron jobs.

# Answer
> 1 votes
The best way to run cron every month is by adding the following command to your crontab.

```
0 0 1 * * wget -O - -q -t 1 http://CRON_URL

```

http://CRON\_URL is replaced with a URL which is different for each Drupal version. For D8 it looks something like http://www.example.com/cron/. You can get this URL from Status report — Reports Administration \> Reports \> Status (/admin/reports/status)

For more info please visit https://www.drupal.org/docs/7/setting-up-cron-for-drupal/configuring-cron-jobs-using-the-cron-command

---
Tags: 8, cron
---


title: Domain Change from .com to .org

text:
# Question
Title: Domain Change from .com to .org
My company wants to change the domain from domain.com to domain.org, how would we do that according to moving the theme, all files, modules, etc. and keeping the Drupal integration intact?

# Answer
Unlike Wordpress, Drupal doesn't care on the hostname. Unless you statically mentioned the domain in any custom modules/themes, this will be a straight forward change.

* Change the domain name using a local host file.
* Change the trusted hosts configuration (for D8, in `settings.php`)
* Try accessing the site after the drupal clear cache, using `drush`.

If you are experiencing any issues, try searching for `domain.com` using `grep` and replace. Better to refactor the code without the domain hardcoded.

**Edit:** The links hard coded in WYSIWYG editors like ckeditor can create issues. You may have to update programatically or manually.

**Edit2:** You can use pathlogic module (not tested, d8 version is usable). to reformat the URLs in the content.
> 4 votes

---
Tags: installation
---


title: Image style URL does not work

text:
# Question
Title: Image style URL does not work
I have an issue related to drupal image styles, and I am not able to fix it since last two days. Have searched and tried everything on google, but of not help.

I have a drupal instance on production where all the images are stored at `imgs/<entity_type>/<entity_id>/<filename>`. All these files have three different styles: `thumbnail`, `entity_image`, and `slide`. All the styles were working initially. Now suddenly most of the times styles do not work. If I change the image, most of the time styles show old images, even if at the URL location no image is present. Sometimes, thumbnails are not getting created.

To resolve this, the following are the things I already tried:

1. `drush image-flush`: *Did not help*
2. Changed permissions of styles to 777: *Did not help*
3. Cleared all caches several times: *Did not help*
4. Disabled and re-enabled clean URLs: *Did not help*
5. Created another instance and tested: *Issue persists*
6. Tried to create style forcefully using `image_style_url`: *Did not help*
7. Changed `+FollowSymLinks` to `+SymLinksIfOwnerMatch` in .htaccess: *Did not help.*
8. Commented `Options None` and `Options +FollowSymLinks` in .htaccess: *Did not help*

Initially it looked like a permission issue but after all this, I am not getting what could be wrong. It could be some issue with inode creation, but not sure. So, please let me know your suggestions, what should be done in this case.

**EDIT:** I disabled clean URLs and everything worked fine. Enabling clean URLs again gives the same issue. SO it has to do something with the menu I guess, but not sure about the fix. Need a permanent solution as I can not afford to keep clean URLs disabled.

# Answer
I added following lines in modules/image/image.module, on line 1056 and it started working.

```
// Create derivated image if it doesn't exist.
  if (!file_exists($file_url) && !file_exists($uri)) {
    if (file_exists($path)) {
      $current_style = image_style_load($style_name);
      image_style_create_derivative($current_style, $path, $uri);
    }
  }

```

**FYI:** This change comes with a risk of when Drupal core updates, this will get removed. Also, I found it affected the performance of search in our platform. So, need a permanent solution.
> 0 votes

---
Tags: media
---


# Question
Title: Published-Draft articles are not searchable
I am using Drupal 8.3.x and Search API 8.x-1.5.

I am new to Drupal and Search API. I have a clarification on Search functionality.

I have created a article where Title and Body fields are indexed. I have published the article.

When I search for the keyword of `Title` or `Body`, article found in search results.

After that I modified the article and saved as draft.

When I am trying search the article with modified text. The article is not returning in the search results.

Can someone please let me know, if this a known issue with the search or it is the expected behaviour? If yes, any specific reason for implementing like this?

# Answer
> 1 votes
> is this a known issue with the search or it is the expected behaviour?

It’s very much the expected behaviour

> If yes, any specific reason for implementing like this?

Yes. Only published content should be visible, unpublished content should not. That’s the whole point of the distinction between the two states.

If unpublished content appeared in search results (without manual intervention if there was an edge-case requirement to do so), that would be a major bug.

---
Tags: search
---


# Question
Title: How can I force changes to go to settings.local.php?
I have a settings.php file in git which has the logic to include settings.local.php already uncommented, with settings.local.php in .gitignore for security purposes.

I would like to be able to install Drupal (8.3.3) so that any changes which are made by the installer (by default: hash salt, databases array, install profile, sync directory location) are made to settings.local.php rather than settings.php as the installation currently does. Is this possible?

# Answer
I think it's possible, but you'll need a custom installation profile to do it.

`drupal_rewrite_settings()` takes a 2nd parameter for a custom path to settings.php, but none of the default core methods make use of it, they let it fallback to sites/default/settings.php. It's used in three key places:

The form and `install_write_profile()` are invoked from an install task, so those can be altered with `hook_install_tasks_alter()`. `drupal_install_config_directories()` is invoked from the form submit method, which you'll be overriding anyway, so you can replace it with your own method.

A completely untested example:

**profiles/foo/foo.profile**

```
function foo_install_tasks_alter(&$tasks, $install_state) {
    $tasks['install_write_profile']['function'] = 'foo_install_write_profile';
    $tasks['install_settings_form']['function'] = 'Drupal\foo\Form\SiteSettingsForm';
}

function foo_install_write_profile($install_state) {
    // Only need to write to settings.php if it is possible. The primary storage
    // for the install profile is the core.extension configuration.
    $settings_path = \Drupal::service('site.path') . '/local.settings.php';

    // Make sure the file exists.
    touch($settings_path);

    if (is_writable($settings_path)) {
        // Remember the profile which was used.
        $settings['settings']['install_profile'] = (object) [
            'value' => $install_state['parameters']['profile'],
            'required' => TRUE,
        ];
        drupal_rewrite_settings($settings, $settings_path);
    }
    elseif (($settings_profile = Settings::get('install_profile')) && $settings_profile !== $install_state['parameters']['profile']) {
        throw new InstallProfileMismatchException($install_state['parameters']['profile'], $settings_profile, $settings_path, \Drupal::translation());
    }
}

```

**profiles/foo/src/Form/SiteSettingsForm.php**

```
namespace Drupal\foo\Form;

use Drupal\Core\Installer\Form\SiteSettingsForm as BaseForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Crypt;

class SiteSettingsForm extends BaseForm {

    public function submitForm(array &$form, FormStateInterface $form_state) {
        global $install_state;

        // Update global settings array and save.
        $settings = [];
        $database = $form_state->get('database');
        $settings['databases']['default']['default'] = (object) [
            'value'    => $database,
            'required' => TRUE,
        ];
        $settings['settings']['hash_salt'] = (object) [
            'value'    => Crypt::randomBytesBase64(55),
            'required' => TRUE,
        ];
        // Remember the profile which was used.
        $settings['settings']['install_profile'] = (object) [
            'value' => $install_state['parameters']['profile'],
            'required' => TRUE,
        ];

        $settings_path = \Drupal::service('site.path') . '/local.settings.php';
        drupal_rewrite_settings($settings, $settings_path);

        // Add the config directories to settings.php.
        $this->installConfigDirectories();

        // Indicate that the settings file has been verified, and check the database
        // for the last completed task, now that we have a valid connection. This
        // last step is important since we want to trigger an error if the new
        // database already has Drupal installed.
        $install_state['settings_verified'] = TRUE;
        $install_state['config_verified'] = TRUE;
        $install_state['database_verified'] = TRUE;
        $install_state['completed_task'] = install_verify_completed_task();
    }

    protected function installConfigDirectories() {
        global $config_directories;

        // Add a randomized config directory name to settings.php, unless it was
        // manually defined in the existing already.
        if (empty($config_directories[CONFIG_SYNC_DIRECTORY])) {
            $config_directories[CONFIG_SYNC_DIRECTORY] = \Drupal::service('site.path') . '/files/config_' . Crypt::randomBytesBase64(55) . '/sync';
            $settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) [
                'value' => $config_directories[CONFIG_SYNC_DIRECTORY],
                'required' => TRUE,
            ];
            // Rewrite settings.php, which also sets the value as global variable.
            $settings_path = \Drupal::service('site.path') . '/local.settings.php';
            drupal_rewrite_settings($settings, $settings_path);
        }

        // This should never fail, since if the config directory was specified in
        // settings.php it will have already been created and verified earlier, and
        // if it wasn't specified in settings.php, it is created here inside the
        // public files directory, which has already been verified to be writable
        // itself. But if it somehow fails anyway, the installation cannot proceed.
        // Bail out using a similar error message as in system_requirements().
        if (!file_prepare_directory($config_directories[CONFIG_SYNC_DIRECTORY], FILE_CREATE_DIRECTORY)
            && !file_exists($config_directories[CONFIG_SYNC_DIRECTORY])) {
            throw new Exception(t('The directory %directory could not be created. To proceed with the installation, either create the directory or ensure that the installer has the permissions to create it automatically. For more information, see the <a href=":handbook_url">online handbook</a>.', [
                '%directory' => config_get_config_directory(CONFIG_SYNC_DIRECTORY),
                ':handbook_url' => 'https://www.drupal.org/server-permissions',
            ]));
        }
        elseif (is_writable($config_directories[CONFIG_SYNC_DIRECTORY])) {
            // Put a README.txt into the sync config directory. This is required so that
            // they can later be added to git. Since this directory is auto-created, we
            // have to write out the README rather than just adding it to the drupal core
            // repo.
            $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, visit admin/config/development/configuration/sync.' . ' For information about deploying configuration between servers, see https://www.drupal.org/documentation/administer/config';
            file_put_contents(config_get_config_directory(CONFIG_SYNC_DIRECTORY) . '/README.txt', $text);
        }
    }

}

```

The last step, if you want this to be fully automated and possibly avoid errors during installation, is an awkward one. You need to programatically uncomment the include for local.settings.php at the bottom of settings.php.

I'm not aware of any Drupal helpers for that (might be wrong though), so you can probably approach that as a general PHP/other task.

I think the top of the `foo_install_write_profile()` function would be as good a place as any to do it, unless of course your dev workflow means you can do it before you even carry out the installation (probably best if possible).
> 1 votes

# Answer
Clive gave a nice answer, but it didn't work, as the form is not picked up by Drupal and instead throws an error. I'm suspecting that the PSR4 autoloading does not pick up the src directory in a profile. As such, I instead implemented hook\_form\_alter to override the submit handler, rather than overriding the form class overall. Here is the working code:

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Crypt;

/**
 * Implements hook__install_tasks_alter().
 */
function MODULE_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_write_profile']['function'] = 'MODULE_install_write_profile';
}

function MODULE_form_install_settings_form_alter(array &$form, FormStateInterface $form_state) {
  $form['actions']['save']['#submit'] = ['MODULE_install_form_submit'];
}

function MODULE_install_form_submit(array &$form, FormStateInterface $form_state) {
  global $install_state;

  // Update global settings array and save.
  $settings = [];
  $database = $form_state->get('database');
  $settings['databases']['default']['default'] = (object) [
    'value'    => $database,
    'required' => TRUE,
  ];
  // Set the hash salt
  $settings['settings']['hash_salt'] = (object) [
    'value'    => Crypt::randomBytesBase64(55),
    'required' => TRUE,
  ];
  // Remember the profile which was used.
  $settings['settings']['install_profile'] = (object) [
    'value' => $install_state['parameters']['profile'],
    'required' => TRUE,
  ];

  $settings_path = \Drupal::service('site.path') . '/settings.local.php';
  drupal_rewrite_settings($settings, $settings_path);

  // Add the config directories to settings.php.
  MODULE_install_config_directories();

  // Indicate that the settings file has been verified, and check the database
  // for the last completed task, now that we have a valid connection. This
  // last step is important since we want to trigger an error if the new
  // database already has Drupal installed.
  $install_state['settings_verified'] = TRUE;
  $install_state['config_verified'] = TRUE;
  $install_state['database_verified'] = TRUE;
  $install_state['completed_task'] = install_verify_completed_task();
}

function MODULE_install_config_directories() {
  global $config_directories;

  // Add a randomized config directory name to settings.php, unless it was
  // manually defined in the existing already.
  if (empty($config_directories[CONFIG_SYNC_DIRECTORY])) {
    $config_directories[CONFIG_SYNC_DIRECTORY] = \Drupal::service('site.path') . '/files/config_' . Crypt::randomBytesBase64(55) . '/sync';
    $settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) [
      'value' => $config_directories[CONFIG_SYNC_DIRECTORY],
      'required' => TRUE,
    ];
    // Rewrite settings.php, which also sets the value as global variable.
    $settings_path = \Drupal::service('site.path') . '/settings.local.php';
    drupal_rewrite_settings($settings, $settings_path);
  }

  // This should never fail, since if the config directory was specified in
  // settings.php it will have already been created and verified earlier, and
  // if it wasn't specified in settings.php, it is created here inside the
  // public files directory, which has already been verified to be writable
  // itself. But if it somehow fails anyway, the installation cannot proceed.
  // Bail out using a similar error message as in system_requirements().
  if (
    !file_prepare_directory($config_directories[CONFIG_SYNC_DIRECTORY], FILE_CREATE_DIRECTORY)
    && !file_exists($config_directories[CONFIG_SYNC_DIRECTORY])
  ) {
    throw new Exception(t('The directory %directory could not be created. To proceed with the installation, either create the directory or ensure that the installer has the permissions to create it automatically. For more information, see the <a href=":handbook_url">online handbook</a>.', [
      '%directory' => config_get_config_directory(CONFIG_SYNC_DIRECTORY),
      ':handbook_url' => 'https://www.drupal.org/server-permissions',
    ]));
  }
  elseif (is_writable($config_directories[CONFIG_SYNC_DIRECTORY])) {
    // Put a README.txt into the sync config directory. This is required so
    // that they can later be added to git. Since this directory is
    // auto-created, we have to write out the README rather than just adding
    // it to the drupal core repo.
    $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, visit admin/config/development/configuration/sync.' . ' For information about deploying configuration between servers, see https://www.drupal.org/documentation/administer/config';
    file_put_contents(config_get_config_directory(CONFIG_SYNC_DIRECTORY) . '/README.txt', $text);
  }
}

/**
 * Callback for the install write profile.
 *
 * @see MODULE_install_tasks_alter()
 */
function MODULE_install_write_profile($install_state) {
  // Only need to write to settings.php if it is possible. The primary storage
  // for the install profile is the core.extension configuration.
  $settings_path = \Drupal::service('site.path') . '/settings.local.php';

  // Make sure the file exists.
  touch($settings_path);

  if (is_writable($settings_path)) {
    // Remember the profile which was used.
    $settings['settings']['install_profile'] = (object) [
      'value' => $install_state['parameters']['profile'],
      'required' => TRUE,
    ];
    drupal_rewrite_settings($settings, $settings_path);
  }
  elseif (($settings_profile = Settings::get('install_profile')) && $settings_profile !== $install_state['parameters']['profile']) {
    throw new InstallProfileMismatchException($install_state['parameters']['profile'], $settings_profile, $settings_path, \Drupal::translation());
  }
}

```
> 0 votes

---
Tags: installation, configuration
---


title: Get the status message string

text:
# Question
Title: Get the status message string
I tried to get the string messages and create a condition based on the string, but I don't know how to pull the string value.

This is an example of message.

>

# Answer
> 1 votes
You don't need to pull the string, you can use the markup object in a string comparision directly:

```
$markup = \Drupal\Core\Render\Markup::create('Test');

if ($markup == 'Test') {
  // the markup string is "Test"
}

```

When you want to use triple equals then you have to type cast the object to a string first:

```
if ((string) $markup === 'Test') {
  // the markup string is "Test"
}

```

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


# Question
Title: drupal 7: How to create a pop-up window with close button, that shows automatically while loading front page
I am struggling to create a pop-up window (webform, node or something else) with close button.

Modal forms can achieve this by click link. But anyone know how to make it shows without link?

# Answer
> 1 votes
You can use Lightbox2 module. This might help you or else you can also try Node pop-up module.

---
Tags: 7, webforms
---