# Question
Title: How do I programmatically log in a user with a POST request?
Do anyone have a working REST Login on Drupal 8?

This is what I tried.

```
POST /user/login HTTP/1.1
Host: 8.d8.local
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: http://nikhilmohan.in
Cache-Control: no-cache

name=test&pass=password&form_id=user_login_form

```

It returns me **HTML** instead of **JSON**.

# Answer
Staring from 8.2, Drupal supports json endpoints for Cookie authentication. You don't need to post the form anymore

```
curl --header "Content-type: application/json" --request POST \
  --data '{"name":"admin", "pass":"admin"}' \
http://drupal.d8/user/login?_format=json

```

Output will look like

> `{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"wBr9ldleaUhmP4CgVh7PiyyxgNn_ig8GgAan9-Ul3Lg","logout_token":"tEulBvihW1SUkrnbCERWmK2jr1JEN_mRAQIdNNhhIDc"}`

Change record: https://www.drupal.org/node/2720655

Other authentication methods: https://www.drupal.org/docs/8/core/modules/rest/using-other-authentication-protocols
> 21 votes

# Answer
Here's how you can login via JavaScript for Drupal 8 REST:

**Drupal 8.2 and beyond**

* *POST*: `http://example.com/user/login?_format=json`
* *Content-type*: `application/json`
* *Data*: `{ "name": "admin", "pass": "myPassword" }`
* *Response*: `200 OK`

This will properly login via cookie authentication, and return a result similar to this:

```
{
  "current_user": {
    "uid":"1",
    "roles":["authenticated"],
    "name":"admin"
  },
  "csrf_token":"abc123",
  "logout_token":"def456"
}

```

I've created a contrib module called jDrupal that makes it very easy to login with JavaScript (among other things):

```
// Login and show the user their id.
jDrupal.userLogin('admin', 'myPassword').then(function() {
  alert(jDrupal.currentUser().id());
});

```

**Prior to Drupal 8.2**

* *POST*: `http://example.com/user/login`
* *Content-type*: `application/x-www-form-urlencoded`
* *Data*: `name=admin&pass=myPassword&form_id=user_login_form`
* *Response*: `200 OK | 303 See Other`

You'll send the data along in the URL as a query string. The result will be HTML, so it won't return anything useful to you, but it will properly login via cookie authentication.
> 15 votes

# Answer
1. A HTTP request is not RESTful based upon Content-Type.
2. "REST Login" is technically an oxymoron.

RESTful authentication means to send authentication with each request because it is stateless. The example provided by Drupal 8 core is the Basic Auth module, which allows to send authentication credentials for a HTTP request via Basic HTTP Authentication given a user with permission to access Content via GET.

## RESTful Example

Curl: `curl -vvv -k -H "Authorization: Basic test:password" http://8.d8.local/node/1?_format=json`

```
GET /node/1?_format=json HTTP/1.1
Host: 8.d8.local
User-Agent: curl/7.43.0
Accept: */*
Authorization: Basic test:password

```

However this is usually not good enough. The simple\_oauth and oauth contrib modules provide OAuth 2 and 1 support respectively., with which a HTTP request can be made with OAuth authentication tokens based on the OAuth work flows described in those modules.

But the real question seems to be

## How do I login via a Web Services API?

There is not a stable Drupal 8 module to do so, but the Services module provides methods for creating non-RESTful actions and targeted actions such as "login".

The following works after setting up an endpoint called "api":

Curl: `curl -vvv -k -H "Content-Type: application/json" -H "Accept: application/json" -d '{"username": "test", "password": "password"}' http://8.d8.local/api/user/login`

```
POST /api/user/login HTTP/1.1
Host: 8.d8.local
Accept: application/json
Content-Type: application/json
Content-Length: 44

{"username": "test", "password": "password"}

```

This returns JSON session id and name (also set in the response's Set-Cookie header).

and also you can login with Jquery ajax call with following snippet

```
$.ajax({
    url : "http://gttc.dd:8083/user/login",
    type : 'post',
    data : 'form_id=user_login_form&name=' + encodeURIComponent("username") + '&pass=' + encodeURIComponent("password"),
    dataType : 'json',
    error : function(data) {
            //error code
    },
    success : function(data) {
      console.log(data);
        //success code
    }
});

```
> 9 votes

# Answer
Drupal Core version: **8.x-4.x**

You need to enable the user login service first thing, this may be accomplished in so many ways, I prefer using REST UI module.

Go to **/admin/config/services/rest** and enable **User** Rest resource.

Once enabled it you can go to **/admin/config/services/rest/resource/entity%3Auser/edit** by clicking on **Edit** next to the **User** resource. Make sure to enable the **GET** method.

Now you have everything setup, you can start using the service by running this command in the terminal or by using any application for curl requests like: Postman and Restlet clients.

**NOTE**: CSRF Token can be obtained from: ***/rest/session/token***

```
curl -i -L -X POST \
  -H "Content-Type:application/json" \
  -H "Accept:application/json" \
  -H "X-CSRF-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
  -d \
     '{
       "name": "my_username",
       "pass": "my_password"
     }' \
'http://SITE-URL/user/login?_format=json'

```

**The return objects are as below:**

***SUCCESS***:

```
{
  "current_user": {
  "uid": "1",
    "roles": [
      "authenticated"
    ],
    "name": "Admin"
  },
  "csrf_token": "bbbbbbbbbbbbbbbbbbbbbbbbbb",
  "logout_token": "ccccccccccccccccccccccccc"
}

```

***FAILURE***:

```
{
  "message":"Sorry, unrecognized username or password."
}

```
> 4 votes

# Answer
I use custom RESTFul login on drupal 8 but not with cookie. It's for an mobile app and every time i need information, i use a simple Authenticate :

Since Drupal 8.2x we need 2 files in a module :

> rest.ressource.user.rest\_ressource.yml in config/install folder

```
langcode: en
status: true
dependencies:
  module:
    - basic_auth
id: user.rest_ressource
plugin_id: 'user_rest_ressource'
granularity: resource
configuration:
  methods:
    - GET
    - PATCH
  formats:
    - json
  authentication:
    - basic_auth

```

You can add more method like DELETE / POST

Then we need the file

> userRestRessource.php in src/Plugin/rest/resource

```
    <?php

    namespace Drupal\yourmodule\Plugin\rest\resource;

    use Drupal\Core\Session\AccountProxyInterface;
    use Drupal\rest\Plugin\ResourceBase;
    use Drupal\rest\ResourceResponse;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    use Psr\Log\LoggerInterface;

    /**
     * Provides a resource to get view modes by entity and bundle.
     *
     * @RestResource(
     *   id = "user_rest_ressource",
     *   label = @Translation("User Rest"),
     *   uri_paths = {
     *     "canonical" = "/api/user/getInfo"
     *   }
     * )
     */
    class UserRestRessource extends ResourceBase {

      /**
       * A current user instance.
       *
       * @var \Drupal\Core\Session\AccountProxyInterface
       */
      protected $currentUser;

      /**
       * Constructs a Drupal\rest\Plugin\ResourceBase object.
       *
       * @param array $configuration
       *   A configuration array containing information about the plugin instance.
       * @param string $plugin_id
       *   The plugin_id for the plugin instance.
       * @param mixed $plugin_definition
       *   The plugin implementation definition.
       * @param array $serializer_formats
       *   The available serialization formats.
       * @param \Psr\Log\LoggerInterface $logger
       *   A logger instance.
       * @param \Drupal\Core\Session\AccountProxyInterface $current_user
       *   A current user instance.
       */
      public function __construct(
        array $configuration,
        $plugin_id,
        $plugin_definition,
        array $serializer_formats,
        LoggerInterface $logger,
        AccountProxyInterface $current_user) {
        parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

        $this->currentUser = $current_user;

      }

      /**
       * {@inheritdoc}
       */
      public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static(
          $configuration,
          $plugin_id,
          $plugin_definition,
          $container->getParameter('serializer.formats'),
          $container->get('logger.factory')->get('yourmodulename'),
          $container->get('current_user')
        );
      }

      /**
       * Responds to GET requests.
       *
       * Returns a list of bundles for specified entity.
       *
       * @throws \Symfony\Component\HttpKernel\Exception\HttpException
       *   Throws exception expected.
       */
      public function get() {

          $uid=$this->currentUser->getAccount()->id();
          $role=$this->currentUser->getAccount()->getRoles(1);

//here you can add your custom code
 $responseResource=new ResourceResponse(
          array()

      );
        return $responseResource;
      }

        /**
         * Responds to PATCH requests.
         *
         * Returns a list of bundles for specified entity.
         *
         * @throws \Symfony\Component\HttpKernel\Exception\HttpException
         *   Throws exception expected.
         */
        public function patch(){

        }

    }

```

Don't forget to go to user right for accept method GET / POST or anything you have add in your config.

With that you can create every custom REST file for every custom entity.

And in my js : Dont forget to call

> yoursiteUrl/rest/session/token

for get token

```
$http({
            method: 'GET',
            url: 'siteUrl/api/user/getInfo?_format=json',
                          withCredentials:true,
                          headers: {
                                   'Content-Type': "application/hal+json",
                                   'X-CSRF-Token': token,
                                   'Authorization': 'Basic ' + btoa(user+':'+password),

                         },

                        }).then(function successCallback(response) {

                             return response;

                          }, function errorCallback(response) {
                              return false;

                          });

```
> 3 votes

# Answer
Following the answer of @tyler.frankenstein, if you wish to implement a login form with Ajax, you can for example use jQuery.

## 1. Get a CSRF token

We need to make a POST request to the `user/login` endpoint of the Drupal 8 API. This endpoint (considered as a "non-safe method") requires that you send a CSRF token.

The first step is to get this token by sending an AJAX request to the `rest/session/token` endpoint:

```
var getCsrfToken = function(callback) {
    $.get(Drupal.url('rest/session/token'))
        .done(function (data) {
            var csrfToken = data;
            callback(csrfToken);
        });
}

```

N.B.:

* The `callback` parameter is a callback function that will be called when the CSRF token will be fetched
* We use the `Drupal.url` function to get the base URL of the site

This token should be send with a `X-CSRF-Token` header.

## 2. Login

Consider the following HTML:

```
<form id="login" method="post" action="" accept-charset="UTF-8">
    <div class="input-field">
        <input id="edit-name" name="name" type="text" class="validate">
        <label for="edit-name">Username or email address</label>
    </div>
    <div class="input-field">
        <input id="edit-pass" name="pass" type="password" class="validate">
        <label for="edit-pass">Password</label>
    </div>
    <p><a href="{{ url('user.pass') }}">Forgot your password?</a></p>
    <button type="submit" class="btn btn-default btn-submit">Sign in</button>
</form>

```

... and the corresponding jQuery code:

```
$('form#login').on('submit', function(e) {
    e.preventDefault();

    var inputUsername = $('#edit-name').val();
    var inputPassword = $('#edit-pass').val();

    if (inputUsername != '' && inputPassword != '') {
        getCsrfToken(function(csrfToken) {
            $.ajax({
                url: Drupal.url('user/login?_format=json'),
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify({name: inputUsername, pass: inputPassword}),
                headers: {
                    'X-CSRF-Token': csrfToken
                },
            }).done(function(response) {
                if (response.current_user) {
                    console.log('The user is logged!');
                }
            }).fail(function(jqXHR, textStatus) {
                ...
            });
        });
    }
});

```

This code has been successfully tested with Drupal 8.3.

I hope this will help you!
> 2 votes

# Answer
Yeah sure, I made a blog about how to test it with postman, and also another one about how to configure your drupal site.

In this project I made a login for Drupal with angular, using the Simple OAuth module for the token.
> 0 votes

---
Tags: 8
---


title: How can I override strings?

text:
# Question
Title: How can I override strings?
I'm trying to change a label of Drupal 8's contact form ('Your email address'). The label is defined /core/modules/contact/src/MessageForm.php, but obviously I don't want to change this in core.

```
$form['mail'] = array(
'#type' => 'email',
'#title' => $this->t('Your email address'),
'#required' => TRUE,
);

```

In Drupal 7 I always used string overrides but the module isn't available for Drupal 8 yet. How can string be overridden in Drupal 8?

# Answer
> 5 votes
The easiest method would be to implement a hook\_form\_alter inside a custom module that overrides the title

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook\_form\_alter/8.2.x

Some information how to create custom module.

https://www.drupal.org/docs/8/creating-custom-modules

# Answer
> 6 votes
You can always override strings in `settings.php` like this:

```
$settings['locale_custom_strings_en'][''] = array(
  'Related entities for @group' => 'Add Content to group @group',
);

```

You can change `en` to `de` or whatever two letter language code you like.

Please note: the entire string must exist by itself. For example, the above string override existed in the group module controller like this:

```
return $this->t('Related entities for @group', ['@group' => $group->label()]);

```

This will NOT work:

```
$settings['locale_custom_strings_en'][''] = array(
  'Related entities for ' => 'Add Content to ',
);

```

So for the example listed in the question, you could use:

```
$settings['locale_custom_strings_en'][''] = array(
  'Your email address' => 'Your email ID',
);

```

---
Tags: 8
---


title: Drush PHP syntax error when running

text:
# Question
Title: Drush PHP syntax error when running
I am following the instructions to install Drush that are listed on this page: https://github.com/drush-ops/drush/blob/master/docs/install.md

I seem to be getting a syntax error within the code:

```
[user@localhost ~]$ wget https://github.com/drush-ops/drush/releases/download/8.0.0-rc4/drush.phar
--2015-11-16 16:23:02--  https://github.com/drush-ops/drush/releases/download/8.0.0-rc4/drush.phar
Resolving github.com (github.com)... 192.30.252.131
Connecting to github.com (github.com)|192.30.252.131|:443... connected.
HTTP request sent, awaiting response... 302 Found
2015-11-16 16:23:05 (1.47 MB/s) - drush.phar saved [3496991/3496991]

[user@localhost ~]$ php drush.phar core-status

Parse error: syntax error, unexpected '[' in phar:///home/user/drush.phar/includes/output.inc on line 188

```

I am not seeing this error on Google. Any idea how to fix it?

# Answer
> 17 votes
You're using Drush 8, which requires a minimum PHP version of 5.4.5 (http://docs.drush.org/en/master/install/).

Your current version (5.3) doesn't understand short array syntax, hence the error you're seeing.

To fix, either upgrade PHP, or switch to an older branch of Drush.

# Answer
> 0 votes
If your system has more than one php versions installed you can define an alias in your *.bashrc* or *.bash\_profile* or */etc/profile.d/global\_aliases.sh* (or any part of your system that you can define an alias). The alias would run drush with appropriate php version.

For example in a plesk system you can probably do something like this

```
alias drush='/opt/plesk/php/5.6/bin/php /usr/local/drush'

```

---
Tags: drush
---


# Question
Title: status report asks me to run update.php but getting 'no pending updates'
I'm on core version 7.58.

My status report says "Some modules have database schema updates to install. You should run the database update script immediately."

But when I run update.php (or drush updb) I get 'no pending updates'.

I'm not experiencing any problems with the site (except for a small bootstrap-issue that doesn't seem related) and the log doesn't display any errors or warnings.

What can cause this?

# Answer
@AjayReddy's answer was very close. I found this thread on Drupal.org and by following hermes\_costell's comment I resolved my issue. It turned out to be the taxonomy module.

Here's the steps I followed (I'm quoting the Drupal.org thread):

in /modules/system/system.install (not in sites/all/... but instead up at the root level) - should be around line 420 change

```
$requirements['update']['description'] = $t('Some modules have database schema updates to install. You should run the <a href="@update">database update script</a> immediately.', array('@update' => base_path() . 'update.php'));

```

to

```
$requirements['update']['description'] = $t('The @which_module module (and possibly others) has database schema updates to install. You should run the <a href="@update">database update script</a> immediately.', array('@which_module' => $module, '@update' => base_path() . 'update.php'));

```

And now on the admin/reports/status page you'll see the exact name of the module.

Now that you have found the name of the offending module you need to go into the module's .install file and do a bit of detective work to try and figure out which schema\_version value should actually be set in there, by essentially starting at the bottom of the module and going through the various MODULE\_NAME\_update\_XXXX functions one by one, asking yourself if the database changes stated in that function HAVE or HAVEN'T been applied to the database yet. You want to start with the highest XXXX value (which should be the lowest in the .install file if they followed standard coding practice) and step lower one-by-one until you hit the function which HAS apparently successfully happened.

For instance let's say you are encountering this issue with the 'cheese' module (which I hope to see soon in Drupal btw), so you go into cheese.install and take a look.

function cheese\_update\_7005 changes the cheese\_sauce.how\_much\_sauce field and turns it into a blob. Looking at the database directly you see that in the cheese sauce table, the how\_much\_sauce field is of type 'int' - so you know cheese\_update\_7005 hasn't successfully done its job yet.

Then in cheese\_update\_7004 you see that cheese\_sauce.how\_much\_sauce is changed from being type 'varchar' into type 'int' - so you deduce that this function has indeed successfully done its job, but as mentioned, 7005 hasn't yet.

Next, you force Drupal to realize it's completed the 7004 step (and is therefore ready to do step 7005 on the next run of update.php) by running the SQL statement on your database: UPDATE system SET schema\_version = 7004 WHERE name = 'cheese';
> 1 votes

# Answer
Go to systam.module and check for `if (max($updates) > $default) {` line after this add `dpm($module)` you will get to know which module prevents this database update and fix that module accordingly. The code will look like below:

```
if (max($updates) > $default) {
   dpm($module);
   $requirements['update']['severity'] = REQUIREMENT_ERROR;
   $requirements['update']['value'] = $t('Out of date');
   $requirements['update']['description'] = $t('Some modules have database schema updates to install. You should run the <a href="@update">database update script</a> immediately.', array('@update' => base_path() . 'update.php'));
   break;
}

```
> 1 votes

---
Tags: 7, updating
---


# Question
Title: Background images using Breakpoints and Picture
I want to serve my background images by breakpoints. I can't seem to find an out of the box way to do this using the Breakpoints and Picture modules, which I'm using for some node images.

Has anyone implemented this using Picture/Breakpoints?

# Answer
> 0 votes
My solution was to use Group Background Image with the patch that you can get here. This allows background images, through the integration of the Picture and Breakpoints modules. The configuration is super easy, and you can change existing div field groups into background images in a split second.

---
Tags: 7, media
---


# Question
Title: Commerce message notify sending duplicate emails
I have created a custom commerce order status called 'Sent'.

When an existing order is updated from 'Invoiced' to 'Sent' I have a custom message type ('Order sent') and, using Rules, a custom rule which creates a message entity and sends the 'Order sent' message.

The rule is as follows:

```
{ "commerce_message_commerce_order_message_order_sent_e_mail" : {
    "LABEL" : "Commerce order message: order sent e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "3",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "message_notify", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:status" ], "value" : "sent" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commerce_order_order_sent",
            "param_user" : [ "commerce-order:owner" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-ds-message-commerce-order" ],
          "value" : [ "commerce-order" ]
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "message_notify_process" : {
          "message" : [ "entity-created" ],
          "save_on_fail" : "0",
          "save_on_success" : "0"
        }
      }
    ]
  }
}

```

At the moment, I am receiving 3 duplicate emails and can't work out why?

# Answer
It's obvious that the update event you're using in your custom rule gets triggered twice, which explains why you get those duplicate mails. I've seen similar issues in the past with other entities being updated (using similar events), for entities such as *users* or *nodes*.

If you cannot find the root cause for the duplicate trigger, and cannot use any other Rules Event as an alternative, then the typical solution is to use the Flag module like so:

* Define a non-global flag to flag orders.
* Add a Rules Action to your custom rule to also flag the order (for which you want to send such eMails).
* Add an extra Rules Condition to check that the order is NOT (repeat: NOT!) yet flagged.

With the above tuning of your existing rule in place, the *first* time your rule is triggered the Rules Actions do get performed (= send the eMail and flag the order) and the *second* time the extra Rules Condition will prevent the Rules Actions to be performed (= no more duplicate eMail).

*Easy, no?* ... And it works for *any* entity ...
> 2 votes

---
Tags: commerce, rules, message-subscribe
---


# Question
Title: How to test the existence of a file in a webform email twig template
I have a webform with a Document File field. In my twig email template, I want to test if that field is empty. For text area fields for example, this syntax works :

`{% if webform_token('[webform_submission:values:question_text_area:value]', webform_submission) %}

 Questions

 {{ webform_token('[webform_submission:values:question_text_area:value]', webform_submission) }}

 {% endif %}`

But for a Document File field, the same syntax does not work, meaning that if no file is uploaded, that part of my template is still printed.

I tried

`{% if webform_token('[webform_submission:values:join_a_file:value]', webform_submission) %}`

or

`{% if webform_token('[webform_submission:values:join_a_file:value]', webform_submission) is not null %}`

or

`{% if webform_token('[webform_submission:values:join_a_file]', webform_submission) is not null %}`

and none of them work.

Does anybody know the proper syntax for what I'm trying to do? Thanks!

# Answer
The solution is to do this

`{% if webform_token('[webform_submission:values:file:clear]', webform_submission) %}
 FILE UPLOADED
{% else %}
 NO FILE UPLOADED
{% endif %}`

Solution given first here : https://www.drupal.org/project/webform/issues/2969437
> 2 votes

---
Tags: 8, webforms
---


# Question
Title: How to redirect to a specifi page of a view?
Here is the code of a custom form:

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

some code here...

    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this->t('Le service « %label » a été ajouté.', [
          '%label' => $entity->label(),
        ]));
        break;

      default:
        drupal_set_message($this->t('Le service « %label » a été modifié.', [
          '%label' => $entity->label(),
        ]));
    }

    $form_state->setRedirect('view.services.page_2');
  }

```

The redirection doesn't work!
After validating my form, it goes to the first page of my view.
By the way, these two pages of the view are displayed as two tabs in a menu (the first being the default one)...

# Answer
> 0 votes
The solution has two parts:
1. The button that takes to my form in 'Add' mode was coded this way: `<a href="/sel/service/add?destination=services" class="form-submit">Ajouter</a>` (/services being the first tab I mentioned).
So I removed the `?destination=services`
2. Looking at the 'Routes info' provided by Devel, I got that:
So i changed my code to `$form_state->setRedirect('view.services.page_2', ['arg_0' => $iSeliste]);` (thanks to the last comment of this page)

And now it works!

---
Tags: 8, forms, routes
---


title: Template Suggestion 403 pages

text:
# Question
Title: Template Suggestion 403 pages
The following implementation adds a template suggestion for page, in this case if you create a page--404.html.twig file in your theme, you'll be able to customize the page and works with Drupal 8.5.3

**MYTHEME.theme:**

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(&$suggestions, $variables, $hook) {
  /**
   * 404 template suggestion.
   */
  if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
    $status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
    switch ($status_code) {
      case 404: {
        $suggestions[] = 'page__' . (string) $status_code;
        break;
      }
      default:
        break;
    }
  }
}

```

(code published by Israel Morales)

Can someone, please, adapt this code to the 403 Pages?

# Answer
The Following code can be applied to MYTHEME.theme and adds a different template suggestion for page (401/403/404). See credit to RuslanP (comment #22)

```
/**
 * Implements hook_theme_suggestions_page_alter() to set 40x template suggestions.
 *
 * @param array $suggestions
 * @param array $variables
 */
function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page');
  $http_error_suggestions = [
    'system.401' => 'page__401',
    'system.403' => 'page__403',
    'system.404' => 'page__404',
  ];

  $route_name = \Drupal::routeMatch()->getRouteName();
  if (isset($http_error_suggestions[$route_name])) {
    $suggestions[] = $http_error_suggestions[$route_name];
  }
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Field value not updating when posting data via JSON
Here I am getting 200 response but the date field over here is not getting updated.

The node is getting created and other fields are getting updated, only this date field is not getting created.

the error which iam getting  The Json and content type format is below:

```
"field_date_of_cage_card_creation": {
        "und": [
            {
                 "date":"17 Dec 2018",
                  "time":"02:45 pm",

                "timezone": "Asia/Kolkata",
                "timezone_db": "Asia/Kolkata",
                "date_type": "datetime"

            }
        ]
    },

```

# Answer
You should be adding your date in the value property and not including a time.

```
"field_date_of_cage_card_creation": {
    "und": [
        {
            "value":"17 Dec 2018",
            // or maybe
            "value":"2018-12-17",
            "timezone": "Asia/Kolkata",
            "timezone_db": "Asia/Kolkata",
            "date_type": "datetime"
        }
    ]
},

```
> 0 votes

---
Tags: services
---


# Question
Title: How to add a redirection at the end of Delete entity process?
I used Drupal Console to create a custom content entity called 'Service' (with command `drupal geco`) which generated all expected code including 'ServiceDeleteForm.php':

```
<?php
namespace Drupal\sel\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
/**
 * Provides a form for deleting Service category entities.
 *
 * @ingroup sel
 */
class ServiceDeleteForm extends ContentEntityDeleteForm {
}

```

I added some code of mine there:

```
class ServiceDeleteForm extends ContentEntityDeleteForm {

  protected function getDeletionMessage() {
    $entity = $this->getEntity();
    drupal_set_message($this->t('Le service « %label » a été supprimé.', [
      '%label' => $entity->label(),
    ]));
  }

  public function getQuestion() {
    return $this->t('Êtes-vous certain de vouloir supprimer le service « %label » ?', [
      '%label' => $this->getEntity()->label(),
    ]);
  }

}

```

which works fine.
I'd like to add a redirection at the end of the Delete process, something like `$form_state->setRedirect('elsewhere', [some argument]);` but I don't know how to do it.
Could someone help? Thanks in advance.

# Answer
> 1 votes
Finally, this code works:

```
<?php
namespace Drupal\sel\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a form for deleting Service entities.
 *
 * @ingroup sel
 */

class ServiceDeleteForm extends ContentEntityDeleteForm {

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $entity = $this->getEntity();

    $entity->delete();
    $form_state->setRedirect('elsewhere', [some argument]);
    drupal_set_message($this->getDeletionMessage());

  }

  protected function getDeletionMessage() { some code }

  public function getQuestion() { some code }

}

```

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


# Question
Title: How to display a node field value in a template file?
I added a custom field in the ‘article‘ content type.
I am using bootstrap as a theme.
I want to print that field value as a css class in the h1 element of every node of type : article

So I duplicated the page.tpl.php in my subtheme template folder and changed the h1 code from :

```
<h1 class="page-header"><?php print $title; ?></h1>

```

to

```
<h1 class="page-header <?php print $node->field_custom_field['und'][0]['value']; ?>"><?php print $title; ?></h1>

```

The problem is that sometimes sometimes I get this error message

```
    Notice: Undefined property: stdClass::$field_custom_field in include()
(line 157 of /home/frost/sites/all/themes/subtheme/templates/page.tpl.php).

```

I have basic php knowledge, so my guess is I need to add a condition saying that the custom field is only printed if the template file is called when an article content type node is being viewed.

How can I add this condition in the template file ?

Thank you

# Answer
Duplicate `node.tpl.php` and rename it `node--article.tpl.php` and then it's just:

```
print render($content['field_custom_field']);

```

If you really want to stay on the page level you better use `page--node--article.php` and then you need to get hold of the `$node` object first somehow. Maybe take a look at Clive's answer here: https://drupal.stackexchange.com/a/32310/15055
> 1 votes

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


# Question
Title: How to sign emails to setup DKIM and DMARC
After setting up my Drupal 8 site in the server, I noticed that none of the emails go to the inbox in Gmail and it all gets stored in Spam. Upon further investigation I found that this is because the emails are being sent via the PHP Mailer and its not being signed and authenticated.

I'm not that familiar with Drupal programming, therefore any suggestions and instructions on how I can get this configured via code/modules etc would be greatly appreciated.

# Answer
> 3 votes
Please check out the following two modules to have your Drupal mails send by a mailserver. Apart from that it may already be sufficient to just set a SPF record for your domain as DKIM and DMARC has actually nothing to do with Drupal.

---

### PHPMailer

https://www.drupal.org/project/phpmailer

> Adds SMTP support for sending e-mails using the PHPMailer library. Comes with detailed configuration instructions for how to use Google Mail as mail server.

### SMTP Authentication Support

https://www.drupal.org/project/smtp

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

---

### How To use an SPF Record to Prevent Spoofing & Improve E-mail Reliability

https://www.digitalocean.com/community/tutorials/how-to-use-an-spf-record-to-prevent-spoofing-improve-e-mail-reliability

> A carefully tailored SPF record will reduce the likelihood of your domain name getting fraudulently spoofed and keep your messages from getting flagged as spam before they reach your recipients.

---
Tags: emails, advertising
---


# Question
Title: Submit button not rendering on a dynamic form with tables
I want to display a dynamic with table field when I click add button, it should add new line of form, also i can't display the add button So how can I resolve this mistakes ?

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

  $this->connection = Database::getConnection();
  $connection = Database::getConnection();
  $req = "SELECT id, name FROM details_types_sejours_field_data;";
  $reponse = $connection->query($req);
  $results = $reponse->fetchAll();
  $this->liste += [
    '0' => t('Choose'),
  ];
  foreach ($results as $result){
    $this->liste += [
      $result->id => $result->name,
    ];
  }
  $header = array();
  $header['journee'] = $this->t('Stays days');
  $header['matin'] = $this->t('Morning');
  $header['soir'] = $this->t('Evening');
  $header['observations'] = $this->t('Comments');

  $config = $this->config('monmodule.homepage');
  $pomoted_items = $config->get('promoted', []);
  $number_promoted = $form_state->getValue('number_promoted', count($pomoted_items));
  $removed = $form_state->getValue('removed_promoted', []);

  $form['number_promoted'] = [
    '#type' => 'value',
    '#value' => $number_promoted,
  ];
  $form['removed'] = [
    '#type' => 'value',
    '#value' => $removed,
  ];
  $form['promoted'] = array(
    '#type' => 'table',
    '#header' => $header,
    '#title' => t("Days number"),
    //'#size' => '14',
    '#tree' => TRUE,
  );
  for ($i = 1; $i <= $number_promoted; $i++) {
    $item = array_shift($pomoted_items);
    if (in_array($i, $removed)) {
      continue;
    }
    $form['promoted'][$i] = [
      '#type' => 'table',
      //'#header' => $header,
      '#title' => t("Day number #@i", ['@i' => $i]),
    ];

    $form['promoted'][$i] = [
      'journee' => array(
        '#type' => 'date',
        '#title' => $this->t('Stays'),
        '#default_value' => $item['title'],
      ),
      // Matin

      'matin' => array(
         array(
          '#type' => 'datetime',
          '#title' => $this->t("Start hour"),
          '#default_value' => $item['title'],
        ),
        array(
          '#type' => 'datetime',
          '#title' => $this->t("End hour"),
          '#default_value' => $item['title'],
        ),
        array(
          '#type' => 'select',
          '#default_value' => 'Choose',
          '#options' => $this->liste,
          '#title' => $this->t('Requested service:'),
        )
      ),

      'soir'=>array(
        array(
          '#type' => 'datetime',
          '#title' => $this->t("Start hour"),
          '#default_value' => $item['title'],
        ),
        array(
          '#type' => 'datetime',
          '#title' => $this->t("End hour"),
          '#default_value' => $item['title'],
        ),
        array(
          '#type' => 'select',
          '#default_value' => 'Choose',
          '#options' => $this->liste,
          '#title' => $this->t('Requested service:'),
        )
      ),

      'observations' => array(
        '#type' => 'textarea',
        '#title' => $this->t('Comments:'),
        '#cols' => '20',
        '#rows' => '5',
      ),
    ];

    /*
    // Observations
    $form['promoted'][$i]['observations'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Comments'),
      '#rows' => 5,
      '#cols' => 20,
      '#resizable' => TRUE,
    ];
    */

    $form['promoted']['remove_' . $i][$i] = [
      '#type' => 'submit',
      '#value' => t("Supprimer l'élément #@i", ['@i' => $i]),
      '#submit' => ['::removeItem'],
      '#attributes' => [
        'class' => ['button--danger'],
        'data-toRemove' => $i,
      ]
    ];
  }

  $form['promoted']['add_item'] = [
    '#type' => 'submit',
    '#value' => t('Ajouter un autre élément'),
    '#submit' => ['::addPromotedItem'],
  ];

  return $form;
}

public function addPromotedItem(array &$form, FormStateInterface $form_state) {
  $form_state->setValue('number_promoted', $form_state->getValue('number_promoted') + 1);
  $form_state->setRebuild();
}

public function removeItem(array &$form, FormStateInterface $form_state) {
  $removed = $form_state->getValue('removed_promoted', []);
  $removed[] = $form_state->getTriggeringElement()['#attributes']['data-toRemove'];
  $form_state->setValue('removed_promoted', $removed);
  $form_state->setRebuild();
}

```

# Answer
> 0 votes
I guess you are following the Example module's `AjaxAddMore.php` example (click: View source).

I also guess Form API is a little bit picky when it comes to element nesting. So please simply try to put the submit in the `$form['actions']` container as in the example or alternatively put it just on the top level.

```
$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
];

```

---
Tags: 8, forms
---


# Question
Title: Is there a way to display SCALD image and have it link to outside website: Drupal 7
I have created a content type that uses a SCALD atom image field. When that content type is displayed on my site, I want the image to link to an outside website if it is clicked upon. I don't want to use a view to make this action happen.

I can easily add a URL field to my SCALD Image atom, but I don't know how to make this link work when the image is clicked on ONLY in the full node view.

Could someone suggest a solution?

# Answer
> 0 votes
I gave the module Image Link Formatter a try, but I could not get it to work and I filed this bug report: https://www.drupal.org/project/image\_link\_formatter/issues/2970937

Instead I used the Linked Field module:https://www.drupal.org/project/linked\_field plus Token: https://www.drupal.org/project/token.

To make this work, I have a content type that uses a SCALD Atom for the image field and I have a separate field to add a URL. Under the **Manage Display tab** for your content type, go to the **Link to Content** section (click on the gear wheel) and opt to **Link this Field**. You will be presented with a **Destination** field.

You'll need to browse the available tokens to find the destination field that pertains to your content type. Make sure to use the one with dashes instead of underscores and in the case of a URL, you'll need to append the token with **:url**. Mine looked like this:

\[node:field-default-content-link-url:**url**\]

If the field on my content type is populated, it links to the website. If it is empty, the image is not formatted as a link.

---
Tags: scald
---


# Question
Title: How to implement click event on dynamically generating <li>?
I have a drop down select box. Through jquery on run time that drop then hides and the new drop down made which made from `<ul>` and `<li>` tags.

Now through firebug I notice that when the drop down is closed then there is one `<li>` and when I expand the drop down then in the firebug more `<li>` displayed.

So I want to implement the click event on these `<li>`. I tried this code.

```
 $(document).ready(function() {
  alert('a');
  $('.fb li').each(function() {
      alert('li');
    $(this).click(function(event) {
           alert('hed');
        var fbpage = $(this).attr("rel");
        if(fbpage != 0) {
            window.open(''+fbpage+'', '_blank');
        }

    });
    });
    });

```

the alert('a') and alert('li') works but then that click event is not working.

Any idea about this? and if you does not understand my question then ask me I will explain it more.

# Answer
> 3 votes
Since you are running D6, you should look into the `live()` jQuery handler ( http://api.jquery.com/live/ ) that can be used to attach these click handlers to your dynamic elements.

More information on this can be found by googling or otherwise searching for

`jquery click event on dynamically generated elements`

You might also want to look into the Drupal.behaviors method of including jQuery and javascript instead of the $(document).ready() approach you've used.

# Answer
> 1 votes
When you code is being executed the extra `<li>` elements you want to capture dont exist on the page, only the one `<li>` element. Therefore nothing can bind to them (makes sense).

The generation of the extra `<li>` elements; is that some code you have written? If it is just add your click event to the script that adds them in. As they now exist on the page you can bind functions to them.

Otherwise if the extra list items are not created by you and are being added by some module that you cant manipulate Jimajamma's answer is the way to go for binding events to dynamicly introduced elements. http://api.jquery.com/live/

# Answer
> 1 votes
Jquery event will not be applicable for dynamic HTML elements. ie, while we load page, your DOM should contain an element for which you are going to do any action like click or some thing.

For dynamically creating element we should use jquery live()

Example code :

```
    $(".fb li").live("click",function(){
   var fbpage = $(this).attr("rel");
        if(fbpage != 0) {
            window.open(''+fbpage+'', '_blank');
        }
});

```

Try below link for more details

jQuery live method example/Demo

# Answer
> 1 votes
I recommend this article. It works very well.

http://makitweb.com/attach-event-to-dynamically-created-elements-with-jquery/#comment-941

---
Tags: 6
---


# Question
Title: Access image/file with REST and Basic Authentication
I'm trying to access images/files in Drupal 8 through REST. They are only accessible for authorized users. I'm able to get the URL to the files, but when I try to load them using Basic Authentication, I get a 403 error.

Using cookies, I'm able to access the files after login, but I'd prefer to use Basic Authentication.

Is there any way to accomplish this?

Thanks.

# Answer
> 1 votes
In my view, Basic Authentication will work only for giving username and password whereas cookie will use the authenticated user cookie set in browser and display results.

If you want to use basic authentication and get file information just see below code:

```
$username = 'SITE USERNAME';
$password = 'SITE PASSWORD';
$url = 'SITE URL';
$response = \Drupal::httpClient()->get($url . "/entity/file/FILE ID?_format=json", [
  'auth' => [$username, $password],
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);
$json_string = (string) $response->getBody();

```

---
Tags: files
---


# Question
Title: How to move files already uploaded to a new subfolder?
I've got a bunch of files in sites/default/files that I'd like to move to a sites/default/files/subfolder to avoid a big mess.

The fields uploading files have been configured to put them in the right folders in the future. What I'm looking for is a solution to organising files already uploaded.

Any suggestions?

# Answer
The module **File (Field) Paths** allows this per file field.

For Drupal 8:

1. `Manage fields`: `Edit` the File field
2. Check the option "Enable File (Field) Paths?"
3. Expand "File (Field) Path settings"
4. Check the option "**Retroactive update**"
5. `Save settings`

Now all of this field’s files will be moved/renamed (you should see a progress bar). This is a one-time action, so if you need to move the files again, you have to repeat these steps.

If you always want to move the files when the path changes, you can check the "**Active updating**" option.
> 2 votes

# Answer
It sounds like you're looking for File Maintenance.

> Ever wanted to move files from your sites/default/files directory (or whatever you have configured) to a (new) subdirectory? Never did it because you knew it's a damn mess since you need do move the physical file, adjust the database files table and look through all the node\_revisions table and other content to adjust the link to the file so as not to break your site?

That should cover any files that are managed under the files table (pretty much any field you should have). If you have any other files under sites/default/files ***that aren't managed by Drupal***, then custom redirect htaccess rules should cover those files.
> 4 votes

# Answer
I found the best solution to be the Organize Files module
> 1 votes

# Answer
1. In `files` table change the `uri` column value from sites/default/files to sites/default/files subfolder.
2. Now move all the files from sites/default/files to sites/default/files subfolder.
> 0 votes

---
Tags: files
---


# Question
Title: How to show kint debug info from a module on a page?
In D8 I would like to display an array in the message part of a page. I did several things but could not get it work. What to do?

I installed the devel and kint modules.

I currently have changed in services.yml the settings into:

```
debug: true
auto_reload: true
cache: false

```

In the twig template I added

```
{{kint("I'm working from the page.html.twig")}}

```

This is displayed in the browser, so the current theme is displaying it which proves kint is working and the correct theme is used.

So now In my module file I have

```
$data_array = json_decode($data,true);
kint($data_array);
var_dump($data_array);
return $data_array;

```

The var\_dump gives a lot of data in a array. However the kint is not displayed.

How to get the kint displayed this array?

# Answer
Try to take a look at this site it has a lot if useful information, print variables using kint.

They say that if you want to output in the message area then you shall use, `ksm()`.
> 4 votes

# Answer
The solution is to run once before and to do the call different:

```
 kint_require();

```

so below code is running good

```
$data_array = json_decode($data,true);
    kint_require();
    \kint::dump($data_array);
return $data_array;

```
> 0 votes

---
Tags: 8, debugging
---


# Question
Title: How to redirect custom login & register url to node?
I have changed below url's to Login & registration instead of default

So URL will be

```
http://www.domain.com/en/login-user
http://www.domain.com/en/register-user

```

I have multiple language so added language prefix.

I would like to redirect it to node via `.htaccess`

I tried

```
RewriteRule ^/login-user http://www.domain.com/en/test

```

But not working

# Answer
Works fine :)

```
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  RewriteRule /login-user /test [L,R=307]
  RewriteRule /register-user /test [L,R=307]

```
> 0 votes

---
Tags: 8, .htaccess
---


# Question
Title: How to generate an unique serial ID based on a select value
I am Drupal beginner. I have created one webform with some fields (name, college, branch, address, email, contact number etc.). And when this form gets submitted I need to generate a unique registration number based on the selected college code and a serial number).

I also installed Webform Rules module but I don't understand how to achieve that.

Can anyone please help me to generate unique serial ID based on a field value during the Webform submission?

# Answer
You can use webform hooks for add your custom code before sending the data or saving it into the database. Create hidden field in webform and set the value of the same using hook\_webform\_submission\_presave For Ex.

```
function yourmodule_webform_submission_presave($node, &$submission) {
  // Update some component's value before it is saved.
  $component_id = 4; // where 4 is your hidden component id
  // Add your logic for registration code
  $submission->data[$component_id][0] = 'registration_code_you_wish_to_set';
}

```

Or If you want unique registration number check this module http://drupal.org/project/regcode

Hope this helps.
> 1 votes

# Answer
Every webform submission already has a unique submission id (SID). It is available via tokens. You can include it in your webform email notifications or use it in webform rules (on webform submit).
> 0 votes

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


title: Drupal cant find search_api namespace

text:
# Question
Title: Drupal cant find search_api namespace
I know i need to use the following imports for a custom module i copied from another Drupal installation.

```
use Drupal\search_api\Entity\Index;
use Drupal\search_api\Query\Query;
use Drupal\search_api\Query\QueryInterface;

```

But phpstorm tells me Entity and Query can't be found, so i assume its the `Drupal/search_api` it doesn't find. How can i import them anyway?

# Answer
So it turns out the search\_api is a different module than i thought. Just install it with composer like this:

```
composer require drupal/search_api

```
> 0 votes

---
Tags: 8
---


# Question
Title: Drupal 8 Webform : Regular expression in conditions to check specific day of the week
I am setting another webform on Drupal 8. I want to enable some fields based on the day of the week selected. I used JS on a site with Drupal 7, it is working fine, thanks to JSDrupal.

I would like to implement it on the Drupal 8 site with a regexp. I am using the HTML5 date field, not the Jquery datepicker. My concern is the same than before :

if the Day selected on field DATE\_D( a Date field) is Tuesday OR Thursday then hide SELECT( select field).

Thank you

# Answer
The Webform module for Drupal 8 supports patterns in the #states API (aka Conditional logic).
> 0 votes

# Answer
I doubt that you can achieve this without some JS involved.

You can use JS `RegExp`.

You could try Form API `#states` and try to hide the desired select field if some other field's value matches your conditions.

```
$form['my_select_element'] = [
  '#type' => 'select',
  '#states' => [
    // Hide this field when the 'weekday' radio has 'tuesday' or 'thursday' selected.
    'invisible' => [
      ':input[name="field_weekday[und]"]' => ['value' => 'tuesday'],
      'or',
      ':input[name="field_weekday[und]"]' => ['value' => 'thursday'],
    ],
  ],
];

```

(`#states` with multiple conditions, Source.)
> 0 votes

---
Tags: webforms
---


# Question
Title: Possible to extract multiple key/value pairs (links) from string in CSV and migrate into multiple link field
I am using migrate source CSV and trying to extract a string which contains multiple key/value pairs of links in format:

```
"Google.com|https://google.com,Yahoo.com|https://yahoo.com"

```

I need to save the values into a multiple link field.

The logic I need to run is:

```
- Explode the string on comma ,
- Iterate each item
  - Explode string on pipe |
    - Extract index 0
      - Store to field_link/title
    - Extract index 1
      - Store to field_link/uri

```

I have it working using a custom process plugin but would like to try and achieve this if possible through chaining of the core process plugins in the migration config yml file.

Thanks

# Answer
> 4 votes
Here is my solution to solve a similar problem:

```
temp_data:
  -
    source: data
    plugin: explode
    delimiter: ','
  -
    plugin: explode
    delimiter: '|'
destination_field:
  plugin: sub_process
  source: '@temp_data'
  process:
    field_attr_1: '0'
    field_attr_2: '1'
    field_attr_3: '2'

```

Hope it helps.

Regards, M.

---
Tags: 8, migrations, importing-exporting
---


# Question
Title: Why does Swift Mailer not use my HTML template?
In some form of my custom module, a condition triggers an email to be sent:

```
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;
    $status = parent::save($form, $form_state);
    $values=$form_state->getValues();
    if (($values['isurgent']['value']==1) && ($values['status']['value']==1)) {
      $iSeliste = \Drupal::currentUser()->id();
      $oSeliste = \Drupal::entityTypeManager()->getStorage('person')->load($iSeliste);
      $sSelite = $oSeliste->firstname->value . " " . $oSeliste->lastname->value;
      $sAction = ($values['action'][0]['value']==0)?"offre":"demande";
      $sDueDate = $values['duedate'][0]['value']->format("d/m/Y");
      _sendEmailForUrgentService($sSelite, $sAction, $sDueDate);
    }

```

in sel.module:

```
function _sendEmailForUrgentService($sSeliste, $sAction, $sDueDate) {
...some code...
  \Drupal::service('plugin.manager.mail')->mail('sel', 'emailforurgentservice', $sTo, 'fr',      $params);
  \Drupal::logger('sel')->info('Courriel pour service urgent : envoi effectué.');
}

```

my hook\_mail:

```
function sel_mail($key, &$message, $params) {
  $sFrom = '[redacted]';
  $message['from'] = $sFrom;
  $message['headers'] = array(
    'Content-Type' => 'text/html',
    'bcc' => $params[3],
    'From' => $sFrom,
    'Sender' => $sFrom,
    'Return-Path' => $sFrom,
  );
  switch ($key) {
    case 'emailforurgentservice':
      $message['subject'] = '[Le Grenier à SÉL] Un service urgent requiert votre attention...';
      $sBody  = $params[0] . " a posté une " . $params[1] . " urgente qui est valide jusqu'au " . $params[2] . ".";
      $message['body'][] = check_markup(nl2br($sBody), 'full_html');
      break;
  }
}

```

The settings of mailsystem are these:

And in my theme templates folder (mysite/web/themes/contrib/mayo/templates/), there is my email template `swiftmailer--sel--emailforurgentservice.html.twig`:

```
<html>
<head>
    <style type="text/css">     table tr td {
          font-family: Candara;
          font-size: 14px;
        }
    </style>
</head>
<body>
<div>
    <table width="800px" cellpadding="0" cellspacing="0">
        <tr>
            <td>
            <div style="padding: 0px 0px 0px 0px;">
                <p>
                    Chers SÉListes,<br><br>
                    {{ body }} <br>
                    Vous pouvez la consulter <a href="http://lejardindepoissy.org/?q=sel_catalogue\">ici</a>.";<br>
                    Si vous ne la trouvez pas, c'est peut-être qu'elle a déjà été satisfaite.";<br><br>
                    --<br>
                    Le Grenier à SÉL
                </p>
            </div>
            </td>
        </tr>
    </table>
</div>
</body>
</html>

```

The email is sent. Everything is OK (From, To, Bcc, Subject) except the body!
Instead what I defined in the template, I have only the content of `$sBody` as defined in `function sel_mail()`.
Any idea what I am doing wrong?

# Answer
My mistake!
I put my email template `swiftmailer--sel--emailforurgentservice.html.twig` in "mayo" theme which is the theme the users of the site will see. Mailsystem was set to use "current" theme.
When I made my tests, I did it as 'user 1' and the theme when the email was triggered was "Seven" (Administration theme).
I changed the settings of Maisystem:
And it works as expected!
> 3 votes

---
Tags: 8, theming, emails
---


# Question
Title: How can I shorten Facet API urls programatically?
My site uses Search API and Facet API for search.

My user search has several entity references that are also indexed. So, when just two facets are activated, this gives me a URL like this:

http://www.example.com/search&f=field\_acc\_gen%253Afield\_location\_taxonomize\_terms%3A885&f=field\_acc\_gen%253Afield\_languages%3A50

This is way too long. What I'd like to do is collapse the `field_acc_gen%253Afield_location_taxonomize_terms` to `co` (country) and `field_acc_gen%253Afield_languages%3A50` to `la` (language).

I know that Facet API Pretty Paths can be used to shorten the URLs but because I have about 20 facets, the regex that it uses seems to really kill performance. I am also thinking about using Search API Page, which does not work with FacetAPI Pretty Paths. So, I was hoping to find a way to rename the facets themselves in code.

I have my facets exported using the Features module. I tried changing `$facet->name`, but this had no affect on the results:

```
  $facet->name = 'search_api@om_user_search::field_acc_gen:field_language';
  $facet->searcher = 'search_api@om_user_search';
  $facet->realm = '';
  $facet->facet = 'field_acc_gen:field_language';

```

to:

```
  $facet->name = 'search_api@om_user_search::la';

```

How can I programmatically rename a facet?

# Answer
> 0 votes
You want facetapi\_alias.

The facets already have a setting "facet alias" internally, which can be different from the facet machine name. But this setting is not exposed in the UI natively.

The FacetAPI Alias module simply exposes this setting on the facet display form.

If you want more advanced solutions, you could use facetapi pretty paths (as you mentioned), or write your own FacetapiUrlProcessor. I have done the latter, and I can tell you it was painful :)

---
Tags: search, uri
---


# Question
Title: PHP Fatal error: Uncaught Error: Call to undefined function cache_get()
I'm trying to get Drupal to work inside an Alpine Linux docker container but for some reason `drush` can't be used to manage the website. The website itselfactually works fine, drush just can't bootstrap.

Here's the pertinent information:

```
 /var/www/html # drush core-status
 Drupal version         :  7.56
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  vlp-dcimysql01.dhe.duke.edu
 Database port          :
 Database username      :  tmp_drupal
 Database name          :  tmp_drupal
 PHP configuration      :  /etc/php7/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/bin/drush
 Drush version          :  8.1.14
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /var/www/html
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

/var/www/html # drush wd-show
PHP Fatal error:  Uncaught Error: Call to undefined function cache_get() in /var/www/html/includes/module.inc:754
Stack trace:
#0 /var/www/html/includes/module.inc(954): module_implements('system_theme_in...')
#1 /var/www/html/modules/system/system.module(2511): module_invoke_all('system_theme_in...')
#2 /var/www/html/includes/theme.inc(798): _system_rebuild_theme_data()
#3 /var/www/html/includes/theme.maintenance.inc(57): list_themes()
#4 /var/www/html/includes/bootstrap.inc(2872): _drupal_maintenance_theme()
#5 /var/www/html/includes/errors.inc(179): drupal_maintenance_theme()
#6 /var/www/html/includes/bootstrap.inc(2609): _drupal_log_error(Array, true)
#7 [internal function]: _drupal_exception_handler(Object(Error))
#8 {main}
  thrown in /var/www/html/includes/module.inc on line 754
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Uncaught Error: Call to undefined function cache_get() in /var/www/html/includes/module.inc:754
Stack trace:
#0 /var/www/html/includes/module.inc(954): module_implements('system_theme_in...')
#1 /var/www/html/modules/system/system.module(2511): module_invoke_all('system_theme_in...')
#2 /var/www/html/includes/theme.inc(798): _system_rebuild_theme_data()
#3 /var/www/html/includes/theme.maintenance.inc(57): list_themes()
#4 /var/www/html/includes/bootstrap.inc(2872): _drupal_maintenance_theme()
#5 /var/www/html/includes/errors.inc(179): drupal_maintenance_theme()
#6 /var/www/html/includes/bootstrap.inc(2609): _drupal_log_error(Array, true)
#7 [internal function]: _drupal_exception_handler(Object(Error))
#8 {main}
  thrown in /var/www/html/includes/module.inc, line 754

```

As stated before, the platform is Alpine Linux, PHP is 7.1.9

I can add more if anything is unclear. I've checked the PHP logs but they just produce the above output. I'm open to there just being a module/extension missing, but I'm not entirely sure how to figure that out if it doesn't ever tell me "undefined function extensionFunctionX" or something like that. The above undefined function appears to be a Drupal core function.

Note that the website works, so it's communicating with the database without issue, I can also do a `SHOW TABLES` in MySQL and see the Drupal installer's tables were created.

# Answer
In my case (moving production website to fresh server) memcached was enabled in settings.php, PHP daemon was installed and running on server, but no PHP extension was installed
> 1 votes

# Answer
The error happens because your Drupal is not correctly bootstrapped. Normally, you should see the following lines when running `drush status`:

```
Database                        :  Connected
Drupal bootstrap                :  Successful

```

So you should double check your database credentials in your settings file whether they're pointing to the right database and host (it's accessible from your command-line), your MySQL client command is installed and present (for example, with `apk add mariadb-client`) and your MySQL server is up-and-running.

You can check your database connection via `drush sql-connect` command. If that's correct, try to connect to the database by running `$(drush sql-connect)` in your shell.

In case of problems, try to clear Drush caches by using `drush cc drush` first.

If your website works fine, double check how you load your database credentials. Sometimes, people are using `if` or `switch`/`case` statements for different environments based on the host and forgot about the command-line interface which is not included.
> 0 votes

---
Tags: 7, drush
---


title: Shortcode in template

text:
# Question
Title: Shortcode in template
I have installed and configured Shortcode in a D8 project. However, when I try to use a short code like \[column\] or \[button\], it gets rendered as is in the node view page.

I have used a block panel in the node view page. And the in the block template I have rendered the body field like `{{ content['#node'].body[0].value|raw }}`.

However, I have noticed, that if I render the `content` as a whole like `{{ content }}`, the short codes gets rendered properly as intended.

What am I doing wrong?

# Answer
You shouldn’t render field values like that. You should be doing it as `{{ content }}` or `{{ content.field_name }}`.
> 1 votes

---
Tags: 8, theming
---


title: Change Field Type from File to Image

text:
# Question
Title: Change Field Type from File to Image
I created a field with the field type "file" I now have to convert this to "image" field type. The field has already content so I cannot not delete and recreate a new one. How can I do this programatically using the hook\_update in my module?

# Answer
Hook update performs an update on a node, it wont be too useful in your case. When you create a field it creates a table in the DB with appropriate datatypes. You cannot just change the datatype of a field without going down the line and changing all the details, including the data in most cases. which trust me is a huge pain in the ass.

I've had to do this before but what i ended up doing was creating new field with the datatype I wanted, then used View Bulk operations *Execute arbitrary PHP script* and ran custom php to get the `FID` from all the File and then add it to the new field. I think there was a user reference for each file as well, so the fidelity is there to transfer your data between fields. Then delete the old field

Worst case scenario, find ways of limiting what types of files(image only) your file upload field can upload.
> 1 votes

# Answer
I did the "inverse" to change from `iamge` to `file` to use the multiupload widget on images gallery without loose any pictures.

```
UPDATE `my_databse`.`field_config` SET `type`='file' WHERE `id`='7';

```

> `id=7` is corresponding to he field I wanted to change.

Hope it could help.
> 0 votes

---
Tags: 7
---


# Question
Title: How to control metatag module's tags from a page callback?
I have some pages which are created by page callback functions. I'm using the metatag module. I'm on D7

I need to control the metatags output (specifically the description/og:description).

This documentation looks like it would have been useful, but is empty: https://www.drupal.org/docs/7/modules/metatag/howto-assign-meta-tags-to-specific-non-entity-pages-d7

Thanks.

# Answer
> 0 votes
There's a hook for that. Here's my implementation.

```
<?php

function mymodule_some_page_callback() {
  global $metatagOverrides;
  // ... generate your page ...

  $metatagOverrides = [
    'og:image' => 'https://example.org/the-image.jpg',
    'og:description' => 'Some description',
    ...
  ];

  return $thePage;
}

function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
if (!empty($metatagOverrides)) {
  foreach ($metatagOverrides as $tagname => $value) {
    if (array_key_exists($tagname, $output)) {
      $output[$tagname]["#attached"]["drupal_add_html_head"][0][0]["#value"] = $value;
    }
    else {
      $output[$tagname] = [
        '#attached' => [
          'drupal_add_html_head' => [
            [
              [
                '#theme' => 'metatag_property',
                '#tag' => 'meta',
                '#id' => "{$tagname}_0",
                '#name' => $tagname,
                '#value' => $value,
                '#weight' => 100,
              ],
              "{$tagname}_0",
            ]
          ]
        ]
      ];
    }
  }
}

```

# Answer
> 0 votes
metatags has its own submodule for this, just enable 'Metatag: Context (metatag\_context)'

then it appears in 'Add reaction' as 'Metadata'

---
Tags: 7, meta-tags
---


# Question
Title: How to configure the CONTEXTUAL FILTER in a View for Rules?
I want to make a component that receives a user as parameter, and will then do something with some of that user’s content.

That something is: delete nodes of contenttype FICHE that have a due date in the past and copy the content of that node to a variable\_mailbody. Send the variable\_mailbody when all records of that user are processed. (After testing the component, it will be called in a viewloop of all active users, so it will be executed for all members, one after another, periodically.)

I know how to make a view that selects all nodes with a due date in the past. This will give me all the nodes to delete, but I want only those for this respective user, because I do not want to send a mail for each deleted item.

So how to configure contextual filter to limit the result to only the nodes of the user for which the component is being executed? Or should I tackle this in a different way?

# Answer
> 1 votes
Make 2 rules-views on NODES, on both views add relationship to author, on first view only add one field UID using relationship and aggregation, filter your nodes as needed, this will display only one user for several nodes that matched your ‘delete criteria’. On second view add only one field NID (with no aggregation) and same filter criteria as first view, in this view add a contextual filter on UID. On both views set row variable settings in middle column, make all fields and parameters as Data Type = Integer, do not send them as objects, it does not work well. Now in your component or rule, first add your first view-loop (UIDs), fetch user by id using your UID variable, inside that loop, add your second view (NIDs), set contextual filter as your variable UID, loop all those nodes, fetch each node by id usig your NID variable, and do your stuff, outside second view loop, but inside first view loop send your email. On second view loop you can add node-content to a variable previously added to hold all node-data for that user and included in your email body.

---
Tags: views, rules
---


title: Sort by node or comment

text:
# Question
Title: Sort by node or comment
We have a Question and Answer setup on Drupal. Question is a node. The answer is a comment.

What we are trying to do is to order Questions by either the latest asked question or by the latest commented question.

So when a new comment it posted, that questions moves on top. I can do it for Question or comments. But can't combine the two together.

Is there any way to achieve this?

# Answer
If you were building the SQL directly, you could do it in the `ORDER BY` clause with the `CASE WHEN` syntax where you do something like:

`CASE WHEN comment_table.timestamp > node_table.timestamp then comment_table.timestamp else node_table.timestamp`

Since there is no default Views core plugin for `CASE WHEN` sorting, you can either build a Views sort plugin that implements the syntax or use existing plugins that allow custom SQL with a notable security caveat that comes with storing code in your configuration.
> 1 votes

---
Tags: views
---


# Question
Title: Composer does not install Calendar Module
Hi I am having trouble migrating my local site to development (two seperate servers). I believe the reason being is because I can not install an unstable Calendar Module, which I have on my local but not on my development. In my development site I `git pull` successfully and checked the repo https://www.drupal.org/project/calendar/releases/8.x-1.x-dev was running. I did `composer require 'drupal/calendar:1.x-dev'`. I also have `"minimum-stability": "dev"` in my composer.json.

When I run drush cr I get:

> \[error\] The "calendar" plugin does not exist.

So it seems that I do not have calendar module downloaded. I check my composer.json file and have

```
"require": {
    "drupal/calendar": "1.x-dev"
},

```

but when I run

```
composer update

```

I get

```
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

```

and nothing gets downloaded. Am I missing anything?

Any help or pointers would be helpful! Thanks in advance.

# Answer
> 1 votes
Is the module installing and working locally? I've had a similar issue with dev modules before. The problem is that they will ship with a .git directory and sometimes when I try to commit the module to my project's git repo it won't be committed because of the .git in the submodule. I bet if you navigate to the calendar directory on your server it will be empty.

A solution to this is to remove the .git directory from the submodule, e.g. `/modules/contrib/calendar/.git` before committing to your project's repo. If you've already committed, git will probably still try to ignore the directory after you remove the .git from the submodule, but you can remedy this by using `git rm -r --cached modules/contrib/calendar` (or whatever appropriate path). Then you can `git add` and `git commit` the submodule.

# Answer
> 0 votes
For the meantime, I just installed calendar module manually since it may be too "dev".

```
wget https://ftp.drupal.org/files/projects/calendar-8.x-1.x-dev.tar.gz
tar -xzf calendar-8.x-1.x-dev.tar.gz

```

hoping they will make a stable calendar in the meantime.

---
Tags: updating, installation, datetime, composer
---


title: Forced HTTPS not working on Home Page

text:
# Question
Title: Forced HTTPS not working on Home Page
I'm using HTACCESS to force all my pages to redirect to the HTTPS version. However the home page is still able to go to the HTTP version.

I tried 2 examples from this post: How to simply make the whole site HTTPS?

And they work, but not for my home page as I mentioned. HTTPS is redirecting everywhere except the home page.

```
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^www\.yourdomainhere\.com*
RewriteRule ^(.*)$ https://www.yourdomainhere.com/ [L,R=301]

```

And

```
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

Edit: When I go to the HTTP version of the home page, any time I click a link it redirects to the HTTPS home page instead of the respective link. After that once on the HTTPS home page all links work correctly.

# Answer
> 0 votes
```
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    </IfModule>
    <IfModule mod_headers.c>
        Header always set Strict-Transport-Security "max-age=31536000; $includeSubDomains"
    </IfModule>

```

Is what you are looking for. Make sure to place these rules before any other rewriting rules (that may e.g. come from your webserver config).

---
Tags: .htaccess, ssl
---


# Question
Title: Add trailing slash to URLs when generating Sitemap with Simple XML sitemap
I am trying to generate Sitemap for my site using Simple XML Sitemap module. I have checked the Documentation for Extending the module features. Since I am newbie to Drupal 8, I am in confusion how to get this achieved. tried some hooks but failed it may be my lack of understanding regarding drupal8 module development. Can anyone help me to get this done. What are the namespaces I should add to my custom module.

Currently my URLs are generated like `www.mysite.com/country/india` but I want it to be like `www.mysite.com/country/india/` since I use trailing slash with URLs.

I've used htaccess to add trailing slash to URLs with 301 redirect.

# Answer
You can use hook\_simple\_sitemap\_links\_alter() to change the links generated before the sitemap is saved.

```
function example_simple_sitemap_links_alter(&$links) {
  global $base_url;
  foreach ($links as $key => $link) {
    if ($links[$key]['url'] != $base_url . '/') { // Excluding base url
      $links[$key]['url'] = $link['url'] . '/'; // Here Trailing slash will be added
    }
  }
}

```

**Before using the hook:**

**After using the hook:**
> 2 votes

# Answer
have a look at this ... it does not do exactly what you want but could be a good place to start.

```
  hook_sitemap_menu_tree_main_alter(array &$menu) {
      /**@var \Drupal\Core\Menu\MenuLinkTreeElement $menuLink **/
     foreach ($menu as $menuLink) {
       dump($menuLink); <-- do stuff with this
     }
  }

```
> -1 votes

---
Tags: 8, hooks
---


# Question
Title: Form displays without <form> after page renders
everyone!

I'm trying to embed custom form (only file upload item, will attach the code below). But I see only inner stuff like divs and inputs. No form tag at all.

In page callback I use function that calls theme. here's hook\_menu() and page callback

```
    $items['invite/%'] = array(
      'page callback' => 'invite_page_content',
      'page arguments' => array(1),
      'access callback' => 'invite_check_access',
      'access arguments' => array(1),
    );

    $output = array(
      '#theme' => 'invite_view',
      '#type' => 'markup',
      '#content' => array(
        'g_id' => $g_id,
        'g_name' => $g_name,
        'user' => $user,
      ),
    );

    return $output;

```

In theme file I have call of the form

```
    $attachment_form = drupal_get_form('invite_attachment_form');
    echo render($attachment_form);

```

Here's form function

```
    function invite_attachment_form($form, &$form_state) {
      $form['attachment'] = array(
        '#type' => 'managed_file',
        '#name' => 'upload_attachment',
        '#title' => t('Attach additional file?'),
        '#upload_location' => 'public://email-attachments/',
        '#upload_validators' => array(
          'file_validate_size' => array(2 * 1048576),
          'file_validate_extensions' => array(
            'png gif jpg jpeg mp4 ogg avi mov wmv flv ogv webm txt pdf zip rar',
          ),
        ),
      );

      return $form;
    }

```

Any help appreciated!

# UPDATE

I've found what was the reason for such behavior. There is some script in my site that deletes first form element. So if I add before my form render - everything will be ok. Need to find what is it.

# Answer
> 0 votes
```
$attachment_form = drupal_get_form('invite_attachment_form');
echo drupal_render($attachment_form); //That should work

```

see https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal\_get\_form/7.x

---
Tags: forms
---


# Question
Title: How can I change page title in node with some options?
how can I change page title drupal 8 in node with some options? I want change my title on "test" if node have field "field\_section" is "dogs". Just in this page I want showing in "field--node--title.html.twig" 'test'.

I tried `function test_theme_preprocess_field(&$variables, $hook) {
if($variables['field_name']=='title'){
 $variables['items']['changetitle']=true;
 // kint($variables);
 }
}`

But I don't know how to search from preprocess field other paramters other fields like my field in node 'field\_section'.

I want mix in preproccesing\_field 'if field\_section have value 'dogs' then showing page\_title is 'test'.

# Answer
You can fix all the things with RouteSubscriberBase https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones...

...

```
/** @var Route $entityUserEditForm */
$entityUserEditFormRoute = $collection->get('entity.user.edit_form');

// Change default user details entity form and title.
if ($entityUserEditFormRoute) {
  $entityUserEditFormRoute->setDefaults([
    '_entity_form' => 'user.complete_registration_form',
    '_title' => 'Complete Registration Form',
  ]);
}

```
> 2 votes

# Answer
Is there any reason you don't want to do this in the node template? The following is pseudo code, but you could do something like this:

```
{% if content.field_section == 'dogs' %}
  CHANGED TITLE
{% else %}
  {{ label }}
{% endif %}

```
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: How to change path using the Content: Link to Content
In Block view I want to set the link of content with the title name How to Rewrite Results using the Content:Link to Content? Example showing node/8 to john-bartlett(content title name) By using this `{{ view_node_1 }}` i am getting the node/8 path but i want the title name john-bartlett.  Please provide any solution regarding this

# Answer
Download Pathauto module. After installing go to http://YOURSITE/admin/config/search/path/patterns and click add patterns like below.

After adding pattern go to http://YOURSITE/admin/config/search/path/update\_bulk and select content and check "Regenerate URL aliases for all paths" and click update. After this, ALL your node path alias should be generated with the title of that nodes.

Then in rewrite result's add this line:

```
<a href="{{ view_node_1 }}">{{ title }}</a>

```

All your links and tags will be on your node titles.
> 2 votes

---
Tags: views, nodes, blocks
---


# Question
Title: Drupal 8: Prevent webform from saving IP
About the webform module: It always stores the IP with a submission unless it's set as confidential. Is there a way to not store the IP while leaving it as not confidential?

In `webform/src/WebformSubmissionForm.php` is the function `save` where it sets the `remote_addr`. Is there any way to hook this? I don't think it works with a custom webform handler...

Thanks! Looking forward for your answers!

# Answer
> 4 votes
You could override the save function of webform/src/WebformSubmissionForm.php, but as you specifically ask for a hook and because this is probably also the easiest solution you can remove the field value set by the form before the entity gets saved:

```
use Drupal\webform\WebformSubmissionInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for webform submissions.
 */
function mymodule_webform_submission_presave(WebformSubmissionInterface $webform_submission) {
  $webform_submission->remote_addr->value = '';
}

```

# Answer
> 0 votes
Try to follow this code..

```
use Drupal\Core\Form\FormStateInterface;

/*
* Implement hook_form_alter()
*/
function my_module_form_alter(&$form,$form_state, $form_id) {
    $form['actions']['submit']['#validate'][] = 'custom_form_validate';
}

function custom_form_validate($form, $form_state) {
  $ip = \Drupal::request()->getClientIp();
  $form_state->setValue('remote_addr', $ip);
}

```

---
Tags: 8, webforms
---


# Question
Title: Modal Error Messages Displaying on Main page
I have a page. Once i click on Button on that page. It opens jQuery Modal.

In that Modal Box. I'm rendering Form. I have put 1 fields test as **required true**.

Issue is when I click on Submit button. It closes Modal Box & showing errors on Main Page.

I need that when it clicks on Submit button. It will not close Modal Box & Display errors on Modal box instead of Main page.

# Answer
I know this is pretty old so hopefully you found another solution by now. Since I happened to come across this near the top of my Google search for a slightly different issue though...

In your form\_alter hook for the modal, you will need to add something like this:

```
$form['#prefix'] = '<div id="modal-form">';
$form['#suffix'] = '</div>';
$form['status_messages'] = [
    '#type' => 'status_messages',
    '#weight' => -10,
];

```

Then the callback function for your form that closes the modal and such will need to look something like this:

```
$response = new AjaxResponse();

// If there are any form errors, re-display the form.
if ($form_state->hasAnyErrors()) {
    $response->addCommand(new ReplaceCommand('#modal-form', $form));
} else {
    //Close the modal.
    $command = new CloseModalDialogCommand();
    $response->addCommand($command);
}
return $response;

```

This will tell it to apply the error message to your #modal-form div instead of the form in the background.
> 1 votes

---
Tags: 8
---


title: 7.x-2.54 Reports as Unsupported

text:
# Question
Title: 7.x-2.54 Reports as Unsupported
Installing the latest Kickstart update, 7.x-2.54, results in the Status report telling me I have an unsupported version of Drupal core. Screencap attached. Notice the installed and recommended versions are the same. I'm also getting emails saying my version of Drupal is unsupported. Does anyone know why this is happening and how to stop it?

# Answer
> 0 votes
Unfortunately, not sure what could be going on there. Drupal 7.59 is definitely the current version of core, so it may just be some odd bug generating a false negative. Does clearing the caches on the site help at all? If not, I'd just ignore it and / or look in the core issue queue for similar reports.

---
Tags: commerce
---


# Question
Title: Increase Product Quantity based on attendees added Drupal Commerce
I am developing a training website using Drupal Commerce. The person can book a single slot every time and can add attendees(used field collection for dynamic rows) to the training slot. How Can I increase the Order total based on the people added in the form in checkout?

For Example, If the slot is 33 dollars per person then if I add two attendees in the checkout, automatically the quantity should increase and should change the order total.

I thought to try with rules, but I didn't get how to get the count of field collection items in the rule and increase the price.

Could anyone please suggest on this?

Thanks in Advance!!!

# Answer
> 0 votes
If you want to do this solely via Rules, then you'd likely need to write a custom Rules action that can count those attendees and apply an appropriate price adjustment to the unit price of the line item. If you want to bypass Rules completely, you can change your price calculation process to support module based alterations and write custom code that hooks into the sell price calculation process via hook\_commerce\_product\_calculate\_sell\_price(). The challenge here is that you aren't getting these attendees until the checkout form, so you'll want to make sure the customer has a chance to review the final price before paying.

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


# Question
Title: Drupal commerce update to 1.14 from 1.13 - breaks checkout screen
I have also a different problem with commerce update with latest 1.14 version. After update via drush, order created and it reached checkout:shipping step, but when I do final order confirmation step, it stuck at payment page \[checkout:payment\] step, it shows blank page, actually I've skipped the checkout payment step on my previous 1.13 version and it worked fine.

what will be the issue? how to track drupal page and functions execution?

# Answer
There is no way for anyone to diagnose the issue with the information given. A blank page typically means a PHP error has interrupted the page request. When you encounter situations like this, look to your PHP / Apache error logs to see what clues is gives you.

I'm not aware of anything in the Commerce 1.14 release that should cause the checkout form to suddenly break, but perhaps it's related to some other contributed module on your site. If you track it down to a core problem that you can reproduce on a clean install of Commerce Kickstart 1.x, feel free to open a bug report in the Drupal Commerce issue queue.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to put a comma in addressfield display?
I'm using the address module with Drupal 8.x. I want a comma in the each line of the below address. Currently addresses display like:

John Peter
1181 Broadway
New York
SW1A 1AA
United Kingdom

I want it to display like:
John Peter,
1181 Broadway,
New York,
SW1A 1AA,
United Kingdom.

# Answer
> 0 votes
It appears you would need to write a custom `address-plain.html.twig` file and add it to the `templates` folder either in a module or in your theme.

Code:

```
<p class="address" translate="no">
  {% if given_name or family_name %}
    {{ given_name }} {{ family_name }}, <br>
  {% endif %}
  {% if organization %}
    {{ organization }}, <br>
  {% endif %}
  {% if address_line1 %}
    {{ address_line1 }}, <br>
  {% endif %}
  {% if address_line2 %}
    {{ address_line2 }}, <br>
  {% endif %}
  {% if dependent_locality.code %}
    {{ dependent_locality.code }}, <br>
  {% endif %}
  {% if locality.code or postal_code or administrative_area.code %}
    {{ locality.code }} {{ postal_code }} {{ administrative_area.code }}, <br>
  {% endif %}
  {{ country.name }}.
</p>

```

---
Tags: 8, forms
---


# Question
Title: How can I load custom module JavaScript on content type edit form?
I'm trying to load jQuery on the admin edit form of a content type.

To accomplish this, I developed a module "exclusivetabs" with the following directory structure:

```
|-- exclusivetabs
    |-- exclusive_tabs.info.yml
    |-- exclusive_tabs.libraries.yml
    |-- exclusive_tabs.module
    |-- js
        |-- cse_banner_header.js

```

The contents of the relevant files are as follows:

*exclusive\_tabs.libraries.yml*

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

```

*exclusive\_tabs.module*

```
<?php

/**
 * Implements hook_form_alter().
 */
function exclusive_tabs_form_node_form_alter(&$form, &$form_state, $form_id) {
  /* @var Drupal\Core\Entity\FieldableEntityInterface $node */
  $node = $form_state->getFormObject()->getEntity();

  if ($node->getType() == 'unit_landing_page') {
   /* var_dump($node);*/
    $form['#attached']['library'][] = 'exclusive_tabs/cse_banner_header';
  }
}

```

*cse\_banner\_header.js*

```
(function($, Drupal) {

/* Add span to wysiwyg button classes for alignment
------------------------------------ */
Drupal.behaviors.calloutControl = {
        attach: function (context, settings) {
                console.log("I'm loaded!");
                $('#callout-link-options .single-link').click(function () {
                        $('input[type="checkbox"]').attr('checked', true);
                        console.log("I'm checked!");
                });
                $('#callout-link-options .multi-link').click(function () {
                        $('input[type="checkbox"]').attr('checked', false);
                        console.log("I'm unchecked!");
                });
        }
};

})(jQuery, Drupal);

```

The module loads on the specific content type edit form as intended; my trouble is that I haven't figured out how to get the jQuery to load from the cse\_banner\_header.js file. I also checked the running scripts in the browser, and from what I can tell, the js file does not load on the page.

What am I missing? How can I get the js file to load on the page?

# Answer
> 5 votes
You need to change this line:

```
$form['#attached']['library'][] = 'exclusive_tabs/cse_banner_header';

```

to:

```
$form['#attached']['library'][] = 'exclusive_tabs/exclusive_tabs';

```

As your library name is *exclusive\_tabs* and not *cse\_banner\_header* the correct way is *'your\_module/library\_name'* check Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.

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


# Question
Title: How to create options in installation profile/ distribution to enable custom content types?
I have created a custom installation profile/ distribution with exported config files of a site. I have 4 content types in this site from which two will be installed by default but for other two are optional.

I can see a couple of options:

1. Creating a custom module for each content type and putting related config files in it. (This does not allow any option at installation time although I can enable the module using info file of profile)
2. Custom form alter of installation form and add check boxes.(If I want to combine this with option 1 then how can I do that?)

Checkbox-\> Content type 1 (This is disabled and checked)

Checkbox-\> Content type 2 (This is disabled and checked)

Checkbox-\> Content type 3 (Optional)

Checkbox-\> Content type 4 (Optional)

All the related config files of checked content types should be enabled at installation.

I would like to go with option two and give user check boxes at the time of installation of profile but if there are any better ways to do it then please do suggest.

Thanks in advance.

# Answer
I would think in either case, you should provide the Content types as modules and allow the user to enable them any time after installation. Otherwise, how do you expect them to enable the content types if he chooses to skip them during install?

The way to provide additional options during a profile install is hook\_install\_tasks(), also check this blog.
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: How to incorporate AMP in an existing theme?
Is there a way to incorporate AMP into my Porto Theme?

# Answer
> 0 votes
The AMP project for Drupal has three parts. The AMP module, the AMP PHP Library, and the AMP Theme work together to provide valid AMP markup for nodes with AMP-enabled content types at paths with `?amp` at the end of the URL.

From the AMP module page:

> The AMP module is designed to convert Drupal pages into pages that comply with the AMP standard. When the AMP module is installed, AMP can be enabled for any **node type**. At that point, AMP content becomes available on URLs such as node/1?amp or node/article-title?amp.
>
> The AMP PHP Library analyzes HTML entered by users into rich text fields and reports issues that might make the HTML non-compliant with the AMP standard. The library does its best to make corrections to the HTML, where possible, to make it more compliant with the AMP HTML standard.

From the AMP Theme page:

> The AMP Theme is designed to produce the very specific markup that the AMP HTML standard requires. The AMP theme is triggered for any node delivered on an ?amp path.

Some additional reading, an article describing the three in more detail on the official AMP blog: AMPing up Drupal.

# Answer
> -1 votes
To answer your question, you need to create a sub-theme bu using amptheme as the base theme. The AMP module will take care of switching the theme for AMP enabled pages along with AMP library.

You need to know that AMP is a separate spec of HTML, it wont support all the HTML tags, also there are restrictions in terms of CSS and JS. for ex: you cannot use !important in CSS.

Check the docs here https://www.ampproject.org/

---
Tags: theming
---


# Question
Title: Entity Update Failing: How can I clean this up?
I recently uninstalled a module and it left behind a bit of a mess in the database. Running `drush entup` lists a number of fields related to this module that need to be uninstalled across a few entity types.

This fails, though. In addition to these field definitions there are a number of other tables that didn't get removed.

How can I clean this up? I'm comfortable manipulating the database and I'm able to find the fields. I'm just unsure of how to clean it up to satisfy `drush entup` so it stops listing it as a pending action.

Edit-Including Error:

```
The following updates are pending:

node entity type :
  The Lingotek translation source field needs to be uninstalled.
  The Lingotek translation status field needs to be uninstalled.
menu_link_content entity type :
  The Lingotek document id field needs to be uninstalled.
  The Lingotek hash field needs to be uninstalled.
  The Lingotek profile field needs to be uninstalled.
  The Lingotek translation source field needs to be uninstalled.
  The Lingotek translation status field needs to be uninstalled.
  The Lingotek translation created time field needs to be uninstalled.
paragraph entity type :
  The Lingotek document id field needs to be uninstalled.
  The Lingotek hash field needs to be uninstalled.
  The Lingotek profile field needs to be uninstalled.
  The Lingotek translation source field needs to be uninstalled.
  The Lingotek translation status field needs to be uninstalled.
  The Translation changed time field needs to be uninstalled.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: The field lingotek_translation_source has already been deleted and it is in the process of being purged. in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->onFieldStorageDefinitionDelete() (line 512 of           [error]
/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).
Failed: Drupal\Core\Entity\EntityStorageException: !message in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->onFieldStorageDefinitionDelete() (line 512 of /docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).       [error]
Cache rebuild complete.                                                                                [ok]
Finished performing updates.

```

# Answer
> 1 votes
Update: it seems that you need to run cron to complete the field purging process drupal goes through.

Also you may be getting some errors when the fields you are deleting have data in them . `entup` does not attemp to drop fields with data in them and you have to do it yourself. You have 2 options:

1. Go to each field in the content type and delete them manually.
2. Write an update hook that delete the fields before you run `entup`. In other words, you run `drush updb` then you run `drush entup` provided you have implemented an update hook that deletes the fields. Something like this (code not tested):

```
function my_module_update_8001() {
   $entity_type = 'node'; // or user or wherever the field appears
   $bundle_name = "article"; // or whereever the field appears
   $field_machine_names = array('field_one', 'field_two');
   foreach($field_machine_names as $field_machine_name) {
    $field = \Drupal::entityManager()->getStorage('field_config')->load($entity_type.$bundle_name.$field_machine_name);
    $field->delete();

  }
}

```

In addition, make sure that you run cron frequently because that's when drupal does garbage collection and deleted field data get purged.

---
Tags: 8, database
---


# Question
Title: Unchecking a boolean field on form render
I have a content type that has a boolean field (checkbox) that editors need to always re-check on saving a new revision, if they want the value to still be `true`. Otherwise, it would be saved as `false`.

I'm using a `hook_form_node_form_alter` to modify the `$form` before the page is shown to the Editor.

```
public function my_module_form_node_form_alter(&$form, &$form_state, &$form_id)
{
   $form['field_my_boolean_field']['#value'] = 0;
}

```

I've tried something similar to the above and have also tried `#checked` and `#default_value` in place of `#value` but nothing seems to work. The checkbox always renders checked (as it is saved in the database). How can I uncheck this boolean field when the form is rendered? Note that I do *not* want to change the actual value of the field for this node, just make it unchecked in the UI when the form for this content is shown.

# Answer
You can use hook\_ENTITY\_TYPE\_prepare\_form() to change entity values before the entity form is built:

```
/**
 * Implements hook_ENTITY_TYPE_prepare_form() for Nodes.
 */
function mymodule_node_prepare_form(\Drupal\node\NodeInterface $node, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($node->getType() != 'my_content_type') {
    return;
  }
  if ($operation == 'edit') {
    $node->field_my_boolean_field->value = 0;
  }
}

```

This changes the value of the field for this node, but only temporary as long as the user doesn't submit the form.
> 3 votes

---
Tags: 8, forms
---