title: How do I theme a custom form?

text:
# Question
Title: How do I theme a custom form?
I generate a simple module "myformtest" with a simple Class form "MyformtestForm". I want to use a different theme for the form.

I followed this great tutorial. I added a "\_theme\_suggestions\_alter" hook in my "myformtest.module", I activated twig debugging and I loaded the form page.

My "suggestion theme" is present and its name is "form--myformtest-form.html.twig". Then in my module directory:

* I added a sub-directory "templates"
* I added the twig file "form--myformtest-form.html.twig" in the sub-directory "drupal/modules/custom/myformtest/templates"

In the twig file, I added this simple code. (I copied it from the drupal/core/themes/classy/templates/form/form.html.twig and added the h1 html element for override)

```
<h1>TEST</h1>
<form{{ attributes }}>
    {{ children }}
</form>

```

I clear caches (drush cr) and I reloaded my form page. But the html element h1 ("TEST") doesn't appear! Where is my mistake?

**UP**

I did it ! I added the hook theme in my .module file :

```
function myformtest_theme($existing, $type, $theme, $path)
{
  return array(
    'form__myformtest_form' => array(
      'render element' => 'form',
      'template' => 'form--myformtest-form',
    ),
  );
}

```

But.... ! When I load my form page, the html element h1 "test" is displayed but not the form :/ I thinked my .twig file override the form.html.twig default theme.

Did I miss something ? Why the form doesn't displayed, how can I fix it ? And how can I pass a custom array from my build method of form Class to my twig template ?

# Answer
> 0 votes
This is the solution :

I don't understand why copy and past the default form twig content doesn't work. (why attributes and children variables doesn't work)

I dumped all availables twig variables from my custom template (via {{ dump() }} ) . I see I had a array named "element"..I tried this and its work ! the form is displayed.

This is the code of my custom form template :

```
<h1>TEST</h1>
<form{{ element }}></form>

```

# Answer
> 3 votes
I've just been encountering a similar problem. And solved it like following.

In my `MYMODULE.module` file:

```
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'mythemename' => [
      'render element' => 'form',
      'template' => 'my-template-name',
    ],
  ];
}

```

In the `$form`:

```
$form['#theme'] = 'mythemename';

```

And finally in the `my-template-name.html.twig` template:

```
<div class="someclass">
  {{ form }}
</div>

```

# Answer
> 0 votes
The form element already has a base template.

To override the base template you will need to add twig file in your theme's templates directory.

*The template directory in modules exists to provide base templates.*

# Answer
> 0 votes
I think you need to copy the content of form.html.twig file to your custom template. Then you can make further changes in your custom template. This way, your form should render on the page.

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


# Question
Title: Drupal 7 WYSIWYG Editor Auto Spell Check
My team and I are trying to have the SCAYT (Spell check as you type) feature in the WYSIWYG bar to be automatically enabled, so that we can make our users' jobs easier for them as many of them have requested this. Currently, people are able to enable it in the editor manually. We'd like it so that it's automatically working once they start typing.

I've looked up the TinyMCE module, but it's severely out of date and we won't be using that. I tried to fumble with the code to no avail. I've read different forum but they are all out of date.

Any advice on this would be greatly appreciated and if more information is needed I'll be happy to provide it.

Thanks!

# Answer
> 1 votes
The CKEditor is a very popular Drupal editor that already has a built in SCAYT as you can see here, as well as many other plugins and extensions.

---
Tags: 7, wysiwyg
---


# Question
Title: How do I define a computed field equal to the concatenation of two fields of my custom entity?
I have a custom entity (Person) with these fields: ID, nom, prenom, telephoneportable, estactive, userID, created, changed. I created it with baseFieldDefinitions.

I want to have a computed field nomprenom = nom ." ".prenom
Here is the corresponding code:

```
$fields['nomprenom'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Nom et Prénom'))
  ->setComputed(TRUE)
  ->setClass('\Drupal\association\NomPrenom');

```

The code of class 'NomPrenom' is here:

```
/**
 * @file
 * Contains \Drupal\association\NomPrenom.
 */

namespace Drupal\association;

use Drupal\Component\Utility\String;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\Core\TypedData\TypedData;

/**
 * A computed property for defining 'Nom Prénom'.
 */
class NomPrenom extends TypedData {

  /**
   * Cached processed value.
   *
   * @var string|null
   */
  protected $processed = NULL;

  /**
   * Implements \Drupal\Core\TypedData\TypedDataInterface::getValue().
   */
  public function getValue($langcode = NULL) {
    if ($this->processed !== NULL) {
      return $this->processed;
    }

    $this->processed = $this->get('nom')->value ." ". $this->get('prenom')->value;
    return $this->processed;
  }

  /**
   * Implements \Drupal\Core\TypedData\TypedDataInterface::setValue().
   */
  public function setValue($value, $notify = TRUE) {
    $this->processed = $value;

    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

}

```

When I try to add a new Person, I get a PHP Fatal error:

> Call to undefined method Drupal\association\NomPrenom::setLangcode()

Why?

# Answer
I found this in ContentEntityBase.php 499 (but you could show us the whole error log):

I think the case is the following: your field is translatable (you didn't set it's not, and I tihnk the default is TRUE).

```
else {
  $field_langcode = $langcode;
}
**$field->setLangcode($field_langcode);**
$this->fields[$name][$langcode] = $field;

```

What I don't understand here: how basefield definition allows you to add a class which doesn't inherit / implements the right class / interface. I think it's a core bug?

You should either: \- add set language method, with a languagecode property \- set your computed field untranslatable
> 0 votes

# Answer
I guess you were following the examples in this article: https://www.drupal.org/node/2112677

Note that one major difference is that the above article talks about computed properties in a (custom) field type, whereas you are trying to use a computed property in a custom entity. I don't know whether the latter is possible – I would like to know that myself.

However, from the above I expect that there is a feasible workaround that you could use: define a custom field type (e.g. called `name`) that defines two regular stored fields (`firstname` and `lastname`), as well as one computed property (`fullname`). You should then be able to create an instance of this field type in your entity's `baseFieldDefinitions()`.
> 0 votes

# Answer
The problem lies probably in the definition:

```
$fields['nomprenom'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Nom et Prénom'))
  ->setComputed(TRUE)
  ->setClass('\Drupal\association\NomPrenom');

```

The example on Drupal.org isn't very clear here, but `setClass` is **not** the class that computes the value. `setClass` is the `ItemList` class that is defined later in the article to work around a bug in core (`\Drupal\mymodule\CurrentCompanyLinkItemList`).

The matching of the field definition and the class happens in `BaseFieldDefinition::create('my_new_field')`. This should be a unique identifier for your new field, not simply `string` etc.

In your class, you set the same as the id in the FieldType annotation:

```
 * @FieldType(
 *   id = "my_new_field",
 *   ...
 * )

```

Also note that the class that implements the FieldType must be in this namespace:

`namespace Drupal\my_module\Plugin\Field\FieldType;`
> 0 votes

---
Tags: entities, 8
---


# Question
Title: Change view & edit route or URL of Entities generated by Drupal Console
I have generated a custom entity using Drupal Console.

```
drupal generate:entity:content

```

However, there is one serious problem. All the default route for the various operation related to that entity are coming under `/admin/..` route. Which prevent non-admins from accessing those pages even if given permission for example to `edit` it.

When I generate an entity called company. My routes are as below:

* View Single Entiy: `/admin/structure/company_entity/{company_entity}`
* Add Entity: `/admin/structure/company_entity/add`
* Edit Entity: `/admin/structure/company_entity/{company_entity}/edit`
* Delete Entity: `/admin/structure/company_entity/{company_entity}/delete`
* List all Enitities: `/admin/structure/company_entity`

Where should we edit the module to override or change these settings.

# Answer
> 5 votes
You need to edit the entity class's annotation, at e.g. module\_name/src/Entity/FooEntity.php.

This is an example of what you need from the Node entity class:

```
links = {
    "canonical" = "/node/{node}",
    "delete-form" = "/node/{node}/delete",
    "edit-form" = "/node/{node}/edit",
    "version-history" = "/node/{node}/revisions",
    "revision" = "/node/{node}/revisions/{node_revision}/view",
}

```

You'll probably need to rebuild cache for the changes to be reflected.

---
Tags: 8, entities, routes, console
---


# Question
Title: Changing the settings on the fly without changing the settings.php
At the moment I'm implementing a module for managing multi-site sites

It would be desirable to implement switching a choice of a site in backend and accordingly change settings database connection on the fly

example

Sites /

```
Default /
    Settings.php

Site1 /
    Settings.php

Site2 /
    Settings.php

```

The work is done on the default site. After selecting in the admin panel - "work at site1", its settings are loaded in default on the fly without changing the settings.php. In particular, only the connection settings of the database change

Tried the following methods

1. Changing the active connection according to the default-extra scheme

\ Drupal \ Core \ Database \ Database :: setActiveConnection ('extra');

Did not work out
2. I tried at the initialization level to place a call at the initialization level

Did not work out

Is it possible to do this? There is an idea on putting a variable in a session and in settings.php checking it. But how to access it from settings.php?

# Answer
The best way to do this is to add multiple databases to your settings.php and then switch which DB you connect to, but since you mentioned that you tried this already and didn't have success, you can try adding all of your database settings into your sites/default/settings.php inside of switch statement which looks at something (anything) persistent that you change. For example, you can write to a local file and read it in settings.php.

This is hacky but since you are looking for alternatives to the more accepted solution...
> 0 votes

---
Tags: database, configuration
---


# Question
Title: entity_reference autocomplete: Allow multiple target_types
I'm creating a new custom entity and would like the ability for my `entity_reference` autocomplete field to be able to allow selecting from any arbitrary set of entities.

For example, let's say I would like the available autocomplete options to draw from:

* two node types (page, my\_custom\_node)
* users
* the terms in the Tags taxonomy vocabulary

Can anyone lend me insight as to how this might be accomplished? I'm a somewhat experienced Drupal 7 developer, but Drupal 8 has been quite an uphill climb for me and I'm afraid that not all of the new concepts are clear enough to me yet to accomplish this task on my own.

Thanks!

# Answer
> 2 votes
entity\_reference fields do not support multiple target types, never have, also not in Drupal 7 :) So you can't have an autocomplete for that as it couldn't be stored then.

However, you can use https://www.drupal.org/project/dynamic\_entity\_reference, which stores entity type and ID in a field and the default widget it provides is a combination of select and auto-complete field to select the type and the specific entity.

---
Tags: 8, entities
---


title: Redirect loop served from cache

text:
# Question
Title: Redirect loop served from cache
My Drupal 8 site occasionally (maybe once a week) gets a redirect loop for an url. The redirect sends a 301 Moved Permanently for that url to the exact same url; not even a to and fro redirect loop. Clearing the Drupal cache will fix the problem. It is not always the same url - it seems pretty random.

I'm including the full anonymized http response:

```
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Tue, 13 Jun 2017 11:41:56 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/7.1.5
Cache-Control: must-revalidate, no-cache, private
X-Drupal-Route-Normalizer: 1
X-UA-Compatible: IE=edge
Content-language: nl
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Expires: Sun, 19 Nov 1978 05:00:00 GMT
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Cache: HIT
Location: http://www.domain.ext/lang/parts/of/url
X-Powered-By: PleskLin
MS-Author-Via: DAV
Content-Length: 488

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=http://www.domain.ext/lang/parts/of/url" />

        <title>Redirecting to http://www.domain.ext/lang/parts/of/url</title>
    </head>
    <body>
        Redirecting to <a href="http://www.domain.ext/lang/parts/of/url">http://www.domain.ext/lang/parts/of/url</a>.
    </body>
</html>

```

# Answer
> X-Drupal-Route-Normalizer: 1

That's either the redirect module or the corresponding core patch, I guess the first.

There have been a bunch of bugs in the past about this but it should work now if you update to the latest version.

This for example someteimes happened with different url query parameters, or a trailing ?, e.g. "some/url?", redirect.module redirected that to /some/url but the page cache in Drupal core actually cached it for a normalized URL without ?, so it cached a redirect to /some/url as /some/url, and then you have your redirect loop.

If you can still reproduce with the latest redirect version, then open a bug report. Also make sure that you are not using a Drupal 7-style configuration for nginx (that e.g. adds a ?q=path qery parameter)
> 2 votes

---
Tags: 8, caching
---


title: Drush MAMP not working

text:
# Question
Title: Drush MAMP not working
I'm running with a big problem for hours now and it's driving me crazy, maybe one of you already know the answer.

Drush seems to not want to work on my OSX (10.8.5) with MAMP (3.0.5). When I execute `$ drush pmi` I get the following output:

```
Command pm-info needs a higher bootstrap level to run - you will need[error]
to invoke drush from a more functional Drupal environment to run this
command.
The drush command 'pmi' could not be executed.                       [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version        :  7.28
 Site URI              :  http://default
 Database driver       :  mysql
 Database hostname     :  127.0.0.1
 Database username     :  root
 Database name         :  db_name
 PHP executable        :  /Applications/MAMP/bin/php/php5.5.10/bin/
                          php
 PHP configuration     :  /Applications/MAMP/bin/php/php5.5.10/conf
                          /php.ini
 PHP OS                :  Darwin
 Drush version         :  7.0-dev
 Drush temp            :  /tmp
 directory
 Drush configuration   :
 Drush alias files     :
 Drupal root           :  /Applications/MAMP/htdocs/drupal
 Site path             :  sites/default

```

I'm running drush in the drupal folder.

I'm using `127.0.0.1` instead of `localhost` in my settings.php.

I have the following setup in my ~/.bash\_profile:

```
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.5.10/bin:$PATH"
export PATH
export DRUSH_PHP="/Applications/MAMP/bin/php/php5.5.10/bin/php"
export PATH=/usr/local/bin:$PATH

```

I've also created a symbolic link to mysql as follows:

```
$ sudo mkdir /var/mysql
$ sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

```

If I run:

```
$ php -i | grep php.ini

```

I get:

```
Configuration File (php.ini) Path => /Applications/MAMP/bin/php/php5.5.10/conf
Loaded Configuration File => /Applications/MAMP/bin/php/php5.5.10/conf/php.ini

```

Which means I'm using the same PHP version either in my apache server than in drush.

Now, I have no clue whatsoever on why drush is not properly working. Maybe one of you have an answer for this and hopefully for all of us who might have encountered this problem.

Thanks in advance!

# Answer
Specifying my port and 127.0.0.1 in settings.php in addition to following every step in this authoritative article and specifying my version of Drush as Drush 7 worked for me. Long slog (been through the same issue twice).

```
  'host' => '127.0.0.1',
  'port' => '8889',

```
> 0 votes

---
Tags: 7, drush
---


# Question
Title: What date format is required to import entityform submissions via feeds?
I am trying to import entityform submissions. When using feeds and feeds entity processor it asks for a default value for the "date submitted". I have tried several date formats and none of them are accepted.

I have tried

m/d/y

mm/dd/yy

mm/dd/yyyy

month dd, year

unix timestamp

What format does this need to be in?

# Answer
> 1 votes
Dates have to be specified as timestamps. There is a patch for the Feeds entity processor module available to add support for date formats: https://www.drupal.org/node/2708243

With the patch applied, date formats can be the following (among more):

* `yyyy-mm-dd`: 2017-06-30
* `yyyy-mm-ddThh:mm:ss`: 2017-06-30T08:53:30
* `mm/dd/yyyy`: 06/30/2017
* `mm-dd-yyyy`: 06-30-2017
* `mm/dd/yyyy hh:mm:ss`: 06/30/2017 08:53:30
* `dd-mm-yyyy`: 30-06-2017
* `dd-mm-yyyy hh:mm:ss`: 30-06-2017 08:53:30

The specified user should be an user ID, not an username.

# Answer
> 2 votes
Checking the code is seems the validation is done by entity module **entity\_property\_verify\_data\_type** which checks for numeric values regarding a date field. So try

```
yyyymmdd
20170627

```

**not working**

**valid date**

---
Tags: 7, feeds
---


# Question
Title: Creating a product page with a template file
I am using Drupal 8.3.2 with the Commerce 2 module. I am trying to theme a product page; I enabled Twig debugging and created a *commerce-product.html.twig* template file to overwrite the default one.

I want to be able to insert the different fields in the HTML markup using Twig, as I have done for custom content types. I created a view and a block; in the block, I added the following markup.

```
<div class="header">
  <h5>{{ fields.field_header.content}}</h5>
</div>
<div class="body">
  {{ fields.body.content}}
</div>

```

I am unsure what is the correct way to proceed with product pages.
Should I create a view for a product page, or can I use code similar to the previous one, where I instead use `{{ product.field_product_image.content}}`?

# Answer
You should start off with copying the template from the Commerce module /modules/contrib/commerce/modules/product/templates/commerce-product.html.twig:

```
{#
/**
 * @file
 *
 * Default product template.
 *
 * Available variables:
 * - attributes: HTML attributes for the wrapper.
 * - product: The rendered product fields.
 *   Use 'product' to print them all, or print a subset such as
 *   'product.title'. Use the following code to exclude the
 *   printing of a given field:
 *   @code
 *   {{ product|without('title') }}
 *   @endcode
 * - product_entity: The product entity.
 * - product_url: The product URL.
 *
 * @ingroup themeable
 */
#}
<article{{ attributes }}>
  {{- product|without('variation_attributes') -}}
</article>

```

You can then adjust the display according to your custom fields, so something like:

```
<article{{ attributes.addClass('product') }}>
  {{ product.field_header }}

  <div class="body">
      {{ product.body }}
  <div>
  {{- product|without('field_header','body') -}}
</article>

```
> 3 votes

---
Tags: 8, theming, commerce
---


# Question
Title: Session not refreshing until the cache is cleared
I am trying to store data entered in the drupal custom form in order to display it in next page using session.

For the first time it is running perfectly, but for the second time it contains the same value in session which was entered previously.

After clearing caches (admin/config/development/performance/clear caches) it is working for the first time, retains the same problem.

```
/**
 * @file
 * Contains \Drupal\resume\Form\PaymentForm.
 */
namespace Drupal\resume\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\SessionManager;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManagerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PaymentForm extends FormBase {

    /**
* @var \Drupal\user\PrivateTempStoreFactory
*/
protected $tempStoreFactory;

/**
* @var \Drupal\Core\Session\SessionManagerInterface
*/
private $sessionManager;

/**
* @var \Drupal\Core\Session\AccountInterface
*/
private $currentUser;

/**
* @var \Drupal\user\PrivateTempStore
*/
protected $store;

public function getFormId() {
    return 'payment_form';
}

public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user) {
    $this->tempStoreFactory = $temp_store_factory;
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;

    $this->store = $this->tempStoreFactory->get('mymodule.storename');
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('user.private_tempstore'),
        $container->get('session_manager'),
        $container->get('current_user')
    );
}

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

if ($this->currentUser->isAnonymous() && !isset($_SESSION['session_started'])) {
    $_SESSION['session_started'] = true;
    $this->sessionManager->start();
}

$form['pay_first_name'] = array(
    '#type' => 'textfield',
    '#title' => ('First Name'),
);

$form['pay_last_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
);

$form['address'] = array(
    '#type' => 'textfield',
    '#title' => ('address'),
);

$form['email_id'] = array(
    '#type' => 'textfield',
    '#title' => t('email_id'),
);

$form['actions']['#type'] = 'actions';
$form['actions']['payment_submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('payment'),
  '#button_type' => 'primary',
);
return $form;
}

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

  $payment_array['first_name'] = $form_state->getValue('pay_first_name');
  $payment_array['last_name'] = $form_state->getValue('pay_last_name');
  $payment_array['line1'] = $form_state->getValue('address');
  $payment_array['email'] = $form_state->getValue('email_id');

  $session = \Drupal::service('user.private_tempstore')->get('resume');
  $session->set('payment_details', $payment_array);
    $form_state->setRedirect('payment_redirect.form');
    return;
  }
}

```

# Answer
What you store in `$session` is not a session. A private tempstore is a different kind of storage for large amount of data, too big to have it preloaded in memory.

If you want to store a small amount of data, that does not exceed a few Megabytes, then use a session. You find the session attached to the request object:

```
$session = \Drupal::request()->getSession();

```

In a form you can get the session from the injected request stack. Use `$session->set()` and `$session->get()` to store:

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

    $session = $this->getRequest()->getSession();
    $session->set('payment_details', $payment_array);

  }

```

and retrieve the data:

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

    $session = $this->getRequest()->getSession();
    $payment_array = $session->get('payment_details', []);

    // make sure the form is not cached and this code is run on every request
    $form['#cache']['max-age'] = 0;

  }

```

---

You don't need to start the session. This is done by Drupal in the background for each request:

When finishing the response, Drupal checks if there is new session data and then starts a session to store the data (which implies setting a cookie). When the user with the session cookie comes back, then the session is restored from the database and is attached to the request.

More info Drupal 8 and Session Management
> 2 votes

---
Tags: 8, caching, sessions
---


# Question
Title: Is it possible to set the sitemap option programmatically using the module Simple XML Sitemap?
On my drupal instance I have enabled the module called Simple XML Sitemap. The problem now is I want to toggle the option to index certain pages programmatically. I can't find out how. Can this be done?

# Answer
There are API methods to alter stored inclusion settings and generate the sitemap programmatically. There is ~~no documentation other than~~ the documentation page and code documentation which is pretty complete. Here are the service methods which can be used to accomplish what you need:

```
getSetting()
saveSetting()
getSitemap()
generateSitemap()
getGeneratedAgo()
enableEntityType()
disableEntityType()
setBundleSettings()
getBundleSettings()
setEntityInstanceSettings()
getEntityInstanceSettings()
removeEntityInstanceSettings()
bundleIsIndexed()
entityTypeIsEnabled()
addCustomLink()
getCustomLinks()
getCustomLink()
removeCustomLink()
removeCustomLinks()

```

You can chain these methods like so:

```
\Drupal::service('simple_sitemap.generator')
  ->saveSetting('remove_duplicates', TRUE)
  ->enableEntityType('node')
  ->setBundleSettings('node', 'page', ['index' => TRUE, 'priority' = 0.5])
  ->removeCustomLinks()
  ->addCustomLink('/some/view/page', ['priority' = 0.5])
  ->generateSitemap();

```

I have just added the above information to the documentation page, we would appreciate anyone further contributing to it.
> 2 votes

---
Tags: 8, xml-sitemap
---


# Question
Title: Trying to fix errores with the admin_menu module
I have a Drupal 8 installation that went bad after installing admin\_menu module. and now the website is down with this error.

> stderr: PHP Fatal error: Call to undefined function user\_access() in /var/www/clients/client1/web7/web/modules/admin\_menu/admin\_menu.module on line 149

I've tried to delete the admin\_menu module with Drush, given website is completely out of order and it gives me this error.

> PHP Fatal error: Call to undefined function variable\_del() in /var/www/clients/client1/web7/web/modules/admin\_menu/admin\_menu.install on line 22
> Drush command terminated abnormally due to an unrecoverable error.
> Error: Call to undefined function variable\_del() in /var/www/clients/client1/web7/web/modules/admin\_menu/admin\_menu.install, line 22

So I've looked into admin\_menu.install and I have commented out its code.

```
function admin_menu_uninstall() {
  // Delete variables.
/*  variable_del('admin_menu_components');
  variable_del('admin_menu_margin_top');
  variable_del('admin_menu_position_fixed');
  variable_del('admin_menu_tweak_modules');
  variable_del('admin_menu_tweak_tabs');
  variable_del('admin_menu_show_all');
  variable_del('admin_menu_display');
  variable_del('admin_menu_cache_server');
  variable_del('admin_menu_cache_client');
  // Unused variables still should be deleted.
  variable_del('admin_menu_devel_modules');
  variable_del('admin_menu_devel_modules_enabled');
  variable_del('admin_menu_devel_modules_skip');
*/
}

```

It appears it was also done in a patch here.

Since it worked, I put the module back on and tried to overcome the issue and deleted content of `admin_menu_page_bottom()` function at line 150 in `admin_menu.module` and this brought the website back online.

* Is it okay to remove this function content? and why is this module still not functional? have anyone else managed to get this working on Drupal?
* Is it okay to do this in Drupal 8 to unsintall `admin_menu` removal with above procedure and is there anything that I am missing?

# Answer
Admin menu hasn't had any development effort for comfortably more than 2 years now. It doesn't have a Drupal 8 release to speak of; the chances of getting the module working without major surgery to the code are pretty slim.

If you can get the module successfully uninstalled by commenting out some code, then definitely do it (then probably delete the module folder so you don't accidentally enable it again).

The Admin Toolbar module is its successor. It integrates with the core toolbar, and has a sub-module which provides the tools menu that you'll be familiar with from Drupal 7 (with clear cache links etc).
> 3 votes

---
Tags: 8
---


# Question
Title: Search API Autocomplete does not return any suggestions when input contains ąčęėįšųūž or similar characters
I am using Drupal 7, Solr 4.x, search\_api, search\_api\_autocomplete modules in project. We have a page, which contains fulltext search with autocomplete settings. Problem is - it does not return any kind of results, when these contain non utf characters, for example ąčęėįšųūž.

# Answer
> 1 votes
Install the Transliteration module and enable the homonymous processor for the index.

---
Tags: search
---


# Question
Title: Taxonomy description for a custom taxonomy view
I have created a custom taxonomy view. When it is disabled, the taxonomy vocabulary term description shows at the top of the taxonomy page for that term, but when my view is enabled, it does not. How do I include in my taxonomy view the description?

# Answer
Edit your taxonomy vocabulary.

Add the field (or fields) that you want. (Hint: The existing field named "Description" doesn't work, so create a new text-area field if that's what you want. I called my replacement field "Definition".)

From the List tab, edit each term's value for the new field.

Create a new view.

Show: Taxonomy terms of type: your\_vocabulary, with a page display

Continue & Edit

Configure the view to display only your new field(s).

Use pager: Display a specified number of items | 1 item

Add a Taxonomy Term contextual filter

Edit the existing Taxonomy Term view.

Click on the "add" button in the Header section

Select Global view type header

Select the new view you created above

Check the "Inherit contextual filters" checkbox

Now when you visit the Taxonomy Term view, your new fields view will be included at the top.
> 1 votes

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


# Question
Title: How can I add extra classes to the title of a node?
I want to add more classes to the title of a node using the following code.

```
<h3{{ title_attributes.addClass(article-full__title) }}>{{ node.label }}</h3>

```

It doesn't work, despite the fact `title_attributes` is described as follows.

> title\_attributes: Same as attributes, except applied to the main title tag that appears in the template.

I know that is possible to add classes straightly with code similar to the following one.

```
<h3 Class="article-full__title" }}>{{ node.label }}</h3>

```

I'm eager to know the standard way of doing this, and I don't want to miss anything.

My class names follow the BEM Name Convention rules and it's hard for me to break and behave contrary to those rules and change my class names.

# Answer
You have to enclose the class in single quotes:

```
{{ title_attributes.addClass('article-full__title') }}

```

Otherwise this is interpreted as a variable name. In Twig unknown variables don't trigger an error, they return silently NULL.
> 2 votes

---
Tags: theming, nodes
---


# Question
Title: Get content of current user + Of the users that are flagged or followed
I have a site, where `users` can follow each other using `Flag`. Currently, I am able to create a `view` which shows content from all the user the currently logged in user is following. This is done adding a `relationship` to the `flag`.

What I am creating is a feed of posts, like in Facebook. So it should also show content posted by the `current user` along with `user` followed. But I am unable to do that unless the user follows himself.

# Answer
In the relationship's settings, uncheck the setting that restricts content to that flag.

Use the regular view filters instead and have two filters with OR between them. They would probably be author: current and author: flag.
> 1 votes

---
Tags: views, flags
---


title: How do I alter the value of a field?

text:
# Question
Title: How do I alter the value of a field?
I am struggling with changing the URL of my field in a view. I am using the following code.

```
function mymodule_views_pre_render(&$view) {
 $view->field['title']->options['alter']['text'] = 'My custom text';
 $view->field['title']->options['alter']['alter_text'] = TRUE;
 $view->field['title']->options['alter']['make_link'] = TRUE;
 $view->field['title']->options['alter']['path'] = "http://url.com";
}

```

The title changes, but the link doesn't.

Any idea?

# Answer
> 0 votes
It seems to me that you need to use matching quotation marks in the second line. Your current code has this: 'My custom text"

It should have this: 'My custom text'

That is, you have a single quotation mark to open the string, but a double quotation mark to close it. That's causing the rest of your block to be quoted. Change the double quotation mark to a single quotation mark.

---
Tags: 7, views
---


# Question
Title: Sent email to entity reference node email field on checkout
I have a commerce store and my client don't want a regler checkout. On the checkout a email must be sent to a marketer of the users choice.

For this I have setup a content type with all the users contact details in for the user to find but when a user order some products the order must be sent to the marketer to prosses.

I have add a entity ref. Field in the billing information.

But I can't get the rules to pickup the email field in the entity reference.

What is the correct settings for this?

# Answer
> 0 votes
The first action for your rule should be "Fetch entity by id." Specify the entity type for the billing information for the entity type. In the Identifier field, use the Data Selector to find the token for the id of that entity type. Now create a second action, "Send mail." The information from the entity you specified in the first action will now be available to you for the Send mail action.

---
Tags: entities
---


title: Get all fields defined in a bundle

text:
# Question
Title: Get all fields defined in a bundle
In Drupal 7, to get all fields used in a content type, I use the following code.

```
$fields = field_info_instances('node', 'article');

```

What is the equivalent for Drupal 8?

# Answer
> 27 votes
I achieved it using `getFieldDefinitions()` defined in `Class EntityManager`. So in order get all fields used in a particular bundle, Here is a way:

```
$bundle_fields = \Drupal::entityManager()->getFieldDefinitions('node', 'article');

```

Though the above `$bundle_fields` also contains `nid, uuid, revisions, langcode, etc` as fields. So to get an accurate output I did something like this:

```
  $entity_type_id = 'node';
  $bundle = 'article';
  foreach (\Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle) as $field_name => $field_definition) {
    if (!empty($field_definition->getTargetBundle())) {
      $bundleFields[$entity_type_id][$field_name]['type'] = $field_definition->getType();
      $bundleFields[$entity_type_id][$field_name]['label'] = $field_definition->getLabel();
    }
  }

```

# Answer
> 55 votes
EntityManager is deprecated moving forward. The following can be used instead:

```
$entityFieldManager = \Drupal::service('entity_field.manager');
$fields = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);

```

Whereas `$entity_type` can be `'node'` and `$bundle` can be `'article'`

# Answer
> 11 votes
EntityManager is deprecated and I used the next code. I added to Controller class:

```
/**
 * The entity field manager.
 *
 * @var \Drupal\Core\Entity\EntityFieldManager
 */
protected $entityFieldManager;

/**
 * Constructor.
 *
 * @param \Drupal\Core\Entity\EntityFieldManager $entity_field_manager
 *   The entity field manager.
 */
public function __construct(EntityFieldManager $entity_field_manager) {
  $this->entityFieldManager = $entity_field_manager;
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('entity_field.manager')
  );
}

// Here some your functions

/**
 * Build table rows.
 */
protected function buildRows() {
  $entity_type_id = 'node';
  $bundle = 'article';
  $fields = $this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle);

  foreach ($fields as $field_name => $field_definition) {
    if (!empty($field_definition->getTargetBundle())) {
      $listFields[$field_name]['type'] = $field_definition->getType();
      $listFields[$field_name]['label'] = $field_definition->getLabel();
    }
  }

  $rows = [];
  foreach ($listFields as $field_name => $info) {
    $rows[] = $this->buildRow($info, $field_name);
  }

  return $rows;
}

```

https://www.drupal.org/node/2549139 is what helped me

---
Tags: 8, entities
---


# Question
Title: How can I display multiple images of single image field each in a different row?
I need to render multiple images that belongs to single image field, each on its own views row.

While on a view single field setting, inside "Multiple field settings", uncheck " "Display all values in the same row", But all values are still displayed on same views row.

How can it be done in Drupal 8?

# Answer
Well, on the same view, on English side of the website the view displays same field, of same field of the same node ID, on separate view rows.

Problem disappeared after the field configured to be to be translate.

Now display every item (image) on its own views row as expected.
> 0 votes

---
Tags: views, 8
---


# Question
Title: the Private files folder outside of "sites/default/files"
The *Private Files* directory is outside of the sites/default/files directory.

Is that fine? I haven't got any problem with that, yet.

I'm using Drupal 7, if that makes any difference.

# Answer
**TL;DR** \- It is okay even if you place the private files directory outside the `sites/default/files` directory. In fact, it is recommended that you keep it outside the Drupal root (source). This is hard to implement on shared hosting.

**More explaination:**
When you specify the path of the private files in Drupal's configuration, Drupal places a `.htaccess` file with `Deny to All` in it. Which means that Apache will not be able to serve any of the files inside that directory. The files inside the directory can only be served by Drupal and their paths are resolved as Drupal path.

**Example:** Let us compare how placing the same file in public and private directory changes the way Drupal handles it. Say the filename is `brochure.pdf`:

1. Public file path - If we place `brochure.pdf` in public directory with path `sites/default/files`. And in the browser you hit `http://yoursite.com/sites/default/files/brochure.pdf`.
This request goes to Apache (considering it as a server), Apache tries to resolve the type of request. It tries to go to the directory structure and see if it can fetch the file. In case of public files it has the permission to do so. It directly fetches the file and returns to the browser where it is presented or downloaded. In fact the request doesn't even need to go to Drupal or the PHP interpreter for that matter.
2. Private file path - If we place `brochure.pdf` in private directory with path `sites/default/files/private`. And in the browser you hit `http://yoursite.com/sites/default/files/private/brochure.pdf`.
Again, the request goes to Apache and it checks the directory to locate the file. It does not have permission to fetch the file from private directory due to `Deny to All`. It passes on the request to Drupal. Drupal then does the access checks as it does on all other menus (routes in D8), with `access callback`.

So, to summarize, it should be okay to place your private directory outside the public files.

**Note:** If you are hosting your site on other servers and not Apache, you might need to check if you need some extra settings as `.htaccess` restrictions might not work with them.
> 5 votes

---
Tags: files
---


# Question
Title: How to show a specific date format in an English view?
I have multi-language web site. I have a date field with a specific format in a view, and I want to display the date in English format.

How can I do this?

# Answer
> 0 votes
In views, click on your date field and select Custom as your `Date format`.

Then see the PHP Date Manual, under `Custom Date Format` type your custom date accordingly.

For Example:

---
Tags: views, datetime
---


title: Add CSS class with hook

text:
# Question
Title: Add CSS class with hook
I have a search box using custom\_search module. I am trying to add multiple classes to the *input* field using a hook.

Here is the code I have tried:

```
<?php
function mytheme_form_search_block_form_alter(&$form, &$form_state) {
      $form['keys']['#attributes']['class'][] = 'custom_search-keys','form-search','form-control';
    }

```

But it does not add the classes to the search box input field?

# Answer
Try this one, add class as array.

```
$form['keys']['#attributes'] = array('class' => array('custom_search-keys','form-search','form-control'));

```
> 0 votes

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


title: User Notifications

text:
# Question
Title: User Notifications
Does anyone have an idea how to send email notification to the user when the file is uploaded?

This file can be uploaded either to the new node or while modifying an existing node.

# Answer
> 1 votes
I know you mentioned that you can't use Rules, but I think you can.

In your condition, just add your file field and set it to "Data value is empty" and negate it.

# Answer
> 0 votes
Sorry but I did not put the description. The website which is drupal 7 has media module installed. I want the notification to launch whenever a file is uploaded in the media manager before it is attached to a node.

---
Tags: emails, notifications
---


title: Dependent product variation type

text:
# Question
Title: Dependent product variation type
I have a question. My site sells tours. For each tour(product) a user can choose a flight and some hotel rooms. Example tour1: user can choose: flight1 and flight2. user can choose: double rooms and/or single rooms.
If the user choose flight1 then -\> double rooms costs 50, single rooms costs 100(a). If the user choose flight2 then -\> double rooms costs 150, single rooms costs 200 (b). I have 3 dependent variation types(flight, doubleRoom, singleRoom). What I want is: if the user choose flight1 I only show double rooms = 50, single rooms =100 (rooms(a)); if the user choose flight2 I only show double rooms = 150, single rooms=200 (rooms(b)). Flights and rooms have a taxonomy terms called 'solution':solution1, solution2 ecc.. I think that a way should be use rules, with event 'After adding a product to the cart' but I can't write the condition('if flight choose solution1') and the action(set visible=true where rooms solution= solution1). Can someone help me please?? Thanks in advice

# Answer
> 0 votes
I am looking for this for Drupal 8, however it appears that the module Commerce Product Add-on provides a solution for Drupal 7 (I have not tested it).

> Commerce Product Add-On allows users to attach products as options to the add to cart form of another product. This is particularly useful for things like event sponsorship, optional accessories, and other up-sells.

---
Tags: commerce
---


# Question
Title: Best method to enable/disable modules depending on the environment
What would be the best solution to enable/disable modules depending on the site environment (dev, stage or production)?

1. Created a database dump containing the `system` table for each installation. Then when deploying I use `mysql -uuser -ppass database < dump-<type>.sql` where the `type` reflects the kind of environment.
2. Created a shell script for each environment, that uses `drush` to enable or disable needed modules and set specific site settings.
3. Wrote a small deploy script for each site that looks something like this:

```
// change working directory to drupal installation path
chdir('public_html');

// define root, include bootstrap.inc and start drupal
define('DRUPAL_ROOT', getcwd());
require_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// modules that should be disabled/enabled on stage site
$modules = array(
   'field_ui' => 1,
   'toolbar' => 1,
   'update' => 1,
   'overlay' => 0,
   'feeds_import' => 0,
   'feeds_ui' => 0,
   'feeds' => 0,
   'menu' => 1,
   'advanced_help' => 1,
   'job_scheduler' => 1,
   'wysiwyg' => 1,
   'views_ui' => 1,
   'dblog' => 1,
);

// enable/disable modules and set site specific variables
foreach ($modules as $module => $state):
  if ($state == 1):
    if (!module_exists($module)):
      module_enable(array($module), FALSE);
    endif;
  else:
    if (module_exists($module)):
      module_disable(array($module), FALSE);
    endif;
  endif;
endforeach;

variable_set('error_level', ERROR_REPORTING_DISPLAY_ALL);
variable_set('preprocess_css', 0);
variable_set('preprocess_js', 0);
variable_set('cache', 1);
variable_set('page_compression', 0);
variable_set('block_cache', 0);

```

Does anyone have a better solution?

# Answer
One possible answer is the Environment module (the 7.x dev release works just fine). It allows you to define arbitrary environments (comes configured with "Development" and "Production", but you can have more if necessary). It then provides `drush environment-switch` to switch between environments. You can then implement `hook_environment_switch()` to do anything you want when the environment is switched. There's no built-in support for enabling and disabling modules, but that's easy enough to do in code, as you demonstrate above. It's also convenient for doing things like changing variable values and blocking development users.

You then put something like `drush environment-switch production` in your deploy steps.

This also has the benefit of being able to switch back to `Development` easily. For instance, I have `views_ui` disabled in `Production`, but enabled in `Development`. If I need to urgently check a view in the ui on the production site, I can switch the environment to `Development`, do what I need, and switch back.

It's also nice that since it's implemented in hooks, you can keep different types of functionality in different modules, and you can keep these things in the code base and under version control.
> 6 votes

# Answer
The Habitat module offers another option. Upon clearing the cache, specified modules are enabled and disabled based on a variable you set in settings.php
> 2 votes

# Answer
Use Drush make and other Installation profile utilities to create separate installation profiles.
> 1 votes

# Answer
Have a look at https://github.com/donquixote/drupal-drux

Create a number of "seed modules" with dependencies\[\] in the \*.info file:

* mysite\_dependencies with shared dependencies
* mysite\_dev\_dependencies with dependencies only for dev.
* mysite\_prod\_dependencies with dependencies only for production (often this will be empty).
* mysite\_krister\_dependencies for localhost stuff you don't want to see enabled in any other environment.
* etc.

Now on each of production, dev and local, you only enable those seed modules applicable for this environment.

Drux provides a number of useful drush commands for this work flow, to fill the \*.info files with dependencies\[\], and to enable the required modules after git pull:

```
drush obs mysite_dependencies mysite_dev_dependencies
drush obs-gen mysite_dependencies mysite_dev_dependencies
drush dep
drush dep-en

```

(see the github page / README.md)
> 1 votes

# Answer
I prefer to use the Master module and put all the dependencies in Features. Master module allows enabling and disabling modules specific to environments via Drush. With this and a few shell/drush scripts you should have everything you need.
> 1 votes

# Answer
For Drupal 7 you can use Tadaa

> Tadaa! is a module aimed at simplifying the process of enabling/disabling modules and altering configuration when switching between different environments, e.g. Production/Staging/Development.
>
> The environments and the corresponding configuration is completely configurable.
> -1 votes

---
Tags: 7, deployment
---


title: Drush with a dockerized Drupal install

text:
# Question
Title: Drush with a dockerized Drupal install
I'm trying to setup a development environment for Drupal using docker.

I've already succeeded on creating a PostgreSQL container and a Drupal container using official images for both, and I can replicate the production environment.

How do I get drush to detect my Drupal install?

I've tried both https://hub.docker.com/r/drush/drush/ and https://github.com/DockerDemos/appstack-drush (had to build that last one) but when I run drush inside the containers they don't see the Drupal install.

I run "docker run --volumes-from `<my-drupal-container>` --link `<my-db-container>`:postgres -it drush/drush dd" and it shows nothing, "drush cc" finds no caches.

# Answer
> 3 votes
There are 2 things you can do here:

1. Use Docker as external container like you are doing. You need to pass the --net parameter too to make that work, see example below. You will always use this drush container as a running command, not a container that is up and running with your stack all the time.

`docker run --net={your_container_network_name} --rm -it -v $(pwd):/app drush/drush sqlc`

2. Simply add drush to your Drupal container and connect to that container to run drush commands:

Dockerfile:

```
ENV DRUSH_VERSION 8.1.2
RUN curl -L --silent https://github.com/drush-ops/drush/releases/download/${DRUSH_VERSION}/drush.phar \
  > /usr/local/bin/drush && chmod +x /usr/local/bin/drush

```

Connect to your container and then run any drush command inside it:

```
docker exec -it {container_id} bash

root@{container_id}:/var/www/html# drush status

```

# Answer
> 2 votes
For the --uri parameter, pass in whatever URI you use to access your site from your local web browser. In addition to --uri, you must also specify --root, which should contain the full path to the Drupal root inside your container.

# Answer
> 0 votes
To have a very convenient way to use drush / drupal console / composer in Docker, I use zsh with autoenv and a little function for each command.

In each drupal project folders, create a `.autoenv.zsh` file the following settings:

```
autostash DRUSH_IN_DOCKER=1
autostash DOCKER_PHP_CONTAINER=myproject_fpm_1
autostash PROJECT_URL=http://www.mydomain

```

Then creates a small zsh function:

```
drush() {
    if [ "$DRUSH_IN_DOCKER" == "1" ]; then
        docker exec -it ${DOCKER_PHP_CONTAINER} /var/www/vendor/bin/drush --root=/var/www/web --uri=${PROJECT_URL} "$@"
    else
        drush "$@"
    fi
}

```

Be sure to replace the provided paths with the one of your drupal project in docker.

# Answer
> 0 votes
Run:

```
docker-compose exec php sh
drush cc all

```

---
Tags: 7, drush
---


title: How to add attributes to forms?

text:
# Question
Title: How to add attributes to forms?
I am trying to style the registration/login forms so far I have copied all the files from `\drupal\core\themes\stable\templates\form\` to `themes\mytheme\template\form`.

Inside this folder, for example there is `input.html.twig` which has the following code.

```
{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<input{{ attributes }} />{{ children }}

```

My question is how can I add a specific class name to this input, so I can apply styles to it in my css file

# Answer
You can use the `addClass()` method of the attribute class:

```
{%
  set classes = [
    'my-class-1',
    'my-class-2',
  ]
%}

<input{{ attributes.addClass(classes) }}>

```

You can either pass an array like the example above or pass a single class in the method directly: `attributes.addClass('my-class')`.

For reference see the Drupal docs: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
> 1 votes

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


title: How do I theme exposed filters?

text:
# Question
Title: How do I theme exposed filters?
I'm theming a Drupal 8 Views page. I created the twig template file and can output the 2 exposed filters with the code below. The problem is that nothing happens when I click Apply on the exposed filters. It's probably missing some attribute, but I can't figure out how to do it. Has anyone done this?

```
{% if exposed %}
  <div class="view-filters form-group">
    {{ exposed.field_category_target_id }}
    {{ exposed.field_address_locality }}
    {{ exposed.actions }}
  </div>
{% endif %}

```

Here are the printout of the **exposed** variable

# Answer
This is not possible in a Views template. Form elements rendered here can't be submitted because they are not in a html form (between `<form>`/`</form>`).

You need a custom form template so that you are inside of the form. For the Views exposed form there is already a customizable form template in core:

*/core/themes/stable/templates/views/views-exposed-form.html.twig*

```
{#
/**
 * @file
 * Theme override of a views exposed form.
 *
 * Available variables:
 * - form: A render element representing the form.
 *
 * @see template_preprocess_views_exposed_form()
 */
#}
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
{{ q }}
{% endif %}
{{ form }}

```

You can copy this twig to the /template folder of your theme and start theming the form elements:

```
  {{ form.field_category_target_id }}
  {{ form.field_address_locality }}
  {{ form|without('field_category_target_id', 'field_address_locality') }}

```

---

See How do I assign a template to the user edit form? for more info how to add and use these form templates in other forms.
> 13 votes

---
Tags: views, theming
---


# Question
Title: Can't add new language to a Drupal 8 installation
I have installed a Drupal 8 installation using the app utility from my hosting.

The main language is Spanish, but when I'm trying to add two new languages from admin/config/regional/language there is no "Add language" button. The module Interface Translation is installed.

Is it possible that languages are locked by any configuration file? How can I make the button appear again?

# Answer
Uff, silly me!!! The problem was that the block that shows the link to add a new language was removed from my admin theme. Ok, I hope this helps somebody else with a similar problem too.
> 0 votes

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


# Question
Title: In drupal 7 I want to crop same image for different device ratios. How can I do this?
In drupal 7 I want to crop same image for different device ratios. How can I do this.

On uploading image and We have to crop for different ratios.

# Answer
> 0 votes
You can use picture module combined with breakpoints module. Worked perfect for me.

---
Tags: media, theming
---


# Question
Title: How to remove 'destination' query paramater from link URLs in Drupal 8
For some SEO related reasons, I want to remove the destination paramaters that are attached to the login and register link urls below nodes.

The Link-URLs look like this:

```
http://example.com/user/login?destination=node/55%23comment-form

```

But I want it that way:

```
http://example.com/user/login

```

For Drupal 7, someone has made it with:

```
function moon_url_outbound_alter(&$path, &$options, $original_path) {
 // here "moon" is my theme, use your own.
  switch ($path) {
  case 'user/login':
  unset( $options['query']['destination'] );
  break;
 }
}

```

Source: How to remove the Destination parameter from an URL in Drupal 7?

This source https://www.drupal.org/node/2238759 says, in Drupal 8 hook\_url\_outbound\_alter has been replaced with OutboundPathProcessorInterface. But with the given example there, I don't understand how I could make it to unset the destination paramaters with my .theme file.

Can someone please help and tell how to unset the destination paramaters in Drupal 8 ?

Thanks in Advance!

# Answer
Before proceeding, realize that although this might be better for SEO; it might be negative for user experience. Personally I'd hate it if I were to comment on a node and after the login I have to navigate back to that node. You might want to perform some session magic to redirect the user back to where he came from.

The answer to your question involves a custom module, with a Path Processor service. In addition to the default module files (`mymodule.module` and `mymodule.info.yml`), you'll need `mymodule.services.yml` and `src/PathProcessor/MyModulePathProcessor.php`.

The services file will expose your path processor to Drupal with this code:

```
services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MyModulePathProcessor
    # Optionally provide arguments.
    #arguments: ['@config.factory', '@entity_type.manager', '@current_user']
    tags:
      - { name: path_processor_outbound, priority: -10} # Low priority acts last.

```

This 'subscribes' the class to the `path_processor_outbound` event.

The Outbound path processor should look something like this:

```
<?php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MyModulePathProcessor.
 */
class MyModulePathProcessor implements OutboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($path == 'user/login') {
      unset( $options['query']['destination'] );
    }
    return $path;
  }

}

```
> 4 votes

---
Tags: 8, navigation
---


title: Show Parent Menu children in sidebar

text:
# Question
Title: Show Parent Menu children in sidebar
I want to explain this as simple as possible...

I have a main navigation placed into the main\_navigation block in my site and I want to add a sidebar menu if the CURRENT main\_navigation page has child menus...

For example:

1. My main navigation is: Home | About | Services | Blog | Contact Us
2. I added **Request Quote** page/form as a child of Contact Us
3. so when I am in Contact Us page, I want to show **Request Quote** in the sidebar but don't show it if I am in About or Services

I saw this question but can't duplicate it

Get menu link siblings

Any help is welcome!

# Answer
> 0 votes
I was able to solved the issue by doing a few things:

1. I downloaded & enabled this module: https://github.com/studgate/expanded\_menu\_block, a temporary Drupal 8 port of menu\_block
2. Placing a new block in the left\_sidebar region, I selected the main navigation menu
3. configure the block to have 'Initial menu level 3' and 'unlimited' menu levels to display
4. Clear cache and make sure your child menus are showing properly in the sidebar

If other child menu items are showing in the sidebar, go to Edit Menu page and edit each Parent Main Navigation menu and uncheck 'Show As Expanded'

If there is even an easier way, just comment...

# Answer
> 1 votes
Use the Menu Block module, create a new Menu Block using the Primary Navigation, starting at Level 2.

This will only show the children of the current parent menu item you are in.

# Answer
> 0 votes
Add this block core\modules\system\src\Plugin\Block\SystemMenuBlock.php

if ($level \> 1) { if (count($parameters-\>activeTrail) \>= $level) { // Active trail array is child-first. Reverse it, and pull the new menu // root based on the parent of the configured start level.

```
   $menu_trail_ids = array_reverse(array_values($parameters->activeTrail));
    $menu_root = $menu_trail_ids[$level - 1];

    $parameters->setRoot($menu_root)->setMinDepth(1);
    if ($depth > 0) {
      $parameters->setMaxDepth(min($level - 1 + $depth - 1, $this->menuTree->maxDepth()));
    }
  }

  else {
    return array();
  }
}

```

Configure level 2 or above level in block layout.

---
Tags: 8
---


title: PHP functions only called once?

text:
# Question
Title: PHP functions only called once?
I have written a tiny module with a custom block. The contents of the block is created in the build() function. That function creates the HTMl, which is rendered. I can see that code changes have effect: after a update.php run, the resulting HTML reflect the changes.

But that function has strange behavior. The first thing I do in it is displaying the current url with

```
   $html = '<p>URL: ' . \Drupal::request()->getRequestUri()) . '</p>'
   .....
   return $html;

```

The strange thing is this function always displays the same URL, no matter the actual current url. Only updating the cache can change the path. After that update, the output will remain the same until the next update. Why is this? Is the output of functions cached as well?

Something similar happens when I try to debug the code and write data to a temporary file:

```
file_put_contents ( '/tmp/zphp1', "$html\n", FILE_APPEND );

```

The file is only written once: right after an update.php-run. Why is drupal/php not executing all code? What can I do to examine variables in order to see what is happening?

# Answer
by asking the question, I almost answered it. It is indeed the result of caching. So when cached, several function calls have no effect. LIke writing to a file, like getting the request url.

When the block is *not* cached, everything works as expected. It is rather confusing behaviour for a newbe like me; caching is default *on*.

caching can be turned off in the output array of the build() function:

```
return array(
        '#markup' => "<p> this is a test</p>",
        '#cache'    => array ( 'max-age'   => 0 ),
      ),

```
> 0 votes

---
Tags: debugging
---


title: Theme file upload form element

text:
# Question
Title: Theme file upload form element
I want to theme all the file upload fields on my site but I don't know how to name the template file.

I want to alter the form-element.html.twig file but as I have multiple file fields I don't think that the best way is to create theme files for each field. So I was thinking to create a theme based on the field type. Is that possible?

I used the hook\_theme\_suggestions\_input\_alter.

```
function MY_MODULE_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (strcmp($element['#type'],'file') == 0) {
    $suggestions[] = 'form-element--file';
  }
}

```

After clearing the caches seems that doesn't work.

Is this the correct way or is there any other way?

# Answer
As suggested by Ivan Jaros, you can override input--file.html.twig if you want to use twig templates. Basic input template is as follow:

```
{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<input{{ attributes }} />{{ children }}

```

If you need to add more dynamic variables, you can use **template\_preprocess\_input()** preprocess function.

Also, you can use **debug: true** under **twig.config** in services.yml. This will help for theme-related development.

**Note: Drupal provides default classes that are from generic to specific to the field. If generic classes helps to theme, I would suggest to avoid all the above.**
> 1 votes

---
Tags: 8, theming, files
---


title: Add taxonomy terms list to homepage

text:
# Question
Title: Add taxonomy terms list to homepage
Please help me to add taxonomy terms from custom taxonomy into home page. I have no idea how to do this as I'm coming from WordPress. In WordPress it is easy as calling get\_terms(). I have following file as my home page: `mytheme/templates/page--front.html.twig`

I have more than one taxonomy type and all of them are going to queried in the home page.

How to query the taxonomy terms?

**UPDATE:**

I have created a new region called `home_content` in my `theme.info.yml` and I have created a view(block) for getting the taxonomy terms, added it to region in back-end and display it as `{{page.home_content}}`. It works but I have few questions.

1. I have fields for logo and text in the taxonomy. I want to list them too.
2. I need to customize the html. How can I do that?

Thanks for the support.

# Answer
> 1 votes
Just create a view and list out taxonomy terms. Then display the view in front page.

Need to place view in `page--front.html.twig`.

Use Twig tweak module.

```
<dd>{{ drupal_view('view_name', 'page_1') }}</dd>

```

For Block

```
{{ drupal_view('view_name', 'block_1') }}

```

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


# Question
Title: Custom Theme - Add page specific meta tags / title to pages
I am new to Drupal, but I am very familiar with WordPress.

In WordPress, I am able to hook into the head of a document with `wp_head` to add things like page specific meta tags.

When using a custom theme based on Stable, how would you add page specific things in the `<head>` of a document in Drupal 8?

Note: I am wondering how this would be done without a custom module.

# Answer
> 1 votes
You can attach the tag to the page's render array via `hook_page_attachments_alter()`.

An example from the related change record:

```
function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
        ),
    );
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
}

```

---
Tags: theming, 8, nodes, meta-tags
---


# Question
Title: Content type / block or page .. how do we create a small text for a page in D8
Let's say, I have a footer where I want to show a simple text **not** menu or link just a simple block of text. So, since it's neither a page, an article or block ... is there any way to create a text and show it somewhere in D8?

# Answer
> 2 votes
Blocks can be used for many things including showing simple texts. Go to `/block/add` and create a block. Here you can provide a description and some body text. After saving your block you are redirected to the block configuration where you can place it.

By placing the block Drupal creates a block instance. For more information please see: https://www.drupal.org/docs/8/core/modules/block/overview

---
Tags: 8, blocks
---


# Question
Title: How to re-order a mini-panel in a Panel generated page?
I've inherited a site and have been slowly unraveling certain aspects of its construction. Specifically right now, I want to change the order/region a page is loading a mini-panel in a page that I believe is being styled as a Panel due to the css-markup and lack of a template file.

I believe the content type and associated fields and panels were all loaded into the site structure via Features. The general layout of the pieces I want to change right now is like this:

```
    <div class="content__main_wrapper clearfix">
  <div class="panel-panel content__main_sidebar eq-col">
    X
    </div>
  <div class="panel-panel content__main_full eq-col">
    </div>
</div>

```

Where X is what I want to move to the div below, or another div below that so that I can display it on mobile devices below the main content. If I go to look at the admin/structure/mini-panels/list/mini\_panel\_name/edit/layout no matter how I change the location of the content, it doesn't seem to impact its layout in the nesting of the page overall.

There does not appear to be a Panel Page that is content-type/node% for the content type the panel and mini-panels are attached to or a template doc, so I'm not sure where to look to impact this. Neither are there published blocks associated with these.

I'm not very familiar with the Features module, but it's set to prevent rebuild and revert. Could there be something that's interfering with? Could there be something buried in the imported Features module that's controlling this layout outside of normal theming locations? This also all lives in Pantheon.

# Answer
Okay, so I ended up finding my own answer while working on something else. I realized my scope was wrong, I was looking for an override page referring to a specific page type/section, but what ended up being the case was that there existed an override page for all nodes with unique content/layouts in use for each of them within the same area.

So there was ultimately a Panel Page doing the dirty deed as I had thought, but I was being too specific in where I assumed the changes were made, in part because I assumed an override page would have to maintain the same layout for all pages it overrides, but that's not the case I've learned.
> 0 votes

---
Tags: panels, features
---


# Question
Title: How to keep Display Suite CSS classes in code?
I'm using `DS` in my D7 project along `Features`, so I've been able to keep all my new DS layouts, CCK, etc. in code, by generating a custom feature.

All good there... until I had to add some custom CSS classes to Display Suite:

Can't see how these values can be exported in code to persist in my project, rather than my DB. Nothing from the `feature` module either.

Is this actually possible? Thanks in advance :)

# Answer
> 1 votes
Seeing that you use Drupal 7, have you checked out the Features and Strongarm modules? Both modules allow you to export most configs as code.

---
Tags: display-suite
---


# Question
Title: token_filter module: [node:nid] for custom block?
Drupal: **8.1.7**

Module: token\_filter 8.x-1.0-beta1

I have a custom block with a Text format that has *Global and entity tokens are replaced with their values* enabled.

The custom block has this value:

```
current-page:url:unaliased :          [current-page:url:unaliased]<br>
current-page:url:unaliased:absolute : [current-page:url:unaliased:absolute]<br>
current-page:url:unaliased:args :     [current-page:url:unaliased:args]<br>
current-page:url:unaliased:brief :    [current-page:url:unaliased:brief]<br>
current-page:url:unaliased:path :     [current-page:url:unaliased:path]<br>
current-page:url:unaliased:relative : [current-page:url:unaliased:relative]<br>

```

that will render as:

```
current-page:url:unaliased : http://www.example.com/node/1657
current-page:url:unaliased:absolute : http://www.example.com/node/1657
current-page:url:unaliased:args : , node, 1657
current-page:url:unaliased:brief : www.example.com/node/1657
current-page:url:unaliased:path : /node/1657
current-page:url:unaliased:relative : /node/1657

```

I am attempting to get the Content Id (e.g. **\[node:nid\]**) from the page, but that token is not available.

*Workaround using Inline Javascript:*

Node Id:

```
<script type="text/javascript">
<!-- language: lang-js -->
document.write("[current-page:url:unaliased:relative]".match(/\/node\/(\d+)/)[1])
</script>

```

which will render as:

```
Node Id: 1657

```

I tried the following:

```
current-page:url:unaliased:args:node : [current-page:url:unaliased:args:node]
current-page:url:unaliased:args:0 : [current-page:url:unaliased:args:1]
current-page:url:unaliased:args:1 : [current-page:url:unaliased:args:1]
current-page:url:unaliased:value:node : [current-page:url:unaliased:value:0]
current-page:url:unaliased:value:0 : [current-page:url:unaliased:value:0]
current-page:url:unaliased:value:1 : [current-page:url:unaliased:value:1]

```

Without modifying the module how would I get **\[node:nid\]** from within a Custom block?

# Answer
\[current-page:url:unaliased:args:value:1\]

gives you the \[node:nid\] even when called from a block.

As per:

https://www.drupal.org/node/1265010

..."\[current-page:url:unaliased:args:value:0\] (The first value, of the array of arguments, of the unaliased URL of the current page)."
> 1 votes

---
Tags: nodes, 8, tokens
---


title: Drupal 8 Title tag - head-placeholder

text:
# Question
Title: Drupal 8 Title tag - head-placeholder
I am using a custom theme with Stable as a base.

I am trying to figure out how to set the `<title>` tag and I'm having a hard time.

I noticed in `html.html.twig` there is the following:

`<head-placeholder token="{{ placeholder_token|raw }}">`

How does the page title find it's way into the above?

# Answer
> 1 votes
I found a way but I'm not sure if it's ideal:

```
function THEME_preprocess_html(&$variables) {
  $variables['head_title']['title'] = 'title here';
}

```

Logic can be added for each page:

```
$path = $current_path = \Drupal::service('path.current')->getPath();
if ($path === '...')

```

Then, in `html.html.twig`:

```
<title>{{ head_title.title }}</title>

```

instead of

```
<title>{{ head_title|safe_join(' | ') }}</title>

```

---
Tags: theming, 8
---


# Question
Title: how to give the same style as the back-office theme for people allowed on edition?
Allowing some roles to edit content, these people get the css from the front theme.

How to set to use the back-office theme for ?

```
 /admin/content

```

and

```
 /node/add/article

```

# Answer
Set the permission `View the administration theme` and make sure that the option `Use the administration theme when editing or creating content` is enabled on page `/admin/appearance`.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How to add select years and months select Drupal 8.1 date picker?
There is no configuration option available in the backoffice nor from configuration synchronisation variables that allows to edit the settings for the jQuery datepicker widget embed in core.

My question is: how to select years and months in Drupal 8 core's date picker widget ?

*By default years and months can only be changed by slowly navigating through adjacent months with left and right arrows.*

# Answer
From locating the core datepicker source code in core/modules/locale/locale.datepicker.js, I was able to inspect the $.datepicker object.

Then \_defaults settings can be altered in a custom javascript fil as easy as:

```
(function ($) {
    Drupal.behaviors.alterDatePicker = {
        attach: function (context, settings) {
            $.datepicker._defaults.changeMonth = true;
            $.datepicker._defaults.changeYear = true;
        }
    };
})(jQuery);

```

All datepicker settings are documented here: http://api.jqueryui.com/datepicker/#option-changeMonth
> 4 votes

# Answer
Here is @B2F's great & correct answer in complete(ish) module form:

**better\_datepicker/better\_datepicker.info.yml**

```
name: 'Better Datepicker'
type: module
description: 'select year and month on datetime fields'
package: "Date"
core: 8.x

#CSS & JS
libraries:
  - 'better_datepicker/better-datepicker'

```

**better\_datepicker/better\_datepicker.libraries.yml**

```
better-datepicker:
  version: 1.x
  js:
    js/better-datepicker.js: {}
  dependencies:
    - core/jquery
    #- core/drupalSettings

```

**better\_datepicker/better\_datepicker.module**

```
<?php

function better_datepicker_element_info_alter(array &$types) {
    if (isset($types['datetime'])) {
        $types['datetime']['#attached']['library'][] = 'better_datepicker/better-datepicker';
    }
}

```

**better\_datepicker/js/better-datepicker.js**

```
(function ($) {
    Drupal.behaviors.alterDatePicker = {
        attach: function (context, settings) {
            $.datepicker._defaults.changeMonth = true;
            $.datepicker._defaults.changeYear = true;
            // adjust year range
            $.datepicker._defaults.yearRange = "c-80:c+10";
        }
    };
})(jQuery);

```
> 1 votes

---
Tags: datetime, 8
---


# Question
Title: Inline entity form complex and cardinatlity
I am adding an ief type field to my form with the following

```
    $form['inline_entity_form'] = [
        '#type' => 'inline_entity_form',
        '#op' => 'add',
        '#entity_type' => 'my_ent_type',
        '#bundle' => 'my_bundle',
    ];

```

I am sure this is something under my nose that i am missing but how do i force this to complex and set a cardinality for this instance?

Grateful for any pointers Mathew

# Answer
> 3 votes
Try changing the **type** to `inline_entity_form_complex` so that you have the following;

```
$form['inline_entity_form'] = [
    '#type' => 'inline_entity_form_complex',
    '#op' => 'add',
    '#entity_type' => 'my_ent_type',
    '#bundle' => 'my_bundle',
];

```

Got the pointer from the following answer. https://drupal.stackexchange.com/a/207582/9906

---
Tags: 8, entities
---


# Question
Title: Should we use drupal_exit() after drupal_goto()?
I think, drupal\_goto() breaks the execution so next lines of code won't execute after `drupal_goto()`, Am I right? Somebody recommended me to use drupal\_exit() on the next line of the `drupal_goto()`.

Is it necessary? Will the code after `drupal_goto()` execute ?

Please guide me.

# Answer
> Will the code after drupal\_goto() execute ?

No - the last line of `drupal_goto()` is:

```
drupal_exit($url);

```

So the script will already have terminated without returning, and no subsequent code will execute.

You can safely ignore that recommendation.
> 3 votes

---
Tags: 7
---


# Question
Title: Region for the footer not working, but the header is working
I have the following regions set up in my \*.info.yml file:

```
name: Test
type: theme
description: 'Theme'
base theme: stable
core: 8.x
regions:
  header: 'Header'
  content: 'Content'
  footer: 'Footer'
libraries-override:
  system/base: false

```

In `page--front.html.twig`, I placed `{{ page.header }}` where I wanted the header to be, and noticed via Twig Debugging that Drupal was expecting a file named `region--header.html.twig`. Great!

So, similarly, I did this for the footer.

`{{ page.footer }}` and `region--footer.html.twig` ... but it does not work! Twig Debug's comments do not reveal any hook for the footer at all.

What am I doing wrong?

# Answer
> 3 votes
Regions are only rendered by default if they contain blocks (of which at least one must have content).

You can check whether the *Footer* region has blocks assigned to it by visiting the Block Layout admin page at /admin/structure/block. If you see the *No blocks in this region* message under the *Footer* block, you know that's the problem.

---
Tags: 8, theming
---


title: How do I make a submit through AJAX?

text:
# Question
Title: How do I make a submit through AJAX?
I created a webform in Drupal 8. While submitting the form, it reloads the whole page, even I had selected inline submission in confirmation message.

# Answer
Just checked your issue by upgrading Webform to version 8.x-5.0-beta15. After enabling AJAX on the form and setting the confirmation to either `inline` or `message` the confirmation worked as expected. I did needed to clear my cache though.

So try upgrading the Webform module and clear your cache.
> 0 votes

---
Tags: 8, ajax, webforms
---


title: How to add content to a block?

text:
# Question
Title: How to add content to a block?
I have created a few blocks via `/block/add` and assigned these blocks to various regions defined in my theme.

How am I able to add content to these blocks?

# Answer
If blocks are added via `/block/add` you can edit the block content via `/admin/structure/block/block-content`. Click on `Edit` and you should see a body text area appear. You can enter your block content there.
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: How to be able to use a content once in a content field?
I created a field in to a content. Let's call the content type **National Anthem** and the field **Country**. **Country** is a content type too.

What I'd like to do is to forbid the use of a country which has been chosen already. * For example, let's say that we have the country *Germany*, *France* and *United-Kingdom*. If I create a new **National Anthem** and for the field **Country**, I choose *United-Kingdom*. I now create a new **National Anthem** and I can only choose between *France* and *Germany*.

Thank you.

# Answer
Assuming you are using an entity reference (default reference in Drupal 8, and provided by the Entity Reference module for Drupal 7). You can do this with an entity reference view:

Create a new view that lists *content* of type *Country*. Then take the following steps:

1. Make sure to add a new *Entity Reference* Display.
2. Enable the *title field* as *Search field* in the formatter settings. (Behind drop down menu.)
3. Add a relation of type *Content using field\_country*.
4. Filter content that has no value for *ID* using the relationship.
5. (optional), if you reference country from more content types than *National Anthem*, filter also for the *Content type* to be of *National Anthem*; again using the relationship.

This view will select all countries, which are used on nodes with no ID. (Thus are not referenced.)

Finally, make sure you enable the view in the content type's field settings:
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: How to use dependency injection for Plugins/Blocks [\Drupal::formbuilder() and \Drupal::config()]?
I cannot get my head around this dependency injection theory. How are we supposed to get the below methods aligned with dependency injection?

```
\Drupal::routeMatch()->getParameter('node');
\Drupal::request();
\Drupal::formBuilder()->getForm('Drupal\enquirycart\Form\EnquiryForm');
\Drupal::config()

```

Here is a class that I need to fix this warning message when viewed in https://pareview.sh/

> "\Drupal calls should be avoided in classes, use | | dependency injection instead"

```
    class EnquirycartBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $default_config = \Drupal::config('enquirycart.settings');

    return [
      'label_display' => FALSE,
      'enquiry_email' => $default_config->get('enquirycart.email'),
    ];

  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $builtForm = \Drupal::formBuilder()->getForm('Drupal\enquirycart\Form\EnquirycartButtonForm');
    $renderArray['form'] = $builtForm;

    return $renderArray;

  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form_new = parent::blockForm($form, $form_state);

    return $form_new;

  }

```

# Answer
> 18 votes
For future reference, from the link by @Kevin:

> The key to making plugins use dependency injection is to implement the ContainerFactoryPluginInterface. When plugins are created, the code first checks if the plugin implements this interface. If it does, it uses the create() and \__construct() pattern, if not, it uses just the \__construct() pattern. - From Acquia's Lesson 11.4 - Dependency injection and plugins

The example code below is written by Mart Matsoo from Chromatic. Please check the full article here: https://chromatichq.com/blog/dependency-injection-drupal-8-plugins. As @Kevin already mentioned in the comments it is a great article about Depencency Injection in Plugins.

**Dependency Injection example in a block**

Note the injection of the 'current\_user' service via `$container->get('current_user')` in the `create()` method. You can pass extra services there.

```
<?php

namespace Drupal\heytaco\Plugin\Block;

use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Hey Taco Results Block
 *
 * @Block(
 *   id = "heytaco_block",
 *   admin_label = @Translation("HeyTaco! Leaderboard"),
 * )
 */
class HeyTacoBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * @var $account \Drupal\Core\Session\AccountProxyInterface
   */
  protected $account;

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   *
   * @return static
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

  /**
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   * @param \Drupal\Core\Session\AccountProxyInterface $account
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
  }

```

**Dependency Injection example in a controller**

The same concept applies here, pass extra services via `$container->get()` in the `create()` method.

```
<?php

namespace Drupal\heytaco\Controller;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for HeyTaco! block.
 */
class HeyTacoController extends ControllerBase {

  protected $account;

  public function __construct(AccountInterface $account) {
    $this->account = $account;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }

```

# Answer
> 3 votes
Thanks to @kevin, I managed to get this DI working as i wanted. If anyone wants to check the core services follow the link below.

All the services are listed in the core API https://api.drupal.org/api/drupal/core%21core.services.yml/8.3.x

Just Posting an example class where it used all the \Drupal services i mentioned in the question. here's how you do it.

```
namespace Drupal\enquirycart\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Routing\CurrentRouteMatch;

class EnquirycartBlock extends BlockBase implements BlockPluginInterface, ContainerFactoryPluginInterface {

    /**
     * @var  \Drupal\Core\Form\FormBuilderInterface $formbuilder
     */
    protected $formbuilder;

    protected $configfactory;

    protected $routematch;

    protected $requestmatch;

    /**
    * @param array $configuration
    * @param string $plugin_id
    * @param mixed $plugin_definition
    * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
    */
    public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder, ConfigFactoryInterface $config_factory, CurrentRouteMatch $route_match, RequestStack $requestdi) {
        parent::__construct($configuration, $plugin_id, $plugin_definition);

        $this->formbuilder = $form_builder;
        $this->configfactory = $config_factory;
        $this->routematch = $route_match;
        $this->requestmatch = $requestdi;
       /*  dpm($this->configfactory->get('enquirycart.settings'));
         dpm($this->routematch->getParameter('node')->getTitle());
         dpm($this->requestmatch->getCurrentRequest()->getSession()->get('enquire'));*/
    }

   /**
   * {@inheritdoc}
   */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
       return new static(
            $configuration,
            $plugin_id,
            $plugin_definition,
            $container->get('form_builder'),
            $container->get('config.factory'),
            $container->get('current_route_match'),
            $container->get('request_stack')
          );
    }

}

```

---
Tags: 8, forms, blocks, dependency-injection
---


# Question
Title: Views slideshow with multi value imagefield
I have created a content type and added an image field with unlimited option. Now I want to setup a views slideshow. Some nodes have single whereas others have multiple images. So my slideshow should show single image as well as all the images if the node has multiple images grouped together.

# Answer
Try field slideshow. It bypasses views entirely, which makes it easy when all your images are in one node.

I don't think it works with the media module, yet, and you have to set your field type has to be "image". You select the slideshow options in the display fields portion.
> 3 votes

# Answer
jags, if you are using the Media module, this might be what your looking for: http://drupalmedia.freeworldmedia.nl/book/howtos-guides/how-use-views-slideshow-and-media-2x-module-create-slideshow

True, it's actually for the 2.x version that's still in development, but it offers a lot of information that's also still kinda valid for Media 1.x.

You can group images together in Views, edit the Image field in Views, you'll see an option for 'multiple values'. That's where you can define this.
> 1 votes

# Answer
In your view, navigate to the image field \> Multiple field settings and check **Display all values in the same row**. Then for those nodes that has single image, it'll show one. For those nodes that have multiple images, it'll show all of them.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to display a view on a customize way?
I've searched similar questions but I'm not sure to have understood how to do it. I would like to create a page for the team of my website. I have several blocs: administrators, moderators, etc.

I'd like to display in a left column the member avatar and on the right, I want to display all the rest of the data such as the nickname, a short description, etc.

If you have any tips on how to search on Stack Exchange, I'd gladly accept the information.

# Answer
> 0 votes
Yes, Panels is what you're looking for. Panels, in a gist, is similar to how the core Structure -\> Block Layout works, except it's more powerful. You use it in conjunction with Page Manager, a submodule of Ctools (if I remember correctly) which lets you create one-off pages as well as override how core pages render. This post will explain what which does.

In summary, the workflow would be like this:

1. Create a content type for your members. Populate it with fields for the data.
2. Enable both Panels and Page Manager
3. Go to Structure -\> Pages and enable the Node View page (the one with the `/node/%` path)
4. Edit the Node View page and add a *variant* \- a config for what to render where, when and how when on the page's path.
5. Configure the variant to render when viewing the content type. I think that's under Selection, then add a Type criteria matching the content type.
6. Configure the layout of the variant. By default, there's a 1-column layout available. You can use Display Suite to provide more layouts or you can write your own.
7. Configure the contents of the variant. Here's where the magic happens. You can virtually add *anything* to the layout. Views, blocks, fields, nodes, entire pages, anything. In this case, position the fields of the content type into where you want them.

That's a quick rundown of how to use Panels. And all of this happens with minimal to no coding at all (except if you create your own layout and/or add a sprinkle of CSS so things don't look very Drupal-y).

---
Tags: views, blocks
---


# Question
Title: Where in the page generation pipeline can an HTML beautifier be placed?
I need to view the HTML generated by Drupal and it is pretty hard. If I want to the final output to be put through an HTML beautifier before sending it off to the client where would I do that?

I am sure some of the page optimization utilities on the `admin/config/development/performance` or the `advagg` module are at the right place in the pipeline. What stage or APIs would I have to hook into to accomplish something this?

Are there any APIs which can be hooked into to accomplish this or even modules to this?

# Answer
> 1 votes
Yes, in advagg is a good example, you have to get the response content with `$response->getContent()` in a response subscriber http://cgit.drupalcode.org/advagg/tree/src/EventSubscriber/ResponseSubscriber.php?h=8.x-3.x

```
  public function onResponse(FilterResponseEvent $event) {
    // Only care about HTML responses.
    if (stripos($event->getResponse()->headers->get('Content-Type'), 'text/html') === FALSE) {
      return;
    }

    $response = $event->getResponse();
    $html_markup = $response->getContent();
    // modify html markup
    $response->setContent($html_markup);
  }

```

---
Tags: 7
---


title: How to use cck time field in rules?

text:
# Question
Title: How to use cck time field in rules?
I'm using a cck\_time field (field\_check\_in) in my content type. I want create a notify when this field is changed but when I try to set **Data comparition** in **Rules Conditions** I not find the entity of the field (\[node:field-check-in\]). How I can do it?

# Answer
> 1 votes
Below is a sample of a rule (in Rules export format) that will send an eMail similar to what is asked in the question:

```
{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_check_in" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-check-in" ],
          "value" : [ "node:field-check-in" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:current-user:mail]",
          "subject" : "Notification about a node with an update field_check_in value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with an updated value (which is [node:field-check-in]) you wanted to be informed about ..."
        }
      }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules event I'm using is "After updating existing content".
* It's about updates to the field `field_check_in`.
* The Rules Condition checks if the "The value changed".
* If the Rules Condition is true, then (as Rules Action), an eMail will be triggered to the editing user.

Adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the Rules UI). That's it.

**Note**: I'm assuming this is about D7.

# Answer
> 0 votes
Try to use a condition: `Entity has field` and select the field you wish to check.

Then do the data comparison.

---
Tags: rules, entities, datetime
---


# Question
Title: Paragraph module won't install or uninstall
I installed the paragraph module from https://www.drupal.org/project/paragraphs specifically the dev version `8.x-1.x-dev tar.gz (118.62 KB) | zip (210.83 KB) 2017-Jun-28` it installed ok but now as you can see in the tab, I am unable to check the checkbox to activate the module, it says some files are missing... I should have downloaded the stable version but I didn't know a module would be hard to remove once added.

this is the screenshot

I went to `/admin/modules/uninstall` searched for this module but it's not there, and if I want to install a stable version from a zip file it says the module is already installed.

Usually on something like this, I would remove the file from `drupal\modules\paragraphs` however, I am not sure if this module has saved some configs in the database which will be left to stay if I physically remove the module by deleting it

# Answer
> The module is not installed, so can't be uninstalled.

To install you need to download/install its dependencies too, foremost the entity\_reference\_revision module.
> 4 votes

---
Tags: 8
---


# Question
Title: Why can't I output the style tag in my twig template?
I'm desperately trying to render a style attribute, inside a paragraph's template. But all of these variations:

```
{%
  set backgroundUrl = content.field_slider_background|render|naked|replace({' ': '', "\\n": '', "\\r": ''})
%}

<div class="wrapper">
  <div class="background-item" style="background-image: url({{ backgroundUrl }});">

```

,

```
{%
  set backgroundAttributes = create_attribute()
%}

<div{{ backgroundAttributes.addClass('background-item').setAttribute('style', 'background-image: url(' ~ backgroundUrl ~ ')') }}>

```

and even:

`<div class="background-item" style="z-index: 0;">`

and

`<div class="background-item" {{ 'style="...' }}>`

just return `<div class="background-item">`. Other tags are fine.

Does twig generally strip style tags?! Using the latest D8 version...

Edit: outputting `backgroundUrl` actually gives me the correct string, so writing a tag like `data-test="{{ backgroundUrl }}"` works nicely

# Answer
I've done it to print a background color like this in a paragraph template

```
<div class="container color-{{ content.field_text_color[0] }}" style="background: #{{ content.field_card_color[0] }};">

```

And it just worked fine. Can you give us the full template maybe we can figure out why it doesn't work.
> 2 votes

---
Tags: theming, 8, paragraphs
---