title: Invoke javascript in hook

text:
# Question
Title: Invoke javascript in hook
I have create a hook to alter page funcionality. It's posible invoke javascript function in hook. I test this function but i had this error --\> Call to undefined function alert()

```
      function catalogo_preprocess_node(&$vars)
      {
        alert("hello");
      }

```

# Answer
D7 you can try function drupal\_add\_js

```
function hook_preprocess_node(&$vars){
  drupal_add_js(drupal_get_path('theme', 'your_theme') . '/js/my_script.js');
}

```

D8 You need define one or more (asset) libraries, add a \*.libraries.yml file to the root of your theme folder

```
library_name:
  version: 1.x
  js:
    js/my_script.js: {}

```

Attaching a library in a preprocess function

```
function hook_preprocess_node(&$variables){
  $variables['#attached']['library'][] =  'your_theme/library_name';
}

```
> 1 votes

---
Tags: javascript, hooks
---


# Question
Title: Remove entire column from the table programmatically in twig file
In my twig file `views-view-table--myview.html` by default a table is coming with header and rows. And I want to remove entire column from the table programmatically in twig file.

How it can be done?

# Answer
> 1 votes
User `hook_views_pre_view()`checkout this code snippet.

```
/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {

  if ($view->id() == 'view_name' && $display_id == 'page_1') {
    $view->removeHandler($display_id, 'field', 'name_of_your_column');
  }
}

```

Bingo!

# Answer
> 0 votes
Personally, I don't think the twig file is the right place for that. It sounds more like a preprocess, or view alteration.

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


# Question
Title: My Ajax call for my submit button does not work?
I am building a form with the form builder but I can't even get my button to use its ajax function to callback. Instead of doing a normal ajax call on the page, it reloads the entire page.

What am I doing wrong here? The DPM function doesn't even run, so i'm assuming i'm not even triggering the ajax call, but I have copy pasted the function name into the callback, so i'm not sure why its not triggering on submit?

```
  $form['suggested_actions']['list']['mentorship'] = array('#type' => 'container');
  $form['suggested_actions']['list']['mentorship']['text'] = array('#type' => 'markup', '#markup' => '');
  $form['suggested_actions']['list']['mentorship']['text']['#markup'] .= '<span class="SugList">Mentorships - <span id="mentorshipunconfirmed">Unconfirmed</span></span>';
  $form['suggested_actions']['list']['mentorship']['button'] = array('#type' => 'button', '#button_type' => 'submit');
  $form['suggested_actions']['list']['mentorship']['button']['#name'] = 'Mentorships';
  $form['suggested_actions']['list']['mentorship']['button']['#attributes'] = array('data-title' => array('Mentorships'), 'class' => array('SA_Button'));
  $form['suggested_actions']['list']['mentorship']['button']['#value'] = 'Confirm Mentorships';
  $form['suggested_actions']['list']['mentorship']['button']['#ajax'] = array(
      'callback' => 'erc360_completeness_report_suggested_actions_mentorship_ajax',
      'wrapper' => 'mentorshipunconfirmed',
      'method' => 'replace',
      'effect' => 'none',
  );

  function erc360_completeness_report_suggested_actions_mentorship_ajax($form, $form_state){
      dpm("The AJAX FUNCTION has ran...");
      return $form['suggested_actions']['list']['mentorship']['text']['#markup'] = '<span>confirm</span>';
  }

```

# Answer
Try following code.

```
$form['suggested_actions']['list']['mentorship']['button']['#ajax'] = array(
  'callback' => 'erc360_completeness_report_suggested_actions_mentorship_ajax',
  'wrapper' => 'mentorshipunconfirmed',
  '#callback' => 'ajax_test',
  '#wrapper' => 'wrapper',
  'method' => 'replace',
  'effect' => 'fade',
);

function erc360_completeness_report_suggested_actions_mentorship_ajax($form, $form_state){
  dpm("The AJAX FUNCTION has ran...");
  $form['suggested_actions']['list']['mentorship']['text']['#markup'] = '<span>confirm</span>';
  return $form['suggested_actions']['list']['mentorship']['text'];
}

```
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Add translation files to custom module doesn't work
I've created translations files with poedit called nl\_NL.mo and nl\_NL.po and added them to a 'translations' folder within my custom module.

Now when I try to re-install my module; the translation isn't being imported.

Could this be because my default language is NL or is some other issue?

# Answer
> 0 votes
You might need to uninstall the module completely and reinstall it again, in order to be able to import the translations. Otherwise, they are not picked up automatically. There are a couple of threads in the Drupal forums mentioning this issue: https://www.drupal.org/node/220341 , https://www.drupal.org/node/435706#comment-2711736

Hope that helps,

# Answer
> 0 votes
in

> your\_module.info.yml

you must indicate the file path

```
'interface translation project': your_module
'interface translation server pattern': modules/custom/your_module/translations/amu_hal-%language.po

```

---
Tags: i18n-l10n
---


# Question
Title: How to get $form_state['values'] after a drupal_get_form() call?
I have an form in a **block** with ajax submission. The block view code calls `drupal_get_form`, adds some other info, uses a custom theme tpl to create the block.

**I want to replace the form in the block with a thank you message after successful submission.**

**AJAX works**: The ajax on the submit element of the form means that a custom ajax callback can replace the entire form with another themed chunk, passing in the form values received by the form so they can be merged in the thank you template. This works well because the ajax function has access to the form\_state.

**But what if AJAX is unavailable** on the client? Then the normal form submit happens and the block view function just gets a blank form.

**So how can my block view function get hold of the submitted values to feed them into the thank you template?**

## Edit: messy work-arounds

1. I could just access `$_POST` but that's nasty and unvalidated! **yuk**
2. In the submit handler I can copy the `$form_state['values']` variable to a superglobal, and check for that.

# Answer
> 1 votes
I realise this is an old question but: drupal\_get\_form() is mostly a wrapper for drupal\_build\_form(), and (the docs say) is intended to be used "instead of drupal\_build\_form() when $form\_state is not needed", with the implication that if $form\_state is needed, it's OK to go straight to drupal\_build\_form().

The only extra bit drupal\_get\_form does is assemble a 'build\_info' array in the $form\_state, so instead of (e.g.) `$block['content']['form'] = drupal_get_form('myform_name', $arg);`, you could do something like this:

```
  $form_state = array();
  $form_state['build_info']['args'][] = $arg;
  $block['content']['form'] = drupal_build_form('myform_name', $form_state);

```

You should find your $form\_state variable is now populated as it would be if you were operating *inside* the form building function, including any `$form_state['values']` or `$form_state['input']` in the event that your form is being rebuilt.

---
Tags: forms
---


# Question
Title: How to get user.field value in node.twig
I have a `field_author` with different values `expert, moderator or contributor`

For get this custom USER field in node.twig i using next function

```
function MYTHEME_preprocess_node(&$variables) {

if ($node = \Drupal::routeMatch()->getParameter('node')) {
                  $variables['author'] = $node->getOwner()->field_fname->value;
        }
    }
}

```

And then `{{ author }}` in node.twig

How to get vlue of this field? For example `{{ author.0 or author.1 or author.3}}`?

Thanl you for helping!

# Answer
Does `field_fname` is a custom field added to users? if so what is the field type (select or textfield) and if it is a select how many values accept limited or unlimited values?

anyway you can try this for checkbox list Try this

```
function MYTHEME_preprocess_node(&$variables) {

if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['author'] = $node->getOwner()->get('field_fname')->getValue();
  }
}

```

node.twig:

```
{% if author.0.target_id == "expert" %}
<h1>Hello Expert<h1>
{% endif %}

```
> 2 votes

# Answer
You can try using variable `node`

Get `user.name`

```
{{ node.uid.entity.name.value }}

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How to display the variation of a custom display in Twig
In my type of product variation, I have 4 different display :

* Default
* Panier (Cart)
* Teaser
* Teaser relation

I have created a template for product type and want to display the "Photo" field of the "Teaser" display of the product variation type.

Here is what I put in my template:

```
{{ product.variation_field_produit_image }}

```

The problem is that it displays the "Photo" field of the "Default" display.

How to get the "Photo" field of the "Teaser" display?

# Answer
> 1 votes
You can create another template for that specific view mode.

The naming of that template should be `commerce-product-variation--product-type--view-mode.html.twig`.

So you can create a template called `commerce-product-variation--PRODUCTTYPE--teaser.html.twig`, and then print the image field from there.

# Answer
> 1 votes
Try the bamboo twig module with

```
{{ bamboo_render_image_style('public://antistatique.jpg', 'thumbnail') }}

```

or

```
{{ bamboo_render_entity('node', 2, 'teaser') }}

```

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


# Question
Title: Is it normal that a site changes to maintenance mode during a module update?
I have created a custom module with a .install file, which includes some `hook_update_N()` hooks, used to update existing nodes.

Whenever I run `drush updb`, the site automatically enters maintenance mode (anonymous requests get a 503), and if the update is successful, the site goes back online, all by itself.

I couldn't find any resource on the web about this situation.

Is it normal? Is there a way to disable this behavior?

# Answer
> 5 votes
It does look to be normal, yes. Drush's `UpdateDBCommands::updateBatch`, which is responsible for processing the updates, contains this:

```
batch_set($batch);

// See updateFinished() for the restore of maint mode.
$this->maintenanceModeOriginalState = \Drupal::service('state')->get('system.maintenance_mode');
\Drupal::service('state')->set('system.maintenance_mode', true);
drush_backend_batch_process();

```

The code deliberately sets maintenance mode to true before processing the batch, and then restores the original state when it's done.

Running `drush help updb` lists the following options:

* `--cache-clear[=CACHE-CLEAR]` Clear caches upon completion. \[default: "true"\]
* `--entity-updates` Run automatic entity schema updates at the end of any update hooks.
* `--post-updates[=POST-UPDATES]` Run post updates after hook\_update\_n and entity updates. `[default: "true"]`
* `--no-cache-clear` Negate `--cache-clear` option.
* `--no-post-updates` Negate `--post-updates` option.

So there doesn't seem to be an obvious way to disable the behaviour. But if you're updating the database you probably don't want people to be able to access the site at the same time. There's a good explanation for that here.

---
Tags: 8, drush, updating, maintenance-mode
---


title: Available node language only English

text:
# Question
Title: Available node language only English
I have a custom content type with "Set custom language as default for new content" and "Require language". Custom default language is Current language.

Entity translation is defined with "Current language" as "Default language" and "Exclude Language neutral from the available languages" enabled.

I have 24 languages enabled but when creating a new node, only English appears as a language. But I need to be able to set any of the 24 languages

What am I missing?

# Answer
> 1 votes
## Change interface lang to the node target lang

The configuration you describe will always only allow one language when creating new nodes: the current language of the interface.

That is because you have `Set custom language as default for new content.` (and the current one as the default).

If you want to create content in other languages, you have to visit the node creation page in that target language (`/fr/node/add/article` if you're using prefixes).

## Or allow other langs to be chosen

But if you want to be able to choose which language to assign to a node no matter what interface language you're currently using you have to ***untick*** the `Set custom language as default for new content.` while ***keeping*** `Require language (Do not allow Language Neutral).`

That way your interface may be English, but you'll be able to choose any language in a drop-down to assign to that node.

# Answer
> 0 votes
Please check the following:
1. In Entity translation settings page: "Use only enabled languages" is checked or not
2. If it is checked, then check in the `admin/config/regional/language` page that all languages are actually enabled not just added
3. If languages are added and enabled, then uncheck the option in 1

---
Tags: 7, entities, i18n-l10n, features, strongarm
---


# Question
Title: How to display custom user_field in user.twig
I created a **custom user field** -`field_interes` and I want to print this field in user.twig. Anybody can help me with this problem?

`{{ content.field_interes }}` does not work.

Thank you!

# Answer
> 2 votes
1. If the field has one single value try :

```

    {{ content.field_interes.0['#context']['value'] }}

```
2. If the field has multi value try to loop.

```

{% for key,value in content.field_interes %}
      {% if key matches '/^\\d+$/' %}
        {{ value['#context']['value'] }}
      {% endif %}
{% endfor %}

```

Don't forget to Manage display for the account fields from `admin/config/people/accounts/display`

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


title: Security model and menu access

text:
# Question
Title: Security model and menu access
Drupal 8.6.1

I have some menu items I would like to hide from some users: An administration menu with documentation about site admin; A contributors menu with documentation for contributors. etc.

It appears that Drupal prefers every menu entry to link to something. I have these menus pointing to `route:<nolink>` and have the content hanging from them, tagged as required to implement https://www.drupal.org/project/permissions\_by\_term.

The result of this is that the top level menu items are visible to everyone.

Is the Drupal philosophy to create some content/view and assign permissions to that for these top-level menus?

# Answer
> 0 votes
> Is the Drupal philosophy to create some content/view and assign permissions to that for these top-level menus?

Obviously there is no hard and fast rule about this, but generally speaking your hunch is correct. Drupal menus expect every link (even a parent) to link to some content. As an example, the "add content" link goes to a page that lists the available content types even though the content types are usually listed under "add content" in the menu anyway.

I do not believe there is an example in core where a menu link is there *only* as a parent and does not link anywhere.

# Answer
> 0 votes
`route:<nolink>` is relatively new in core (since 8.2) but also what would you rely on to check access for an item that doesn't go anywhere?

You can manually assign menu item permissions through Menu Item Role Access.

Or create your links lists through Views (Block Display). There you can assign Access by Role or existing Permission. That may be the most flexible solution if you are able to filter out your target content this way.

---
Tags: 8, navigation, security
---


title: Taxonomy overview search term

text:
# Question
Title: Taxonomy overview search term
In this manager:

admin/structure/taxonomy

admin/structure/taxonomy/manage/\[fruit\]/overview

There is a way to add a search a term?

So, if you have 100 terms it will easier to find a term.

This one is not ported at all https://www.drupal.org/project/term\_search

This module is not full ported to D8 https://www.drupal.org/project/taxonomy\_manager

I also find this interested article to alter a task in a specific vocabulary. https://www.computerminds.co.uk/drupal-code/replacing-vocabulary-listing I created the view, but I still find out how to add a tab for that view in the overview taxonomy.

There other way to add an option to search a term in manager?

# Answer
> 0 votes
Views with exposed filters sound like a great way to add a Search page to Vocabulary configuration tabs.

You can add your Views page to Vocabulary pages through Views configuration. Since the List already exists as the default tab, simply configure your Views page `Menu` option as a normal `Menu tab` and set the page path to the `[path-to-default-vocabulary-page]/search`.

The tab will appear as one of the tabs you see when you visit the Vocabulary configuration page.

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


# Question
Title: Temporarily change the current language during a request
**Background information**

I am developing a multilingual Drupal 8 commerce site where only authenticated users (customers) can place orders (anonymous users can't place orders). Customers can edit their preferred language using the default language field on their account. After an order is placed, another user with a special role (webmaster) has to prepare the order and physically fill a box with the contents of the order. When the webmaster is ready, he performs a transition on the order changing it's state. This transition triggers an e-mail that is sent to the customer, informing him that his order is ready for shipment. This e-mail is triggered through an event subscriber that reacts on the shipping transition of orders. The e-mail is formed by rendering a custom template.

**Problem**

A customer who's preferred language is Dutch, has placed an order. A webmaster is using the website in English and sets the order 'ready for shipment'. The customer gets an English e-mail while he should get a Dutch e-mail.

**Code**

The code that triggers the e-mail:

```
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $event->getEntity();

$to = $order->getCustomer()->getEmail();
$langcode = $order->getCustomer()->getPreferredLangcode();
$subject = $this->t('Your order #@order_number is packed', ['@order_number' => $order->getOrderNumber()], ['langcode' => $langcode]);

$build = [
  '#theme' => 'commerce_order_shipped_mail',
  '#subject' => $subject,
  '#order_number' => $order->getOrderNumber(),
  '#order_date' => $this->dateFormatter->format($order->getCompletedTime(), 'default_date_only'),
  '#order_url' => Url::fromRoute('entity.commerce_order.user_view', [
    'user' => $order->getCustomer()->id(),
    'commerce_order' => $order->id(),
  ], ['absolute' => TRUE]),
];

$mail = $this->mailManager->mail('order_shipped_mail', $to, $subject, $build, $langcode);

```

The mail function of the mail manger (wrapper):

```
$name = \Drupal::config('system.site')->get('name');
$email = \Drupal::config('system.site')->get('mail');
$from = '"' . $name . '" <' . $email . '>';

$params = [
  'headers' => [
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'From' => $from,
  ],
  'from' => $from,
  'subject' => $subject,
  'body' => $this->renderer->renderRoot($body),
];

$langcode = $langcode ?: $this->languageManager->getDefaultLanguage()->getId();

return $this->mailManager->mail('XXX_general', $key, $to, $langcode, $params);

```

The custom template:

```
<table>
<tbody>
<tr>
    <td>
        <h2>{{ 'Shipping confirmation'|t }}</h2>
        <p>{{ 'Dear customer,'|t }}</p>
        <p>
            {% trans %}
            Your order #{{ order_number }} of {{ order_date }} has been handed over to XXX.<br />
            You will receive an email from XXX with the tracking information of your package.
            {% endtrans %}
        </p>

        <p><a href="{{ order_url }}" target="{{ 'Order details'|t }}">{{ 'Order details'|t }}</a></p>

        <p>The XXX team</p>
    </td>
</tr>
</tbody>

```

As you can see a custom template is rendered that contains the body of the e-mail.

**Actual question**

How can I temporarily change the current language during a request so rendering happens in the correct language? I know I can give a langcode to a t-function but my rendered order URL would still be an English URL so this doesn't fix the problem. I have tried suggestions from here, and I thought the LanguageNegotiation Plugin would do the trick, but it doesn't.

Please excuse me if my question is malformed or if I provided to little information.

# Answer
See How to progragrammatically get NodeType translated value in D8?, that example is actually based on `user_mail()` which has exactly the same use case, to send things like password reset e-mails in the language that the user set in his profile.

That will however only work for stored configuration. I think you can't easily change the active interface language, what you can do is explicitly pass the language to each t() call, also inside twig, at least for t().

The only thing I can think of right now that might allow to override it is do a fake negotiator, set that with setNegotiator() on the language manager, then at the end set back the original one.
> 2 votes

---
Tags: 8
---


# Question
Title: Change add node select field to show data from 2 different fields of other content type
I didn't know exactly how to ask this but the idea of what I need is very simple.

I have content type A with 2 fields: title and A2

Then I have another content type, B, with a node reference field (select box) that references title from node type A.

What I need is that the options in the select box are the concatenation of both title and A2 field.

Is this possible without coding my own module?

# Answer
> 2 votes
Install the Entity Reference module. It allows you to pull up information from one content type into another. Here is a super helpful tutorial of pretty much what you want to achieve so there is no need for me to provide detail explanation here. https://atendesigngroup.com/blog/getting-started-references-drupal

---
Tags: nodes
---


# Question
Title: Attempt URL alias for spanish version of page - "The path */* is either invalid or you do not have access to it."
Drupal 7.59. We have the page whatever.tld/thanks and whatever.tld/es/thanks. I'm trying to setup whatver.tlp/gracias as a URL alias for es/thanks and it says "The path 'es/thanks' is either invalid or you do not have access to it."

The page itself is a tpl.php file referred to by a view and has individual blocks on it that are translated.

This translation stuff is beyond me. I have a dev site to practice on so I'm happy to try out any ideas. The following (apparently) applicable modules are enabled:

* GTranslate
* Block languages
* Internationalization
* Menu translation
* Multilingual content
* String translation
* Translation sets

# Answer
As @prkos mentioned enable the languages module. In the Configuration/Regional and language/Languages settings you select the code you wish to use for your languages. The choice is obviously yours but when I have a multilingual site I prefer to use the ISO language code to help define the languages on the site.
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Theme Preprocess Conditional Field Display
Looking for a way to preprocess two fields. I am trying to hide Field 1 from display if Field 2 has value.

If Field 1 has value and Field 2 has value display Field 2 only. If Field 1 has value and Field 2 has NO value display Field 1.

This should only apply to content type USER POSTS. And I am using Display Suite to arrange the fields if that makes a difference.

What would be the preprocess hook to place on mytheme.theme?

Any help is greatly appreciated.

# Answer
Can you hide it with CSS? In which case you could do something simple like:

```
<?php

/**
 * Implements template_preprocess_hook().
 *
 * Adapt logic, field names etc to suit your needs.
 */
function MYTHEME_preprocess_page(&$variables) {

  if (empty($variables['node']->get('my_field_2')->value)) {
    $variables['page_classes']['#plain_text'] .= ' field_two--display-none';
  }

}

/* CSS */
.field_two--display-none { display: none; }

```

Not super elegant but would do the trick.

Your other option is to use the conditional fields module.
> 1 votes

---
Tags: 8, theming, hooks, display-suite
---


title: How do I get the base path?

text:
# Question
Title: How do I get the base path?
I want to use the base path in a Drupal 8 template file. I tried the following, but I don't get the correct result.

```
{{ app.request.baseUrl  }}

{{base_path}}

```

What I need is the absolute path to the node `{{ app.request.baseUrl }}/{{ url }}`.

One solution I found is putting this code in a preprocess hook, and pass it to the theme.

```
 $host = \Drupal::request()->getHost();
$response = \Drupal::httpClient()

```

I am looking for a better solution. What could should I use instead of the one I am using?

# Answer
And According to Page Documentation on 8.2.x , two global variables added to return front page and Base Path Urls :

> front\_page: The URL of the front page. Use this instead of base\_path when linking to the front page. This includes the language domain or prefix.
>
> base\_path: The base URL path of the Drupal installation. Will usually be "/" unless you have installed Drupal in a sub-directory.

**So** you can get font page Url with `front_page` and base Url with `base_url`

**Note**

getting front page url with `{{ url('<front>') }}` has a issue when you want concat it with other path, as example

```
{%  set base_url = url('<front>')  %}
{% set url = [ base_url,'/landing-page?invitecode=' ,invite_code] | join  %}
{{ url }}

```

return

```
Array/landing-page?invitecode=

```

this mean by default is not text and return a render able array to twig
> 4 votes

# Answer
You can use `url()` to generate a base url to any route in Drupal. You can supply the `<front>` route which, in effect, will be your base URL.

```
{{ url('<front>') }}

```

But, **render** it first if you're concatenating it:

```
{{ url('<front>')|render ~ file_url('public://image.jpg') }}

```

For example:

```
{{ url('<front>') ~ file_url('public://image.jpg') }}
# Outputs: "Array/sites/all/default/files/image.jpg"

{{ url('<front>')|render ~ file_url('public://image.jpg') }}
# Outputs: "http://example.com/sites/all/default/files/image.jpg"

```
> 48 votes

# Answer
In `page.html.twig` you *will* have a working `{{ base_path }}` variable. Why it isn't available in every template, i have no idea. As i think it should be and everything else looks messy, my preferred solution is to do exactly as Drupal does in the preprocess page function for any place i need it.

To make `{{ base_path }}` available to block templates in a theme named example, add this code to the `example.theme` file:

```
/**
 * Implements hook_preprocess_block().
 */
function example_preprocess_block(&$variables) {

  $variables['base_path'] = base_path();
}

```

As noted in the accepted answer provided by MPD, if getting a node's or other entity's URL there are methods to do it all for you.

However, there are reasons for getting the base\_path, such as when displaying images that live in your theme folder. `{{ directory }}` provides the path to the theme folder, but it leaves off the base path (usually just a / but in order to preserve Drupal's proper functioning from a subdirectory of a domain that shouldn't be hardcoded). On `page.html.twig` or in any template which has the above preprocesser, this will work for that purpose:

```
<img src="{{ base_path ~ directory }}/images/nsf1.svg"
     alt="National Science Foundation logo" height="80" width="80" />

```

And of course Shawn Conn's answer works fine if you can suppress your desire for pretty templates, but i couldn't.
> 17 votes

# Answer
You almost never need to explicitly build up paths from parts in Drupal 8. I would go with something like this:

```
function FOO_preprocess_node(&$variables) {
  /** @var \Drupal\node\NodeInterface $node */
  $node = $variables['node'];
  $variables['url'] = $node->toUrl('canonical', [
    'absolute' => TRUE,
    'language' => $node->language(),
  ])->toString();
}

```
> 13 votes

# Answer
All of the above failed for me, because I have language paths setup, so my front page URL looks like `https://example.com/en`.

I ended up using this code to get the actual base URL for my site:

```
{% set base_url = url('<front>')|render|split('/', -1)|join('/') %}

```
> 12 votes

# Answer
So far this thread doesn't bring any proper solution. We can concatenate it by using render\_val()

Here is the way I used it, to get the absolute path of an entity image:

```
{% set base_url = render_var(url('<front>'))  %}
{% set url = base_url|trim('/', 'right')~file_url(content.field_media[0]['#media'].get('field_image').entity.uri.value)  %}

```

1st we get the base URL of the site. Then we need to remove an extra /. Then we concatenate our base path with our image relative path.
> 4 votes

# Answer
In

```
function hook_preprocess(&$variables) {
  $variables['base_path'] = base_path();
}

```

& in template file u can call via

```
{{ base_path ~ directory }}

```
> 3 votes

# Answer
```
{{ path('<front>') }}

```

I know you've already marked this as correct, but this can be used as a twig element in a template file without any extra work. I found this in the block--system-branding-block.html.twig from the Classy theme. So you can use it like this:

```
<a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>

```
> 2 votes

---
Tags: theming
---


# Question
Title: How to add template suggestion for user--VIEW-MODE--ROLE.html.twig
I used `hook_theme_suggestions_HOOK_alter`:

```
function MYTHEME_theme_suggestions_user_alter(&$suggestions, $vars, $hook) {

  // Define the view mode.
  $mode = $vars['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;
}

```

Now I can work with `user--full.html.twig` and `user--compact.html.twig`

But I have a role `editor` and I want to `user--compact--editor.html.twig` to be picked up. How can I add a template suggestion based on user roles?

# Answer
All you need to do is to get the current user object, get its roles, and then add the suggestion like in the following snippet. The current user also already is available in the `$variables`.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_user_alter(array &$suggestions, array $variables) {

  // Define the view mode.
  $view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $view_mode;

  // Get current user.
  $current_user = $variables['elements']['#user'];

  // Get current user's roles.
  $roles = $current_user->getRoles();

  // Add suggestion per role.
  foreach ($roles as $role) {
    $suggestions[] = 'user__' . $view_mode . '__' . $role;
  }
}

```

This will give you:

```
<!-- FILE NAME SUGGESTIONS:
   * user--full--administrator.html.twig
   * user--full--authenticated.html.twig
   * user--full.html.twig
   x user.html.twig
-->

```
> 11 votes

---
Tags: 8, theming, users
---


title: Turn /node off but keep aliases

text:
# Question
Title: Turn /node off but keep aliases
I want my node page turned off. I don't want mysite/node/3 to work. I want it to display 404. I tried rabbit hole and it worked but the problem ws that it also stopped the aliases from working.

Is there a solution where I can turn off the node/whatever but keep my aliases?

# Answer
> 0 votes
I'm guessing you're on drupal 7?

Rather than trying to disable/show a 404 you could install this module: https://www.drupal.org/project/globalredirect

That will make it so that if anyone tries to access one of the "node/\*" urls they will be automatically be redirected to the proper alias of the page. Would that work for what you need?

# Answer
> -1 votes
You can check the path in a preprocess function using this algorithm:

**If** current route is /node/\* **and** current route is not an admin/config path **then**

Redirect to 403 page

**End if**

---
Tags: path-aliases
---


# Question
Title: How to add a percent field in content type
Simple question. When creating a content type field, we have a float, decimal and integer number type, but how can we create a field with percentage type value, basically a range of 1-100%.

# Answer
Could you not just create either a integer or float number field and just label the field as "percentage" or whatever? And also use the "suffix" option on the field options to add "%"

You can also set the min and max values of 0 to 100 to keep it within percentage range of options

Or how would you be expecting a percentage field to act different from a float/integer field?
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Module dependent on field configuration in another module
I have two modules that rely on the same field; A simple boolean field that represents a state for taxonomy terms. My problem is my configuration management for this. My ideal situation would be to put this field storage configuration in my site's config directory and then both modules' info files specify a configuration dependency (using the field config's ID) on this field. But I cannot get it working.

This is what I have tried to far in both my module's info files:

```
dependencies:
  - taxonomy
  - config:
    - taxonomy_term.field_my_field

```

and

```
config_dependencies:
  - taxonomy_term.field_my_field

```

For both of these methods, the field.storage.taxonomy\_term.field\_my\_field.yml file is among the rest of the site's config. I can move it to either module's `config/install` directories and it makes no difference.

My field's storage config file is as so:

```
uuid: 8e23dc90-2da9-4824-9783-093181987869
langcode: en
status: true
dependencies:
  module:
    - taxonomy
_core:
  default_config_hash: pr_yX1hCVsd_ni59pjsAQh5n7hCJ2eAnPNzJCBCHJig
id: taxonomy_term.field_my_field
field_name: field_my_field
entity_type: taxonomy_term
type: boolean
settings: {  }
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

So my question is, what is generally the best practice for managing a single piece of configuration that's required by 2+ modules?

# Answer
Updating Drush solved my problem... I went from 8.1.16 which I used deliberately due to it's compatibility with D7 & 8 as I'm still working with lots of 7 sites. After updating to 9.4.0, the field's storage config in the site's configuration directory gets imported no problem.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: Prevent JS code to be called more than once? ( "once and for all' behavior-attached functions )
this jquery code works fine (demo codepen ): https://codepen.io/matoeil/pen/XxapEL

**jquery**

```
var $exposed_form=$('.views-exposed-form').clone();
$exposed_form.prependTo('.pagerer-right-pane');

```

**html**

```
<form class="views-exposed-form grid-x grid-margin-x" data-drupal-selector="views-exposed-form-users-index-page-1" action="/en/directory" method="get" id="views-exposed-form-users-index-page-1" accept-charset="UTF-8">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_exposed_form' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/views/views-exposed-form.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/form-element.html.twig' -->
<div class="js-form-item form-item js-form-type-textfield form-item-search-api-fulltext js-form-item-search-api-fulltext cell small-12 medium-6">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/form-element-label.html.twig' -->
<label for="edit-search-api-fulltext">recherche par nom</label>
<!-- END OUTPUT from 'core/themes/stable/templates/form/form-element-label.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'input__textfield' -->
<!-- FILE NAME SUGGESTIONS:
   * input--textfield.html.twig
   x input.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/input.html.twig' -->
<input data-drupal-selector="edit-search-api-fulltext" type="text" id="edit-search-api-fulltext" name="search_api_fulltext" value="" size="30" maxlength="128" class="form-text">

<!-- END OUTPUT from 'core/themes/stable/templates/form/input.html.twig' -->

        </div>

<!-- END OUTPUT from 'core/themes/stable/templates/form/form-element.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/form-element.html.twig' -->
<div class="js-form-item form-item js-form-type-select form-item-items-per-page js-form-item-items-per-page cell small-12 medium-6">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/form-element-label.html.twig' -->
<label for="edit-items-per-page">VOIR</label>
<!-- END OUTPUT from 'core/themes/stable/templates/form/form-element-label.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'select' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/select.html.twig' -->
<select data-drupal-selector="edit-items-per-page" id="edit-items-per-page" name="items_per_page" class="form-select"><option value="10" selected="selected">10</option><option value="20">20</option><option value="50">50</option><option value="100">100</option></select>
<!-- END OUTPUT from 'core/themes/stable/templates/form/select.html.twig' -->

        </div>

<!-- END OUTPUT from 'core/themes/stable/templates/form/form-element.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'container' -->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/container.html.twig' -->
<div data-drupal-selector="edit-actions" class="form-actions js-form-wrapper form-wrapper cell small-12 medium-6" id="edit-actions">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'input__submit' -->
<!-- FILE NAME SUGGESTIONS:
   * input--submit.html.twig
   x input.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/input.html.twig' -->
<input data-drupal-selector="edit-submit-users-index" type="submit" id="edit-submit-users-index" value="Apply" class="button js-form-submit form-submit">

<!-- END OUTPUT from 'core/themes/stable/templates/form/input.html.twig' -->

</div>

<!-- END OUTPUT from 'core/themes/stable/templates/form/container.html.twig' -->

<!-- END OUTPUT from 'core/themes/stable/templates/views/views-exposed-form.html.twig' -->

</form>

<div class="pagerer-right-pane"></div>

```

but crashes my browser by being called many times in the drupal context.

**my library js file**

```
(function ($, Drupal, drupalSettings) { // closure
    'use strict';

    Drupal.behaviors.directory = {
        attach: function (context) {
            $('main', context).ready(init);
            function init() {
    var $exposed_form=$('.views-exposed-form').clone();
$exposed_form.prependTo('.pagerer-right-pane');

            }
        }
    };
}(jQuery, Drupal, drupalSettings));

```

How to prevent globally this recurrent problem?

# Answer
Don't use `.ready` use `.once`. Drupal behaviors will fire on their own, so all you need is `.once`.

See: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

> When using jQuery it is standard for a large majority of situations to wrap almost all code inside the $(document).ready() function, like this:
>
> `$(document).ready(function () { // Do some fancy stuff. });`
>
> This ensures that our code will only run after the DOM has loaded and all elements are available. However with Drupal there is an alternate better method; using the functionality of Drupal.behaviors and once(). If used properly this will ensure that your code runs both on normal page loads and when data is loaded by AJAX (or BigPipe!) - but not jQuery methods like load() which should be avoided as Drupal behaviors will fail to load for loading functions other than ajax().

So you'd be looking at something like..

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {
      $('.views-exposed-form', context).once('myBehaviorUniqueKeyHere').clone().prependTo('.pagerer-right-pane');
    }
  };
}(jQuery, Drupal, drupalSettings));

```

I would tighten up on the selectors - there could be multiples of these on one page, so make sure you're targeting the exact thing to clone and manipulate. Example, `#views-exposed-form-users-index-page-1` or using form alter to append your own unique data-attribute on the form to select by.

All thats left is using `#attached` property or other methods of attaching the JS script to the page or element.
> 5 votes

---
Tags: javascript
---


title: How do I setup a proper 404 page?

text:
# Question
Title: How do I setup a proper 404 page?
At present, my Drupal 7 website’s "Page not found" is 301 redirected to a custom 404 page.

However, I just checked the HTTP response code for a random URL and I noticed it 301 redirects to a custom "Page not found" page, but that page returns a 200 HTTP response code.

Shouldn't the page response header be 404?

If that's the case how do I fix the response code to 404 in Drupal 7?

# Answer
> 2 votes
Instead of using a 301 redirect to your custom 404 page, just go to

Admin \> Config \> System \> Site Information

```
/admin/config/system/site-information

```

Enter your new path into the 404 error page box, and click "Save configuration".

You might also want to try the CustomError module: https://www.drupal.org/project/customerror

# Answer
> 0 votes
The default response of the not-found request is 404. Even if you use a custom page for 404 requests. The path to the page needs to set at `admin/config/system/site-information` for the
**`Default 404 (not found) page`**. Check the network tab for verifying the status of `Type` `document`.

---
Tags: 7
---


# Question
Title: Can't import configs on server due to some entities
So when i try to manually import configs (/admin/config/development/configuration) i get these messages:

* Entities exist of type Media and Media type Image. These entities need to be deleted before importing.
* Entities exist of type Media and Media type File. These entities need to be deleted before importing.
* Entities exist of type Content and Content type Media tester. These entities need to be deleted before importing.

Core is 8.6.1

Anyone know how to solve this? Btw this is prod, so deleting content is a no go.

# Answer
> 1 votes
This is tricky to solve. And with the limited data provided in the question, there are a few steps that I would suggest you take:

1. **Backup!!!** No need to emphasize more as this is production environment. The following steps should be carried out on your local setup and not production.
2. Find out what changed in the entities. The change should most probably be in the field settings for one or more fields in the entity types listed in the messages. Check with the developer if you are not sure about the changes. If the changes are not desired, simply export the current configuration using `drush cex` and push it. If this is the case, then it will be ideal for all. If not continue to next step.
3. Since deleting the fields is not an option as it would delete the data, create a new field with exactly the same label but different machine name. These fields could have desired settings.
4. Write a script (update hook, migration, drush command - recommended, etc) which will copy the data from the original fields' to the new field with the correct settings.
5. This script could also then delete the field with the older setting which was preventing the config import.

**Note:** You need to consider the usage of the field at the implementation level and make sure you handle those. Like:

1. In any view mode for the entities.
2. In any view.
3. Any preprocess function.
4. If the field template has been overridden.

The data is very crucial here. So TEST, TEST, and TEST! Everything would be easy if there are a limited amount of entities with values in the conflicting fields and that the data could be handled manually by deleting the fields.

---
Tags: entities, media, configuration
---


# Question
Title: node API hook that can be used to alter fields before loaded by Views?
I need to use a node API hook to alter some node content before it's displayed, in Drupal 7.

It just occurred to me though that if I used `hook_node_view()` it will not effect the output of a View that display's those nodes fields (right?).

I need to alter the fields in **both** the display of the node and the node's display in any views. Hopefull this can be done in one function, and not have duplicate code in both `hook_node_view()` and `hook_views_pre_render()` or `function hook_views_data()`whichever hook is used.

# Answer
> 2 votes
There are multiple ways in which this could be achieved:

1. Override the field itself in your theme with `template_preprocess_field()`.
2. If the customization is more towards the markup, you can directly achieve that by overriding the field template.
3. Or you could just write a field formatter for this field, and select it in the field settings of the views and the view-mode (manage display) of your content type.

---
Tags: 7, views, nodes, hooks
---


title: Pass argument to view for pager limit

text:
# Question
Title: Pass argument to view for pager limit
It is possible to pass and argument to a view for the limit on its pager? I see that there is this question for Drupal 7, but not Drupal 8.

# Answer
Try this out :

```
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_build().
 */
function customModule_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'your_view_id') {
   //- Set the new limit here // 3
   $view->setItemsPerPage(3);
  }
}

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to alter the owner/authored by field to the current user when using quick_node_clone
Using Drupal 8 with quick\_node\_clone module.

When a node is cloned I need to change the 'owner' or 'authored by' value to the person who is cloning the node.

There is an opportunity of manually changing this but I need to automate this. I am have been trying the `hook_form_alter` with some alternatives, see the commented out section, without success.

```
function quick_node_clone_form_alter(&$form, FormStateInterface $form_state, $form_id) {

 print_r($form_id);

 if ($form_id == 'quick_node_clone') {
  // change author
  //$form['author']['name']['#value'] = $user->uid;
  //$form->setOwnerId($current_user);
  //$form->uid = $user->uid;

  print_r($form['field_author']['nid']['nid']['#value']);
  global $user;
  $form['field_author']['nid']['nid']['#value'] == $user->uid;
 }
}

```

Any direction would be appreciated.

# Answer
Try this out:

```
use Drupal\Core\Entity\EntityInterface;
/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  $entity->setOwnerId($current_user_id);
}

```

**Edit**
You would be better to check on your content type:

```
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  if ($entity->bundle() == 'your_content_type_name'){
    $entity->setOwnerId($current_user_id);
  }
}

```
> 0 votes

---
Tags: 8, nodes, hooks
---


# Question
Title: Different page--user.html.twig for different user roles
I have a few user roles - simple user, editor and contributor.

How to make different profile pages for all of this roles?

Now I can work with:

```
FILE NAME SUGGESTIONS:
   * page--user--16.html.twig
   * page--user--%.html.twig
   x page--user.html.twig
   * page.html.twig

```

But I want work with `page--user--somerole.html.twig` (not (!) `user--page--somerole.html.twig`)

Thank you for any help.

# Answer
It's not much different from how it got solved in the other question you asked. You just have to target `page` this time. So `hook_theme_suggestions_HOOK_alter()` becomes `hook_theme_suggestions_page_alter()`.

And you need to check if you are currently on a user page before you add the suggestion.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_match = \Drupal::routeMatch();

  // Check if on user page.
  if ($route_match->getRouteName() == 'entity.user.canonical') {

    // Get current user
    $current_user = $route_match->getParameter('user');
    if ($current_user instanceof \Drupal\user\entity\User) {

      // Get user roles.
      $roles = $current_user->getRoles();
      foreach ($roles as $role) {

        // Add template suggestion per role.
        $suggestions[] = 'page__user__' . $role;
      }
    }
  }
}

```

---

Alternatively, if you want the suggestion to be added only for a certain role, try that:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_match = \Drupal::routeMatch();

  // Check if on user page.
  if ($route_match->getRouteName() == 'entity.user.canonical') {

    // Get current user
    $current_user = $route_match->getParameter('user');
    if ($current_user instanceof \Drupal\user\entity\User) {

      // Add template suggestion for certain role.
      $role = 'somerole';
      if ($current_user->hasRole($role)) {
        $suggestions[] = 'page__user__' . $role;
      }
    }
  }
}

```
> 6 votes

---
Tags: 8, theming
---


# Question
Title: Connection timed out and lock_may_be_available() on working site
I'm hoping someone can point me to a fix. My drupal 7 app was running fine locally this a.m. while I was testing a way to insert a row using mysql tools for a non-Drupal function. My environment is Apache running virtual host on php 5.4.34 on a Ubuntu VM.

After not getting satisfaction using the mysql functions, I started a simple PDO function using Drupal's database settings from the settings.php file. I was able to insert a row successfully but when I returned to the local site I got this error after a long time:

```
drupal_log_error(Array ([%type] => PDOException,[!message] => SQLSTATE[HY000] [2002] Connection timed out,[%function] => lock_may_be_available(),[%file] => /media/psf/Home/apps/habitatnashville/includes/lock.inc,[%line] => 167, etc

[%type] => PDOException
    [!message] => SQLSTATE[HY000] [2002] Connection timed out
    [%function] => lock_may_be_available()
    [%file] => /media/psf/Home/apps/habitatnashville/includes/lock.inc
    [%line] => 167
    [severity_level] => 3

```

I've looked here and on Drupal's site. Because it's a connection error the likely suspects are that I've munged the credentials somehow.

When something like this happened months ago, I did a service mysql restart, did that again a few minutes ago, rebooted the ubuntu VM and rebooted entire computer to shake that lock.

I've removed that test file with the PDO just in case. Here's the output of my drush status:

```
Drupal version                  :  7.27
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database username               :  admin
 Database name                   :  my_db
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  My_theme
 Administration theme            :  rubik
 PHP executable                  :  /home/sam/.phpbrew/php/php-5.4.34/bin/php
 PHP configuration               :  /home/sam/.phpbrew/php/php-5.4.34/etc/php.i
                                    ni
 PHP OS                          :  Linux
 Drush version                   :  6.2.0

```

My database is running as "service mysql status" =\> mysql: start/running, process 1291. What else could be affecting this?

# Answer
> 0 votes
There could be multiple reasons/thoughts:

1. Are you sure mysql is running?
2. Has your site got just too big for the resources allocated to mysql in the configuration?
3. Did you manually "emptied" all of the cache files via the database?
4. Low file system space on the database server
5. If you just moved the site to the other server and mysql is not set up to accept enough connections.
6. The user you are connecting with has SELECT permissions on mysql but not DELETE or UPDATE etc.
7. The host settings in sites/default/settings.php doesn't matche the one from the User in the database
8. MySQL 5.7 does not allow root user to access a database from client app. After switching to a normal user, it solves.
9. Sometimes tuning xampp like on php.ini (memory\_limit=256M) and my.ini (max\_allowed\_packet = 32M) and disable devel by drush (drush dis -y devel) also works. ...

---
Tags: database
---


# Question
Title: How to send the emails related to the user account in HTML?
I want to send the emails related to the user account in HTML version:

* forgotten password
* new account
* account canceled
* ...

If I make a copied paste of my HTML code, it does not work.

```
/admin/config/people/accounts

```

How to send the emails related to the user account in HTML ?

# Answer
The mimemail module is what usually would be the right solution for this, but is seems to contain an error, so that it does'nt add HTML to the user account mails.

Check issue here, mimemail issue.
> 1 votes

# Answer
Mimemail helps you send the emails with html. Are you sure you have updates those system emails with html/css?

With mimemail, it is not guaranteed that user will see email in html. User clients may be configure to receive plain text emails only.

\[Edit\] Have a look at this module: https://www.drupal.org/project/mailsystem
> 1 votes

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


# Question
Title: Why does the shopping cart display the login form?
When I'm not logged in and click on the cart logo, the following page appears with the login form:

```
/cart

```

1) I want the contents of the shopping cart to be displayed.

2) When I click on the "Checkout" button I want to display the login form.

How to do this ?

Why does the shopping cart display the login form ?

# Answer
> 0 votes
There are a a few ways. 1) Set permission to access cart to logged in users only 2) On site information page, set 403 to user/login

There should be a module for this. As soon as I find it, I will update my answer.

---
Tags: 8, users, commerce
---


title: How to use short codes with arguments

text:
# Question
Title: How to use short codes with arguments
I came across this. That shows how you can get a code like {{ cta }} populated with any data you want, and get that inserted in a template. I want the same sort of solution, but for content. In other words, let's say I have a blog post, I want to be able to add:

```
{{ cta }}

```

or

```
[[ cta ]]

```

or any convention that works. But the end result is that I must be able to populate the variable via code.

**BACKGROUND INFO**

I have a bunch of events on my website. I often write blog posts where I refer to events on the site. To add dynamic content to my blog posts, I'd love to simply add things like:

```
{{ events || from:19dec2014 || to: 23dec2018 }}

```

I would then populate these with the correct information.

Any ideas on how to do this correctly?

# Answer
> 1 votes
Try the Shortcode module. It was the among the first hits when I searched for Drupal 8 shortcode.

---

For the second part of your question I'd recommend Insert View. You can embed a view via a short code in your content and also pass arguments to it.

> Insert View is a filter that allows users to embed content lists generated by the Views module into node bodies and blocks using relatively simple tag syntax.
>
> Why would you want to use an Insert View tag when you could just invoke a view using PHP? Simple. When you want to allow users to insert views or edit content on a page with an inserted view without granting them permission to use PHP.
>
> The tag syntax is `[view:name=display=args]`
>
> The parameters are: view name, view display id, view arguments.
>
> Valid examples:
>
> * `[view:my_view]` is replaced by the content listing.
> * `[view:my_view=my_display]` invokes the view using the specified display.
> * `[view:my_view=my_display=arg1/arg2/arg3]` invokes the view using the specified display and passes arg1, arg2 and arg3 to the view.
> * `[view:my_view==arg1/arg2/arg3]` passes arg1 to the view and will use the "default" display set for the view.

---
Tags: 8
---


# Question
Title: hook_form_form_id_alter doesn't save data by default
I use `hook_form_form_id_alter()` to edit the `user_form`. I'm creating some checkboxes and textfields. Thats working fine. I also can output the values, when clicking the submit button.

But it doesn't save the values by default.

How do I save my values?

# Answer
`hook_form_form_id_alter` only alters the form object for *presentation / behavioral changes* on existing forms. It doesn't alter *processing or storage* for existing forms.

For that you'll need to add a custom submission handler, or use the Form UI to create new custom user fields if you don't need custom processing/storage needs.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Display single field from argument taxonomy term in Views header area
I have a view with a taxonomy term ID in the URL which is used to filter the displayed entities in the view.

I want to display the description from the taxonomy term.

I've tried this a million different ways.

I've even gone as far as defining a view mode for the vocabulary which only includes the field - that doesn't work because it insists on displaying the title linked to the term page (which I definitely don't want). I even tried the layout builder but that displayed the title as well.

This is not the same as modifying the page title - which I am doing successfully.

Any ideas what I can do?

# Answer
I've included my original response below but it turns out I'm an idiot: All you have to do is create the taxonomy-term as a relationship and then you can just pick out the field you want. D'oh!

~~~ my original answer

Yeah, so this is a problem that is currently unsolvable without code as of Drupal 8.6.0. Unless you deploy Display Suite, which is using a sledgehammer to crack a nut.

There's a lot of discussion on drupal.org about the lack of control on title fields in respect to nodes but the issue goes deeper. It applies to Taxonomy as well: You cannot stop the title field from appearing in any view mode because that's the way the template works.

The only solution is to create a new template that doesn't display the title (in my case `taxonomy-term--book-series.twig.html`) plus the supporting `hook_theme()` and `hook_preprocess_taxonomy_term__book_series()` all of which is a PITA.

Even then it's not great because there are no (default) theme suggestions for taxonomy terms that include view modes. It would have been much nicer if I could have designed a view mode called "description" and then had a theme suggestion of `taxonomy-term--description.twig.html` because that would then work in all cases. Instead I have to create the same template and support code but for a different vocabulary.

All-in-all, not the best experience.
> 0 votes

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


# Question
Title: How to specify AND, OR with dynamic query
I’m trying to create a dynamic query, the query logic conditions needed are: AND, and OR.

The main query will include two sub queries.

The ConditionInterface::condition documentation states that:

> If called with 1 parameter, it should be a ConditionInterface that in itself forms a valid where clause. Use e.g. to build clauses with nested AND's and OR's.

I cannot find the example to build clauses with nested AND’s and OR’s so I’ve done some digging through the ConditionInterface API Reference (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21ConditionInterface.php/interface/ConditionInterface/8.6.x)

I found a function conditionGroupFactory (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21ConditionInterface.php/function/ConditionInterface%3A%3AconditionGroupFactory/8.6.x)

The conditionGroupFactory function appears to be what I need, however I cannot find any implementation examples.

Could someone please explain the implementation of this function.

```
$result = $connection->select('inventory', 'inv');
$result->fields('inv', ['part_number']);
$result->condition('inv.visable', 1);
$result->conditionGroupFactory('AND')->condition('inv.part_number', $queryOne, 'IN');
$result->conditionGroupFactory('OR')->condition('inv.part_number', $queryTwo, 'IN');

```

Note: `$queryOne, $queryTwo;` Are of type SelectInterface.

My Objective SQL Statement:

```
SELECT inv.part_number
 FROM inventory AS inv
 WHERE inv.visable = 1
 AND (inv.part_number IN (SUBQUERY_1)
 OR  inv.part_number IN (SUBQUERY_2));

```

# Answer
> 1 votes
I don't have the same structure of your table but i test it with the following statement it works:

```
SELECT *
 FROM `node__body` AS n_b
 WHERE n_b.`deleted` = 0
 AND (
 n_b.`revision_id` IN (32,6,17)
 OR  n_b.`langcode` IN ('fr')
 );

```

here is the code snippet for your case:

```
  $query = $connection->select('inventory', 'inv')
    ->fields('inv', ['part_number'])
    ->condition('inv.visable', '1', '=');
  //- Set Or Query group
  $group = $query
    ->orConditionGroup()
    ->condition('inv.part_number', [SUBQUERY_1], 'IN')
    ->condition('inv.part_number', [SUBQUERY_2], 'IN');
  //- Add Or group
  $query->condition($group);
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

```

---
Tags: 8, database
---


# Question
Title: Customize "Access Denied" (403) page for specific content type
I'm currently setting up a simple LMS in Drupal 8 and would like to customize the *Access Denied* page as follows:

* **Anonymous users** should be redirected to the *Login* page, when they hit a 403 error.
* **Logged in users** trying to access a **specific content type** (a Course), which they are not allowed to access, should be redirected to a custom message (telling them to buy the course or something like that). It would be even better, if they could be shown the teaser of that node, but that's not a necessity.
* In all other cases, I would like to show a general *Access Denied* page.

Fwiw, there were similiar questions for D6 here and here that also didn't receive any good replies.

Does anybody happen to know a good solution (for D8)? Any help would be much appreciated.

# Answer
> 1 votes
You could do that using the rules module.

Create a rule using the Rules module, with as Event something like `After visiting node no_access`. So that the entire rule configuration would look something like this:

**Events:** After visiting node no\_access

**Conditions:** User has role - Parameter: User: \[site:current-user\], Roles: anonymous user NOT Text comparison - Parameter: Text: \[site:current-page:url\], Matching text: user/login

**Actions:** Page redirect - Parameter: URL: user/login

And then for the logged in user, you can create another rule that checks if the user is logged in, and then redirects to a custom page if the user visits a `no_access` page.

For the general access denied page, you can set a url in `Admin > Configuration > System > Site information`, under error pages.

Hope it helps

---
Tags: 8, users, redirection
---


# Question
Title: Edit field in contentType B when creating or editing node of contentType A
I need to edit a field in contentType B when I create or edit nodes of contentType A.

I know it's possible to use rules for this but I need to have more control so I want to do it in my own module.

Tried this code without success:

```
function MYMODULE_node_presave($node) {
    MYMODULE_change_value($node);
}

function MYMODULE_change_value($node) {
    $node = node_load($node->nid);

    $referenced_nid = $node->referenced_node[LANGUAGE_NOE][0]['target_id']

    $referenced_node = node_load(referenced_nid);

    $referenced_node->my_field[LANGUAGE_NONE][0]['value'] = 12345.0;
    node_save($referenced_node);
}

```

Am I choosing the wrong hook?

# Answer
> 1 votes
Try the following:

```
/**
 * Implements hook_node_presave().
 */
function yourModule_node_presave($node) {
  if ($node->type == 'your_typeA') {
    yourModule_change_value($node);
  }
}

function yourModule_change_value($node) {
  if (isset($node->field_node_referenced[LANGUAGE_NONE][0]['target_id'])) {
    //- Get referenced node id
    $referenced_node_id = $node->field_node_referenced[LANGUAGE_NONE][0]['target_id'];
    //- Load referenced node
    $wrapper = entity_metadata_wrapper('node', $referenced_node_id);
    $wrapper->field_name->set(array(
      'value' => 'test new field value'
    ));
    $wrapper->save();
  }
}

```

---
Tags: 7, nodes, hooks
---


# Question
Title: How to change the variation title in the add to cart block in Drupal Commerce 1?
I'm building a store in D7 and Commerce 1. My product variations have a Size attribute - these are displayed in the Add to Cart block as a list of radio options.

I would like the option labels to include the price of that variation, e.g.

* Small - $10
* Medium - $15
* Large - $20

These labels should be generated automatically from the price.

I figure this could be achieved with a simple function, but I haven't been able to find one. Any suggestions welcomed!

# Answer
> 0 votes
OK. I got it working. Perhaps not quite as simple as I'd hoped, but this function will do the trick ...

```
function commerce_price_attribute_form_commerce_cart_add_to_cart_form_alter(&$form, $form_state) {
    if (isset($form['attributes'])) {
        $entity = entity_load_single($form_state['context']['entity_type'], $form_state['context']['entity_id']);
        foreach (element_children($form['attributes']) as $field) {
            foreach (field_get_items($form_state['context']['entity_type'], $entity, 'field_product') as $product) {
                $product = commerce_product_load($product['product_id']);
                $status = entity_metadata_wrapper('commerce_product', $product)->status->value();
                if ($status) {
                    $items = field_get_items('commerce_product', $product, $field);
                    if (is_array($items)) {
                        $attribute = reset($items);
                        $attribute = taxonomy_term_load($attribute['tid']);
                        $items = field_get_items('commerce_product', $product, 'commerce_price');
                        $item = reset($items);
                        $price = commerce_currency_format($item['amount'], $item['currency_code'], $product);
                        $form['attributes'][$field]['#options'][$attribute->tid] = $attribute->name . ' - ' . $price;
                    }
                }
            }
        }
    }
}

```

Note that the $status value checks whether the variation is disabled and skips over it if it is - without that, disabled products were still showing in the list of options.

---
Tags: commerce
---


# Question
Title: Pre-process node type for each node and print within region.html.twig template
I'm trying to figure out how I can check the node type/content type for each node using pre-process and print it on a region template `(region.html.twig)`

It seems to be returning `NULL`

```
function iom_preprocess_node(&$variables) {
    $node = $variables["node"];
    $variables['content_type'] = load($node->bundle())->label();
}

```

`{{ content_type }}`

# Answer
> 1 votes
You need to use preprocess region:

```
function iom_preprocess_region(&$variables) {
    $node = $variables["node"];
    $variables['content_type'] = $node->getType();
}

```

Clear/flush cache after adding it.

---
Tags: theming
---


# Question
Title: How to disable aggregation from either drush or PHPmyadmin?
I've been searching for this and ALL I found deals with Drupal 7. Old drush command `drush vset preprocess_js 0` doesn't work for Drupal 8 and the "variable" table in DB doesn't exist in 8...

Yet, I can't disable aggregation in my D8 site for some reason and want to disable it from either drush or DB.

Do you know a way?

# Answer
Drupal 8 version to disable aggregation:

# disable CSS/JS aggregation

```
drush -y config-set system.performance css.preprocess 0
drush -y config-set system.performance js.preprocess 0

```
> 38 votes

# Answer
If you need it for your development environment you can enable `settings.local.php` in your `settings.php`

```
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

```

and than make sure ONLY in your local `settings.local.php` (not on your live enviroment) the following settings are used

```
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

```

**NOTE:** those settings can probably be found in `sites/default.settings.local.php` which you can copy to `sites/default/settings.local.php` and make use of.
> 6 votes

# Answer
Use these commands to unset the CSS and JS aggregation using Drush.

## Drupal 7

```
drush vset preprocess_js 0 --yes
drush vset preprocess_css 0 --yes

```

## Drupal 8

Refer above comments.
> 3 votes

---
Tags: 8, css-js-aggregation
---


# Question
Title: Processing the content generated by a node?
What call would I use to modify a node's content. For example, let's say I have the words "12345678" located in various nodes. If I wanted to replace all occurences of this in Drupal 7 with "abcdefgh", I could easily hack it in a template like this:

```
$content = str_replace("12345678", "abcdefgh", $content);
print $content;

```

This is probably very bad practice, but hopefully it will demonstrate that I just want to be able to replace the occurrence of any text with some other piece of text.

What is the best way to do that in Drupal 8?

**UPDATE**

I had a look at template\_preprocess\_node. But it looks like this will allow me to add more variables to the theme, but not to actually replace specific pieces of text.

# Answer
> 1 votes
This is what I was looking for:

```
function my_theme_preprocess_node(&$variables)
{
    $variables['content']['body'][0]['#text'] = str_replace("Replace This", "with this", $variables['content']['body'][0]['#text']);
}

```

# Answer
> 4 votes
In Drupal 8, you can use `hook_ENTITY_TYPE_view_alter()` (which in this case would be `hook_node_view_alter()`) to alter the render array for the entity; otherwise, as the documentation for that hook suggests, you can use `hook_preprocess_HOOK()` (which in this case would be `hook_preprocess_node()`).

> If a module wishes to act on the rendered HTML of the entity rather than the structured content array, it may use this hook to add a #post\_render callback. Alternatively, it could also implement `hook_preprocess_HOOK()` for the particular entity type template, if there is one (e.g., node.html.twig).

As for `template_preprocess_node()` implemented by a theme, that is not different from `hook_preprocess_node()`: It can either add new variables, or change the content of existing variables. In both the cases, the `$variables` parameter is passed by reference, so any change to the array is passed back to the function/method invoking those hooks.

The other alternative would be implementing an input filter in a module, and add the input filter to the input format used from the content type. This would have the pro of stopping the replacements simply by removing the input filter from the input format, and it would also have the pro of changing in the site configuration which content types would have the text replaced, and document to users the changes done to nodes.
The con is that it cannot be used in fields that don't use input formats, but it works for the body field of nodes. If you need to alter the text that appears in a link field, for example, an input filter would not help (since the link field would ask for a URL and the text to show as link title).

---
Tags: 8, nodes
---


# Question
Title: Custom save message for site information form
Folks, I need to alter the site information form. I used `api_form_system_site_information_settings_alter` hook to do so. After submitting I need to print a custom message. I used one submission handler, but the data not saved. My .module file is given below.

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

function api_key_form_system_site_information_settings_alter(&$form,
 FormStateInterface $form_state, $form_id) {
 if($form_id != 'system_site_information_settings') {
    return;
}
$site_api = \Drupal::config('api_key.settings')->get('siteapikey');

$form['api_settings'] = array(
    '#type' => 'details',
    '#title' =>t('Site API settings'),
    '#open' => true
);

$form['api_settings']['siteapikey'] = [
    '#type' => 'textfield',
    '#title' => t('API Key'),
    '#default_value' => $site_api,
    '#description' => t('Enter the API key for making the site
        protected on API calls'),
    '#maxlength' => 32,
    '#required' => true,
    '#placeholder'=> t('No API key yet')
];

$value = !empty($site_api)? t('Update Configuration'): t('Save Configuration');
$form['api_settings']['actions']['#type'] = 'actions';
$form['api_settings']['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $value,
    '#button_type' => 'primary',
];
$form['actions']['submit']['#submit'][] = 'api_key_form_submit';
return $form;
 }

function api_key_form_submit(array $form, FormStateInterface $form_state) {

$site_api = \Drupal::config('api_key.settings')->get('siteapikey');
//Reads the new value form the form instance.
$new_value = $form_state->getValue('siteapikey');
//Changes the success message based on the condtions.
if(!empty($site_api)) {
        //Sets update message.
    $message = t('Site API key is changed from @old_value to
        @new_value', [
            '@old_value'=> $site_api,
            '@new_value'=> $new_value
        ]);
} else {
        //Sets success message.
    $message = t('@new_value is set as site API key.',
        ['@new_value'=>$new_value]);
}

//Prints the message.
drupal_set_message($message,$type='status', $repeat=true);
}

```

# Answer
> 0 votes
It seems you have success with displaying the message but not with saving the value? For this you need to load the editable version of the config, set the value and save:

```
function api_key_form_submit($form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('api_key.settings');
  $config->set('siteapikey', $form_state->getValue('siteapikey'));
  $config->save();
}

```

By the way it's also a good idea to get the value from the editable version because the config might be overridden and you want to fill the form with the original value:

```
$site_api = \Drupal::service('config.factory')->getEditable('api_key.settings')->get('siteapikey');

```

# Answer
> 0 votes
@vishnu jayan You need to change custom submit handler assign.

```
function api_key_form_system_site_information_settings_alter(&$form,
 FormStateInterface $form_state, $form_id) {
  if($form_id != 'system_site_information_settings') {
    return;
  }
$site_api = \Drupal::config('api_key.settings')->get('siteapikey');

$form['api_settings'] = array(
    '#type' => 'details',
    '#title' =>t('Site API settings'),
    '#open' => true
);

$form['api_settings']['siteapikey'] = [
    '#type' => 'textfield',
    '#title' => t('API Key'),
    '#default_value' => $site_api,
    '#description' => t('Enter the API key for making the site
        protected on API calls'),
    '#maxlength' => 32,
    '#required' => true,
    '#placeholder'=> t('No API key yet')
];

  $value = !empty($site_api)? t('Update Configuration'): t('Save Configuration');
  $form['api_settings']['actions']['#type'] = 'actions';
  $form['api_settings']['actions']['#type'] = 'actions';

      $form['#submit'][] = 'api_key_form_submit';
      return $form;
    }

    function api_key_form_submit($form, FormStateInterface $form_state) {
      $config = \Drupal::service('config.factory')->getEditable('api_key.settings');
      $config->set('siteapikey', $form_state->getValue('siteapikey'));
      $config->save();
      //Prints the message.
      drupal_set_message($message,$type='status', $repeat=true);
    }

```

---
Tags: forms
---


# Question
Title: Modify a custom block field value with hook_form_alter and validate
I'm trying to modify a custom block form with `hook_form_alter` .In its validate function I have a case where one of the field value needs to be unset. For modifying its value I tried with

`$form_state->setValue('field_name', '')` /

`$form['field_name']['#default_value'] = ''` /

`$form['field_name']['#value'] = ''`

But none of these approach seems to work. Below is my code -

```
function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    //create or edit form
    if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
      $form['#validate'][] = 'coolblockvalidate';
    }
}

function coolblockvalidate(array &$form, FormStateInterface &$form_state) {
    //trying to unset the field value here, which is not working.
    $form_state->setValue('field_mycoolfield', '');

    //tried these approach too with no luck.
    //$form['field_mycoolfield']['#default_value'] = '';
    //$form['field_mycoolfield']['#default_value'] = '';

}

```

I'm very interested in knowing why the field value can't be changed. I tried the same with a custom form alter and it works.

Any ideas/ suggestions would save me. Thanks.

# Answer
> 1 votes
Got this working by adding a submit handler.

Below is the code -

```
function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  //create or edit form
  if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
    //extra submit handler that will execute after default submit
    $form['actions']['submit']['#submit'][] = 'coolmodule_coolblocksubmit';
  }
}

function coolmodule_coolblocksubmit(array &$form, FormStateInterface &$form_state) {

  $entity = $form_state->getFormObject()->getEntity();
  // unset field.
  $entity->set('myfield', '');
  // Saving the entity.
  $entity->save();
}

```

# Answer
> 0 votes
You can unset the field using the Hook\_preprocess\_hook something like the following.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function coolmodule_preprocess_block(&$variables) {
  if (
    isset($variables['elements']['content']['#block_content'])
   && $variables['elements']['content']['#block_content']->bundle() == 'your_custom_block_type'
  ) {
    if (isset($variables['content']['field_custom_field_test'])){
      //- set field to empty value
      $variables['content']['field_name'] = [];
      //- Or Unset the field totaly
      unset($variables['content']['field_name']);
    }
  }
}

```

# Answer
> 0 votes
You does not need to saved entity multiple time.

```
function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  //create or edit form
  if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
    //extra submit handler that will execute after default submit
    array_unshift($form['actions']['submit']['#submit'] , 'coolmodule_coolblocksubmit');
  }
}

function coolmodule_coolblocksubmit(array &$form, FormStateInterface &$form_state) {

  $entity = $form_state->getFormObject()->getEntity();
  // unset field.
  $entity->set('myfield', '');
}

```

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


title: Add captcha to webform

text:
# Question
Title: Add captcha to webform
I'm working on a drupal 8 project, I've created a webform and trying to associate a captcha to my webform using captcha contrib module. I've a personalized template for my webform in which I render the webform fields. I've associate the captcha to the webform under /admin/config/people/captcha/captcha-points and test as anonymous user it is always unable to associate captcha to the webform.

* Should I print captcha in my webform template file? if so how to do it?
* Should I add an element Captcha to my webform fields? if so is that element by default use captcha contrib module settings?

Any help is appreciate.

# Answer
> 2 votes
To captcha protect a webform you NEED to add a captcha element to it. When captcha contrib module is enabled on your site the available captcha `challenge types` are available to be used on a per webform basis.

The template twig file is mostly for design puproses.

If the placement of captcha within the form is not to your liking you should copy the default webform template from `/modules/contrib/webform/webform.html.twig` to your theme `/themes/custom/MYTHEME/templates/webform--WEBFORM_MACHINE_NAME.html.twig` and perhaps place each element seperately.

The default `webform.html.twig` is

```
<form{{ attributes }}>
  {{ title_prefix }}
  {{ children }}
  {{ title_suffix }}
</form>

```

And in our own copy we should take out `{{ children }}` and replace with individual elements but also we have to make sure form ids and actions are included manually and it the final template should end up looking similar to this

```
<form{{ attributes }}>
  {{ title_prefix }}
  {{ element.elements.first_name }}
  {{ element.elements.last_name }}
  {{ element.elements.captcha }}

  {# necessary elements #}
  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.actions }}

  {{ title_suffix }}
</form>

```

Where `captcha` for example is the machine name of the captcha field

---
Tags: 8, webforms, captcha
---


# Question
Title: Trying to display/printing latitude and longitude from Geolocation Field to node template
I've been trying to figure how I can fetch the latitude and longitude values using geolocation field and display it on my `node.html.twig` template.

I've been using to `kint()` to see how I would be able to fetch but I can't seem to figure out the right syntax. It seems to be inside an array

Tried `node.field_geolocation.latitude.value` or `node.field_geolocation.longitude.value`

# Answer
> 3 votes
I did this by printing, `{{ node.field_geolocation.lat }}` and `{{ node.field_geolocation.lng }}`.

That should print the values.

---
Tags: 8, theming
---


# Question
Title: How to remove unwanted form state values before validation
What is the good way of validating a form in Drupal 8 ?

I have a bunch of fields which are supposed to be filled by a positive numeric value (and that's all, no other input types, just positive int).

```
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();

foreach ($values as $method => $fee) {
  if ($method != 'Free order') {
    if (!is_numeric($fee) || floatval($fee) < 0) {
      $form_state->setErrorByName($method, t('Value must be a positive integer.'));
    }
  }
}

```

}

The issue is when using `$form_state->getValues()` it also returns "submit", "form\_token", "form\_build", "form\_id", "op" which is quite boring as those infos are not needed for performing validation.

So what I did is removing those four unwanted values with :

```
$values = array_splice($values, count($values) - 5, 5);

```

But it's really annoying, am I doing something wrong, or is just as it ? Because I think those values are really not necessary in the validation process.

# Answer
> 8 votes
The `FormState` class has a method for that: `FormState::cleanValues()`. From its description, it's the method you should use.

> This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.
>
> * form\_id
> * form\_token
> * form\_build\_id
> * op

You simply call it before getting the submitted values.

```
public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->cleanValues()->getValues();

  foreach ($values as $method => $fee) {
    if ($method != 'Free order') {
      if (!is_numeric($fee) || floatval($fee) < 0) {
        $form_state->setErrorByName($method, t('Value must be a positive integer.'));
      }
    }
  }

```

Since `FormState::cleanValues()` returns the `FormState` object, you can simply call it in the same line you call `FormState::getValues()` concatenating the two calls.

If you need to add more keys to remove from the submitted values, you could use `FormState::setCleanValueKeys()`, but keep in mind that:

* The array passed to the method needs to contain also the default array keys Drupal would remove
* The method alters the array keys that are removed from `FormState::cleanValues()` for every Drupal form

---
Tags: 8, forms
---


# Question
Title: In Commerce 2, is it possible to have the product variation automatically created during product creation?
We have a Commerce 2 store whose products will always only have one variation.

The current workflow to create a new product **and** its variation is a bit complicated for the user's who will be entering in the product data.

Out of the box you have to click the 'create variation' button after entering in the variation information. There is then additional option buttons to Edit, Remove, or Duplicate the variation.

We'd like to streamline this process and have the single variation created automatically so all the user needs to do is enter a price during the product creation and not have to click any additional buttons.

I was hoping there was a module available that would facilitate this functionality but I was unable to find one.

If not module exists, what would be the best way to achieve this?

Perhaps a custom 'product' form that then creates the Commerce Product programmatically when the form is submitted? I don't really like this idea because I would also have to consider editing the product as well.

Would some custom code be able to tweak the existing workflow to hide the variation info and create it automatically? Perhaps getting the price from a custom price field added to the product entity?

# Answer
> 4 votes
Update to Commerce 2.10.

Then, edit your product type and uncheck the *Allow each product to have multiple variations* checkbox. This will give you a *Product information* fieldset on the product add/edit form with the variation fields.

---
Tags: commerce
---


title: Modify label on view exposed filter

text:
# Question
Title: Modify label on view exposed filter
I have a view with exposed filter to a field as follows :

I want to change the text '**Deployment date from**' and '**And**' to **`'From' and 'To'`**

Can i do this with **`hook_views_query_alter`** or **`hook_views_pre_render`**

# Answer
> 5 votes
You can easily change the first label with the views editor, by setting it in Filter criteria part. But for the "And" i think you have it because you selected the "is between" operator. So the easiest way to change it is to use hook\_form\_alter() our hook\_form\_FORM\_ID\_alter() and change the '#title' of that second form field.

If you inspect the html of your field in front, you will see that it is in a tag. So get the id of that form, for example

```
<form id="views-exposed-form-activities-page-1" ></form>

```

then in your\_module.module file implements hook\_form\_FORM\_ID\_alter():

```
<?php

/**
 * @file
 * This is your_module.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOURMODULE_form_views_exposed_form_activities_page_1_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['your_annoying_field']['#title'] = t('To'); //Instead of "And".
}

```

# Answer
> 5 votes
Finally i got the answer . Actually it should be used like **`YOURMODULE_form_views_exposed_form_alter`** only . No need of **`activities_page_1_`** as expected . Am adding the answer below :

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function module_name_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  $form['created']['min']['#title'] = t('From');
  $form['created']['max']['#title'] = t('To');
}

```

# Answer
> 2 votes
The easiest way to do this is with the String Overrides module. It's still under heavy development for Drupal 8 but MegaChriz (maintainer of the Feeds module a.o.) made a pretty stable version that you can download here:

https://www.drupal.org/files/issues/stringoverrides.zip

More information:

https://www.drupal.org/node/2236791#comment-8783307

# Answer
> 2 votes
I was able to do this with the following code.

Note that my field is actually called `field_date`, but to access the label I had to add "\_value" to the end of my field to make it `field_date_value`.

Also note that `$form_id` for an exposed form is going to be generic. To check for a unique form ID, check `$form['#id']`.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-my-unique-form-id') {
    $form['field_date_value']['min']['#title'] = t('From');
    $form['field_date_value']['max']['#title'] = t('To');
  }
}

```

---
Tags: 8, views
---


title: Views image field

text:
# Question
Title: Views image field
I'm trying to add inline styling to my Drupal image using the image field under view. No matter what method I try, nothing is working. I've run out of options.

Any help?

Below are a few code examples of what I've used:

```
<img src="[field_image_upload]" height="150" style="margin: 5px; margin-right: 15px; float: left;">

[field_image_upload]

[<img src="[field_image_upload]" height="150" style="margin: 5px; margin-right: 15px; float: left;">]

```

# Answer
Inline styles are generally not the best way to go. You will be happier in the long run if you apply CSS classes to your Views and handle the styling in external CSS.

That said, you could try checking the box that says "Exclude from display. Enable to load this field as hidden. Often used to group fields, or to use as token in another field." on your `field_image_upload` field.

Then create a new field of type "Global: custom text" and build your custom markup in that field, using the token as you have in your first example above:

```
<img src="[field_image_upload]" height="150" style="margin: 5px; margin-right: 15px; float: left;">

```

If the token is not available for use, make sure that you rearrange the field order in your Views display so that the image field comes before the Global custom text field.

**UPDATE:**

You *can't* use inline CSS to do what you're trying to do:

https://www.drupal.org/forum/support/post-installation/2017-06-12/d7-how-do-i-use-inline-css-in-global-custom-text

> View Global custom text field uses `filter_xss_admin`, so you can't include inline css in this field. One solution you can build is overriding `view-view-field.tpl.php` for this field specifically and in template file you can theme it as you like.
> 0 votes

# Answer
Here's my custom text code

```
**<img src="[field_image_upload]" height="150" style="margin: 5px; margin-right: 15px; float: left;">**

```

and here's what comes out from that code:

```
" height="150">

```
> 0 votes

---
Tags: 7, views, media
---


# Question
Title: How to programmatically populate a country field
We are using the Countries module to provide country fields where editors can choose a country and it gets displayed in the frontend. Which works absolutely fine.

But we want to fill that field programmatically through a custom module. No matter what value we provide to fill the field (country name, ISO 2 code etc.) the field doesn't get populated.

We are certainly sure that there is no any error somewhere else as we are filling multiple fields in our module and all are working as expected.

We want to know in which format does the country field expect the value to be?

---

Clarification:

We have a field `field_country` in profile2 with the `Country` type coming through Countries module. We are getting input in our module through following code in our form:

```
include_once DRUPAL_ROOT . '/includes/iso.inc';
include_once DRUPAL_ROOT . '/includes/locale.inc';

$form['country'] = array(
  '#title' => t('Country'),
  '#type' => 'select',
  '#description' => t('Please Select Your Country Where Do You Belong To.'),
  '#required' => 'true',
  '#options' => array('' => t('-Select a Country-')) + country_get_list(),
  '#default_value' => isset($values['country']) ? $values['country'] : '',
);

```

We have also tried `'#type' => 'country'` and a few other things but same result.

For submitting this value we are using the code:

```
$profile->field_country['LANGUAGE_NONE'][0]['value'] = $data;

```

# Answer
I played around with this now for a little while. Seems all you need is the `iso2` key to be set.

```
global $user;

$node = new stdClass();
$node->title = 'Lorem Ipsum';
$node->type = 'article';
node_object_prepare($node);

$node->language = LANGUAGE_NONE;
$node->uid = $user->uid;
$node->status = 1;

// In the end this was it.
$node->field_country[LANGUAGE_NONE][] = [
  'iso2' => 'FR',
];

$node = node_submit($node);
node_save($node);

```

---

Apart from that you can use the Devel module to either dump variables like that

```
dpm($variables);

```

for example in a `MYMODULE_preprocess_node()` hook. After you filled out a node with a country field from the UI you can use that to check which values are set. Or you can checkout node values directly by appending `/devel` to a node path (http://example.com/node/42/devel). Although I must admit that what I got there as output was quite misleading. All that really was needed was the `iso2` key.
> 0 votes

---
Tags: 7, forms
---


title: Why is my text hyphenated?

text:
# Question
Title: Why is my text hyphenated?
I have a text field. When I enter text in the CKEditor the words look OK. But when I look at the rendered page, it seems as if Drupal has split all word instead of put the entire word in the next line.

For example the word "Materialien" in the screenshot is split and this is not correct. I tried the CSS `word-break` property, but it seems that something is coming from Drupal and is breaking all the words.

# Answer
> 2 votes
There's some hyphenation library on your page. That's no default Drupal behavior. Find that library and remove it or make it ignore your body fields. Probably some JS library.

---

OP found `hyphenator.js` inside `MYTHEME/vendor/hyphenator.js`.

To remove the library, find out where it got added to the site. `drupal_add_js()` in D7, or some `MYTHEME.libraries.yml` library declaration in D8. Or just from the theme's info file.

I'd recommend to fix the hyphenation and simply exclude it for certain fields. This probably can be done with only a few lines of custom JS. Find out how by visiting the docs of that library from the link above.

---
Tags: theming
---


# Question
Title: Send email notification for the new created survey using webform
I'm looking for a way to send email notification to all my users once my scheduled survey is already open. Upon checking the Webform module, all I can see about email notification is when a user submitted a response to the surey.

# Answer
> 0 votes
Webforms does not work that way. Webforms is for you or an administrator to receive an email when a user on your site fills out a form.

For example, if a customer wants you to send them a brochure in the mail, Webforms will let you know when they fill out your form.

If you want to notify multiple site users (not administrators) about a form being available, consider trying something like MailChimp, or one of the other popular mailing list programs. The well-known ones (MailChimp, Constant Contact, etc.) all have modules that will allow you to integrate them with your Drupal web site.

---
Tags: 8, webforms
---


# Question
Title: How to add an extra field in file upload widget?
I know that it is possible to enable a description field in the core file upload widget for Drupal 7.

However, I want to add an *extra* description field like the one already present. For this I've spent hours googling, but not found the perfect solution. Please, someone, help me to solve my problem

# Answer
This module might be a great way to do what you want. The File Entity module is a module that creates fieldable files. Try to read the module description, hope it helps you.

> File entity provides interfaces for managing files. It also extends the core file entity, allowing files to be fieldable, grouped into types, viewed (using display modes) and formatted using field formatters. File entity integrates with a number of modules, exposing files to Views, Entity API, Token and

UPDATE now you want to add an entity reference field on your content type that references your custom file.
> 2 votes

---
Tags: 7, entities, files
---