# Question
Title: How to create a custom field programmatically on content type creation?
I have a module which creates custom fields to the selected content type. This works fine when the content type already exists.

With `hook_form_node_type_form_alter` I create a extra tab on the edit page of the content type. In this tab is a simple checkbox.

```
function hook_seo_form_node_type_form_alter(&$form)
{
    /* @ CREATE VERTICAL TAB ON CONTENT TYPE TO ADD OR REMOVE SEO  */
    //get node type
    $bundle = $form['type']['#default_value'];
    if ($bundle != null) {
        $node_type = NodeType::load($bundle);
        $default_value = $node_type->getThirdPartySetting('seo', 'seo_options');
    } else {
        $default_value = 0;
    }

    //create vertical tab
    $form['seo'] = array(
        '#type' => 'details',
        '#title' => t('SEO'),
        '#group' => 'additional_settings',
    );

    //add checkbox to vertical tab
    $form['seo']['seo_options'] = array(
        '#type' => 'checkbox',
        '#title' => t('Use custom SEO fields'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => 10,
        '#default_value' => $default_value,
    );

    //create submit handler
    $form['actions']['submit']['#submit'][] = 'seo_form_submit';
}

```

I use the following function to see if the form of the content type is submitted and run my script to add fields.

```
function seo_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    /* @ ON SUBMIT SAVE CONFIG & ADD/REMOVE FIELDS  */
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);
    $checkbox = $form['seo']['seo_options']['#value'];

    //set checkbox value to config and save
    $node_type->setThirdPartySetting('seo', 'seo_options', $checkbox);
    $node_type->save();

    if ($checkbox == 1) {
        //Add fields
        seo_enable_field(
            'add',
            'node',
            $bundle,
            'page_title',
            'string_textfield',
            'basic_string',
            'Page title',
            'Description'
        );
    }

```

But for some reason this only works when the content type already exist and I edit it. When I create a new content type it doesn't work and my fields are not created.

How can I solve this?

# Answer
> 0 votes
It is the `NodeType::load()` in `seo_form_submit()` that is failing because the bundle doesn't exist at the time the form is submitted for the first time.

My recommendation would be to redesign this code so that the logic to create/destroy the field is in both a `hook_node_type_insert()` and a `hook_node_type_update()`.

You will need some way to pass the value of the checkbox on the form to these respective hooks. Most likely through a custom configuration or schema.

Edit: It looks like there is more than one design pattern that would work as well as the one I recommended in this answer. Please reference Entity CRUD, editing, and view hooks.

---
Tags: 8
---


# Question
Title: How to prevent a block from being cached?
After login. I'm adding one sidebar block. Once I clear cache then only updates variable or it's value.

```
namespace Drupal\test_demo\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides 'Sidebar' Block
 *
 * @Block(
 *   id = "sidebar_block",
 *   admin_label = @Translation("Sidebar Block"),
 *   category = @Translation("Sidebar Block"),
 * )
 */

class SidebarBlock extends BlockBase {
  public function build() {
    return [
      '#markup' => $this->t('Sidebar'),
      '#cache' => [
            'max-age' => 0,
          ]
      ];
  }
}

```

In **mytheme.theme**

```
function theme_preprocess_block(array &$variables) {
  echo $variables['elements']['#id'];
}

```

How can I stop that block to being cached. So once I refresh the page. It loads the value immediately.

# Answer
> 34 votes
Got the solution via https://stefvanlooveren.me/blog/disable-block-caching-drupal-8

Add below function to your block

https://stefvanlooveren.me/blog/disable-block-caching-drupal-8

```
public function getCacheMaxAge() {
    return 0;
}

```

https://www.drupal.org/docs/8/api/cache-api/cache-max-age

# Answer
> -1 votes
You can simply switch Caching to None on advanced options of view's block

---
Tags: 8, blocks
---


# Question
Title: Module requires Composer install of third-party library
I am trying to learn about drupal 8 and composer within aegir. It seems like aegir has some support for it but the problem that I am running into right now is that aegir doesn't seem to install composer dependencies for modules. For instance, I am using the "real\_aes" module in my first drupal 8 deploy which requires that defuse php-encryption be required. Normally, I would just use composer require and everything would be no problem. However, I am trying to use aegir to manage all of this.

My question is really this. Is there a way in aegir to specify composer requirements or to get aegir to install all module requirements based on the module's composer.json file? And if not, what is the best way to handle this via aegir? Will i need to alter the composer.json file in the drupal root directory after I deploy the drupal 8 platform and run composer update via the command line or are there any other work-arounds that would be better?

I should say that I found the hosting\_composer module and installed it and it's dependencies. However, I immediately got several warnings right after install. Since this is going to be managing live drupal sites, I am hesitant to rely on so many dev modules especially since they are showing issues right after install.

I have about 20-30 drupal 7 sites that I am looking to migrate to d8 over the next year.

# Answer
For anyone else facing a similar problem, I just wanted to add that, as of Aegir 3.18, it seems possible to configure Composer to download and install third party libraries for Drupal modules from https://asset-packagist.org. Of course, those libraries should exist as Composer packages on the asset-packagist site.

I was able to get this going yesterday by following the instructions at the link below, but after a lot of trial and error as the docs are not always accurate, especially in terms of the line endings, JSON syntax etc.: https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies#third-party-libraries

The composer.json file to edit is at the Aegir path /platforms/drupal-x.x.x/composer.json
> 0 votes

---
Tags: composer, aegir
---


# Question
Title: How to check if a link field uses <nolink> in template
* I have a Custom Block type.
* It has a link field that allows `<nolink>`
* In the twig template for that Custom Block type I want to check if the link field has `<nolink>`.

I can see there is a protected value under #url for routeName that is NULL when there is a link, and `<nolink>` when `<nolink>` is used, but I can't figure out how to check it.

I can also see there's a protected uri under #url with a similar situation. If `<nolink>` is used, that value is NULL. If there is a link, the link is in there.

# Answer
Assuming your link field only allows 1 value.

```
{% if content.field_link.0['#url'].toString() is empty %} # or use "is not empty" if you're checking if there is a url.
    # your code goes here
{% endif %}

```

If your field allows multiple link values then loop:

```
{% for link in content.field_link %}
  {% if link['#url'].toString() is empty %} # or use "is not empty" if you're checking if there is a url.
    # your code goes here
  {% endif %}
{% endfor %}

```
> 4 votes

---
Tags: 8, theming
---


title: Solr search not returning content type

text:
# Question
Title: Solr search not returning content type
I have a site set up with Solr search. Drupal says 100% of the site is indexed, and the Search appears to work for most content types and their fields. However, the search does not seem to be searching all fields of the "Publications" Content Type.

For example, the second item in the list of publications (Title = "Bibliography of dry valleys...") has the following text in the "Bibliographic Citation" field:

> Mead, Kay L. Bibliography of dry valleys publications produced under the aegis of the New Zealand Antarctic Research Program 1959-1976 1977

However, when I search "Mead" in the Solr search I get "no results found". The same with "overseas", which appears in the abstract of the publication.

Yet, if I search "aegis" which appears in the title, the publication is returned.

How can I get Solr to index the other fields?

# Answer
You have to tell Search API exactly what it should index:

1. Go to Admin -\> Configuration -\> Search and metadata -\> Search API
2. For the relevant index, choose "Fields" from the drop down
3. Add your desired field(s) to the index and configure appropriate data types
4. Re-index all content
> 0 votes

---
Tags: search
---


# Question
Title: Drupal Commerce and large product inventories
Does anyone have any insight into using Drupal commerce with a large inventory? We are utilising using Drupal 8.1 headless and scoping an eCommerce integration using Drupal Commerce with around 30 million products. Currently, our thoughts are to use a MongoDB backend and Elasticsearch on top of it.

Does anyone have any experience or insight into handling such a large inventory and our planned approach?

The products will not have to be managed via the front end and instead will be imported with their various categories and attributes. Any changes we plan to do from a staging database and synchronise accordingly.

Thank you for any insight.

# Answer
The Akademika case study might help. They're at 18 million products right now, regular MySQL database plus Elasticsearch.

You can find the NyMedia team in #commerce on Drupal Slack (or contact them directly).
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: When does the user interface translation gets updated?
If you turn off "Check for updates" in `/admin/config/regional/translate/settings`, on what occasion does the user interface translation actually gets updated?

As far as I know there're two ways to update it:

* Installing modules. (Related PO files will be downloaded and imported)
* Manually importing PO files from `/admin/config/regional/translate/import`

Is that all?

# Answer
> 2 votes
The check for updates is being called on the cron job 'Interface Translation' If you disable the cron job or disable the "check for updates" on the page you mentioned, there will not be an automatic update on cron runs.

The other methods you name are manually methods.

There is one more method in Core UI, if you translate the interface text manually on the `admin/config/regional/translate` page.

It also depends on the settings "Import behavior" on the `admin/config/regional/translate/settings` page. If the import gets updated.

This is what I know is available in Core UI.

You can of course have other contributed modules as `Drush` or `Drupal Console` to update your translations. Or even `Composer` see `https://github.com/drupal-composer/drupal-l10n`

---
Tags: 8
---


title: Issue regading custom form

text:
# Question
Title: Issue regading custom form
https://wineshipinsure.com/newdrupal/ex81/helloform

I have been using the custom form and followed all the process for creating the custom form but my form is not working and every time getting page not found issue.

Below I share the code for custom form

```
  ex81.hello_form:
  path: 'ex81/helloform'
  defaults:
    _form: 'Drupal\ex81\Form\HelloForm'
    _title: 'Simple custom form example'
  requirements:
    _permission: 'access content'

```

HelloForm.php

```
<?php
namespace Drupal\ex81\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * HelloForm controller.
 */
class HelloForm extends FormBase {
  /**
   * Returns a unique string identifying the form.
   *
   * The returned ID should be a unique string that can be a valid PHP function
   * name, since it's used in hook implementation names such as
   * hook_form_FORM_ID_alter().
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'ex81_hello_form';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['description'] = [
      '#type' => 'item',
      '#markup' => $this->t('Please enter the title and accept the terms of use of the site.'),
    ];

    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#description' => $this->t('Enter the title of the book. Note that the title must be at least 10 characters in length.'),
      '#required' => TRUE,
    ];

    $form['accept'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('I accept the terms of use of the site'),
      '#description' => $this->t('Please read and accept the terms of use'),
    ];

    // Group submit handlers in an actions element with a key of "actions" so
    // that it gets styled correctly, and so that other modules may add actions
    // to the form. This is not required, but is convention.
    $form['actions'] = [
      '#type' => 'actions',
    ];

    // Add a submit button that handles the submission of the form.
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;

  }

  /**
   * Validate the title and the checkbox of the form.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    $title = $form_state->getValue('title');
    $accept = $form_state->getValue('accept');

    if (strlen($title) < 10) {
      // Set an error for the form element with a key of "title".
      $form_state->setErrorByName('title', $this->t('The title must be at least 10 characters long.'));
    }

    if (empty($accept)) {
      // Set an error for the form element with a key of "accept".
      $form_state->setErrorByName('accept', $this->t('You must accept the terms of use to continue'));
    }

  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Display the results
    // Call the Static Service Container wrapper
    // We should inject the messenger service, but its beyond the scope
    // of this example.
    $messenger = \Drupal::messenger();
    $messenger->addMessage('Title: ' . $form_state->getValue('title'));
    $messenger->addMessage('Accept: ' . $form_state->getValue('accept'));

    // Redirect to home.
    $form_state->setRedirect('<front>');
  }

}

```

If anyone finds the solution please let me know asap....

# Answer
Indenting is very important in .yml files. Yours is incorrect. You need to change this:

```
  ex81.hello_form:
  path: 'ex81/helloform'
  defaults:
    _form: 'Drupal\ex81\Form\HelloForm'
    _title: 'Simple custom form example'
  requirements:
    _permission: 'access content'

```

To this

```
ex81.hello_form:
  path: 'ex81/helloform'
  defaults:
    _form: 'Drupal\ex81\Form\HelloForm'
    _title: 'Simple custom form example'
  requirements:
    _permission: 'access content'

```
> 0 votes

---
Tags: modal-dialogs
---


# Question
Title: how to filter by date in view - drupal 8
Hello **everyone** i am working with views ind **Drupal8** ,i have a **5 content types** that contains all a field 'date' , so i want to display just the content types with date == 2020 , how can i do it the with back-office without code, if not we can d it by code.

# Answer
> 2 votes
I Agree with Leigh. I regularly use the filter operator 'is between'. Click on the 'add' button aginst filter criteria, select start date and enter 1st jan 2020 then 31st December in the end date box and job done.

# Answer
> 1 votes
To add date filter by year without code check Views Year Filter module.
From module description:

> This module add views filter by year exact, instead of full date like mm-dd-yyyy you can use date year like yyyy.

---
Tags: views, 8
---


title: Drupal challenges for learning

text:
# Question
Title: Drupal challenges for learning
For newbie Drupal developers:

Is there a repo, blog post or similar with increasing difficulty challenges?

I am willing to test my skills, which may be more than basic.

It would be nice to have a learn path.

# Answer
We have all felt like a newbie at something. Usually, that means our brains are growing. I recently read an inspiring article about this very thing:

http://paulgraham.com/noob.html

Anyway, if you're just looking for a repo with coding examples, then the Examples project is literally what you have described.

As far as tutorials, there are quite a few to choose from.

Start with Acquia Academy. Their tutorials are quick, linear, and easy to follow, and they also have some free training materials. **UPDATE:** Actually it looks like a lot of the good stuff *is* free! I didn't know, because I was always logging in through an employer account.

Drupalize.me used to be really good. Their Drupal 7 courses are very well organized and easy to follow in a linear fashion. Unfortunately, their D8 courses are not as good. D8 has changed a lot since they wrote the tutorials and they haven't necessarily updated them. Also, they are not as well structured and you might start to feel lost in a labyrinth of forking paths. Still, some of their content is available for free, and you can learn quite a lot if you just start with that and keep in mind that it might have changed since Drupal 8.1 or whatever.

There are a ton of other tutorials out there. Some of my favorites are at codekarate.com but as with Drupalize.me the Drupal 7 material is far more comprehensive. The D8 material is good, but tends to be less of a broad overview and more of a deep dive into specific niche things.

This list is far from complete. You’ll find a million other tutorials on DuckDuckGo (or Google, if that’s how you roll)

If you really want to learn Drupal 8 (and 9) development, you might actually want to start by taking a course on MVC development with the Symfony framework. I guess Symfony 3 is still the place to start (although with D9 fast approaching everybody is learning Symfony 4) so here’s a likely option:

https://www.udemy.com/course/learn-symfony-3-framework-by-practical-examples/
> 0 votes

---
Tags: 8
---


# Question
Title: View contextual filter not working inside Panels
I have a view with a contextual filter of type "Raw value from URL". This block view works fine in the page footer. But when added inside Panels & Page Manager, the view stops working. Hence it seems that Panels is somehow blocking the view from being able to access the URL.

As a test, I have the view in Panels and in the footer on the same page, and the footer view displays fine, but the Panels view does not, giving me a "Page not found" error.

I read I need a "context" in Panels to pass information to a view. I also read that view contextual filters that use URLs don't need contexts in Panels, so I'm finding conflicting information.

Every time I try to create a Panels context, I get an error, mostly since I have no idea what to enter into the form fields.

The view looks for a value in the URL, such as `/puppies/10`, where 10 is the node of the puppy. Then the view will only show information for that puppy.

Most of the information out there is for Panels on Drupal 7, and there seems to be enough of a difference that I can't figure it out for Drupal 8.

# Answer
> 0 votes
I had the same problem and figured it out. Enter `/your/path/{parameter}` for your page path and the `Page Context` link will change to a `Page parameter` link. You can use any word for `{parameter}`, it is just a variable name. You specify the type of the parameter under `Page parameter`. It would have saved everyone an enormous amount of time, if this was included in the instructions underneath the path field.

---
Tags: views, 8, panels
---


title: Sync content between two Drupal sites

text:
# Question
Title: Sync content between two Drupal sites
I have two Drupal 7 sites running a very similar structure (views, content types, etc) but with a different theme and a few other changes.

I need to have all the nodes of specific content types that are created in site A to be copied to site B. If it is possible, it should work automatically or by running a script. For example, the sync would run as a scheduled cron job.

I do not need both sites to run in the same database, they must have their own separate database, just the same nodes for specific content types.

I've been investigating, and I see that I can use Node Export, Feeds and even a drush command (ne-export/ne-import). I'm not sure yet about how to put all the pieces together. Has anyone done this already?

# Answer
> 2 votes
For Drupal 8 you can use the Content Synchronization module. From the project page:

> The content synchronization module provides a mechanism to export single content items, or all content items, from an environment, and move them to another, effortlessly.

# Answer
> 0 votes
Try the Drupal Sync module This module is still in dev but I've tested it with success between 3 websites.

> The present module allows synchronizing content among multiple websites. Supported entity types: node and taxonomy, menu items. Many hooks were used during creation of the module. It allows widening synchronization functional by developing additional modules.

# Answer
> 0 votes
The following method is not officially recommended. But if you understand what you are doing and what the consequences are, the benefits can outweigh the drawbacks.

**See Share tables across instances (not recommended)**

I'm using this setup to run a network of sites for a client of mine where content is identical across sites, but the presentation (including views, modules, variables, block placement) is different. My particular setup is Drupal 6, but it could easily be adapted for Drupal 7.

The first step is to configure each of the sites to run off the same database (using table prefixing) and codebase (using Drupal's multisite functionality)(\*). Once the sites are all running off the same DB and codebase, you can create a $db\_prefix array in your settings file.

In my setup, each of the sites shares all tables with the default site by default:

```
$db_prefix['default'] = 'default_';

```

And the following tables are unique per site (again, this is D6, D7 would be slightly different):

```
$db_prefix = array(
    "sessions" => "site1_",
    "authmap" => "site1_",
    "variable" => "site1_",
    "system" => "site1_",
    "role" => "site1_",
    "menu_custom" => "site1_",
    "menu_links" => "site1_",
    "menu_router" => "site1_",
    "cache" => "site1_",
    "cache_block" => "site1_",
    "cache_form" => "site1_",
    "cache_menu" => "site1_",
    "cache_page" => "site1_",
    "cache_update" => "site1_",
    "cache_views" => "site1_",
    "cache_views_data" => "site1_",
    "views_display" => "site1_",
    "views_object_cache" => "site1_",
    "views_view" => "site1_",
    "blocks" => "site1_",
    "blocks_roles" => "site1_",
);

```

I've been running these sites in production for a couple of years now. Editors only login to the "default" site (defined in /sites/all) and all content (nodes) is managed there. Changes to nodes take effect on all of the "slave" sites immediately and without any intervention (save for whatever caching you have in place).

This is definitely an advanced option and it has it's drawbacks (upgrading between major versions of Drupal is nearly impossible), but if you are comfortable and understand what you are doing, it can be a great solution.

(\*) *As long as all of the sites are on the same server or have access to the same database server, I guess you don't need to set it up as a multisite. But to make sure there are no differences in core files, I would still recommend it.*

# Answer
> 0 votes
First of all, there is no coding needed, or direct database interaction.

Easy solution:

1. Make a a View of nodes you want to export using https://www.drupal.org/project/views\_rss
2. Set up periodic node import using https://www.drupal.org/project/feeds

---
Tags: nodes
---


# Question
Title: Can I have Composer or something else download a Git repo as a dependency of my contrib module?
I'm working on a module and there is a sub module for scanning barcodes that requires this, quagga.
Currently you have to manually download the library and put it into the libraries dir. If I add this as a dependency to the module you cannot install it without doing this first.

Can I have composer or something download a git repo to the libraries when installing the submodule?

Edit:
libraries.yml

```
form:
  version: VERSION
  css:
    layout:
      css/commerce_pos_barcode_scanning.css: {}
  js:
    js/commerce_pos_barcode_scanning.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - commerce_pos/quagga
quagga:
  remote: https://github.com/serratus/quaggaJS.git
  version: 1.0.0
  license:
    name: MIT
    url: https://github.com/serratus/quaggaJS/blob/master/LICENSE
    gpl-compatible: yes
  js:
    /libraries/webrtc/adapter-latest.js: {}
    /libraries/quagga/quagga.min.js: {}

```

install.yml

```
function commerce_pos_barcode_scanning_requirements($phase) {
  $requirements = [];
  if ($phase == 'install' || $phase == 'runtime') {
    $path = 'libraries/quagga/quagga.min.js';
    if (!file_exists($path)) {
      $requirements['commerce_pos_barcode_scanning'] = [
        'title' => t('POS Barcode Scanning'),
        'description' => t('To scan barcodes, you need to install the quagga JavaScript library. <a href="/modules/contrib/commerce_pos/modules/barcode_scanning/README.md">How To</a>'),
        'severity' => REQUIREMENT_WARNING,
      ];
    }
    else {
      $requirements['commerce_pos_barcode_scanning'] = [
        'title' => t('POS Barcode Scanning'),
        'severity' => REQUIREMENT_OK,
        'value' => t('quagga JavaScript library has been configured.'),
      ];
    }
  }

  return $requirements;
}

```

# Answer
> 0 votes
You can edit file `composer.js`

find `"web/libraries/{$name}": ["type:drupal-library"],` change to

```
"web/libraries/{$name}": [
                "type:drupal-library",
                "type:bower-asset",
                "type:npm-asset",
                "vendor:npm-asset",
                "vendor:bower-asset",

            ],

```

add repositories

```
{
            "type": "package",
            "package": {
                "name": "serratus/quaggaJS",
                "version": "0.12.1",
                "type": "drupal-library",
                "source": {
                    "url": "https://github.com/serratus/quaggaJS.git",
                    "type": "git",
                    "reference": "master"
                },
                "dist": {
                    "url": "https://github.com/serratus/quaggaJS/zipball/master/serratus-quaggaJS-v0.12.1-14-g862df88.zip",
                    "type": "zip"
                },
                "require": {
                    "composer/installers": "^1.0.20"
                }
            }
        }

```

and run `composer require "serratus/quaggaJS"`

# Answer
> 0 votes
To have this be done automatically people will simply configure their project's `composer.json` themselves. So I'd recommend to just explain one more time how this is supposed to be done via Composer on your project's page on drupal.org or in the documentation to your module.

---

Another inadvisable approach would be to provided a Drush command to download the library. Like Semantic UI API does it. Browse their code on GitLab. The command has not been ported to D8 yet. But I think you'll get the idea. Probably worth looking at their 8.x-1.x branch as well. And see how they solved it in D8.

Below code is from 7.x-1.x. `SEMANTIC_UI_DOWNLOAD_URL` leads to a Zip file on GitHub.

> ```
>   $args = func_get_args();
>   if ($args[0]) {
>     $path = $args[0];
>   }
>   else {
>     //we have dependencies on libraries module so no need to check for that
>     //TODO: any way to get path for libraries directory?
>     //Just in case if it is site specific? e.g. sites/domain.com/libraries ?
>     $path = drush_get_context('DRUSH_DRUPAL_ROOT') . '/sites/all/libraries/semantic_ui';
>   }
>   // Create the path if it does not exist yet. Added substr check for preventing
>   // any wrong attempts or hacks !
>   if (substr($path, -11) == 'semantic_ui' && !is_dir($path)) {
>     drush_mkdir($path);
>   }
>   if (is_dir($path . '/dist')) {
>     drush_log(dt('Semantic Ui already present at @path. No download required.', array('@path' => $path)), 'ok');
>   }
>   elseif (drush_op('chdir', $path) &&
>       drush_shell_exec('wget ' . SEMANTIC_UI_DOWNLOAD_URL . '  -O semantic_ui.zip') &&
>       drush_shell_exec('unzip semantic_ui.zip') &&
>       drush_shell_exec('rm -rf semantic_ui.zip') &&
>       drush_shell_exec('mv Semantic-UI-master/dist/* .') &&
>       drush_shell_exec('rm -rf Semantic-UI-master')) {
>     drush_log(dt('The latest Semantic Ui library has been downloaded to @path', array('@path' => $path)), 'success');
>   }
>   else {
>     drush_log(dt('Drush was unable to download the Semantic Ui library to @path', array('@path' => $path)), 'error');
>   }
>
> ```

---
Tags: 8, installation, composer
---


title: Trouble sending redirect after logout

text:
# Question
Title: Trouble sending redirect after logout
I'm trying to send a redirect after logout, but it is not sending properly. I tried using the *hook\_user\_logout* in a module as follows:

```
use Drupal\Core\Routing\TrustedRedirectResponse;

function module_user_logout($account) {
  $redirect = new TrustedRedirectResponse($url);
  $redirect->send();
}

```

The send() call causes the page to crash with the message: "The \__ page isn't working"

# Answer
> 3 votes
To resolve current issue we need to create RouteSubscriber my\_custom/src/EventSubscriber/MyCustomRouteSubscriber.php :

```
<?php

namespace Drupal\my_custom\EventSubscriber;

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

    /**
     * MyCustom Route subscriber.
     */
    class MyCustomRouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = parent::getSubscribedEvents();
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -300];
        return $events;
      }

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('user.logout')) {
          $route->setDefaults([
            '_controller' => '\Drupal\my_custom\Controller\MyCustomUserLogoutController::logout',
          ]);
        }
      }

    }

```

Then add entry into my\_custom.services.yml:

```
  my_custom.route_subscriber:
    class: Drupal\my_custom\EventSubscriber\MyCustomRouteSubscriber
    tags:
      - { name: event_subscriber }

```

Then create actual controller which will replace users module logout method. my\_custom/src/Controller/MyCustomUserLogoutController.php

```
<?php

namespace Drupal\my_custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class MyCustomUserLogoutController.
 */
class MyCustomUserLogoutController extends ControllerBase {

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    $logout_url = 'https://google.com'
    return new TrustedRedirectResponse($logout_url);
  }

}

```

Hope it will save your time.

Thanks

---
Tags: 8, hooks, redirection
---


title: Cannot uninstall modules anymore

text:
# Question
Title: Cannot uninstall modules anymore
Why do I get the following message when trying to uninstall a module with Drupal 8?

The website encountered an unexpected error. Please try again later.

```
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pantheon.aggregator_feed' doesn't exist: SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table

LIMIT 1 OFFSET 0; Array()
in Drupal\Core\Entity\EntityStorageBase->hasData()</em> (line 588 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).
Drupal\Core\Database\Statement->execute(Array, Array) (Line: 631)
Drupal\Core\Database\Connection->query('SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table
LIMIT 1 OFFSET 0', Array, Array) (Line: 358)
Drupal\Core\Database\Driver\mysql\Connection->query('SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table
LIMIT 1 OFFSET 0', Array, Array) (Line: 510)
Drupal\Core\Database\Query\Select->execute() (Line: 267)
Drupal\Core\Entity\Query\Sql\Query->result() (Line: 83)
Drupal\Core\Entity\Query\Sql\Query->execute() (Line: 588)
Drupal\Core\Entity\EntityStorageBase->hasData() (Line: 56)
Drupal\Core\Entity\ContentUninstallValidator->validate('aggregator') (Line: 573)
Drupal\Core\Extension\ModuleInstaller->validateUninstall(Array) (Line: 99)
Drupal\Core\ProxyClass\Extension\ModuleInstaller->validateUninstall(Array) (Line: 121)
Drupal\system\Form\ModulesUninstallForm->buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 519)
Drupal\Core\Form\FormBuilder->retrieveForm('system_modules_uninstall', Object) (Line: 276)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 93)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

# Answer
As @codesmith mentioned it looks like you have some issue with the Aggregator module but, usually you might also see other problems once you fix the aggregator module issue. The reason you see the issue on `aggregator_feed` is that it is the first table in your table list.

In case you are lucky and the issue is only on the aggregator module use the query below to recreate the missing tables (I am providing the two tables that are created when you install aggregator module).

```
CREATE TABLE `aggregator_feed` (
`fid` int(10) UNSIGNED NOT NULL,
`uuid` varchar(128) CHARACTER SET ascii NOT NULL,
`langcode` varchar(12) CHARACTER SET ascii NOT NULL,
`title` varchar(255) NOT NULL,
`url` varchar(2048) NOT NULL,
`refresh` int(11) DEFAULT NULL,
`checked` int(11) DEFAULT NULL,
`queued` int(11) NOT NULL,
`link` varchar(2048) DEFAULT NULL,
`description` longtext,
`image` varchar(2048) DEFAULT NULL,
`hash` varchar(255) CHARACTER SET ascii DEFAULT NULL,
`etag` varchar(255) DEFAULT NULL,
`modified` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_feed entities.';

```

and the second table

```
   CREATE TABLE `aggregator_item` (
  `iid` int(10) UNSIGNED NOT NULL,
  `langcode` varchar(12) CHARACTER SET ascii NOT NULL,
  `fid` int(10) UNSIGNED DEFAULT NULL COMMENT 'The ID of the target entity.',
  `title` varchar(255) DEFAULT NULL,
  `link` varchar(2048) DEFAULT NULL,
  `author` varchar(255) DEFAULT NULL,
  `description` longtext,
  `timestamp` int(11) NOT NULL,
  `guid` longtext
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_item entities.';

```
> 0 votes

# Answer
I think that table is part of the core Aggregator module. Looks like Drupal thinks the module is installed but one or more of the module's database tables are missing. Try enabling/disabling the module.
> -2 votes

---
Tags: 8
---


# Question
Title: How to log to console when in a Drupal attach behavior?
I'm using Drupal 7. I have the following code that tries to log to the console:

```
function mymodule_get_jquery() {
  $jquery = <<<JAVASCRIPT

  console.log("here");

  (function($) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery);

JAVASCRIPT;

  return $jquery;
}

```

If I open the Console in Firefox or Chrome, the log outputs the following:

```
JQMIGRATE: Migrate is installed, version 1.4.1
here
there

```

Why isn't the "everywhere" line getting logged? Is there any way to log JavaScript info in the Drupal behavior attach function?

UPDATE:

Here is how I am calling the mymodule\_get\_jquery() function:

```
/*
 * Implements hook_page().
 */
function mymodule_page() {

  /* ... */

  $jquery = mymodule_get_jquery();
  drupal_add_js($jquery, "inline");

  /* ... */
}

```

# Answer
> -1 votes
Drupal object should be passed as function parameter like below:

```
(function($, Drupal) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery, Drupal);

```

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


# Question
Title: Update UI lists modules/themes that are already updated
I have a D7 (7.69) site. On both dev and production, I can update a module (using the web UI - */admin/modules/update*), apparently successfully, yet afterwards, that module *stays* listed as requiring an update with *Installed Version* and *Recommended Version* exactly the same.

e.g.

> Adminimal - Responsive Administration Theme (Theme)
> Installed version 7.x-1.26
> Recommended version 7.x-1.26

(I've seen it with themes, such as the one above, and modules such as *Views*).

I've tried:

* clearing the cache
* downloading a clean latest version to a new directory, and comparing the md5hashes of all files between the two (as well as simpler checks like the module *.info* file.)
* wiping the module/theme directory and replacing with a freshly extracted .tar.gz
* checking if any database updates are pending (they're not)

Is there anything else that could be causing it to get stuck?

I've looked at the *system* table - specifically the `system.info` field - but nothing looks "wrong".

# Answer
> 1 votes
This was caused by the Update Status Advanced Settings (update\_advanced) module.

I didn't know this module was installed or what it was, so here's how I traced it back:

*modules/update/update.compare.inc* is where the core update module checks versions of each module and theme, beginning with *update\_calculate\_project\_data()* \- this creates a $project array that contains current/recommended versions, plus a numeric 'status' key.

'status' is a constant, set in *modules/update/update.module*, with values including:

```
define('UPDATE_CURRENT', 5); // project is up to date
define('UPDATE_NOT_CHECKED', -1); // Project's status cannot be checked.

```

I used Xdebug on *update\_calculate\_project\_data()*, specifically tracking the modules that were stuck on the update screen.

They all had a status of `UPDATE_CURRENT` initially (as expected/desired), but that changed to `UPDATE_NOT_CHECKED` after the call to the hook in line 363:

```
drupal_alter('update_status', $projects);

```

Searching the code base, found this hook is implemented in *sites/all/modules/update\_advanced/update\_advanced.module:50* by *update\_advanced\_update\_status\_alter()*

If you've got this module, the settings page is */admin/reports/updates/settings*; you can instruct it to not *warn* you about specific modules.

The side effect is that by changing the status to anything other than `UPDATE_CURRENT`, a module/theme will always be listed in the Update UI (modules/update/update.manager.inc:94), including if the module *is* "current" really.

---
Tags: 7, updating
---


# Question
Title: Logout user programmatically without redirect
I need to logout the current user in my code. For now I use : `user_logout();` but this function seems to have a redirect at the end.

How can I logout a user without any redirect ?

It need to be for a single case, not a hook to every logout.

Thanks.

# Answer
The logout controller (`UserController::logout()`) does this in a separate step.

```
  public function logout() {
    user_logout();
    return $this->redirect('<front>');
  }

```

You can alter the controller class for the *user.logout* route to replace this with custom code.

What do you want to do instead? Building an anonymous response a redirect seems to be the most straightforward solution.
> 6 votes

# Answer
Just throwing this in for Drupal 7, since Google sent me here (I am aware the question is for Drupal 8, but this answer should be valid for 8 too?)

`user_logout_current_user();` appears to perform this without the redirect.

https://api.drupal.org/api/drupal/modules!user!user.pages.inc/function/user\_logout/7.x https://api.drupal.org/api/drupal/modules%21user%21user.pages.inc/function/user\_logout\_current\_user/7.x
> 0 votes

---
Tags: 8, users
---


# Question
Title: Avoid hard crash if user searches when Solr stopped
I use search\_api\_solr with a server-based Solr installation. Works fine. For reasons I won't explain, the Solr service is stopped sometimes. If a user does a search while Solr is stopped, they crash with "The website encountered an unexpected error."

The error log says "Drupal\search\_api\_solr\SearchApiSolrException: An error occurred while trying to search with Solr: Solr endpoint http://localhost:8983/ unreachable or returned unexpected response code "0"." No surprise, since the service is stopped.

How can I trap this error and display a "Search isn't working" page instead of crashing? Seems like there should be a way to intercept it, but I haven't figured it out.

# Answer
Based on the comment by @4k4 and post at https://drupal.stackexchange.com/a/235942/70681 and further reading, I used my existing custom module (`rsc`) to solve the problem as follows:

In `modules/custom/rsc/rsc.services.yml`

```
services:
  rsc.event.SolrException:
    class: Drupal\rsc\EventSubscriber\rscSolrException
    tags:
      - { name: event_subscriber }

```

In `modules/custom/rsc/src/EventSubscriber/rscSolrException.php`

```
<?php
namespace Drupal\rsc\EventSubscriber;

use Drupal\search_api_solr\SearchApiSolrException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;

class rscSolrException implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 60];
    return $events;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof SearchApiSolrException) {
      $event->setResponse(new RedirectResponse('/search-not-working'));
    }
  }
}

```

When a Solr exception occurs, users are redirected to the search-not-working page instead of to "The website encountered an unexpected error." Much nicer.
> 4 votes

---
Tags: 8, search
---


# Question
Title: Drupal Webform View Form Submitted data to user
I want my users to view their submitted data after submission to let them know what they submitted. How can I do this? Please help!!

# Answer
> 1 votes
On your webform submission settings on

scroll down, then check **"Allow users to view a submission using a secure token? "**

then as it has been mentioned there

> Allow users to view a submission using a secure token If checked users will be able to view a submission using the webform submission's URL appended with the submission's (secure) token. The 'tokenized' URL to view a submission will be available when viewing a submission's information and can be inserted into an email using the \[webform\_submission:view-url\] token.

---
Tags: webforms
---


# Question
Title: Twig: How to access multiple values from node reference field with number_format
I'm adding fields to array:

```
{% for item in content.field_notes | field_target_entity %}
   {% set field_component_pages = item.field_component_pages|view|number_format %}
{% endfor %}

```

In my scenario the value of item.field\_component\_pages|view is equal "16", but when I convert it to number with number\_format I get value of 1.

I presume the `item.field_component_pages|view` is not a real value. How can I access field field\_component\_pages correctly in this case?

# Answer
You can get it form the value. something like `item.field_component_pages.0.value` properly works for you

```
{% for item in content.field_notes | field_target_entity %}
   {% set field_component_pages = item.field_component_pages.0.value|number_format %}
{% endfor %}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Send email only if a field has a certain value
I am using webform in Drupal 7 and have a case where I need to send an e-mail only if a certain select field has an option selected. I have installed Rules and Webform rules but am a bit stuck on how to get this going.

In my webform I have the field called type (which is nested in a fieldset called shipping). My 3 options in the field are Ground, Air, Ocean. What I would like to do is send an email (using Rules due to a pdf that is attached to the email) only if the option selected is Ground.

Is this possible with Drupal 7 and rules / webform rules?

# Answer
> 1 votes
I would use a technique similar to what is described in my answer to "How can I compare data comparison with values submitted in a webform?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
* In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).

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


# Question
Title: Can't set a default theme in a FunctionalJavascript test with $defaultTheme class property
Trying multiple ways here to set a default theme to use in FunctionalJavascript tests and it is not working (I am watching them execute in VNC viewer). Bartik always shows.

I also tried setting $defaultTheme to `stark`, it does not appear either. It is always Bartik. According to the class and docs, this is supported in Drupal 8.8.2.

How can I make my theme default and load? This is the class my FunctionalJavascript class tests extend:

```
abstract class WebDriverTestBase extends CoreWebDriverTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'MYTHEME';

  protected $profile = 'standard';

  /**
   * {@inheritdoc}
   */
  protected $strictConfigSchema = FALSE;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->container->get('module_installer')->uninstall(['page_cache']);
    $this->container->get('theme_installer')->install(['MYTHEME'], TRUE);
    $this->container->get('config.factory')->getEditable('system.theme')->set('default', 'MYTHEME')->save();
  }

```

Edit: command being run:

`docker-compose exec --user=$DOCKER_COMPOSE_USER php phpunit --testsuite unit,kernel,functional,functional-javascript`

My phpunit.xml.dist file has limited those suites to my modules/custom folder.

Edit 2:

I have now done the following:

```
drush si --sites-subdir=testing.docker.localhost
drush then MYTHEME
drush cedit system.theme (set MYTHEME default)
drush pm-uninstall page_cache
drush en mymodule_user_auth
drush cr
phpunit ....

```

I had to set the block too (one test looks for the presence of a block). Now the tests pass. But why is the setUp() method not doing the above even though its being told to do so? Regular Functional tests adhere to this, why not FunctionalJavascript ones?

# Answer
I wound up installing a barebones install with `drush si` and exporting certain configuration to an install profile. After adding this to `drush si` in CI and local, all functional javascript browser tests work without complaints.

I double checked and the parent `BrowserTestBase` class does have defaultTheme and profile properties, so I don't know why those were not installed.
> 0 votes

---
Tags: 8, testing
---


# Question
Title: Display selected menu parent with children in sidebar
I have a menu build with taxonomy menu structured like this :

Agenda

* agenda1
* agenda2

News

* News1
* News2

Access

* Access1
* Access2

My main navigation is like this (no children): Agenda | News | Access

What i want to do is , when i click Agenda for example ,i would like to dispay in agenda page in the side bar the block menu corresponding with children

Agenda

* Agenda1
* Agenda2

I have read many forum on this but not able to get it working :

Show Parent Menu children in sidebar Get menu link siblings How to display a block with menu child items programmatically?

I try Menu bloc module to do this but when i set Initial visibility level = 1 , all the menu with children is displaying , but i would like just display the selected menu with his children

When i set Initial visibility level \> 1 nothing is display

Any help is welcome

# Answer
> 0 votes
I get it working by using this module : Hierarchical Taxonomy Menu https://www.drupal.org/project/hierarchical\_taxonomy\_menu

Thanks

---
Tags: navigation
---


# Question
Title: How to make fields of a cloned node available in Rules
I have a rule that clones a node once it's flagged. I can set certain parameters for this newly cloned node but not all. I read in other posts that you have to use a conditional rule to identify what the node type is of that cloned node and then you have access to all the fields. But again not to "all" fields.

I want to set the cloned node text field "student name" to the author's first name, a text field on the user's profile. Many fields from the flagging user's profile are available but not all.

# Answer
It looks like you already found "a" solution for your own question, but since you don't really understand your own solution, and because IMO there is an easier to understand solution, consider the below alternative ...

# Step 1: Create a Rules Component

Create a Rules Component (of type "action set") like so:

* Parameter "`node_to_update`" and "`node_author`".
* Rules Action = "*show message*".

Here is a prototype of such Rules Component (in rules export format, use the Rules UI to import it in your site):

```
{ "rules_update_cloned_node" : {
    "LABEL" : "Update cloned node",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_to_update" : { "label" : "Node to be updated", "type" : "node" },
      "node_author" : { "label" : "Node author", "type" : "user" }
    },
    "ACTION SET" : [
      { "drupal_message" : { "message" : "The field firstname in node with id [node-to-update:nid] needs updating with value \r\n[node-author:field-firstname]. To actually do so, replace this (informational) Rules Action with setting the appropriate value for the appropriate field ..." } }
    ]
  }
}

```

The actual action only displays a Drupal message (to show the values of the variables passed to it). Replace that action with the actual update of your cloned node.

# Step 2: Update your existing Rule

Update your existing Rules Actions by performing the Rules Component (from step 1), whereas you pass these 2 **parameters**:

* the `node_to_update`, which you can pass via the value (token) of the cloned node's `nid`.
* the `node_author`, which you can pass via the value (token) of the cloned node's `uid`.
> 1 votes

# Answer
The problem was that I had to fetch the entity by property \[cloned-node:author:field-firstname\] inside the conditional and set the data value \[cloned-node:field-student-name:0\] to \[firstname-fetched:0:field-firstname\] I still don't understand the actual logic why \[firstname-fetched:\] has to be followed by \[0:field-firstname\] but that works. See screenshots. Hope this helps someone else out too.

After @Pierre.Vriens helped out my component code is now:

```
    { "rules_update_the_cloned_course_with_values_for_the_student" : {
    "LABEL" : "Update the cloned Course with values for the Student",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "cloned node", "component", "course", "update" ],
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "USES VARIABLES" : {
      "node_to_update" : { "label" : "Node to be updated", "type" : "node" },
      "node_author" : { "label" : "Node author", "type" : "user" }
    },
    "ACTION SET" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_is_of_bundle" : {
                "entity" : [ "node-to-update" ],
                "type" : "node",
                "bundle" : { "value" : { "course" : "course" } }
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "node-to-update:field-student-name:0" ],
                  "value" : [ "node-author:field-firstname" ]
                }
              },
              { "drupal_message" : { "message" : "Machine name of this Component was: \u0022rules_update_the_cloned_course_with_values_for_the_student\u0022" } },
              { "data_set" : { "data" : [ "node-to-update:field-status" ], "value" : "359" } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : {
                  "message" : "The field \u0022Student name\u0022 could not be set with the value of the Student\u0027s first name.\u003Cbr \/\u003E\r\nMachine name of this Component was: \u0022rules_update_the_cloned_course_with_values_for_the_student\u0022",
                  "type" : "warning"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

```
> 2 votes

---
Tags: 7, rules
---


# Question
Title: Feeds import from Restful Web Service module output
I have a D7 website, which expose a node through the module `Restful Web Service` https://www.drupal.org/project/restws

It does exposed my website node in Json format. The only issue I have, is the photo field, which has multiple images but JSON output from RESTWS is only expose the `photo file id`, not the file name.

My question, is there're plugin for the Feeds module that I can use to convert the file ID to a file name, so the feed can import that. Or is there other way that I can use to directly import the file fid to Drupal.

Here's a little info about my website: The user can list their content on `bronze plan content type`, and then they decide to upgrade to `silver content type`, what I'm doing in the background, is export the bronze content type through Restful Web Service and re-import through feeds to `silver content type`.

# Answer
> 0 votes
I just want to post my plan for everyone to review and response. After days of no response, it does mean I'm having a crazy idea.

I've re-think my solution and came up with writing my own custom module to do the data copy from one content type to another. It was easy than I expected. Copy of data from one content type to another is very easy if the both field type are the same. It's a straight assign of field from one node object to another content type object. That's it.

---
Tags: 7, feeds
---


title: Override entity form handler

text:
# Question
Title: Override entity form handler
I'm trying to alter an entity form handler. The method EntityType::setHandlerClass() allows for the 'form' handler to be set, but this value is an array, and I only want to override a single item of the array.

The entity handlers definition:

```
handlers = {
    "storage" = "Drupal\user\UserStorage",
    "storage_schema" = "Drupal\user\UserStorageSchema",
    "access" = "Drupal\user\UserAccessControlHandler",
    "list_builder" = "Drupal\user\UserListBuilder",
    "views_data" = "Drupal\user\UserViewsData",
    "route_provider" = {
      "html" = "Drupal\user\Entity\UserRouteProvider",
    },
    "form" = {
      "default" = "Drupal\user\ProfileForm",
      "cancel" = "Drupal\user\Form\UserCancelForm",
      "register" = "Drupal\user\RegisterForm"
    },
    "translation" = "Drupal\user\ProfileTranslationHandler"
  }

```

I'm trying to figure out how to override the form.register handler, but as the first argument to setEntityHandler() is a string, I cannot figure out how to set a nested value.

# Answer
> 2 votes
I have found the solution. Instead of using EntityType::setHandlerClass(), use EntityType::setFormClass().

---
Tags: 8
---


# Question
Title: How to create a google map block to display number of nodes for a content type
I have a content type "Houses".

I added 3 nodes as follows.

* Node 1 for county X and state A
* Node 2 for county X and state A
* Node 3 for county Y and state B.

I like to create a google map block which will show 2 in County X in google map and 1 in County Y section in google map.

Below is an example

Google doc

---

Update 1

https://docs.google.com/document/d/1q9uLBQpWY\_a3du6HbWH3s0Gz2k\_F4gJDYQDpeX9mcaw/edit?usp=sharing

# Answer
> 1 votes
Use Geofield\_map module:

> Geofield Map is an advanced, complete and easy-to-use Geo Mapping solution for Drupal 8, based on and fully compatible with the Geofield module, that lets you manage the Geofield with an interactive Map both in back-end and in the front-end.
>
> It represents the perfect solution to:
>
> geolocate (with one or more Locations / Geofields) any fieldable Drupal entity throughout an Interactive Geofield Map widget; render each Content's Locations throughout a fully customizable Interactive Geofield Map Formatter; expose and query Contents throughout fully customizable Map Views Integration; implement advanced front-end Google Maps with Marker Icon & Infowindow advanced customizations, custom Google Map Styles and Marker Clustering capabilities; customize Map Geometries properties (Lines & Polylines, Polygons, Multipolygons, etc.), based on Google Maps Polygons APIs;

Take a look at Demo.

So, in summary, you need to install this module and add it to your content type. then with creating a custom view, you can achieve what you want.

---
Tags: google-maps
---


# Question
Title: Use a custom install profile for Nightwatch tests?
How can you set a custom install profile to run a Nightwatch test in? I am not seeing it in the docs. The definition of the `.drupalInstall()` command has:

```
commandAsWebserver(
        `php ./scripts/test-site.php install ${setupFile} --install-profile nightwatch_testing --base-url ${process.env.DRUPAL_TEST_BASE_URL} ${dbOption} --json`,
      ),

```

Which looks like the profile is hardcoded with no way to set.

# Answer
> 0 votes
As you understood it's been hardcoded. if you want to make it dynamic you can create your custom parameter.

you can do it in a way like the following :

https://www.drupal.org/project/drupal/issues/3017176

this patch help you to know what you can do : https://www.drupal.org/files/issues/2019-11-11/3017176-16.patch

---
Tags: 8, testing
---


# Question
Title: How do I change the salt used for the user password when creating an account?
I am working on Drupal 8 site where the client has asked us to use their own custom salt when storing the user password in the database.

Is it possible to set a custom salt for a Drupal site?

The client is thinking of the feature from a security perspective. What can be done?

# Answer
In `site/default/settings.php` there is a config for salt

`$settings['hash_salt']`, passwords are hashed with this salt. you can change it to whatever the client has asked you.
> 1 votes

---
Tags: 8, users
---


# Question
Title: I am getting a PDO error which seems related to the Media module
After Drupal 8.8 upgrade media module is not working. In admin media links are not working e.g **/admin/content/media** Error : The website encountered an unexpected error. Please try again later.

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'media' doesn't exist: SELECT COUNT(\*) AS expression FROM (SELECT 1 AS expression FROM {media} base\_table GROUP BY base\_table.vid, base\_table.mid) subquery; Array ( ) in Drupal\media\MediaListBuilder-\>getEntityIds() (line 158 of core/modules/media/src/MediaListBuilder.php).

# Answer
> 0 votes
it seems you have not done the update completely. one part of Drupal updating is Database updating.

there are some solutions to update it.

* solution go to `YOUR_WEBSITE_ADDRESS/update.php` the go through the steps.
* solution if you have *drush*, run `drush updb`

---
Tags: media
---


# Question
Title: How can you display document file sizes next to a media link button?
I'm trying to display the file size of a file next to a media link button on a page.

I have two content types with a media entity reference field in each. Each field is restricted to only pull from a file media type. What I was trying to do was create a twig variable using a field preprocess and pop that variable inside each of my field templates. However, my preprocess below doesn't seem to be displaying the file size as I want. What am I doing wrong?

```
function theme_preprocess_field(&$variables, $hook) {

  $pdf_fields = [
    'field_1',
    'field_2'
  ];

  if (in_array($element['#field_name'], $pdf_fields) && $element['#entity_type'] == 'node') {

    if ($variables['items'][0]) {

      $field_name = $element['#field_name'];

      $node = $element['#object'];
      // Get first referenced media id.
      $media_id = $node->$field_name->target_id;
      // Get file object.
      $file = \Drupal\file\Entity\File::load($media_id);
      if ($file) {
        // Get file size.
        $file_size = format_size($file->getSize());
        // Set file size variable.
        $variables['file_size'] = $file_size;
      }
    }
  }
}

```

Twig field template

```
{% for item in items %}
  <a href="{{ item.content['#url'] }}" class="button">Download Paper</a><span>(PDF | {{ file_size }})</span>
{% endfor %}

```

# Answer
```
function HOOK_preprocess_file_link(&$variables) {
  if (isset($variables['file'])) {
    $variables['fileLinkDisplay'] = [
      'fileSize' => $variables['file']
        ->getSize(),
      'fileSizeFormatted' => format_size($variables['file']
        ->getSize()),
    ];
  }
}

```

`{{ fileLinkDisplay.fileSize }}`and `{{ fileLinkDisplay.fileSizeFormatted }}` will be available in your template.

**PS:** if it works then you can more filter to restrict to the content type and field you want applied for.

Additionally, there is a module that show the size https://www.drupal.org/project/field\_formatter\_file\_size

> Field Formatter File Size is a field formatter to display the file size.
> 1 votes

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


# Question
Title: Difference between creating a Rest endpoint and a route&controller with jsonResponse
What is the difference between creating a Rest plugin with the Rest API and creating a route/controller that returns a jsonResponse ?

In which case i have to create a custom route/controller with a jsonResponse ?

# Answer
> 1 votes
The main difference is the authentication and authorization, is Rest Solution you should provide different way to authentication and authorization to access to the endpoint. but in Controller,route solution is MVC base solution that drupal and it's ACL ( role and permissions) hanle the access to the results not REST authorization methods like basic\_auth, oauth2 etc.

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


# Question
Title: Categories REST API relation with Blog Posts
I am new to Drupal. I am trying to create a news app with Drupal as back end. I created a Category Taxonomy and attached it with Articles Content type. Then I created View for Articles Rest api and I am successfully getting all the content. You can see here - Link

Then I created a new Rest Api View for Categories with is also returning List of Categories. Link

**1.** The problem is how can I link both ? So I can return the list of posts in categories when user click on a category name.

**2.** I also want to show the list of categories and when someone click on a category, it should return all the posts of that category.

**This is something relationship issue. How can I achieve this ? I am new in Drupal. Please help.**

# Answer
> 0 votes
My suggestion is to add an extra field in your views and render the URL to content as a result of it.

( add title field, in the formatter section, chose URL )

let me know if you don't know how to create link to content view field.

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


# Question
Title: Why this specific string is untranslatable
I want to translate "You can only change the parent menu item for the *published* version of this content" which belongs to Menu UI module.

The string is defined in `/core/modules/menu_ui/src/Plugin/Validation/Constraint/MenuSettingsConstraint.php` like below:

```
<?php

namespace Drupal\menu_ui\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Validation constraint for changing the menu settings in pending revisions.
 *
 * @Constraint(
 *   id = "MenuSettings",
 *   label = @Translation("Menu settings.", context = "Validation"),
 * )
 */
class MenuSettingsConstraint extends Constraint {

  // This string is untranslatable.
  public $message = 'You can only change the menu settings for the <em>published</em> version of this content.';
  public $messageWeight = 'You can only change the menu item weight for the <em>published</em> version of this content.';
  public $messageParent = 'You can only change the parent menu item for the <em>published</em> version of this content.';
  public $messageRemove = 'You can only remove the menu item in the <em>published</em> version of this content.';

}

```

This extends a class from Symfony and doesn't use t() function, but other strings defined in the same way are translatable(which means you can find the string in the localize.drupal.org). Below is an example of a translatable string.

```
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 * @Target({"CLASS", "PROPERTY", "METHOD", "ANNOTATION"})
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class Expression extends Constraint
{
    const EXPRESSION_FAILED_ERROR = '6b3befbc-2f01-4ddf-be21-b57898905284';

    protected static $errorNames = [
        self::EXPRESSION_FAILED_ERROR => 'EXPRESSION_FAILED_ERROR',
    ];

    // This string is translatable.
    public $message = 'This value is not valid.';
    public $expression;

    /**
     * {@inheritdoc}
     */
    public function getDefaultOption()
    {
        return 'expression';
    }

    /**
     * {@inheritdoc}
     */
    public function getRequiredOptions()
    {
        return ['expression'];
    }

    /**
     * {@inheritdoc}
     */
    public function getTargets()
    {
        return [self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT];
    }

    /**
     * {@inheritdoc}
     */
    public function validatedBy()
    {
        return 'validator.expression';
    }
}

```

I guess there're Drupal wrappers to make the strings originated in Symfony class implementations translatable. But why does the string in Menu UI remain untranslatable? It's not urgent, but I'm curious.

EDIT: Entity Validation API overview says "Symfony validator is configured to use a Drupal translator class, such that violation messages correctly run through t(). ". So if my understanding is right, the untranslatable string also gets wrapped in t() eventually...?

# Answer
> 2 votes
There are two different aspects. The first one is how Drupal compiles the core translation list. This is based on the (not running) PHP code using the Translation template extractor (POTX).

You find only the first of the four messages on localize.drupal.org because of a naming issue in this particular constraint. Drupal searches for translation strings in certain locations and `$messageParent` doesn't match:

```
/**
 * Detect validation constraint messages. Drupal 8+.
 *
 * This sequences is searched for:
 *   T_POTX_CONSTRAINT = T_CONSTANT_ENCAPSED_STRING.
 *
 * note: T_POTX_CONSTRAINT is marked for T_VARIABLE tokens inside .php files
 *   with the "Constraint" suffix, where the token is "$message", or ends
 *   with "Message"
 *
 * @param string $file_name
 *   Name of file parsed.
 * @param string $save_callback
 *   Callback function used to save strings.
 */
function _potx_find_constraint_messages($file_name, $save_callback) {

```

See https://www.drupal.org/project/potx/issues/2884361#comment-13052396

The second aspect is about the run-time behavior. Symfony contraints are integrated into the Drupal translation system, so that messages are wrapped in a Drupal translatable markup object.

So a quick fix would be to visit the site in a non english language and trigger the error, then the string will be added to the translation list of your local site.

---
Tags: 8
---


title: Change Superfish menu on specific pages

text:
# Question
Title: Change Superfish menu on specific pages
Is there any way I can change the menu in Superfish module in specific pages? What I know so far is that Superfish uses the "Main Navigation" in the admin structures by default. Can I create a customised menu and make Superfish use that menu?

# Answer
> 0 votes
I guess you want Mega menu(Navigation),As your requirement you need to create custom menu module.

Using these module - https://www.drupal.org/project/menu\_item\_extras. You can make your own fields,which are u need to print making new block from custom module.

Hope my suggestion will help u. Thanks!

---
Tags: 8, navigation
---


# Question
Title: How do I get only node IDs from the search results?
I'm using Search API Solr with custom searches in code, but I want to find a way to limit the return results to only the nid to save on bandwidth with our third-party solr server. I've tried $query-\>fields(array('nid')) but I receive the following error.

> SearchApiException: Trying to search on field nid which is no indexed fulltext field.

I am using the following code (simplified).

```
$index = search_api_index_load('my_index');
$query = $index->query();
$query->keys($search_terms);
$query->fields(array('nid')); // doesn't work
$results = $query->execute();
return $results;

```

How do I get only node IDs from `$results`?

# Answer
As @AjitS mentions, if the original node ID is not indexed, then you can't retrieve it from the fields of the search results.

The annoying thing is that the search API knows the IDs, but they're not in an easy to use form. It's happy to give you a list of `entity:node/1:en` type references, which you can decompose into the original node IDs with something cheesy like this:

```
  # Converts a list of "entity:node/1:en" type strings to a list of integers
  public function get_nids_from_search_ids($ids) {
    $nids = [];
    foreach($ids as $id) {
      if(substr($id, 0, 12) == 'entity:node/') {
        $rest = substr($id, 12);
        $pieces = explode(':', $rest);
        if($pieces[0] != "") {
          array_push($nids, $pieces[0]);
        }
      }
    }
    return $nids;
  }

```

It feels like there ought to be a better way *without* needing to additionally index the node IDs, but it seems there isn't. I guess one day the search API may include convenience methods to get (rigorously) at the "parts" of the IDs it returns.
> 1 votes

# Answer
This is because the `fields()` method of the `SearchAPIQuery` class makes the search in fields with datatype `fulltext`.

In order to get the `nid` in the result, you have to ensure that its value is being indexed by search\_api. You can check that at `/admin/config/search/search_api/index/my_index/fields` (`my_index` is the name of the index in this case).

To filter using the nid field you might have to use the `condition` method instead. The following should work:

```
$index = search_api_index_load('my_index');
$query = $index->query();
$query->keys($search_terms);
$query->condition('nid', $val); // The third parameter "operator" defaults to "="
$results = $query->execute();
return $results;

```
> 0 votes

---
Tags: 7, search
---


# Question
Title: How can I use Twig tempalte to handle label of form input field?
In a custom module (association), I have a form (MembershipStep3).
I'd like to use Twig template to handle form fields titles and need some advice about that.
In `association.module`, I have this code:

```
function association_theme()
{
  return [
    'association' => [
      'render element' => 'children',
    ],
    'membership_step3' => [
      'render element' => 'form',
      'template' => 'membership-step3',
    ],
  ];
}

```

In `MembershipStep3.php`, two almost identical fields are defined this way:

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

    $form = parent::buildForm($form, $form_state);
    $form['amap1'] = [
      '#type' => 'checkbox',
      '#title' => 'Je souhaite faire partie de l’AMAP (cas 1)',
    ];
    $form['amap2'] = [
      '#type' => 'checkbox',
    ];
    some other stuff...

```

And here is `membership-step3.html.twig`:

```
<form{{ attributes }}> {{ form.form_build_id }} {{ form.form_token }} {{ form.form_id }}

<div>

    {{ form.amap1 }}

    <br>
  {{ form.amap2 }}
    <label for="edit-amap2" class="option">
    Je souhaite faire partie de l’AMAP (cas 2)
    </label>

    {# Renders the rest of the form #} {{ form | without('amap1', 'amap2') }}

</div>

```

The result is:

The generated HTML is:

```
<div>

    <div class="js-form-item form-item js-form-type-checkbox form-item-amap1 js-form-item-amap1">
        <input data-drupal-selector="edit-amap1" type="checkbox" id="edit-amap1" name="amap1" value="1" class="form-checkbox">

        <label for="edit-amap1" class="option">Je souhaite faire partie de l’AMAP (cas 1)</label>
      </div>

    <br>
  <div class="js-form-item form-item js-form-type-checkbox form-item-amap2 js-form-item-amap2 form-no-label">
        <input data-drupal-selector="edit-amap2" type="checkbox" id="edit-amap2" name="amap2" value="1" class="form-checkbox">

        </div>

    <label for="edit-amap2" class="option">
    Je souhaite faire partie de l’AMAP (cas 2)
    </label>

```

As you can see, the label for `amap2`is outside of the div created by `{{ form.amap2 }}`.

How can I change my Twig template in order to have a result similar to `amap1`?

# Answer
Drupal theming engine provides lots of layers. For example there's a twig template for the HTML wrapper (html.html.twig) then a template for the body (page.html.twig) which gets included in the HTML wrapper, then there's body elements which are included in the body template etc.

Forms are also same, there's a general Form wrapper, and when you print `{{ form.amap1 }}` in your `membership-step3.html.twig` this basically includes the `checkboxes.html.twig`, and passes it the `$form['amap1']` array for the details to output.

The answer to your question is - I don't know why you're trying to do this. But the label is already output inside a different twig file, and this form wrapper twig is the wrong place to try and add in field/form element labels. All you need to do to make them look consistent is do what you did for `amap1` \- use the `#title` in the form array to specify the label. This way all you need in your `membership-step3.html.twig` file is:

```
<form{{ attributes }}> {{ form.form_build_id }} {{ form.form_token }} {{ form.form_id }}
  <div>{{ form }}</div>
</form> <!-- Don't forget the closing tag -->

```

Tip: Switch on Twig Debug to see where the templates came from straight inside the html output.
> 0 votes

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


# Question
Title: Why can't you assert the response status in a FunctionalJavascript test?
If I do this in a FunctionalJavascript test:

```
    $assert_session->statusCodeEquals(200);

```

I get:

> Behat\Mink\Exception\UnsupportedDriverActionException: Status code is not available from Drupal\FunctionalJavascriptTests\DrupalSelenium2Driver

Why though?

# Answer
This has a little history behind it.

Mink is the library that build on top of phpunit for functional testing:

> One of the most important parts in the web is a browser. A browser is the window through which web users interact with web applications and other users. Users are always talking with web applications through browsers.
>
> So, in order to test that our web application behaves correctly, we need a way to simulate this interaction between the browser and the web application in our tests. We need Mink.

Mike supports several ways to simulate a browser, through drivers.

Normal functional tests use `BrowserTestBase`, which uses the Goutte driver.

Javascript tests used to use the PhantomJS driver, but that is an abandoned project now. This has been migrated to `WebDriverTestBase`, which uses the Selenium2 driver.

Selenium2 essentially does a remote control of a headless browser, through the WebDriver protocol. This allows you to run the same driver against multiple browsers (Chrome, Firefox, and I think Safari).

The problem is that Selenium2 gives you the advantage of a real browser, but has limitations. It is slow. The other is that there isn't full parity between the other drivers, and getting the response code is one of these limitations.

So, this is a Mink/Selenium2 problem and not a genral Drupal testing framework problem.
> 1 votes

---
Tags: testing
---


title: HTTPS with and without www

text:
# Question
Title: HTTPS with and without www
I have drupal 8 based website implemented.

global $base\_url; is used in two different modules.

* Module-1:

$content .= $base\_url .'/user/role/1';

it gives the URL pattern as: `https://www.example.com/user/role/1`
* Module-2:

$content .= $base\_url .'/services';

it gives the URL pattern as: `https://example.com/services`

Are there any settings or configs that need to be set up to get the same pattern when I call the $base\_url?

.htaccess file

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "/\.|^\.(?!well-known/)" - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Various header fixes.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
  # Disable Proxy header, since it's an attack vector.
  RequestHeader unset Proxy
</IfModule>

```

# Answer
> 0 votes
In the root directory of the Drupal project, open `.htaccess` file,

there are two commented groups that base on your preferences you can uncomment a group.

if you want always use `www`, uncomment the following

```
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

if you want always **do not use** `www`, uncomment the following

```
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

```

**do not forget to clear the drupal cache and your browser cache.**

**update** **this `.htacess`** is working for me

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock)|web\.config)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "/\.|^\.(?!well-known/)" - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  RewriteCond %{HTTP_HOST} .
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Various header fixes.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
  # Disable Proxy header, since it's an attack vector.
  RequestHeader unset Proxy
</IfModule>

```

---
Tags: .htaccess
---


title: Twig define dynamic generate variable

text:
# Question
Title: Twig define dynamic generate variable
I have field names:

* field\_en\_image
* field\_sv\_image

node\_lang is set as a variable in the .theme file under \_preprocess\_node hook.

I want to print the field dynamically in the twig template file based on the current language.

```
{{ node.["field_"~node_lang~"image"]|view }}

```

but this seems to be not working.

# Answer
> 1 votes
Try the following

```
{% set field_name = "field_"~node_lang~"image" %}
{{ attribute(node,field_name) | view }}

```

or

```
{% set field_name = "field_"~node_lang~"image" %}
{{ attribute(content,field_name) }}

```

> If you want to access a dynamic attribute of a variable, use the attribute function instead.
>
> The attribute function is also useful when the attribute contains special characters (like - that would be interpreted as the minus operator):
>
> ```
> {# equivalent to the non-working foo.data-foo #}
> {{ attribute(foo, 'data-foo') }}
>
> ```

# Answer
> 0 votes
You should be using the \_context variable instead, which represent the whole accessibles variables, you can find some informations about that variable under Macros documentation.

That snippet may help :

```
{% set language = 'fr' %}

{% set foobar = _context["field_" ~ language ~ "_foobar"] is defined ? _context["field_" ~ language ~ "_foobar"] : null %}

{{ foobar }}

```

I've wrote to you a little TwigFiddle, check it out :)

---
Tags: 8, theming
---