# Question
Title: Why isn't this Config API Code saving options?
I can see the form, using the Config API, and submit it. However, it doesn't save the changes. Here is my code:

```
    <?php

namespace Drupal\my_config\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class MyConfigForm extends ConfigFormBase {

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

  protected function getEditableConfigNames() {
    return [
      'my_config.config',
    ];
  }

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

    $form['author_config'] = array(
      '#type' => 'textfield',
      '#default_value' => \Drupal::config('config.factory')->get('author_config'),
      '#title' => 'Author of Config',
      '#required' => TRUE,
    );
    $form['language'] = array(
      '#type' => 'radios',
      '#title' => 'Language',
      '#options' => array(
        'EN' => t('English'),
        'SP' => t('Spanish'),
        'FR' => t('French'),
        'DE' => t('German'),
      ),
    );
    $form['drink'] = array (
      '#type' => 'select',
      '#title' => 'Select your drink',
      '#options' => array(
        'RB' => t('Root Beer'),
        'SD' => t('Sunny Delight'),
        'WR' => t('Water'),
        'OJ' => t('Orange Juice'),
      ),
    );
    return parent::buildForm($form, $form_state);
  }

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

    \Drupal::service('config.factory')->getEditable('my_config.config')->set('author_config', $form_state->getValue('author_config'))
     ->set('language', $form_state->getValue('language'))
         ->set('drink', $form_state->getValue('drink'))->save();
    parent::submitForm($form, $form_state);
  }

}

```

This is my routing file:

```
my_config.settings:
  path: '/my-config/config'
  defaults:
    _form: '\Drupal\my_config\Form\MyConfigForm'
    _title: 'Configuration Form'
  requirements:
    _permission: 'administer site configuration'

```

# Answer
This is wrong:

```
'#default_value' => \Drupal::config('config.factory')->get('author_config'),

```

It should be:

```
'#default_value' => \Drupal::config('my_config.config')->get('author_config'),

```

This is the entire form:

```
$form['author_config'] = array(
  '#type' => 'textfield',
  '#default_value' => \Drupal::config('my_config.config')->get('author_config'),
  '#title' => 'Author of Config',
  '#required' => TRUE,
);
$form['language'] = array(
  '#type' => 'radios',
  '#title' => 'Language',
  '#default_value' => \Drupal::config('my_config.config')->get('language'),
  '#options' => array(
    'EN' => t('English'),
    'SP' => t('Spanish'),
    'FR' => t('French'),
    'DE' => t('German'),
  ),
);
$form['drink'] = array(
  '#type' => 'select',
  '#title' => 'Select your drink',
  '#default_value' => \Drupal::config('my_config.config')->get('drink'),
  '#options' => array(
    'RB' => t('Root Beer'),
    'SD' => t('Sunny Delight'),
    'WR' => t('Water'),
    'OJ' => t('Orange Juice'),
  ),
);

```

Probably using $this-\>config the problem will be solved too
> 1 votes

---
Tags: 8, forms
---


# Question
Title: $form_state->setRedirect not working after a $form_state->setResponse
In the `submitForm` of a custom form, I have this:

```
$sFileName = 'sites/default/files/_private/bulletins/' . $form_state->getValue('adherent')[1] . ".pdf";
$response = new BinaryFileResponse($sFileName);
$response->setContentDisposition(
  ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  'bulletin.pdf'
);
$form_state->setResponse($response);

```

This triggers the download of a pdf document and it works.
Then, I try to execute:

```
$form_state->setRedirect('<front>');

```

and that is not working!
In `FormState::setResponse` documentation, I read « If a response is set, it will be used during processing and returned directly. The form will not be rebuilt or redirected ».
I guess it is why my redirection to doesn't work...

How can I do it anyway?

# Answer
short answer RedirectResponse;

```
use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('/where-ever');
$response->send();

```
> -1 votes

---
Tags: 8, forms
---


# Question
Title: How can I get rid of Contribute 8.x-5.0-beta3 module?
What's wrong with Contribute 8.x-5.0-beta3 module?

After 8.6.10 update I have a problem with Contribute module. First it's marked as outdated/not supported but on some sites I can not remove it fully as it lefts something in the db.

So finally I get the errors like

```
"The following module is missing from the file system: block_user bootstrap.inc:276"

```

even after the

```
drush pm:uninstall

```

It's a composer managed install.

# Answer
> 1 votes
Always you have to first uninstall the module, then remove the codebase from filesystem.

Composer have nothing to do with installing or uninstalling of modules in drupal. Composer is responsible for downloading the needed files, or removing if not longer in use.

If you first remove the files from the filesystem, you cannot uninstall it properly, because drupal not knows what to do. Therefore you see such errors about missing things.

What can you do now to get rid of this error if such happen:

1. Go one step back & put missing files back to filesystem.

* If you use git, checkout your last composer.lock before this error, than type `composer install` to get the old module files back.
    * Or use your backup or your ftp-program to bring the module files back.
2. Now you can uninstall the module as you like, perhaps using the gui or with drush (typing `drush pmu modulename`). This step is important, because it removes all things installed by this module. If you skip this, you will get such errors.
3. Now delete unwanted module files again:

* checkout your newest state of composer.lock (without that module)
    * and type `composer install` and composer will remove the unwanted files
4. Don't forget to clear the cache. (`drush cr`)

# Answer
> 0 votes
Drupal 8.6.11 update solved the problem. After the update the Contribute module was removed as it should be.

---
Tags: installation
---


# Question
Title: Can not update drupal/core with composer
Can not update drupal/core to 8.6.11

```
composer prohibits drupal/core:8.6.11

```

shows

```
webflo/drupal-core-require-dev  8.6.10  requires  drupal/core (8.6.10)

```

How can I solve it ??

# Answer
The trick is, that drupal/core and webflo/drupal-core-require-dev always have to point to the very same version.

If you use `composer update` composer will look for this and pull the needed actual versions alone.

There are some articles recommending not to do so, but instead to update in minor parts and specify a concrete packet for better testing and reverting possibilities if something goes wrong. This means typing:

`composer update drupal/core --with-dependencies`

This may be true, but I often run in such errors with dependencies then I have to solve myself. You have now to specify both packets in the same command, then it will work too:

`composer update drupal/core webflo/drupal-core-require-dev --with-dependencies`

My private conclusion:

* If I have time to go the suggested way and solve such dependencies, than I will specify the single packet to update.
* If it makes problems and I have an actual backup of my codebase and my database (as you should alwas have before updating anything!) and have not so much time, I simple type `composer update` and mostly all will work out of the box at the first try.
> 2 votes

# Answer
Simple

```
composer update

```

did the trick by have no idea why

```
composer update drupal/core --with-dependencies

```

did not ...

final result is:

```
  - Updating drupal/core (8.6.10 => 8.6.11): Downloading (100%)
  - Updating webflo/drupal-core-require-dev (8.6.10 => 8.6.11)

```
> 1 votes

---
Tags: composer
---


# Question
Title: Why are my if/else statements in page.html.twig ignored?
in my theme template of page.html.twig (theme is a subtheme of classy core theme), my if statements to render a region or not are completely ignored by twig template engine. The regions (e.g. the first sidebar are always rendered.

**Code of my page.html.twig:**

```
  <header role="banner">
    {{ page.header }}
  </header>

  {{ page.primary_menu }}
  {{ page.secondary_menu }}

      {% if page.navigation %}
      <nav class="layout-navigation" role="navigation">
        {{ page.navigation }}
      </nav>
    {% endif %}

  {{ page.breadcrumb }}

  {% if page.system_messages_area %}

    {{ page.system_messages_area }}

  {% endif %}

  {{ page.highlighted }}

  {{ page.help }}

  <div id="main-wrapper">
    <main role="main">
      <a id="main-content" tabindex="-1"></a>{# link is in html.html.twig #}

      <div class="layout-content">
        {{ page.content }}
      </div>{# /.layout-content #}

      {% if page.sidebar_first %}
        <aside class="layout-sidebar-first sidebar" role="complementary">
          {{ page.sidebar_first }}
        </aside>
      {% endif %}

      {% if page.sidebar_second %}
        <aside class="layout-sidebar-second sidebar" role="complementary">
          {{ page.sidebar_second }}
        </aside>
      {% endif %}

    </main>
  </div>

  {% if page.footer %}
    <footer role="contentinfo">
      {{ page.footer }}
    </footer>
  {% endif %}

```

**Code of my theme.info.yml:**

```
name: mytheme
type: theme
description: Based on classy core base theme.
core: 8.x
# Defines the base theme
base theme: classy
# Defines libraries group in which we can add css/js.
logo: logo.png
libraries:
  - mytheme/global-styling
# Regions
regions:
  header: Header
  navigation: Navigation and Menus
  system_messages_area: Area for system messages
  highlighted: Featured
  help: Help
  content: Content
  sidebar_first: First sidebar
  sidebar_second: Second sidebar
  footer: Footer

```

Maybe someone could help me to find the mistake, as far as I can see everything is at it's right place.

Thanks in advance

Best regards phil

# Answer
I would check, if the page render-array contains the element sidebar\_first. You can do this with

`{{ dump( page|keys) }}`

in your page.html.twig (or use devels kint function for that). The |keys filter will prevent you from memory overflow if your page is big.

If this is the case, then your template is ok and you don't have to look at twig, but to search, what else is in the render array and where it could be originated.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Upon submitting a webform, set a date field on the article node equals to "current time" + "X minutes"
I am using the Field Timer module to display countdown timer on my article node.

This module will take the value of the date/time field (my case: field\_article\_datetime) and convert it into a countdown timer in the display of the article.

I have a webform (machine name: ABC) attached as a field to the **article** content type so I can use `[webform_submission:node:nid]` to retrieve the **article nid** of the article to be updated.

The webform (machine name: ABC) has below element:

1) **Select** element (machine name: increase\_time\_in\_minutes):

1. Text: Increase by 15 minutes (Value: 15)
2. Text: Increase by 30 minutes (Value: 30)
3. Text: Increase by 45 minutes (Value: 45)

And the article content type has below field:

1. date/time field (machine name: field\_article\_datetime) (the Field Timer module is applied to this field)

When the webform "ABC" is submitted, I want to:

1. Fetch the article nid (`[webform_submission:node:nid]`)
2. Set the value of the date/time field (field\_article\_datetime) equal to **current time + increase\_time\_in\_minutes**

**EXAMPLE:**

Say at **14/03/2019 08:30:15 PM**, a user has submitted the webform "ABC" and selected **Increase by 15 minutes** option from the select list... So I need the related article to be fetched and update the (field\_article\_datetime) to have the value of **14/03/2019 08:45:15 PM**

This way, the user will see a countdown timer for 15 minutes on the article node display page.

---

I am not a programmer, but I think the best Idea is to use a customwebformhandler.php file which will be enabled for the webform settings page.

I have created the file but I need help to finish it:

```
<?php

namespace Drupal\my_module_extras\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Update a node entity from a webform submission.
 *
 * @WebformHandler(
 *   id = "Update a node",
 *   label = @Translation("Update a node"),
 *   category = @Translation("Entity Update"),
 *   description = @Translation("Updates a node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class SetTimerOnNodeWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Fetch & Update node object from webform-submission.
    //get current node or use any other way to get the current node
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
    $current_time = \Drupal::time()->getCurrentTime();
    date_default_timezone_set('GMT');

    //get value from webform
    $increase = $values["increase_time_in_minutes"];

    //calculate new time
    $timer = date('Y-m-d\TH:i:s', $current_time + $increase * 60);

    //add it to article field and save
    $node->field_article_datetime->value = $timer;
    $node->save();
  }
}

```

}

**Update #2:** The below error is generated because of one missing `}` at the end of the file. (Stupid mistake)

**Update #1:** Error logged in in the dblog after trying to add the webformhandler.php file to the webform:

```
ParseError: syntax error, unexpected end of file, expecting function (T_FUNCTION) or const (T_CONST) in Composer\Autoload\includeFile() (line 59 of S:\######\dev.####\web\modules\custom\my_module_extras\src\Plugin\WebformHandler\SetTimerOnNodeWebformHandler.php) #0 S:\######\dev.#####\vendor\composer\ClassLoader.php(322): Composer\Autoload\includeFile('S:\\###### ...') #1 [internal function]: Composer\Autoload\ClassLoader->loadClass('Drupal\\my_module...') #2 [internal function]: spl_autoload_call('Drupal\\my_module...') #3 S:\#######\dev.#####\web\core\lib\Drupal\Component\Plugin\Factory\DefaultFactory.php(96): class_exists('Drupal\\my_module...') #4 S:\#######\dev.#####\web\core\lib\Drupal\Core\Plugin\Factory\ContainerFactory.php(17): Drupal\Component\Plugin\Factory\DefaultFactory::getPluginClass('Update a node', Array, 'Drupal\\webform\\...')

```

# Answer
> 2 votes
Use this as your `submitForm`

```
$values = $webform_submission->getData();

//get current node or use any other way to get the current node
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $current_time = \Drupal::time()->getCurrentTime();
  date_default_timezone_set('GMT');

  //get value from webform
  $increase = $values["increase_time_in_minutes"];

  //calculate new time
  $timer = date('Y-m-d\TH:i:s', $current_time + $increase * 60);

  //add it to article field and save
  $node->field_article_datetime->value = $timer;
  $node->save();
}

```

The answer asumes that you have included the webform as a block for article content types. Another possibility is to include the webform as field and it should work exactly the same.

NOTE: before the webform handler works you have to enable your custom module and than go to your webform `settings > email/handlers` and include your handler

---
Tags: 8, webforms, datetime
---


# Question
Title: How do I programmatically set the preferred language for a user?
I would like to update the preferred\_langcode of a user as soon as he changes the language in a language switcher block.

I'm already aware of the `getPreferredLangcode` method mentioned in https://api.drupal.org/api/drupal/core!modules!user!src!Entity!User.php/function/User%3A%3AgetPreferredLangcode/8.6.x and looking for a `setPreferredLangcode` method, if one exists.

If not, what other options do I have?

# Answer
> 4 votes
Seems D8 doesn't have a `setPreferredLangcode` method yet. So, the preferred approach IMHO would be to use the default `set` method of D8 Entity API as below

```
$user = \Drupal\user\Entity\User::load('uid');
$user->set('preferred_langcode', 'en or whatever langcode we want');
$user->save();

```

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


# Question
Title: Rewrite query string for exposed taxonomy filter
I have this page: https://www.meubelentheo.be/catalogus

On the top of this page, just below the title you will see links such as Babykamer, Bureau, Decoratie etc.

These are taxonomy terms in an exposed filter. I use the Views module together with Better exposed filter.

If you click on the first term Babykamer, you will see the URL changes to https://www.meubelentheo.be/catalogus?field\_portfolio\_tags\_tid=34

What I want to achieve: rewrite the part after the ? to something like `?term=babykamer` or even better, rewrite the whole querystring to `catalogus/babykamer`

I tried the Query paramters to URL module and this indeed rewrites the URL to but this is not what I want. I want the taxonomy term name to be shown in the URL.

Any ideas?

# Answer
You can accomplish this look by using Contextual Filters instead of an exposed filter in Views. But this approach will involve several changes. In a nutshell you would need to:

1. The list of tags on top would need to be a different (taxonomy) Views, embedded in the Header area of your catalogus View using `Global: View area`. In the taxonomy view, you will need to rewrite the output of the Taxonomy field (use "Rewrite results" in the taxonomy field) to a link that points to `/catalogus/[field_portfolio_tags]`
2. Add a Contextual Filter to your catalogus View. Be sure to add the taxonomy field `Portfolio tags` to the list of fields in this View (you can hide it if you don't want it to display for every single product). Choose the taxonomy `Content: Portfolio tags`. Choose **Display all results** in **When filter value is not in URL**. In **WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED** choose **Specify validation criteria**. Validator: taxonomy term. Filter value type: term name converted to Term Id.

When you click on a taxonomy term in the embedded header View you will be redirected to /catalogus/name\_of\_tag. The Contextual Filter will assure that only products with that tag will be shown.

This should be it!
> 3 votes

# Answer
The use case "Filter my view results with the Term Name in my url" we are discussing here can easily be achieved with "Contextual filter by term ID" + the very old, stable and light "URL alias" feature. Easier and faster.

Please do note also on Drupal 8 this is even more complicated (follow on Druapl.org)

Url alias will make you work easier on both D8 and D7
> 0 votes

---
Tags: views, taxonomy-terms, uri
---


# Question
Title: How do I get the value submitted for a form element?
I have a custom form for emails with the following form element.

```
$form['type'] = array(
  '#title' => t('TYPE DE SOIN SOUHAITÉ'),
  '#type' => 'select',
  '#options' => array("Choisissez le type de soin ou offrez un cadeau",
      "Entrees Spa","Soins du visage","Massage", "Soins Duo","Soins du corps","Offres speciales","Invitation cadeau"),
);

```

When I try to get the value submitted from the users, I get the array index of the chosen option, not the option string. For example, if the selected value is *Soins Duo*, I get 4 as submitted value?

# Answer
> 0 votes
That happens because the array you are passing for #options is the following one.

```
array(
  0 => "Choisissez le type de soin ou offrez un cadeau",
  1 => "Entrees Spa",
  2 => "Soins du visage",
  3 => "Massage",
  4 => "Soins Duo",
  5 => "Soins du corps",
  6 => "Offres speciales",
  7 => "Invitation cadeau"
)

```

Drupal uses the array index as selected value, and the array value as string to show for the form element. 4 is the array index for `"Soins Duo"`.

If you want the value to be a string too, you need to use the following code, for that form element.

```
$form['type'] = array(
  '#title' => 'TYPE DE SOIN SOUHAITÉ',
  '#type' => 'select',
  '#options' => drupal_map_assoc(array("Choisissez le type de soin ou offrez un cadeau",
      "Entrees Spa","Soins du visage","Massage", "Soins Duo","Soins du corps","Offres speciales","Invitation cadeau")),
);

```

As side note, the literal string passed to `t()` needs to be in English. If you are using another language, it is better not to use `t()` at all, since it only translates from English to the language set for the site. Better, you use `t()` with an English string, and use the Drupal translation system to get the site in the language you prefer.

# Answer
> 0 votes
If it is a Drupal 7 field, maybe you can try this:

```
$field = field_info_field('field_replace'); //replace for your field_name
$label = $field['settings']['allowed_values'][$key]; //$key is the value of your "type"

```

---
Tags: 7, forms
---


title: Custom Entity Type and Bundle Creation

text:
# Question
Title: Custom Entity Type and Bundle Creation
I've been building custom entities for a while now, but have been using the entity construction kit (eck) to build them. This has limitations as it requires you to #1 depend on the package for new installs, and #2, wrap your entities into a feature and hope there aren't conflicts later.

I would like to get into the world of building out the entity types programatically, on module install, as well as removing them on module uninstall.

I was recently diving into an ECK created entity I made that I exported into a feature, and it looks like the feature for the entity type is in the correct format for if you were to programatically create the entity. I have been trying to learn by looking at documentation on how to build a custom fieldable entity (with bundle) for a while, but all the documentation I have found has either been inconsistent, or spread all over the place making it difficult to follow.

My question is, could I in theory copy the `field_instance.inc`, `field_base.inc`, and the `features.inc` (where the entity is defined at), and plug that into my modules `hook_install()` and create my entity inside of the install file, instead of having to rely on ECK and features? I should note that I am also using the conditional\_fields module so that I can dyanmically show/hide certain fields inside of this entity and save time on building my own ajax functionality, so I would probably need to build the entity out so that the fields can be updated from the Fields UI if needed (but usually they'll be updated in `hook_update_N`.

# Answer
After some research and some helpful suggestions from another user, I ended up taking a look at the core modules `user` and `node` and got a pretty good understanding how to make base entities and attach fields to them. I suggest anybody who is stuck trying to figure out how to do it do the same as once you see it in live working code it's pretty easy to understand.
> 0 votes

---
Tags: entities, hooks
---


# Question
Title: How to remove the form_state, form_id and form_build_id when submitting a form?
I have been creating a payment gateway integration module for Drupal 7.

When I post the form to the payment gateway API, it is posting extra variables like `form_id`, `form_build_id`, and `form_token`.

Can anybody tell me a way to eliminate these extra variables?

# Answer
> 1 votes
In Drupal 7, you can use the `form_state_values_clean()` function that removes:

* **`form_id`**
* **`form_token`**
* **`form_build_id`**
* `op`

Usage example:

```
<?php
/**
 * Let's say this is your form.
 */
function your_form($form, &$form_state) {
  // Form items go here.

  // Let's add the form actions element...
  $form['actions'] = array(
    '#type' => 'actions',
  );

  // ...and the form submission button with a function callback that removes
  // 'form_id', 'form_token', 'form_build_id' and 'op' values upon form submit.
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('your_form_submit'),
  );
}

/**
 * And this is the submission handler/callback for your form where
 * 'form_id', 'form_token', 'form_build_id' and 'op' values will be removed.
 */
function your_form_submit($form, &$form_state) {
  // Let's unset 'form_id', 'form_token', 'form_build_id' and 'op'.
  form_state_values_clean($form_state);

  // Now the $form_state['values'] doesn't contain 'form_id', 'form_token',
  // 'form_build_id' and 'op'.
  $form_values = $form_state['values'];

  // Do the rest…
}

```

# Answer
> 0 votes
I would create a form handler and submit the results via AJAX.

Meaning, take your form, submit it and take the response and parse it for the information you are interested in packaging it up and sending it off as an AJAX request to your payment gateway API.

As Ayesh said, these are important parts of the form and are not intended to be left out.

---
Tags: commerce, payment-gateways
---


title: Two different editor in one content typ

text:
# Question
Title: Two different editor in one content typ
is there a way in drupal 8 to use two different editors (CKeditor with two different buttonpanels or two differently allowed html tags) in one content type?

I have created a content type of a text field (body) and with the module paragraph other text fields are created. the user should use the possibilities in the body field of pictures and tables but in the text fields of paragraph the user should not be allowed to do so.

I have now created two different editors but the user can always switch between the editors. How can I determine that only one editor can be used in the body field and only the other one in the remaining text fields? many thanks for your help! s-webz

# Answer
> 1 votes
You probably need the module https://www.drupal.org/project/allowed\_formats.

> Limit which text formats are available for each field instance.

---
Tags: 8, paragraphs
---


# Question
Title: Create config object with array containing key-value pairs
We have a custom module, `mymodule`, that we want to use to create a config object for so that it can contain an array of `key-value` pairs. We need to be able to click button `Add More` on the form that will add more `key` and `value` fields that will be mapped together.

**How can we create a form that would not only display existing `key-value` pairs, but also provide option to add more?**

Goals:

1. On the admin Form, `MyModuleForm` be able to see existing `key-value` pairs.
2. Add more `key-value` pairs.
3. `Key` and `value` are text fields.
4. Use the `config_object` within the `mymodule.module` file and fetch all the `key-value` pairs.

Below is what we tried, but got stuck on how to add the `Add more` functionality and how to properly store `customKey` and `customValue` into an `array`.

**MyModuleForm.php**

```
class MyModuleForm extends ConfigFormbase {
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'mymodule.settings'
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mymodule_settings';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('mymodule.settings');
    $form['customKey'] = [
      '#title' => $this->t('Key value for array.'),
      '#type' => 'textfield',
      '#default_value' => $config->get('customKey'),
      '#maxlength' => 255,
      '#required' => TRUE,
    ];
    $form['customValue'] = [
      '#title' => $this->t('value for array.'),
      '#type' => 'textfield',
      '#default_value' => $config->get('customValue'),
      '#maxlength' => 255,
      '#required' => TRUE,
    ];

    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration
    $this->configFactory->getEditable('mymodule.settings')
      ->set('customKey', $form_state->getValue('customKey'))
      ->set('customValue', $form_state->getValue('customValue'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}

```

# Answer
To add an add more button you'll need to create a callback function that will increase the number of fields necessary and rebuild that part of the form based on that information. You can make a new config variable based on some sort of index as you do a loop through all the necessary fields.

I haven't tested this so the syntax might be off but here's the basic idea in an example I wrote.

```
public function buildForm(array $form, FormStateInterface $form_state) {
        if (empty($number_of_member_fields)) {
            $number_of_member_fields = $form_state->set('number_of_member_fields', 1);
        }
        $forms['members_fieldset'] = [
            '#type' => 'fieldset',
            '#title' => t('Member types'),
            '#attributes' => [
                'id' => 'names-fieldset-wrapper'
            ],
        ];
        for ($i = 0; $i < $number_of_member_fields; $i++) {
            $form['members_fieldset']['memberType'.$i] = [
                '#type'          => 'textfield',
                '#title'         => t('Name'),
                '#default_value' => $config->get('memberType'.$i),
            ];
        }
        $form['members_fieldset']['actions']['add_name'] = [
            '#type'     => 'submit',
            '#value'    => t('Add one more'),
            '#submit'   => array('::addOne'),
            '#ajax'     => [
                'callback' => '::addmoreCallback',
                'wrapper'  => 'names-fieldset-wrapper',
            ],
        ];
    }
    public function addmoreCallback(array&$form, FormStateInterface $form_state) {
        return $form['members_fieldset'];
    }
    public function addOne(array&$form, FormStateInterface $form_state) {
        $number_of_member_fields = $form_state->get('number_of_member_fields');
        $number_of_member_fields++;
        $form_state->set('number_of_member_fields', $number_of_member_fields);
        $form_state->setRebuild();
    }

```
> 3 votes

---
Tags: 8, forms, hooks, configuration
---


# Question
Title: How to add a class to menu items that are not expanded (or don't have children) in the navigation Twig template?
How do you add a class to menu items that are not expanded (or don't have children)?

```
    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded dropdown panel simple-dropdown',
          item.is_collapsed ? 'collapsed',
          item.in_active_trail ? 'active',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}

```

Edit: Can anyone point me into getting the answer provided, implemented in my example?

# Answer
I think you can do some cool things when you set classes. A colon `:` indicates 'else'.

```
{%
  set classes = [
    item.is_expanded ? 'is-expanded' : 'not-expanded',
    item.is_collapsed ? 'is-collapsed' : 'not-collapsed',
    item.in_active_trail ? 'active',
    item.below ? 'has-children': 'no-children',
  ]
%}

```

EDIT: Added ', after no-children
> 3 votes

# Answer
Since Twig builds out the menu recursively the only way (I've found) to do this is to first check if the current item has any active children, and add a class to it once that is determined. So, *before* the li is posted, check if it has any children. Something like:

```
{% for child in item.below %}
  {% set children = item.below ? '1': '0' %}

  {% if children %}
    {# the current item has expanded/active children #}
  {% else %}
    {# the current item has no children #}
    {% set classes = classes|merge(['no_active_children']) %}
  {% endif %}

  <li{{ item.attributes.addClass(classes) }}>{{ link(item.title, item.url) }}
    {% if item.below %}
        {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}
  </li>
{% endfor %}

```

Hope that helps.
> 3 votes

---
Tags: theming, 8, navigation
---


title: Add classes to form select option item

text:
# Question
Title: Add classes to form select option item
How can I add classes to a form option tag without JS? At the moment in Form API I can pass a keyed array like this

```
array(
  '0' => 'option 0',
  '1' => 'option 1',
)

```

and I'll get html like this

```
<option value="0">option 0</option>
<option value="1">option 1</option>

```

Is there a way to do something like this:

```
array(
  array(
    'value' => 0,
    'text' => 'option 0',
    'class' => 'bob 0',
  ),
  array(
    'value' => 1,
    'text' => 'option 1',
    'class' => 'bob 1',
  ),
)

```

and then get this

```
<option value="0" class="bob 0">option 0</option>
<option value="1" class="bob 1">option 1</option>

```

# Answer
So I wasn't able to get the fully flexible option done but here is a way to add classes to the `options` tag based on the option value. It works but overriding the `theme_select` function to use my own version of `form_select_options`

```
// theme_select
function THEME_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));
  return '<select' . drupal_attributes($element['#attributes']) . '>' . THEME_form_select_options($element) . '</select>';
}

/**
 *
 * @param type $element
 * @param type $choices
 * @return string
 */
function THEME_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice)) {
      $options .= '<optgroup label="' . $key . '">';
      $options .= THEME_form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= THEME_form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option class="' . drupal_clean_css_identifier($key) . '"  value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}

```
> 5 votes

# Answer
Unfortunately this isn't very easy using the Form API currently.

There's an issue open to add this functionality (it goes all the way back to 2008) that would theoretically allow you to do something like this:

```
$form['optiontest'] = array(
  '#type' => 'select',
  '#title' => t('Option test'),
  '#options' => array(
    array(
      '#return_value' => 0,
      '#value' => t('First option'),
      '#attributes' => array('class' => 'first', 'title' => t('First option')),
    ),
    array(
      '#value' => t('Option group'),
      '#attributes' => array('class' => 'group', 'title' => t('This is an optgroup')),
      '#options' => array(
        array('#return_value' => 2, '#value' => t('1st sub-option')),
        array('#return_value' => 4, '#value' => t('2nd sub-option')),
      ),
    ),
  ),
);

```

But unfortunately there are nothing but failed patches attached to the issue at the moment.

The only way I can think of to do it at the moment would be to add a `#process` function to the select element, and add the class(es) to each option when they're broken down individually.
> 10 votes

# Answer
There is actually a way to override individual `option` items, but it works with `checkboxes` and `radios`. I've been told that it doesn't work with `SELECT` though. Also, I'm not sure if it works in Drupal 7.

Here's some code that works in Drupal 8. Might be worth a try.

```
$form['select'] = [
  '#type' => 'select',
  '#title' => t('Select'),
  '#options' => [
    '0' => t('Bob 0'),
    '1' => t('Bob 1'),
  ],
  // You define attributes for individual options as follows.
  '0' => [
    // I have tried 'disabled' = TRUE and it works.
    'disabled' => TRUE,
    // I have never tried #attributes, but I think it should work.
    '#attributes' => [
      'class' => ['bob-0'],
    ],
  ]
]

```

I hope it helps. Cheers! Alternatively, go for one of the other solutions.
> -1 votes

---
Tags: theming, forms
---


# Question
Title: drupal_get_path function for third party PHP includes files
I am trying to add some PHP includes files into Drupal 7 site. The files are on this page - https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/connecting\_to\_the\_api\_using\_php.htm under the "Required PHP Includes" heading. It looks like I need these files: **soap-wsse.php**, **exacttarget\_soap\_client.php**, **xmlseclibs.php** in my Drupal install.

I will need to use the require('exacttarget\_soap\_client.php') function in a Drupal custom module.

My question is where to place these files in the file structure of Drupal and what would be the $type using drupal\_get\_path() function? Should I be using the Libraries API instead?

# Answer
`drupal_get_path()` returns the path of a module, a theme, a theme engine, or a profile. It's not for loading a generic PHP file, for which you need `module_load_include()` which (despite the name) can be used for a PHP file that can be loaded with `require_once`.

Supposing you add the *soap-wsse.php* file in the *includes* directory of the *test\_module* module, you cal load that file using the following code.

```
module_load_include('php', 'test_module', 'includes/soap-wsse');

```
> 1 votes

---
Tags: 7
---


title: Is exposing the UID a security issue?

text:
# Question
Title: Is exposing the UID a security issue?
I noticed that the UID of users is exposed in the HTML code of a page on my site that authenticated users can access.

Is it a problem if authenticated users with "view user profiles" permission are able to find the UID of any non-disabled user account?

# Answer
> 0 votes
According to this post by the Drupal Security Team, it is not considered a vulnerability:

Disclosure of usernames and user ids is not considered a weakness

> ## Drupal's philosophy
>
> Usernames are an important part of online identity. Having a public username helps other users of a site to know the identity of the person they are interacting with in a forum or a blog. Drupal is primarily intended to be used for sites where identity and interaction are key elements so it is reasonable for that information to be public.

Of course, it will vary by site, depending on what that information allows other users to see.

---
Tags: users, security
---


# Question
Title: How do I add a minipanel to a panel page?
In D7 I've created a new minipanel and would like to add it to a panel page.

However, when I go to add it I cannot find it. It's not under the category I've set it in and it's not under the Mini Panels category. I've tried clearing cache, rebuilding the registry and have ensured the minipanel has a unique machine name.

How can I add it?

# Answer
I found the problem: It was because the Mini Panel contained a Block that was also contained on my Panel Page. Once I removed the block on the Panel Page I was able to add it.

I wish there was a way I could have the Block in both, but I guess not.
> 1 votes

# Answer
Note that your mini-panel category shows up as a first order item in the list of possible entity-types available for inclusion in your panel.

I expected that my mini-panels category would be a section under one of the entity-type filters and that the first order items would be permanent types, not something like a category that I created.

So the first couple times I tried to find my mini-panels in the the page panel UI I also couldn't find them.

In the example below, my category used for mini-panels is called "Home Page Redux."
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Node is flagged, node author comes back to the site, how to show how many new flags since last visit?
I created a "new activity feed" view page in which a user can see how many **new comments** have been posted to his own nodes since his last visit

Eg : since you last last visit :
\- 21 new comments have been published on your node #title, in a total of 65 comments
\- 3 new comments have been published on your node #title2, in a total of 8 comments

The nodes can also be flagged by other users.

Using flag module and views, it is possible to get the total amount of flags a node has received at any time.

I would like to be able to show the node author, how many "new" flags each of his nodes has received since his last visit.

Any help is welcome

# Answer
> 0 votes
To answer your posted question (title), you'll need to extend functionality.

By default, the core comment module & flag module have no default mechanism to store comment/flag view history. You would need to do something like:

* Build something like the Drupal core history module that tracks a user's comment/flag views
* Build a simple aggregate comment/flag query based on a user's last login/access time
* ...or maybe find a module that offers this functionality (not sure it exists and module recommendations are off topic here)

---
Tags: 7, views, flags
---


# Question
Title: How do I call a controller method from a twig template and passing arguments to it?
I know I can pass variables to templates using render arrays.

```
$theme = 'block-AcademicDisplay';

return array(
  '#theme' => $theme,
  '#content' => $content,
  '#url' => urlencode($url),
);

```

How can I pass variables and call controller methods from that template? On that template, when clicking on some buttons or links, I would like to call a controller method and pass it 2 parameters.

# Answer
> 1 votes
**Passing arguments in route parameters**

I think the missing part is the route that you have defined for the controller. You have to use this to generate the url:

```
$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);

```

This example is for the node controller and passes the argument nid=1. The parameter names are defined in the route definition.

**Passing arguments in query parameters**

I've seen in one of your other posts that you want to use query parameters. This is an example for the user login:

```
$url = Url::fromRoute('user.login', [], ['query' => ['destination' => 'http://example.com']]);

```

For this to work you don't need to define a query parameter in the route. Simply inject the request as function argument (the request is always available to a controller, it's not necessary to define it in the route) and get the query parameter:

```
use Symfony\Component\HttpFoundation\Request;

  public function myController(Request $request) {

    $destination = $request->query->get('destination');

  }

```

# Answer
> 0 votes
i have used parameter upcasting in routes to convert dynamic values in url to object instances

https://www.drupal.org/docs/8/api/routing-system/parameter-upcasting-in-routes

in a bloc template listing all publications

```
 <a href="/publication/{{ row.halId_s }}">call to publication detail</a>

```

my\_module.routing.yml , linking the route to the controller, with upcasting parameters

```
my_module.publication_detail:
#parameter upcasting
  path: '/publication/{halId_s}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::publicationDetail'
    _title: 'publication detail'
  options:
    parameters:
      halId_s:
        type: int
  requirements:
    _permission: 'access content'

```

MyModuleController.php

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;

/**
 *
 * for created routes publication/{}
 */
class MyModuleController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function publicationDetail($halId_s) {

    $module_global_config = \Drupal::configFactory()
      ->getEditable('amu_hal.settings');
    $amu_hal_url_ws = $module_global_config->get('amu_hal_url_ws');
    $docType_s = $module_global_config->get('docType_s');

    $url = $amu_hal_url_ws . 'search/?fl=title_s,en_title_s,docid,label_s,en_label_s,docType_s,authIdHal_s,halId_s,structId_i,uri_s,keyword_s,en_keyword_s,authLastNameFirstName_s,journalTitle_s,abstract_s,en_abstract_s,producedDate_tdate,producedDateY_i,language_s,fileMain_s&fq=halId_s:' . $halId_s;

    try {
      $client = new Client();
      $response = $client->request('GET', $url);
      $content = json_decode($response->getBody(), TRUE);
    } catch (ConnectException $e) {
      \Drupal::logger('amu_hal')->error('cette url n est pas bonne' . $url);
    }

    $theme = 'page-PublicationDetails';

    $module_path = file_create_url(drupal_get_path('module', 'my_module'));

    $build = [
      '#theme' => $theme,
      "#content" => $content,
      '#url' => $url,
      '#docTypes_array' => $docType_s,
      '#module_path' => $module_path,
    ];
    return $build;
  }

}

```

page-PublicationDetails.html.twig

```
{% for doc in content.response.docs %}
      {{ doc.title_s|first }}
    // some more //
 {% endfor %}

```

---
Tags: 8, routes
---


# Question
Title: Import image with migrate tools changing its name
I’m trying to migrate some data from a remote rest/api (json) using the plugin source url. My problem is in the json i consume the image name field comes with an incorrect value.

In `imageName` comes '0\_3.jpg' and the correct name is '0\_3.png', for example

So i have the following code trying to transform the name:

```
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - imageName:
            plugin: str_replace
            source: imageName
            search: "jpg"
            replace: "png"

```

but this gives the following error:

> TypeError: Argument 2 passed to Drupal\Component\Utility\NestedArray::getValue() must be of the type array, null given

Anyone has any idea?

# Answer
> 1 votes
Two options:

```
_image_fixed:
  - plugin: str_replace
    source: imageName
    search: "jpg"
    replace: "png"

source_full_path:
  - plugin: concat
    delimiter: /
    source:
      - constants/source_base_path
      - @_image_fixed

```

Or:

```
source_full_path:
  - plugin: concat
    delimiter: /
    source:
      - constants/source_base_path
      - imageName
  - plugin: str_replace
    search: "jpg"
    replace: "png"

```

---
Tags: 8, migrations
---


# Question
Title: In Commerce 2, how can we allow users with a role to bypass payment during checkout (bill me later)
We have a Commerce 2 site that we need to be able to assign users a role ('Bill Me Later') that will allow the user to select the payment option 'Bill Me Later' during checkout.

I have not found a module that provides this functionality. I started to dive into creating a custom payment processor but I'm not sure if this is the correct route to go. If the user were to select 'Bill Me Later' then no further information would be needed. The order would go through (completed) but now marked paid.

Could someone offer some insight into the best way to achieve this? We're open to building a custom payment gateway module if that is required but could use a little guidance as to get started since this technically is not a payment gateway.

# Answer
You can enable the "Commerce Payment Example" module that comes with commerce2. From there on, go to commerce-\>settings-\>payment-\>payment gateways and add a new payment gateway. Choose the "Manual" plugin and set the proper roles on the bottom and you should be done.
> 0 votes

---
Tags: commerce, payment-gateways
---


title: Negate contextual filters in views

text:
# Question
Title: Negate contextual filters in views
I got a view, which lists nodes of same type, a "Other activities" view, i use this view on a activity node view. However i don't want the node i am currently viewing, to show in the list as well.

So what i did, was to make a contextual filter for nid, and provide a default value of "Content ID of URL", of course now my list only provides me with the currently viewing node.

Isn't there anyway to negate this? So it shows all other nodes, that don't have the nid, og the current?

# Answer
There is an option on contextual filters to exclude the resulting value, rather than limiting the search to that value. Turn on this checkbox, and you should have the results you are seeking.
> 16 votes

# Answer
https://www.drupal.org/project/views\_negate

Synopsis

The Views Negate module provides a "Not Equal" to condition for textfield and list field in contextual filter. It works same as exclude option of numeric type field.

A checkbox with "Negate" label is added under "MORE" fieldset. By selecing the Negate option, it applies the "not equal" condition or "not in" if selected "Allow multiple values" option.
> 1 votes

---
Tags: 7, views
---


title: Get Entity ID when is saved

text:
# Question
Title: Get Entity ID when is saved
I need to capture the entity\_id when the entity is saved. The ID will process and insert in a custom field. I use hook\_entity\_presave(), but when is a new entity the ID is void. Is there any way to capture the ID?

```
/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_type = $entity->getEntityType()->id();
  if(($entity_type === 'node' || $entity_type === 'taxonomy_term')) {
    $entity->field_custom_token->value = _process_token($entity->id()); // if entity is new, the ID is Null :(
  }
}

```

# Answer
> 2 votes
Try changing your code to use hook\_entity\_insert which is run after the saving to the database: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_entity\_insert/8.2.x

As the reason you can't get the entity ID in presave is because if its a new entity then the ID hasn't been generated by the autoincrement ID field in the database yet so an ID doesn't exist for it until it's saved for the first time

---
Tags: 8, entities, hooks
---


# Question
Title: Installation fails with missing "file" -plugin error
We are creating our own D8 installation profile from previously built site. We exported config and split it to modules, so that our custom modules are defining their own configs.

We've had a lot of issues, basically because we don't know how to debug site installation. XDebug seems to catch nothing. But now I've gotten pretty far, modules do get installed, but the configuration import fails on following error:

```
[ERROR] The "file" entity type does not exist.

```

Error gets thrown at Drupal\Component\Plugin\Discovery\DiscoveryTrait.php, but sadly I'm not able to get PHPStorm's debugger to catch that file.

```
protected function doGetDefinition(array $definitions, $plugin_id, $exception_on_invalid) {
    // Avoid using a ternary that would create a copy of the array.
    if (isset($definitions[$plugin_id])) {
      return $definitions[$plugin_id];
    }
    elseif (!$exception_on_invalid) {
      return NULL;
    }

    throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist.', $plugin_id));
  }

```

So basically I'd need a way to debug this installation via profile or some way to find out which config file is responsible. I'm finding this unnecessarily difficult, so any help is appreciated.

Cheers,

Janne

# Answer
> 0 votes
Yeah, got this sorted.

The reason for this strange behavior was unsurprisingly misconfigured field in some entity's baseFieldDefinition method.

Someone had used in display plugin configuration "file" instead of correct "file\_generic" and for some reason this hadn't been triggered before this. The app has been live for about 6 months and gone through numerous updb's and entity-updates.

This was a nice one. I'll just leave this here in case someone has same mistakes :)

---
Tags: installation-profiles
---


title: Customize title template based on page

text:
# Question
Title: Customize title template based on page
I know I can customize the template by overriding `page-title.html.twig` but I'm looking for a way to have more than one title template. in my case, the suggested name form my path is `page__manage__customer_list` So I tried to override it with `page--manage--customer-list-title.html.twig`. how is that possible to override the title template?

to make the question more generalize and could be useful for other guys that looking for similar circumstances this could be helpful.

**How can I override the title template based on content type or route?**

# Answer
You can add new templates to already existing using hook\_theme\_suggestions\_HOOK\_alter

Example of adding a content type:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page_title__' . $content_type;
  }
}

```

Then use **page-title--content-type.html.twig**

---

You could use `$node->id();` if content type is too broad.
> 4 votes

# Answer
Many thanks for @No Sssweat give a clue to me. her solution works for content types only. **but for Taxonomy page and General pages ( custom pages you've created by custom route like me) the following snippet will work charmingly:**

on `YOURTHEMENAME.theme` file

```
use \Drupal\taxonomy\Entity\Term;
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function YOURTHEMENAME_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {

  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page_title');

  if ($tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $vid = $term->vid->getValue();
    $suggestions[] = 'page_title__taxonomy__vocabulary__' . $vid[0]['target_id'];
  }

  elseif ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page_title__' . $content_type;
  }
 // ksm($suggestions);
}

```

then it works for all pages.

**page-title--CONTENT\_TYPE\_MACHINE\_NAME.html.twig** (sample for article content type : **page-title--article.html.twig**

**page\_title\__taxonomy\__vocabulary\__VOCABULARY\_MACHINE\_NAME.html.twig** ( sample for tags vocabulary is : **page\_title\__taxonomy\__vocabulary\__tags.html.twig**

Ref : hook\_theme\_suggestions\_HOOK\_alter
> 2 votes

---
Tags: 8, theming
---


title: File upload through form type file

text:
# Question
Title: File upload through form type file
**My Drupal version is 8.6.10**

I am trying to upload a file through the file\_save\_upload function and the function is looking for the file in

**Symfony\Component\HttpFoundation\FileBag Object**

```
$all_files = \Drupal::request()->files;
debug($all_files);

Symfony\Component\HttpFoundation\FileBag Object
(
    [parameters:protected] => Array
        (
        )

)

```

But my file is in

**Symfony\Component\HttpFoundation\ParameterBag Object.**

```
$all_files = \Drupal::request()->request;
debug($all_files);

Symfony\Component\HttpFoundation\ParameterBag Object
(
    [parameters:protected] => Array
        (
            [name] =>
            [type] => 4
            [files] => Array
                (
                    [image_section] => logo_capnord.png
                )

            [op] => Ajouter
            [form_build_id] => form-wMTrCGaN5mPlOOv8bqS7UsJ0lRiSN6QQp9UviA0cTIA
            [form_token] => 1hTMXJRfoQvFV9Lqq3TuJ29eYC6L-zt3U7Bow1P8yJ0
            [form_id] => capnord_section_form_list
        )

)

```

The field is generated through the reloading of the form in ajax.

```
  $form["base"]["fields"] += [
    "image_section" => [
      "#type" => "file",
      "#title" => "Image",
    ]
  ];

```

# Answer
**Solution**

```
$form["#attributes"] = ["enctype" => "multipart/form-data"];

$form["base"]["fields"] += [
   "image_section" => [
    "#type" => "file",
    "#title" => "Image",
   ]
];

```

I solved my problem, as I only reloaded one part of the form, the form generator did not know that there was a file element, so it did not add "multipart enctype / form-data" to the form.

I hope this will help someone in the same situation as me in the future.
> 0 votes

---
Tags: forms, files
---


title: Get fields of referenced entity in view

text:
# Question
Title: Get fields of referenced entity in view
I have two content types, Project and Resource,

I have a view displaying fields from Projects, and I would like to display fields from resources referenced by projects in that view.

If I Twig debug, I can see the resource fields are available in the view, but I cannot output them using `{{ fields.field_project_linked_resource.content }}` or similar...

Any help much appreciated!

# Answer
> 1 votes
You can display information from nodes that are connected through Entity reference fields right in the Views interface.

In your case you're referencing Resources from Projects, so you need to add the Relationship for the Entity reference field, then you will be able to add Fields that you can find on the Resources Content type (they will automatically use the Relationship).

If it's a field that both Content types have (for example Title) then if you don't use the Relationship on it the title will be for the Project node, and if you do make it use the Relationship it will show the Resource title.

---
Tags: views, 8
---


# Question
Title: How to edit a web form value so that the column name can be as required in a table in UI
I have a submissions form where I am displaying all the form submissions in a table with custom columns, which I build from my form elements I created. But also I am using an built-in drupal column called 'completed', which will display the date and time of the submissions. I need to edit this column name to 'submitted at'.

I tried `theme_table` and `module_table` methods to edit the value but I am not able to hit those methods. When I tried `hook_form_alter` I am not able to see the table values when I did var\_dump($form) to edit them in form\[\] array. I kept knit(\_context) in the twig file of the table and I am able to see the values of the table and the value is coming from \_context-\>few layers Drupal\Core\Template\AttributeString.

How do I use this info in form\_alter or any other hook to edit that string value?

Like I don't know how to use \_context array in form\_alter method. when I tried form\['\_context'\] its giving me null.

# Answer
I was able to edit it using theme\_preprocess\_table method below is the method which I used.

```
   function theme_preprocess_table(&$variables)
   {
       $variables['header']['completed']['content'] = 'your requirement';
   }

```
> 0 votes

---
Tags: 8
---


# Question
Title: Render a menu block in current user's language
I have a multi-language site.

How this is supposed to work is that on /fr pages, everything except main navigation block should be in French. However, main navigation menu block should be in whatever currently logged user's language.

I tried to change language code in custom module using block or menu hook, but none of them worked.

Thanks in advance.

# Answer
You don't need a custom module for this.

Drupal can have seperate language detection for interface (menu item/interface elements) and content. There was a bug that was fixed recently so make sure you are on the latest 8.6.x version.

Assuming you have enabled all 4 core language modules and you have enabled at least 1 extra language than configure the **language detection methods** to accomplish what you want as I its outlined below.

Go to `Configuration > Regional and language > Languages > Detection and selection` and

* enable **Account administration pages**. This will allow each user to choose their preferred interface language (there will be a new option when they edit their profile page)
* enable content language detection. This will make available the `language switcher (content)`) block.
* enable 1 detection method. In my case I choose url (i.e. /en /fr) but you can choose any other or more methods if you like.

**ΝΟΤΕ:** The detection methods take precedence as they appear from top to bottom provided they are also enabled.

Go to `Structure > Block layout` and enable `language switcher (content)` (not `language switcher (interface text)`

Now lets say a user has chosen English as their `interface language` they can press on the `language switcher (content)` and their interface (menu, admin menu etc) will always stay English.
> 0 votes

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


# Question
Title: Is it possible to make a patch that modifies a module's composer.json?
I want to confirm some behavior of Composer to see if this is a limitation of Composer or something I did wrong.

This is based on an issue in the Markdown module queue.

Basically, here's the issue.

1. The Markdown module requires `^0.15` of a library.
2. I wrote a patch to require `~0.15` of the library. (to allow 0.16, 0.17, etc.)

But, when I apply this patch via Composer, and then try to update the library, I still get a `drupal/markdown 1.2.0 requires league/commonmark (^0.15.0)` even though the module's (patched) code on my site requires `~0.15`.

So, is there no way to "patch" a composer.json so that it will be picked up for `composer update`? Am I reliant on the module maintainer to commit the patch?

# Answer
> 10 votes
This issue is actually addressed in the `composer-patches` documentation:

> Because patching occurs after Composer calculates dependencies and installs packages, changes to an underlying dependency's composer.json file introduced in a patch will have no effect on installed packages.
>
> If you need to modify a dependency's composer.json or its underlying dependencies, you cannot use this plugin. Instead, you must do one of the following:
>
> * Work to get the underlying issue resolved in the upstream package.
> * Fork the package and specify your fork as the package repository in your root composer.json
> * Specify compatible package version requirements in your root composer.json

If you want to follow option #2, you can fork the project's git repo, modify it, and add the forked repo to your project's `repositories` property:

```
    {
        "type":"git",
        "url": "https://github.com/vendor/module"
    }

```

So you can reference that dependency until the upstream has resolved the issue.

---
Tags: composer
---


# Question
Title: messenger()->addMessage not working after a $form_state->setResponse
In the `submitForm` of a custom form, I have this:

```
switch ($form_state->getValue('suscribe')) {
  case 0:
    $iStatus = 1;
    break;
  case 1:
    $iStatus = 3;
    $sFileName = 'sites/default/files/_private/bulletins/' . $form_state->getValue('adherent')[1] . ".pdf";
    $response = new BinaryFileResponse($sFileName);
    $response->setContentDisposition(
      ResponseHeaderBag::DISPOSITION_ATTACHMENT,
      'bulletin.pdf'
    );
    $form_state->setResponse($response);
    break;
}

$storage = \Drupal::entityTypeManager()->getStorage('member');
$id = $form_state->getValue('adherent')[0];
$entity = $storage->load($id);
$entity->status = $iStatus;
$entity->save();

\Drupal::messenger()->addMessage($this->t('Your wish has been recorded.'));

```

`suscribe` is a Yes/No radio button.
`$form_state->setResponse($response);` triggers the automatic download of a pdf document.

The message (Your wish...) is correctly displayed in case 0.
In case 1, the message shows only if I refresh the page (or go to another page).
How can I have the message displayed without doing another action after submitting the form in case 1?

By the way, database is correctly updated in both cases.
I'm using Drupal 8.6.10.

# Answer
> 0 votes
Finally and using advice from @Clive, I made it this way:

```
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    switch ($form_state->getValue('suscribe')) {
      case 0:
        $iStatus = 1;
        $sMessage = $this->t('Your wish has been recorded.');
        break;
      case 1:
        $iStatus = 3;
        $Url = Url::fromUri('base:/association/membership/download/' . $form_state->getValue('adherent')[0]);
        $sLink = \Drupal\Core\Link::fromTextAndUrl($this->t('here'), $Url)->toString();
        $sMessage = $this->t('Your wish has been recorded.<BR>To download your membership form, please click %link.', ['%link' => $sLink]);
        break;
    }
    $storage = \Drupal::entityTypeManager()->getStorage('member');
    $id = $form_state->getValue('adherent')[0];
    $entity = $storage->load($id);
    $entity->status = $iStatus;
    $entity->save();
    \Drupal::messenger()->addMessage($sMessage);
  }

```

which gives

Case 0: a simple message saying that wish has been recorded.

Case 1: the same message plus a link to download the document

In association.routing.yml:

```
association.membership_download:
  path: '/association/membership/download/{member}'
  defaults:
    _controller: '\Drupal\association\Controller\MembershipController::download'
  requirements:
    _permission: 'renew membership'

```

In MembershipController.php:

```
  public function download($member)
  {

    $storage = \Drupal::entityTypeManager()->getStorage('member');
    $entity = $storage->load($member);
    $sFileName = 'sites/default/files/_private/bulletins/' . $entity->designation->value . '.pdf';
    $response = new BinaryFileResponse($sFileName);
    $response->setContentDisposition(
      ResponseHeaderBag::DISPOSITION_ATTACHMENT,
      'bulletin.pdf'
    );
    return $response;
  }

```

# Answer
> 2 votes
> How can I have the message displayed without doing another action after submitting the form in case 1?

You can't - when you force download a file the page you see behind it is the original form request, and always will be. It's just how browsers work.

You'll need to refresh the page (or visit a new page) to see the messages, which haven't been rendered as part of the force-download request, and so are still sitting in the session waiting to be rendered.

You might be able to hack something together with JS to make this work, but in my experience it's not worth the hassle. The browser doesn't even report back to you when the file is downloaded (what if it isn't? What if the user cancels or there are network problems?), so it's a real pain to implement.

---
Tags: 8, forms
---


title: Views arguments as part of path

text:
# Question
Title: Views arguments as part of path
Is it possible to create views pages with urls like "prefix-%-postfix" instead of "prefix/%/postfix"?

# Answer
No. The menu router system only understands `%` as placeholder within `/` characters as an argument to pass through to the callback function that will render it. It won't understand `prefix-%-postfix` other than its literal value. The underlying function, `arg()`, that the Views `Content ID from URL` contextual filter relies on to retrieve an argument relies on this system so it wouldn't be able to pull the argument.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Get 404 for url specified in module.routing.yml
I am new to Drupal and I got stuck with the problem that I don't know how to debug even: I have made a simple module 'final', its structure:

```
Applications/MAMP/htdocs/drupal_dir_1/modules/final > ls
final.info.yml    final.routing.yml src

/Applications/MAMP/htdocs/drupal_dir_1/modules/final > ls src/Controller/
ExampleController.php

```

Files contents:

```
> cat final.info.yml
name: Final
type: module
description: This is an final module
core: 8.x⏎

> cat final.routing.yml
final.content:
  path: '/final'
  defaults:
    _controller: '\Drupal\final\Controller\ExampleController::content'
    _title: 'Hello world bitch!'
  requirements:
    _permission: 'access content'

> cat src/Controller/ExampleController.php
<?php
namespace Drupal\final\Controller;
use Drupal\Core\Controller\ControllerBase;
class ExampleController extends ControllerBase {
  public function content() {
    $build = [
      '#markup' => $this->t('Hello World, bitch!'),
    ];
return $build;
  }
}

```

# Answer
I believe you did not install the module

if you tried to install you would get

```
drush en final

```

> ParseError: syntax error, unexpected 'final' (T\_FINAL), expecting identifier (T\_STRING) in /home/giorgos/share/gwebsites/dru8.dev/web/modules/custom/final/src/Controller/ExampleController.php on line 2 #0 /home/giorgos/share/gwebsites/dru8.dev/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/home/giorgos/s...') #1 \[internal function\]: Composer\Autoload\ClassLoader-\>loadClass('Drupal\final\Co...') ...

`final` is reserved keyword thus it confuses the php parser when it sees

```
namespace Drupal\final\Controller;

```

Can also be caught with my vscode setup and linter

You have to change `final` to something else but then you have to rename it elsewhere in your module (folder name, file names, reference to the class etc)

Otherwise the module is working fine.
> 1 votes

---
Tags: 8, uri
---


# Question
Title: How to render author custom fields info on comment and node twig template?
I am trying to render the author Full Name and other authors customs fields information in comment.html.twig and node.html.twig. But not any of the fields that I made for users such as "First Name", "Last Name", and Auther UID etc. render in comments.

I tried with the following code for comment author

```
{{ comments.author.field-first_name.entity.value }}
{{ comment.author.user_picture.0.entity.uri.value }}
{{ comments.author.uid.entity.value }}

```

And, I tryed following code for node author:

`{{ node.author.field-first_name.entity.value }}
{{ node.author.user_picture.0.entity.uri.value }}
{{ node.author.uid.entity.value }}`

Any ideas, how do I render this info in comment template?

# Answer
> 4 votes
For Node:

```
{{ node.getOwner.field_first_name.value }}
{{ file_url(node.getOwner.user_picture.entity.fileuri) }}
{{ node.getOwner.uid.value }}

```

For Comment:

```
{{ comment.getOwner.field_first_name.value }}
{{ file_url(comment.getOwner.user_picture.entity.fileuri) }}
{{ comment.getOwner.uid.value }}

```

# Answer
> 0 votes
To find a solution I would first check, if the information I want to display is in the actual render array. You can do this by using a variable dump.

`{{ dump(comments|keys }}`

or

`{{ dump(comments.author|keys }}`

(If you have devel with kint installed, you can use this vor variable dump.)

Now you can look: If your first-name field is not in the render array, then no template will be possible to show it.

To get custom pieces of information in your render array, this answer my perhaps helpful to you: How do I print custom user fields?

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


# Question
Title: Can I aggregate all stylesheets core, contrib and custom into one single stylesheet?
Is there any way to avoid Drupal from serving multiple stylesheets and instead bundle them together? I am going to look into https://www.drupal.org/project/webpack

I want to avoid all the multiple @imports if possible that get created by the modules. Reason I want to do this is I am archiving my site with wget and I want to have less stylesheet links to monitor.

# Answer
> 1 votes
Enable aggregation of css by going to `admin/config/development/performance`

This is the best Drupal 7 can do without the need for any contrib module

You can also try Advanced CSS/JS Aggregation which gives some more advanced aggregation.

---
Tags: 7, css-js-aggregation
---


title: Count unread message by tag

text:
# Question
Title: Count unread message by tag
I am trying to display the number of unread message for each individual tag. I found it's possible to use `privatemsg_unread_count()` or create a query with `_privatemsg_assemble_query('list', $user, 'inbox')`.

How do I make that work?

# Answer
> 0 votes
You can use `_privatemsg_assemble_query()` or `privatemsg_unread_count()`. The latter returns the number of unread messages for an account.

# Answer
> 0 votes
```
 $count = _privatemsg_assemble_query('list', $user,'My_tags_name');
$unread = privatemsg_unread_count($count);
 if($unread > 0)
  {
   echo '<div class="height:50px;">'.$unread. 'new messages</div>';
  } else {
 }

```

or

```
$query = _privatemsg_assemble_query('list', $user, 'inbox');
$total_count = db_result(db_query($query['count']));
echo $total_count;

```

---
Tags: privatemsg
---


title: Sort view by tag count

text:
# Question
Title: Sort view by tag count
I have to show all the tags and sort based on count. I am able to get the count of tag used by pages through views but not able sort based on count as this option is not available in views. Any suggestions?

# Answer
It is possible with just core views.

* Create a view that displays *terms*
* enable *aggregation*
* add relationship *Content with term*
* add sort *content uuid* with *aggregation type: count*
* add field *content uuid* with *aggregation type: count*
* add field *taxonomy term*

Your view should look similar to the following
> 5 votes

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


# Question
Title: How to successfully follow Drupal.org's instructions for updating via composer
In following the instructions at https://www.drupal.org/docs/8/update/update-core-via-composer, prior to updating core from 8.5.3 to 8.6.12, when I attempt to go through the list of available module updates

```
composer outdated "drupal/*

```

the very first update:

```
composer update drupal/admin_toolbar --with-dependencies

```

results in:

```
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - don't install drupal/core 8.6.12|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.12|remove drupal/drupal dev-master
    - Installation request for drupal/drupal dev-master -> satisfiable by drupal/drupal[dev-master].
    - Installation request for drupal/core (locked at 8.6.12, required as ^8.6) -> satisfiable by drupal/core[8.6.12].

```

Following are the contents of my composer.json file:

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
    "drupal/core": "^8.6",
    "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/console": "~1.0",
        "drupal/migrate_d2d": "3.x-dev",
        "drupal/codesnippet": "^1.6",
        "drupal/nexus": "^1.0@beta",
        "drupal/social_media_links": "^2.2",
        "drupal/twitter_block": "^2.1",
        "drupal/nocaptcha_recaptcha": "1.x-dev",
        "drupal/adsense": "^1.0",
        "drupal/pathauto": "^1.0",
        "drupal/admin_toolbar": "^1.19",
        "drupal/recaptcha": "^2.2",
        "drupal/blazy": "^1.0@RC",
        "drupal/calendar": "1.x-dev",
        "drupal/computed_field": "^2.0@alpha",
        "drupal/crop": "^1.2",
        "drupal/date": "1.x-dev",
        "drupal/dropzonejs": "^1.0@alpha",
        "drupal/embed": "^1.0",
        "drupal/entity_browser": "^1.1",
        "drupal/entity_embed": "^1.0@beta",
        "drupal/image_widget_crop": "^2.0",
        "drupal/languageicons": "1.0-beta1",
        "drupal/media_entity_document": "^1.1",
        "drupal/media_entity_image": "^1.2",
        "drupal/media_entity_instagram": "^1.4",
        "drupal/media_entity_slideshow": "^1.2",
        "drupal/media_entity_twitter": "^1.3",
        "drupal/scheduler": "^1.0@RC",
        "drupal/simple_gmap": "^1.3",
        "drupal/views_field_view": "^1.0@beta",
        "drupal/views_php": "1.x-dev",
        "drupal/webform": "^5.0@beta",
        "drush/drush": "9.0.0-beta7",
        "drupal/social_login": "2.72",
        "drupal/likebtn": "^2.13",
        "drupal/drupal8_zymphonies_theme": "^1.3"
    },
    "replace": {
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": [
          "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
        ],
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

```

# Answer
> 0 votes
The problem, in part or in whole, turns out to be related to the d.o. instructions to create the composer implementation with drupal/drupal. This doesn't work when then subsequently updating.

The issue is discussed in this issue and the composer command project mentioned in it, here resolved my issue.

# Answer
> 0 votes
Had a similar problem and the only solution I found working was to use an older version of composer.

I downloaded composer 1.7.2 and installed it at `/usr/local/bin/composer1.7.2` and than I was able to run

```
composer1.7.2 update --with-dependencies

```

Which run without any problems.

I picked this tip from this issue but I had not seen this one which seems to propose a different workaround which might be worth a try.

---
Tags: composer
---


# Question
Title: Get value from twig tweak without additional markup
I am using the following code to set a variable "tab1visibility" from the twig tweak value for field\_hidden based on a block id. `{% set tab1visibility = drupal_field('field_hidden', 'block_content', 7) %}`

This works perfectly but returns the value with the expected markup.

When I try to use |striptags on this newly created value it returns nothing.

So

```
{% set tab1visibility =  drupal_field('field_hidden', 'block_content', 7)  %}

<p>{{tab1visibility}}</p>

```

returns true or false wrapped in my typical field div templating.

```
{% set tab1visibility =  drupal_field('field_hidden', 'block_content', 7)  %}

<p>{{tab1visibility|striptags}}</p>

```

returns nothing no markup or the raw value.

How do I get just the value without the surrounding markup?

# Answer
> 3 votes
A field formatter stores the field object inside of the render array for reference later, so that you can still access the raw values:

```
{% set field = drupal_field('field_example', 'block_content', 1) %}
{% set value = field['#items'].0.value %}
{{ value }}

```

This is the same for all field formatters.

---

Your approach might also work, if you `|render` the field first and then apply `|striptags`:

```
{{ tab1visibility|render|striptags }}

```

But not in a consistent way, because it depends on the specific field type and the configured field formatter.

# Answer
> 5 votes
I suppose the markup comes from field.html.twig template. You can override that template for this field in your theme. Another approach is to turn off the theming like follows.

```
{{ drupal_field('field_hidden', 'block_content', 7)|without('#theme') }}

```

---
Tags: theming
---


title: Views query alter add grouping

text:
# Question
Title: Views query alter add grouping
Can anyone please help me how to add/alter/remove aggregate options like count/sum/average etc. along with groupings using `hook_views_query_alter` in Drupal 8. I cant seem to find a suitable example.

Thanks BR/Pratip

# Answer
> 1 votes
I am not sure why people down-voted my question. It might have been a little silly to ask if there's a way to alter the group by of a views query using `hook_views_query_alter` because I think aggregation is actually a part of the base query and not views. So instead of using `hook_views_query_alter` we need to use `hook_query_alter`.

Ex.

```
/**
 * Implements hook_query_alter().
 */
function my_module_query_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  if ($query->getMetaData('view') && $query->getMetaData('view')->id() === 'my_view') {
    $group_by =& $query->getGroupBy();
    unset($group_by['users_field_data.uid']);
  }
}

```

There are a lot of other memeber function that you can check out like `$query->groupBy('field_name)` that can add another group by clause and so on...

Still not sure why it was down-voted, but I'm sure this might help someone some someday like me.

---
Tags: views, 8
---


# Question
Title: View is duplicating content added by entity reference
I have two content types, Project and Resource,

I have a view displaying fields from Project, and also fields from Resources via an entity reference field.

The problem is, if I add more than one linked resource to a project via my entity reference field, the view duplicates that Project node, instead of adding another linked resource to that project.

Any help much appreciated!

# Answer
I assume that you have a view, that shows content of type Project. In project you have a nested reference to a Resource. Basically you are asking views to show you all the Projects, and related to them Resources, so for every Resource that you are adding, views is showing you projects that are related to new Resource, but, since you have only one node of type Project - views showing you Project for every Resource that you added, so you have what was implied to happen.

If you want to have list of Resources on a Project page - I would suggest you to create small view blocks, using node id of a resource as a context filter to the view, (So in this case view would be showing you list of the Resources to the given Project on each project page.) For that you need to create another entity\_reference field on a content type of Project and filter it through the view that you created.

If this is what you were looking for. It was hard to understand you tbh
> 0 votes

---
Tags: views
---


# Question
Title: How do I reset a user's name using Drush in Drupal 7?
To change a password I would use:

```
drush user-password USERNAME --password="SOMEPASSWORD"

```

Is there a similar way to change a user's name using Drush from the command line?

# Answer
> 2 votes
There isn't a built in Drush command, but you can use Drush's `sql-query` command (or `sqlq` shorthand) to update the user's name:

```
drush sql-query "update users set name='SOMENEWNAME' where uid=####"

```

Where `####` is the user's `uid` and `users` is the user table.

# Answer
> 5 votes
Just an update for those looking for this for Drupal 8.6+. The query should be

```
drush sql-query "UPDATE users_field_data SET name='somenewname' WHERE uid=##";

```

---
Tags: 7, drush, database
---


# Question
Title: Site Branding Block not appearing in regular page--html--twig template
I have a sub theme with the parent theme being the bootstrap theme. I am able to configure the site branding block to show up on my content type pages and that's because my sub theme has a hook which suggests this full--width--page template. This full--width--page template has the {{page.branding}} region in it and it works fine.

However it wont appear on the contact page or the user login page? I suspect the boostrap theme or parent drupal engine uses the regular page.html.twig template for contact page and user login page and other pages. the {{page.branding}} does not seem to work in the page.thml.twig template.

I am looking for possible solutions. Maybe I ened a hook to tell the theme to use the full--width--page.twig template but I don't know how to write that hook, or maybe I ened to find out what is wrong witht he page--html.twig template.

Any help would be appreciated.

# Answer
> 0 votes
You can probably override the suggestions using `hook_theme_suggestions_page_alter` in your `THEMENAME.theme` file

```
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  //the routes to use the specified template
  $use_template = [
    "user.register", // user/register
    "user.login", // user/login
    "user.pass", // user/password
    "entity.contact_form.canonical", // core contact form (website feedback)
    "entity.webform.canonical", // all webforms will have this route
  ];

  // what route are we on ?
  $route_name = \Drupal::routeMatch()->getRouteName();

  if (in_array($route_name, $use_template) ){
    $suggestions[] = 'full__width__page';
  }
}

```

You should clear the cache and your specific template should take control.

If you have twig debugging enabled and your browser has show html comments enabled you should see something similar to this the *page source*

```
<!-- FILE NAME SUGGESTIONS:
   X full--width--page.html.twig
   * page--user--register.html.twig
   * page--user.html.twig
   * page.html.twig
-->

```

With x indicating the twig template responsible for the particular output. In this case `full--width--page.html.twig` is the twig template used.

---
Tags: theming
---


# Question
Title: Redirect to a form with an array of Terms as a parameter of buildForm
Here is my use case:

1-I select few nodes from a view with VBO

2-I run a custom action on those nodes

3-As a result, this action create an array of Terms ($resultedTerms)

My goal, after that, is to redirect the user to a custom form.

This custom form will use $resultedTerms to create a lot of widgets.

How can I achieve this? How can I pass $resultedTerms to the buildForm function of my custom form?

Note that I do not want to save the original selected nodes in the vbo view...

# Answer
Yep so your going to have to hook into the VOB results or submit function I assume you have already done this. then in your function you can create a Response such as the following:

```
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

$resultedTerms = [
  'terms' => [1, 2, 7]
];
// Get the current request to re-use some stuff.
$request = \Drupal::request();
$redirect_request = Request::create(
  '/the-url-to-your-form',
  'POST', // this also can be GET
  $resultedTerms,
  $request->cookies->all(),
  [],
  $request->server->all()
);
if (is_object($request)) {
  $response = \Drupal::service('http_kernel')->handle($redirect_request, HttpKernelInterface::SUB_REQUEST);
  return $response;
}

```

then in your buildForm function:

```
//Get the post data.
$posted = \Drupal::request()->request->all();
// if using GET try dump($_GET);
if (!empty($posted['terms'])) {
  $form['filed_name']['#default_value'] = $posted['terms'];
}

```

References: see "static Request create" at https://api.symfony.com/3.4/Symfony/Component/HttpFoundation/Request.html#method\___construct

also see use of this in Drupal core: core/modules/comment/src/Controller/CommentController.php

line 128 ish.

and yes obviously one should use proper dependency injection but this should get you started ... also note you will test on the vbo result page not your custom form page.
> 0 votes

---
Tags: 8, views
---


# Question
Title: How to replace a preprocess function entirely?
I need to replace `template_preprocess_links` with my own preprocess function and I can't find in the documentation how to replace a preprocess function entirely. Here is my current HOOK\_theme implementation:

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path)
{
  return [
    'links' => [
      'variables' => [
        'links' => NULL,
        'raw_links' => NULL,
        'attributes' => NULL,
        'heading' => NULL
      ],
      'override preprocess functions' => TRUE
    ]
  ];
}

```

But even with `override preprocess functions` set to TRUE, the core `template_preprocess_links` is still called and pollute the output with rendered links.

How can I replace this preprocess function entirely?

# Answer
`hook_theme()` is for new theme implementations, not altering the existing ones, and `'override preprocess functions'` can be used just from themes.
The hook you need to implement is `hook_theme_registry_alter()`.

This example code shows how to remove a preprocess function for a theme implementation.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  // Kill the next/previous forum topic navigation links.
  foreach ($theme_registry['forum_topic_navigation']['preprocess functions'] as $key => $value) {
    if ($value == 'template_preprocess_forum_topic_navigation') {
      unset($theme_registry['forum_topic_navigation']['preprocess functions'][$key]);
    }
  }
}

```

Removing all the preprocess functions would just require a line like `unset($theme_registry['forum_topic_navigation']['preprocess functions']`.

The same is true for Drupal 7. (See the example code given in `hook_theme_registry_alter()` \- Drupal 7.)
> 2 votes

---
Tags: theming
---


# Question
Title: Sum up views custom text field using aggregation
Would it be possible to set the `custom text field` value in views? I have a simple calculation in `custom text field`. It gives me the correct calculation, but when I'm trying to aggregate the views to calculate the total sum from `custom text field` it returns 0 value.

I'm thinking that `custom text field` has no value in the first place and it's only output an HTML. Would it be possible to set `custom text field` value from the calculated output? Or is there any other way to achieve this without using the hook system?

Please note that I'm also attaching another view into `custom text field` which returns a total sum from another field.

# Answer
> 2 votes
Yes short Answer have a look at creating a custom twig extension:

the idea would be to pass the details required as an "exclude from display" field (or fields) to the custom global text field. Note excluded from display fields can be accessed in the "REPLACEMENT PATTERNS" section under view text.

then basically in the text field you would do something like:

```
{myCustomTwigFunctionToCalculate( add_REPLACEMENT_fields_here)}
// or example ...
{myCustomTwigFunctionToCalculate( entity_id, nid, uid)}

  namespace Drupal\YOURMODULE\Twig;

  class CustomTwigToCalculateTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'myCustomTwigFunctionToCalculate';
  }

  /**
   * {@inheritdoc}
   */
 public function getFunctions() {
    return [
      new \Twig_SimpleFunction('myCustomTwigFunctionToCalculate', [$this,
      'myCustomTwigFunctionToCalculate'], [
      'is_safe' => ['html'],
    ]),
  ];
 }

 public function myCustomTwigFunctionToCalculated($param1 , $param2 ) : string {
 // Do the stuff you need to to calculate prams you pass.

  $output = '';
  $output = $param1 + $param2 + 42;
  return (string) $output;
 }

}

```

you will also need a service file ... see below examples.

Links to custom twig extension for Drupal 8:

https://www.openaccess.fr/la-veille-du-web/create-twig-extension-drupal-8

https://medium.com/@thihathit/extending-custom-twig-extension-to-drupal-8-twig-extension-class-d4b99c2177ae

https://www.youtube.com/watch?v=9PeAfExNSDk

---
Tags: views, 8
---


title: Content approval by roles workflow

text:
# Question
Title: Content approval by roles workflow
So I am looking at creating a website in Drupal (In the past I have used PHP and in the past few years, Symfony), however, I can not work out the workflows when it comes to approval for content.

The way the organisation will work is there will be a large number of people that will need to be able to create and edit content pages, but should not be able to publish them. Then one of the admins will look at the page and fix up any code required and make the page a bit neater, and then publish.

The first thing is, I need to know how to make a role where the user can add (not sure if adding will be required yet) and edit a page, but not publish it.

The second thing is when a page is edited and the checkbox for publishing is not selected, it unpublishes the page! That really should not be the case, it should just stay at the current revision and the saved page should just be a newer revision awaiting publishing.

I am running tests on the opensourcecms servers at the moment (with their 24hr testing system), so can not upload my own modules to the server.

# Answer
> 1 votes
I think for your use can you should use workbench with workbench\_moderation

> Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.

---
Tags: workflows
---