# Question
Title: Is there a way to add Query string in URL after webform submission and remove the ?token from confirmation page
Actually, I would like to add `?sid=submission_id` in the url except `?token=random_token_value` after webform submission. Is there a way for that?

# Answer
You probably need to write a custom WebformHandler.

BTW, the sid is not being passed to the confirmation page for security reasons because malicious users would be able to guess a submission's sid and then see a submission's confirmation page.
> 0 votes

---
Tags: webforms
---


# Question
Title: Remote attribute in mymodule.libraries.yml
When creating a library, I noticed there is an attribute `remote` that can be added. I cannot really find any good documentation as to what it is for nor does it seem like it is required.

Questions:

1. What is the purpose of this `remote` when defining a library?
2. How can we be sure the value we add is correct?

Example from https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module:

```
font-awesome:
  remote: https://fortawesome.github.io/Font-Awesome/
  version: 4.5.0
  license:
    name: MIT
    url: https://fortawesome.github.io/Font-Awesome/license/
    gpl-compatible: true
  css:
    theme:
      https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css: { type: external, minified: true }

```

# Answer
According to the code/comments in `LibraryDiscoveryParser::buildByExtension`, it's to help ensure licensing info is included for 3rd party libraries:

```
// If this is a 3rd party library, the license info is required.
if (isset($library['remote']) && !isset($library['license'])) {
  throw new LibraryDefinitionMissingLicenseException(sprintf("Missing license information in library definition for definition '%s' extension '%s': it has a remote, but no license.", $id, $extension));
}

```

It's also mentioned in the library docs, but it just says that it's a good idea to include the remote info, not why. It doesn't appear to be used in the code other than the licensing, so I think it's safe to assume it's a reference/info value for now. There is no incorrect value to-to-speak, but it would make sense to set it to the URL of the project you're referencing.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Adding Display Suite fields to Search API results
## Problem

I have some Display Suite token fields, and I want to include these and other entity fields in the Search API search results.

I also want to include the Search API `Excerpt` field in the results.

What's the easiest way to get these DS fields into the search results along with other entity fields?

## What I've tried

I have tried using `Fields` for the view's `Format > Show` setting, but the DS fields don't appear as field options.

I have tried using `Rendered entity` for the view's `Format > Show` setting, but the `Excerpt` field doesn't appear as a field option in any of the display configurations.

I have tried adding custom theme templates to override the display, and I get a fatal error. I haven't resolved this error after a bit of searching, so theme overrides doesn't look like the easiest route.

```
When a #lazy_builder callback is specified, no properties can exist; all properties must be generated by the #lazy_builder callback. You specified the following properties: #attributes.

```

# Answer
I missed it earlier, but it turns out that Search API just exposed the Excerpt field to view modes.

Updating Search API to `8.x-1.x-dev` and a cache rebuild gave me the functionality I need.
> 0 votes

---
Tags: 8, search, display-suite
---


# Question
Title: After save empty cache of referenced node
I have two content types. For clearer question I will work with the content types *event* and *location*.

From my *location* content type I can reference to and *event*.

Then on the *event* page I show the *location* that is connected to this *event*. I do this by creating a Views Block. This views block is showing content of the type *location* with a contextual filter to only show content with the *Content ID from url*.

This works fine. But there are events that don't have a *location*. On these events page I have a button saying *add location*. I do this with the following Twig Tweak:

```
{% if drupal_view_result('view-name', 'location-block') is empty %}
    <a href="/node/add/location">Add location</a>
{% else %}
    {{ drupal_view('view-name', 'location-block') }}
{% endif %}

```

This also works. But when I am on a *event* page and click the *add location* button I can add the location. When I go back to the same *event page* I was before I still see the *add location* button. Because the page is cached.

Is there a way to empty the cache of this *event* page after saving the *location* that is refering to the *event*? Or is there a other way to deal with this?

I tried if the problem was in the views cache but it wasn't turning it off for the block or removing only the views cache didn't work.

Thanks in advance

# Answer
You may specify any cache meta data directly in your Twig template. I suppose 'node\_list' cache tag can help in this case.

```
{{ {'#cache': {'tags': ['node_list']}} }}

```

Another approach could be configuring views 'No results behavior' to show that link.
> 1 votes

# Answer
Since you're creating a reference to a location node, you'll know its node id upon saving the event.

At that point, you need to call `\Drupal\Core\Cache\Cache::invalidateTags([$nid])` where `$nid` is the node id of the location.

There are many possibilities where this could be invoked, for example, in `hook_entity_presave()`
> 0 votes

---
Tags: views, 8, caching
---


# Question
Title: How do I create a time range form field?
Is there any way to add time range input fields in a form, for example using code similar to the following one?

```
$form['notification_hours'] = array(
  '#type' => 'time_range', // type time_range doesn't work
  '#title' => $this->t('Notification hours:'),
  '#default_value' => $config->get('ecc_general.notification_hours'),
  '#description' => $this->t('what are the hours that messages should not be sent?'),
);

```

I have tried the Time Range and and Time Field modules. I'm able to add the time range field, but I failed to programmatically create it.

# Answer
> 0 votes
Haven't tested this but if you install time field module you then could do this to simulate a range:

```
$form['from'] = [
  '#type' => 'time',
  '#title' => 'from',
];
$form['to'] = [
  '#type' => 'time',
  '#title' => 'to',
];

```

---
Tags: 8, datetime
---


title: CSS changes not updating

text:
# Question
Title: CSS changes not updating
Basic caching settings all off:

`settings.local.php` is loaded:

Bottom of settings.php:

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

```

And it contains:

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

```

**Issue:** Add any changes to bootstrap subtheme at `themes/contrib/tekatheme/css/style.css` and save. Refresh page, no change. Has to run `drush cr` each time.

Running `drush cr` for each CSS edit is not a solution, it's impossible to work like that.

# Answer
> 1 votes
This is not a Drupal caching issue. When CSS aggregation is disabled your browser loads the CSS files directly. So caching is between your browser and the web server. To disable caching you can either enable the dev mode in the browser or adjust the headers for CSS files in the web server.

By the way, `drush cr` doesn't clear CSS in cache. This wouldn't be possible because it is the browser cache. Instead it forces a reload by invalidating the cache-busting query string.

# Answer
> 1 votes
Have you tried setting up `development.services.yml`?

Put this next to your `sites.php`.

**development.services.yml**:

```
# Local development services.
#
# Place this file in the /sites/ directory.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    # Twig debugging:
    #
    # When debugging is enabled:
    # - The markup of each Twig template is surrounded by HTML comments that
    #   contain theming information, such as template file name suggestions.
    # - Note that this debugging markup will cause automated tests that directly
    #   check rendered HTML to fail. When running automated tests, 'debug'
    #   should be set to FALSE.
    # - The dump() function can be used in Twig templates to output information
    #   about template variables.
    # - Twig templates are automatically recompiled whenever the source code
    #   changes (see auto_reload below).
    #
    # For more information about debugging Twig templates, see
    # https://www.drupal.org/node/1906392.
    #
    # Not recommended in production environments
    # @default false
    debug: true
    # Twig auto-reload:
    #
    # Automatically recompile Twig templates whenever the source code changes.
    # If you don't provide a value for auto_reload, it will be determined
    # based on the value of debug.
    #
    # Not recommended in production environments
    # @default null
    auto_reload: auto_reload
    # Twig cache:
    #
    # By default, Twig templates will be compiled and stored in the filesystem
    # to increase performance. Disabling the Twig cache will recompile the
    # templates from source each time they are used. In most cases the
    # auto_reload setting above should be enabled rather than disabling the
    # Twig cache.
    #
    # Not recommended in production environments
    # @default true
    cache: false

```

Then in your `settings.php`, or preferrably your `settings.local.php` add this line:

```
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';

```

---
Tags: 8, theming, caching
---


title: How to correct disappearing admin menu?

text:
# Question
Title: How to correct disappearing admin menu?
I use the Admin Menu module for my projects. In my Drupal 7 and Pressflow 7 instances, it randomly shows only some menu items.

At first, I thought I could correct this by clearing menu cache. When I went to the front page, I once again got the corrupted menu.

How do I solve this error, permanently?

I found out this issue is reported in detail, but there is only a workaround (disable menu caching).

I disabled menu caching with `drush vset admin_menu_cache_client 0` as a workaround. (I am still testing this issue with the menu cache enabled.)

I checked and eliminated JavaScript errors using Firebug browser extension.

I removed BOM from \*.js files as suggested in this answer.

# Answer
> 4 votes
*Modules* \> *Administration Menu* \> *Configure*

In the Performance tab, untick **Cache menu in client-side browser**.

Save configuration.

# Answer
> 4 votes
Add this to the bottom of your settings.php file:

`$conf['admin_menu_cache_client'] = FALSE;`

# Answer
> 0 votes
There is an option for rebuilding, although it refreshes all the menus. If the user has the permission to access that menu, it will be shown.

# Answer
> 0 votes
I had issues with this, but it had to do with the mod\_rewrite module in Apache's config file (httpd.conf). Make sure it's not commented out!

This:

```
LoadModule rewrite_module modules/mod_rewrite.so

```

Instead of this:

```
# LoadModule rewrite_module modules/mod_rewrite.so

```

As soon as I did that, my admin menu appeared again and it fixed another issue with my configuration changes not saving.

# Answer
> 0 votes
In your profile settings: uncheck the "Use the overlay for administrative pages." option under "Administrative overlay".

---
Tags: 7, routes, caching
---


title: Format date field in twig

text:
# Question
Title: Format date field in twig
Date field having multiple values. Need to format the output.

```
{% for item in items %}
<div{{ attributes }}>{{ item.content|date(format="F j, Y") }}</div>
{% endfor %}

```

`item.content` showing the date as updated. But not able to format the result. Got the below error,

> TypeError: DateTime::\__construct() expects parameter 1 to be string, array given in...

Please suggest on this issue.

# Answer
In Twig, drill down to the timestamp value:

**node.html.twig**:

```
{{ content.field_name['#items'].value | date('F d, Y') }}

```

For a loop, do:

```
{% for items in content.field_name['#items'] %}
  {{ items.value | date('F d, Y') }}
{% endfor %}

```

**field.html.twig**:

```
{% for item in items %}
  {{ item.content["#markup"] | date('F d, Y') }}
{% endfor %}

```

Note: *Set field format display option to `plain` or `custom` if using the field template. This field option can break your site just by someone changing the format option for the field, so use caution.*
> 5 votes

---
Tags: 8, theming, datetime
---


# Question
Title: How to apply the attribute "rel=nofollow" to links in the comments?
I configured the Text Format "Plain text" (admin/config/content/formats) to "Convert URLs into links" so I would like to add the attribute `rel="nofollow"` to all the links in the comments.

This way I would minimize the effects of spammy links in the comments.

Is there an easier way than using regular expressions to insert the attribute?

# Answer
> 11 votes
Go to *Configuration -\> Content authoring -\> Text formats -\> Plain text (your format)*, then tick the `Limit allowed HTML tags` option.

In the filter settings at the bottom of the page is the `Add rel="nofollow" to all links` checkbox. Tick that... Since this is plain text, you will probably want to remove the contents of the `Allowed HTML Tags` field, too.

# Answer
> 1 votes
Jim is mostly Right (but it matters what order the filters are in and you would need to add the `<a>` at least to that filter). A slightly better way (in that it lets users still put in just the URL or protects you if they try to all a rel=follow to their a tag) would be:

1. Go to `admin/config/content/formats/plain_text`
2. Check only `Limit allowed HTML tags`, `Convert line breaks...`, and `Convert URLs into links`.
3. Make sure your filter is ordered starting with `Convert URLs into links`, then `Limit allowed HTML tags`, then `Convert line breaks into HTML...`
4. Under Limit allowed HTML Tags filter settings, change allowed HTML to just `<a>` and make sure the Add `rel="no-follow"` to all links is checked. I like to unchecked the Display basic HTML help in long filter tips here.

# Answer
> 0 votes
noindex\_external\_links is a nice module to add rel=nofollow to external sites. We can dofollow selected sites and it does not add nofollow to internal links.

To make it work I placed the filters in this order(for plain text format): Display any HTML as plain text -\> Content URL's into links -\> Noindex external links filter

# Answer
> 0 votes
You can also use - https://www.drupal.org/project/ckeditor\_nofollow module, which provide an widget, which can be used to add rel="nofollow".

---
Tags: 7, comments
---


# Question
Title: Functional test fails with PHPunit on local
Getting following error when running core functional test with PHPUnit:

> vendor/bin/phpunit -c core/phpunit.xml core/modules/user/tests/src/Functional/AccessRoleUITest.php

```
There was 1 error:

1) Drupal\Tests\user\Functional\AccessRoleUITest::testAccessRoleUI
Drupal\Core\Installer\Exception\AlreadyInstalledException: <ul>
<li>To start over, you must empty your existing database and copy <em>default.settings.php</em> over <em>settings.php</em>.</li>
<li>To upgrade an existing installation, proceed to the <a href="/update.php">update script</a>.</li>
<li>View your <a href="http://drupal-8-5-demo2.dd:8083">existing site</a>.</li>
</ul>

```

**Phpunit.xml:**

```
<?xml version="1.0" encoding="UTF-8"?>

<!-- TODO set checkForUnintentionallyCoveredCode="true" once https://www.drupal.org/node/2626832 is resolved. -->
<!-- PHPUnit expects functional tests to be run with either a privileged user
 or your current system user. See core/tests/README.md and
 https://www.drupal.org/node/2116263 for details.
-->
<phpunit bootstrap="tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">
<!-- TODO set printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter" once
 https://youtrack.jetbrains.com/issue/WI-24808 is resolved. Drupal provides a
 result printer that links to the html output results for functional tests.
 Unfortunately, this breaks the output of PHPStorm's PHPUnit runner. However, if
 using the command line you can add
 - -printer="\Drupal\Tests\Listeners\HtmlOutputPrinter" to use it (note there
 should be no spaces between the hyphens).
-->
  <php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <env name="SIMPLETEST_BASE_URL" value="http://drupal-8-5-demo2.dd:8083/"/>
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="mysql://root:@localhost:8083/drupal_8_5_demo2"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/Users/gaurav/Sites/devdesktop/drupal-8-5-demo2/sites/default/files/simpletest"/>
    <!-- To disable deprecation testing uncomment the next line. -->
    <env name="SYMFONY_DEPRECATIONS_HELPER" value="weak_vendors"/>
    <!-- Example for changing the driver class for mink tests MINK_DRIVER_CLASS value: 'Drupal\FunctionalJavascriptTests\DrupalSelenium2Driver' -->
    <!-- Example for changing the driver args to mink tests MINK_DRIVER_ARGS value: '["http://127.0.0.1:8510"]' -->
    <!-- Example for changing the driver args to phantomjs tests MINK_DRIVER_ARGS_PHANTOMJS value: '["http://127.0.0.1:8510"]' -->
    <!-- Example for changing the driver args to webdriver tests MINK_DRIVER_ARGS_WEBDRIVER value: '["firefox", null, "http://localhost:4444/wd/hub"]' -->
  </php>
  <testsuites>
    <testsuite name="unit">
      <file>./tests/TestSuites/UnitTestSuite.php</file>
    </testsuite>
    <testsuite name="kernel">
      <file>./tests/TestSuites/KernelTestSuite.php</file>
    </testsuite>
    <testsuite name="functional">
      <file>./tests/TestSuites/FunctionalTestSuite.php</file>
    </testsuite>
    <testsuite name="functional-javascript">
      <file>./tests/TestSuites/FunctionalJavascriptTestSuite.php</file>
    </testsuite>
  </testsuites>
  <listeners>
    <listener class="\Drupal\Tests\Listeners\DrupalListener">
    </listener>
    <!-- The Symfony deprecation listener has to come after the Drupal listener -->
    <listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener">
    </listener>
  </listeners>
  <!-- Filter for coverage reports. -->
  <filter>
    <whitelist>
      <directory>./includes</directory>
      <directory>./lib</directory>
      <directory>./modules</directory>
      <directory>../modules</directory>
      <directory>../sites</directory>
      <!-- By definition test classes have no tests. -->
      <exclude>
        <directory suffix="Test.php">./</directory>
        <directory suffix="TestBase.php">./</directory>
      </exclude>
     </whitelist>
  </filter>
</phpunit>

```

I have followed Running PHPUnit tests to configure Phpunit.xml, What else I am missing here ?

# Answer
> 2 votes
I *think* this is because it's not picking up the port number from your mysql host. I had the same issue and by using a mysql connection on the default port (3306) it started working.

# Answer
> 0 votes
In the phpunit.xml the same port for Base\_URL and Database is used, this looks like a mistake.

The `AlreadyInstalledException` is very unhelpful in this case. You have to be really sure the Base\_URL is correct and reachable from inside the container, the database connection works and the database is empty, and the BROWSERTEST\_OUTPUT\_DIRECTORY is writeable for the user running phpunit. Even with a patch from https://www.drupal.org/project/drupal/issues/2459671 the exception was suggesting to delete the settings.php, when I really had a stupid typo in the database credentials.

---
Tags: 8, testing
---


# Question
Title: View with relationship - column displaying count of related nodes
I have a content type ("Interviewee") and a Media entity using the new media stuff in core (e.g. Remote Video) which have entity references back to the Interviewee entity.

I then have a view of the Interviewee content type, with a relationship to Media.

Rather than displaying multiple rows per person for each related media file, I'd just like display the total number of audio/video files linked to that content type in a column – *including*, this is important, a 0 for anyone who doesn't have media files - also ideally the column would be sortable.

Is this kind of basic counting of relationships possible in core / with a widely used module, without having to code a custom views field or a views sort plugin?

I've written similar plugins before, however I kind of assumed I could do it using aggregation - but I'm not getting anywhere.

# Answer
> 1 votes
You can do this with Aggregation.

First create your normal Views listing Interviewee nodes. Add the Media reference field and set to show all values in one row.

Turn Aggregation on, and change the Aggregation settings for the Media reference field to `Count` or `Count DISTINCT`.

Sorting criteria can sometimes mess up Aggregation counting so it's best not to have any while you're configuring the Aggregation, then add later once you know Aggregation is working and check each step that it's working as expected.

You can even add the Sort criteria for the reference field and use Aggregation on it (again `Count` or `Count DISTINCT`), Expose it if you want to allow users to change the order Ascending/Descending.

Sorting also works in a table Format if you turn on sorting for that field.

---
Tags: views, 8
---


title: Migration SQL Source with Track Changes

text:
# Question
Title: Migration SQL Source with Track Changes
I have a D8 migration from a SQL source to nodes which is working perfectly apart from `track_changes` is not working, in my YAML I simply have:

```
source:
  plugin: job
  constants:
    slash: /
  track_changes: true

```

I discovered track\_changes does not work when the map is joinable and applied the patch, but every time I run the migration I get:

`[notice] Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'job'`

Do I need to add anything specific to the source plugin? For now I'm getting round this by updating the whole migration each time, but I would prefer not to. If necessary I will have to use the `high_water_property` instead.

# Answer
> 0 votes
I had an issue like you did and i solve it by changing my:

```
track_changes: true

```

on

```
  high_water_property:
    name: changed
    alias: n

```

But the problem with this way that you need to:

1. Manually **delete**, NOT update your database destination fields.
2. Import old data.(Before check your source plugin, it must have **changed** field!)
3. Update your database with new data.

(and only than *high\_water\_property* will work)

> About this two Source Plugins
>
> Declaring highwater property in Migrate
>
> About track\_changes

---
Tags: 8, migrations
---


# Question
Title: Following Drupal 8 Commerce custom offer tutorial, but getting "name already in use" error
I am following the tutorial for creating a custom offer at the official Drupal 8 Commerce documentation. But I'm getting an error that I pasted below when I click on any of the conditions, and none of the forms are appearing for any of the commerce built-in offers. I followed the tutorial exactly, except for extending the OrderPromotionOfferBase class instead of the OrderFixedAmountOff class. I pasted the contents of the OrderItemFixedAmountTarget class I defined for the offer below the error.

Error

```
AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /promotion/1/edit?destination=/admin/commerce/promotions&ajax_form=1
StatusText: OK
ResponseText:
( ! ) Fatal error: Cannot declare class Drupal\my_module\Plugin\Commerce\PromotionOffer\OrderItemFixedAmountTarget, because the name is already in use in /home/usertest/workspace/drupalsite/web/modules/my_module/src/Plugin/Commerce/PromotionOffer/OrderItemFixedAmountTarget.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0000438056{main}(  ).../index.php:0
20.0006554920Drupal\Core\DrupalKernel->handle(  ).../index.php:19
30.00441717448Stack\StackedHttpKernel->handle(  ).../DrupalKernel.php:693
40.00441717448Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(  ).../StackedHttpKernel.php:23
50.00441718144Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(  ).../NegotiationMiddleware.php:52
60.00441718144Drupal\page_cache\StackMiddleware\PageCache->handle(  ).../ReverseProxyMiddleware.php:47
70.00441718144Drupal\page_cache\StackMiddleware\PageCache->pass(  ).../PageCache.php:85
80.00441718144Drupal\Core\StackMiddleware\KernelPreHandle->handle(  ).../PageCache.php:106
90.00562139576Drupal\Core\StackMiddleware\Session->handle(  ).../KernelPreHandle.php:47
100.00642260136Symfony\Component\HttpKernel\HttpKernel->handle(  ).../Session.php:57
110.00652260552Symfony\Component\HttpKernel\HttpKernel->handleRaw(  ).../HttpKernel.php:68
120.02877724544Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}(  ).../HttpKernel.php:151
130.02877724544Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(  ).../EarlyRenderingControllerWrapperSubscriber.php:97
140.02877727080Drupal\Core\Render\Renderer->executeInRenderContext(  ).../EarlyRenderingControllerWrapperSubscriber.php:124
150.02877727432Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}(  ).../Renderer.php:582
160.02877727432call_user_func_array:{/home/usertest/workspace/drupalsite/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php:123}
(  ).../EarlyRenderingControllerWrapperSubscriber.php:123
170.02877727840Drupal\Core\Entity\HtmlEntityFormController->getContentResult(  ).../EarlyRenderingControllerWrapperSubscriber.php:123
180.02917849224Drupal\Core\Form\FormBuilder->buildForm(  ).../FormController.php:93
190.043110154816Drupal\Core\Form\FormBuilder->processForm(  ).../FormBuilder.php:319
200.087912157904Drupal\Core\Form\FormBuilder->rebuildForm(  ).../FormBuilder.php:626
210.087912157904Drupal\Core\Form\FormBuilder->retrieveForm(  ).../FormBuilder.php:369
220.087912160160call_user_func_array:{/home/usertest/workspace/drupalsite/web/core/lib/Drupal/Core/Form/FormBuilder.php:519}
(  ).../FormBuilder.php:519
230.087912160568Drupal\commerce_promotion\Form\PromotionForm->buildForm(  ).../FormBuilder.php:519
240.088212170728Drupal\commerce_promotion\Form\PromotionForm->buildForm(  ).../PromotionForm.php:31
250.088312171952Drupal\commerce_promotion\Form\PromotionForm->form(  ).../EntityForm.php:117
260.088312171952Drupal\commerce_promotion\Form\PromotionForm->form(  ).../PromotionForm.php:38
270.088312172728Drupal\Core\Entity\Entity\EntityFormDisplay->buildForm(  ).../ContentEntityForm.php:125
280.089312198408Drupal\commerce\Plugin\Field\FieldWidget\PluginSelectWidget->form(  ).../EntityFormDisplay.php:177
290.089312198408Drupal\commerce\Plugin\Field\FieldWidget\PluginSelectWidget->formMultipleElements(  ).../WidgetBase.php:104
300.089312198784Drupal\commerce\Plugin\Field\FieldWidget\PluginSelectWidget->formSingleElement(  ).../WidgetBase.php:202
310.089312199160Drupal\commerce\Plugin\Field\FieldWidget\PluginSelectWidget->formElement(  ).../WidgetBase.php:335
320.089312201184Drupal\commerce\Plugin\Field\FieldWidget\PluginSelectWidget->supportsConfiguration(  ).../PluginSelectWidget.php:116
330.089312201584is_subclass_of
(  ).../PluginSelectWidget.php:149
340.089312201712spl_autoload_call
(  ).../PluginSelectWidget.php:149
350.089312201840Composer\Autoload\ClassLoader->loadClass(  ).../PluginSelectWidget.php:149
360.089412202032Composer\Autoload\includeFile(  ).../ClassLoader.php:322
370.089412202272include( '/home/usertest/workspace/drupalsite/web/modules/my_module/src/Plugin/Commerce/PromotionOffer/OrderItemFixedAmountTarget.php' ).../ClassLoader.php:444

```

OrderItemFixedAmountTarget.php

```
namespace Drupal\my_module\Plugin\Commerce\PromotionOffer;

use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\OrderPromotionOfferBase;
use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\FixedAmountOffTrait;
use Drupal\commerce_order\Adjustment;
use Drupal\commerce_promotion\Entity\PromotionInterface;
use Drupal\Core\Entity\EntityInterface;

/**
 * @CommercePromotionOffer(
 *   id = "my_module_fixed_amount_target",
 *   label = @Translation("Discount each matching product to fixed amount"),
 *   entity_type = "commerce_order_item",
 * )
 */
class OrderItemFixedAmountTarget extends OrderPromotionOfferBase {

  use FixedAmountOffTrait;

  /**
   * {@inheritdoc}
   */
  public function apply(EntityInterface $entity, PromotionInterface $promotion) {
    $this->assertEntity($entity);
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $entity;
    $subtotal_price = $order->getSubTotalPrice();
    $amount = $this->getAmount();
    if ($subtotal_price->getCurrencyCode() != $amount->getCurrencyCode()) {
      return;
    }
    // The promotion amount can't be larger than the subtotal, to avoid
    // potentially having a negative order total.
    if ($amount->greaterThan($subtotal_price)) {
      $amount = $subtotal_price;
    }
    // Split the amount between order items.
    $amounts = $this->splitter->split($order, $amount);

    foreach ($order->getItems() as $order_item) {
      if (isset($amounts[$order_item->id()])) {
        $order_item->addAdjustment(new Adjustment([
          'type' => 'promotion',
          // @todo Change to label from UI when added in #2770731.
          'label' => t('Discount'),
          'amount' => $amounts[$order_item->id()]->multiply('-1'),
          'source_id' => $promotion->id(),
        ]));
      }
    }
  }
}

```

my\_module.info.yml:

```
name: 'Custom Promotion Conditions'
type: module
description: 'Provides Custom Offers and Conditions'
core: 8.x
package: 'Custom'
dependencies:
  - commerce:commerce
  - commerce:commerce_order
  - drupal:options

```

my\_module.module:

```
<?php

/**
 * @file
 * Contains my_module_custom_promotion.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function my_module_custom_promotion_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the my_module_custom_promotion module.
    case 'help.page.my_module_custom_promotion':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('My Awesome Module') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_theme().
 */
function my_module_custom_promotion_theme() {
  return [
    'my_module_custom_promotion' => [
      'render element' => 'children',
    ],
  ];
}

```

I've tried my best but I cannot figure out what I'm doing wrong and causing this "name already in use" error. I've searched my entire project just in case, but the text "OrderItemFixedAmountTarget" is only used in this one file.

# Answer
Giorgosk's answer didn't fix the problem but it did lead me to notice that the name of my .yml and .module files didn't match the short name I had given the module, and that was the reason for the bizarre error messages. Thanks!
> 0 votes

---
Tags: 8, commerce
---


title: Update migrations to import new content

text:
# Question
Title: Update migrations to import new content
I'm using migrate upgrade drush command to generate migrations from a live DB of website. So content is created during my migrations. How can I do an update of these migrations to import new content when re-run migrations ?

Thanks

# Answer
> 0 votes
You could use the `track_changes` option, ex.

```
source:
   plugin: d7_node
   node_type: article
   # Allows to import changed as well as new records from the source.
   track_changes: true

```

https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/overview-of-migrate-source-plugins#track\_changes

---
Tags: 8, migrations, updating
---


# Question
Title: Disable "Operating in maintenance mode. Go online."
The solution for Drupal 7 is using the following code, as per answer of How can I disable the message “Operating in maintenance mode. Go online.” in maintenance mode?

```
function mytheme_preprocess_page(&$vars) {
  if (variable_get('maintenance_mode', 0)) {
    $message_count = count($_SESSION['messages']['status']);
    if($message_count > 1) {
      array_shift($_SESSION['messages']['status']);
    }
    else {
      unset($_SESSION['messages']['status']);
    }
  }
}

```

What is the solution for Drupal 8?

I cannot figure out how to do it with https://www.drupal.org/project/disable\_messages.

Hide/disable the message for everyone including the user #1.

# Answer
> 1 votes
Drupal 8 version:

```
function mytheme_preprocess_status_messages(&$variables) {
  if (\Drupal::state()->get('system.maintenance_mode')) {
    $message_count = count($variables['message_list']['status']);
    if ($message_count > 1) {
      array_shift($variables['message_list']['status']);
    }
    else {
      unset($variables['message_list']['status']);
    }
  }
}

```

---
Tags: 8, maintenance-mode
---


# Question
Title: Is there a standard place 3rd party module pages report what PHP version they're tested on?
Is this info reported anywhere?

for e.g. https://www.drupal.org/project/optimizely

or

https://git.drupalcode.org/project/optimizely

# Answer
> 2 votes
There is a route for all modules of the pattern `https://www.drupal.org/node/{nid}/qa` for showing testing reports. Nightly runs, per-commit runs, and one offs should appear there.

For the module you mentioned, the page is https://www.drupal.org/node/1305958/qa, and it looks like automated tests aren't set up.

The Poll module does show tests, https://www.drupal.org/node/1896974/qa

In general, the default test (if set up) will track the min versions for PHP and MySQL for the chosen core branch.

---
Tags: 8
---


title: Node ID from hook_comment_insert

text:
# Question
Title: Node ID from hook_comment_insert
I need the ID of the node the inserted comment is attached to. This is what I have tried:

```
function my-module_comment_insert(Drupal\Core\Entity\EntityInterface $entity)
{

   // According to https://drupal.stackexchange.com/questions/145823/how-do-i-get-the-current-node-id
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
        $nid = $node->id();
    }
    drupal_set_message("The vaue is " . print_r($nid), 'warning');
}

```

But... The value I get is "1", while it should be (according to node URL) "55". Or am I using drupal\_set\_message for debugging the wrong way?

I also tried **$entity-\>get('entity\_id')-\>target\_id** (according to: How to get the node id the comment is attached to in hook\_comment\_insert?) or **\Drupal::routeMatch()-\>getRawParameter('node')**, but I always get "1" and I'm positive that the website cache has been cleared.

# Answer
`print_r($variable)` does not return anything useful, it just outputs text (which it does successfully, so it returns boolean TRUE \[which is rendered as `1` when printed\]). Your `drupal_set_message` basically does something like `echo ($string . $boolean . $string)`

Use `print_r($variable, true)` to return the output of the print\_r to the calling function, instead of rendering it.

See https://www.php.net/manual/function.print-r.php
> 0 votes

# Answer
Look here https://git.drupalcode.org/project/drupal/blob/8.8.x/core/modules/comment/src/Entity/Comment.php#L369 https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21Entity%21Comment.php/function/Comment%3A%3AgetCommentedEntity/8.2.x

and... =) How to get the node id the comment is attached to in hook\_comment\_insert?
> 0 votes

---
Tags: 8
---


title: Organizing config for use with a module

text:
# Question
Title: Organizing config for use with a module
I've recently learned about adding a `config/optional` directory to a module to provide config items that will be imported upon enabling the module if there are no conflicts.

Is there an easier way to retrieve config for use in this way than cherry-picking it out of a site's config directory? For instance — if I wanted a module to include the config for a menu, a content type, etc is there a convenient way to retrieve all config related to those items?

# Answer
> 1 votes
Use a config export Console command with the options --module and --optional.

Example for config:export:single:

```
drupal config:export:single --name=system.site \
 --remove-uuid --remove-config-hash \
 --module mymodule --optional

```

Add `--include-dependencies` to export dependencies of the configuration as well.

For exporting content types including fields and display modes use config:export:content:type.

Or more generic for any config entity type see this answer (not yet included in the documentation).

---
Tags: configuration
---


title: How to achieve clean HTML markup?

text:
# Question
Title: How to achieve clean HTML markup?
If you visit official website of Dries Buytaert https://dri.es/ and look into the source you will see very clean and minimal markup with no unnecessary tags and classes, eg:

When I create a simple custom block it has lots of junk under each field, eg:

How to strip and delete all the junk and leave or add only classes and wrappers you need?

I did look up Fences, but it's latest version is in alpha since 2016 (and not sure if it does that) and cannot figure out how to strip at least classes with Display Suite extras module, it seem that it doesn't do anything, went though all settings.

Did Dries use any of known public modules or is it all custom code?

# Answer
This is no junk, this is the HTML and CSS (classes) required and defined by the theme and modules you use.

If you want a more minimal markup, you have to create your own theme with your own templates, but remember that modules like `QuickEdit`, `Views` or `Layout Builder` require a specific markup structure based upon the markup of the `stable` core theme.

Regarding dri.es: He seems to be using a custom, minimal theme and a very reduced setup with many modules disabled (e.g. QuickEdit will not work with his theme).
> 2 votes

# Answer
A lot of those classes are added by the classy base theme templates. You'll be able to get rid of them with a theme based on stable instead.
> 4 votes

---
Tags: 8, theming, performance
---


# Question
Title: How to set "Language Selector dropdown" required in node form
I want to know How to set "Language Selector Drop-Down " required in node form?

I tried to do this via hook\_form\_alter, but it seems $form\['language'\] is not created in this hook !

Is there any hook that let me modify language Drop-Down selector?

# Answer
I found the solution here

```
You can enable i18n_node module that is included in i18n module. Then:

    Go to edit the content type (admin/structure/types/manage/page).
    Open the 'Multilingual settings' tab.
    Check the 'Require language' checkbox.

Done.

```

**Multilingual content** must be installed at first and then in content type, **Multilingual settings** tab will be added
> 0 votes

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


# Question
Title: How do I modify the "Formats" dropdown in CKEditor
The CKEditor in Drupal 8 has a Formats toolbar button containing different text formats: "Heading 1", "Heading 2" etc. How can I add and remove items from this list?

# Answer
> 8 votes
I would use `Styles` instead of `Formats`, because styles are fully controlled by you, from admin interface, no need for editing files.

When you add it to the toolbar you can configure it and add as many elements as you wish.

Here is an example config:

# Answer
> 5 votes
You modify the "Formats" dropdown by changing the list of allowed HTML tags. Any block-level HTML tags are shown in the "Formats" dropdown by CKEditor automatically.

For a tutorial/full explanation, see https://www.drupaleasy.com/quicktips/limiting-block-level-styles-drupal-8-ckeditor.

# Answer
> 4 votes
After many hours of researching I finally found full solution for this subject (I merged answer of rémy, information from this article, and of course ckeditor docs).

```
function MODULENAME_editor_js_settings_alter(array &$settings) {
    foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
        if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {

            //Reference just to code be shorter:
            $ck = &$settings['editor']['formats'][$text_format_id]['editorSettings'];

            //Check if index 'format_tags' exists, it means that format list is active
            if (isset($ck['format_tags'])) {

                //Add my custom format at the end of list of formats, it's possible to add as many formats as you wish. Of course it's possible to remove other formats or change theirs order, by overwrite all variable.

                $ck['format_tags'] .= ';MyCustomFormat';

                // And now is the most important thing to do - setting of added format:
                // Name it's name which will be shown at the list and it's possible to put there anything what you want.
                // Element is html element - beware that this element should be allowed in back-office!
                // Attributes - it's an array where you can add class and other allowed attributes
                $ck['format_MyCustomFormat'] = [
                    'name' => 'MyCustomFormat Name',
                    'element' => 'p',
                    'attributes' => [
                        'class' => 'MyCustomFormatClass',
                        'data' => 'SOME DATA',
                        'name' => 'SOME NAME'
                    ]
                ];
            }
        }
    }
}

```

Allowed attributes you can set here, separately for each format: http://localhost:8081/admin/config/content/formats/ (Click for configuration - list of attributes is at the bottom of page).

Good luck!

# Answer
> 2 votes
You need to hook\_editor\_js\_settings\_alter(), for adding **DIV**, like this:

```
function YOUR_MODULE_editor_js_settings_alter(array &$settings) {
  foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
    if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
      $settings['editor']['formats'][$text_format_id]['editorSettings']['format_tags'] .= ';div';
    }
  }
}

```

# Answer
> 1 votes
I disable the formats, and define custom styles like explained in https://drupal.stackexchange.com/a/193528/71941. Then, to get a live preview in your editor, include your theme css in your editor with the snippet below. Concerning usability, this seems the best approach for a webmaster.

```
use Drupal\editor\Entity\Editor;

/**
 * Implements hook_ckeditor_css_alter().
 *
 * Injects our CSS sheets anytime CKEditor has loaded.
 *
 * @param array $css
 * @param Drupal\editor\Entity\Editor $editor
 */
function MY_MODULE_ckeditor_css_alter(array &$css, Editor $editor) {
  if (!$editor->hasAssociatedFilterFormat()) {
    return;
  }

  $known_formats = [
    'basic_html',
    'full_html',
  ];

  if (in_array($editor->getFilterFormat()->id(), $known_formats)) {
    $css[] = drupal_get_path('theme', 'MY_THEME_NAME') . '/css/main.css';
  }
}

```

# Answer
> -3 votes
After you install the ck-editor module, there is a file name `ckeditor.styles.js` in the root of the module folder.Copy that file and paste in your theme folder and edit that file per your need. For quick check you can edit the file directly there also but it is not recommended.

---
Tags: 8, wysiwyg
---


# Question
Title: How can I set value to hidden field (Form Api) and send them with post method?
I’ve created a form with Form Api in a custom module.

I send datas with `post` method to a web service.

In `buildForm()`

```
$form['mode'] = array(
    '#type' => 'hidden',
    '#value' => 'INTERACTIVE',
);

$form['amount'] = array(
    '#type' => 'textfield'
);

$form['signature'] = array(
    '#type' => 'hidden',
     // here is the field I need to set its value on submit because its value depends on other field.
    '#value' => ''
 );

$form['#action'] = 'https://url-webservices.fr/‘

```

It works. But I need to set value to hidden fields `'signature'` on submit.

How can I set value to hidden field and send them with form with post method ?

Something like this but it doesn't work :

```
in submitForm()

form_state->setValue('signature', $signature);

```

I’ve studied some examples and I can do that :

In `validateForm()`

```
$signature = 'string-to-send';
$form_state->setValue('signature', $signature);
$form_state->setRebuild();

```

And in `buildForm()` :

```
$signature = $form_state->getValue('signature');

$form['signature'] = array(
    '#type' => 'hidden',
    '#value' => $signature
);

```

Of course, it works only when page is reloaded when the form is rebuilt. If datas is send to an external URL with `POST` method, the field value is empty.

# Answer
> 0 votes
To summarize the question : I use an API where a SHA signature had to be sent along the form . That signature is calculated based on the other form inputs, so it had to be calculated after the user clicks the submit button and it had to be sent as a form field with POST method .

In `buildForm()`, I have :

```
$form['#action'] = 'https://url-webservices.fr/';

```

It is like it is executed before I can call `validateForm()` where I can set the value I need.

I've searched a lot for a solution but didn't find an easy way like set a news value in `submitForm()`.

So here is a solution. I'm not completely happy with it but it works.

I've built a 2 steps forms.

In first step, the `$form['#action']` is empty. After validation, I set a value to `$form['#action']` and to the form fields I need :

```
$form_state->setValue('action', $url_action);

```

I also change the text of the submit button with something like "confirm".

Then user could confirm and validate the form.

All the mechanic of the 2 steps could be seen in that answer (thanx to Clive) :

How to use ConfirmFormBase to confirm the action of another form?

---
Tags: 8, forms
---


# Question
Title: How to fix “Cannot read property 'icons' of null” error?
First of all, I'd like to mention this answer is not related, I'm using Drupal 8.6.1.

I'm trying to create a CKEditor plugin with a new button. In the */admin/config/content* page I get the error but the button appears well:

However when I go to */node/add/article* page, I get the error and there is a display issue on CKEditor windows:

Clearing the cache does not change anything.
The error does not appear anymore when I uninstall my custom D8 module.

---

*modules/custom/inline\_comment/js/plugins/inline\_comment/plugin.js*

```
CKEDITOR.plugins.add('comment', {

    icons: 'comment',

    // The plugin initialization logic goes inside this method.
    init: function (editor) {
        // Define the editor command that add a comment.
        editor.addCommand('comment', {
            // Define the function that will be fired when the command is executed.
            exec: function (editor) {
                ...
            }
        });

        // Create the toolbar button that executes the above command.
        editor.ui.addButton('Comment', {
            label: 'Add comment',
            command: 'comment',
            toolbar: 'insert'
        });

```

---

*modules/custom/inline\_comment/src/Plugin/CKEditorPlugin/InlineComment.php*

```
namespace Drupal\inline_comment\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\ckeditor\CKEditorPluginConfigurableInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "inline_comment" plugin.
 *
 * @CKEditorPlugin(
 *   id = "inline_comment",
 *   label = @Translation("CKEditor Inline Comment")
 * )
 */
class InlineComment extends CKEditorPluginBase implements CKEditorPluginConfigurableInterface {

  public function getFile() {
    return drupal_get_path('module', 'inline_comment') . '/js/plugins/inline_comment/plugin.js';
  }

  public function getButtons() {
    return [
      'Comment' => [
        'label' => t('Linkit'),
        'image' => drupal_get_path('module', 'inline_comment') . '/js/plugins/inline_comment/icons/comment.png',
      ],
    ];
  }

```

---

The location of the icon is: `modules/custom/inline_comment/js/plugins/inline_comment/icons/comment.png`

# Answer
> 3 votes
To anyone who is running into this issue:

```
 * Defines the "inline_comment" plugin.
 *
 * @CKEditorPlugin(
 *   id = "machine_name_that_must_match_with_icons",
 *   label = @Translation("CKEditor Inline Comment")
 * )
 */

```

and

`getButtons()` must return the same ID.

Annotation is new to me and I am sure it's not new to anyone else who are Drupal 8 developers but it might help someone who is new/still learning about how Drupal 8 works.

https://www.drupal.org/docs/8/api/plugin-api/annotations-based-plugins

---
Tags: 8, wysiwyg, plugins
---


title: Views Add Link to product field missing

text:
# Question
Title: Views Add Link to product field missing
I have a search results View which list the (Commerce) products. I show the title and the image fields. I those fields to wrap in a custom `<a>` link tag. When I am adding fields, I miss the 'Link to product' field, so I am able to rewrite the fields and use the path `{{ path }}` token and theme it to my needs.

Do I miss or do I have to activate something?

# Answer
> 0 votes
The Path field has been deprecated, use `Link to content` instead. More info in this answer: How to get Node Url in RSS view?

When you have to construct a different output out of field values it's good to use the `Custom text` Field.

Exclude from display your Title, Image, and Link to content fields, reorder the fields so the Custom text field comes last.

Enter your anchor HTML into the Custom text area and use the `Replacement patterns` you see in the list below the area to construct the full HTML code. One of them will be the URL token. Something like:

`<a href="{{ view_node }}">{{ title }} {{ field_image }}</a>`

Make sure your Title field settings aren't using links, and you may have to adjust the image field code further.

---
Tags: views, theming, commerce
---


# Question
Title: How to get the node id the comment is attached to in hook_comment_insert?
How can I get the node `id` the comment is attached to in `hook_comment_insert`?

I tried the following code:

```
function mymodule_comment_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() == 'comment_custom' && $entity->get('entity_type')->value == 'node') {

    // Below returns empty, because "$entity->get('entity_id')->value" is empty.
    $node = Node::load($entity->get('entity_id')->value);

    // No luck with this one too.
    $node = \Drupal::routeMatch()->getParameter('node');

  }
}

```

# Answer
> 6 votes
the correct way to load nid is,

`$entity->get('entity_id')->target_id`

and not

`$entity->get('entity_id')->value`

In case of doubt which key to use,

try,

`$entity->get('entity_id')->getValue()`

and inspect the returned value.

# Answer
> 5 votes
This is a late answer based on another question flagged as duplicate of this one.

The Comment entity has some helpful methods for getting back the entity it's associated with.

CommentInterface::getCommentedEntity should get the entity object that the comment is attached to.

So

```
if ($entity instanceof \Drupal\comment\CommentInterface) {
   $commentedEntity = $entity->getCommentedEntity();
   if ($commentedEntity && $commentedEntity instanceof \Drupal\node\NodeInterface) {
     // The entity that the comment is attached to is a node.
     // Do something with the commented entity.
   }
}

```

---
Tags: 8, hooks, comments
---


# Question
Title: In the Counter module the Visitors "This Year" count is decreasing. How can I get it to increase instead?
The Visitors "This Year" count decreases in number in the D8 Counter module while the "Hits" and "Visits" increase as normal. For example, one afternoon the "This Year" count was 329,546. The next morning it was 328,149. The third day is was 327,138. The "Visits" and "Hits" only increase on the average of 150 per week. The "This Year" is decreasing more than a thousand by the day(????) What's going on? Any help would be appreciated.

# Answer
> 1 votes
I've checked the module and i can confirm that the behaviour of the module is like previously i explained in comments. So, it is not a problem related to a module. It's a problem related to marketing analysis. Probably the "Visits" and "Hits" are absolute values ( they are always increasing ). On the other hand, the "This Year" value is a calculated value for 365 last days.

At this time last year, you had lots of visitors.

---
Tags: 8
---


# Question
Title: How can I stop auto uploading of managed_file elements?
I am trying to create a field to upload the xml format of site map. But when I add a file to my filed it automatically uploaded and saved in the S3 bucket before I click on the submit button.

The issue is when someone added a xml file to that field and then closes the tab without submitting the form. The xml file is already uploaded to S3 bucket that way.

I need a way to manually upload this. I need to upload the image only after I pressed the submit button in the form. Without uploading the xml file automatically when selecting.

This is my buildForm() function.

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

  $form['sitemap'] = [
    '#type'              => 'managed_file',
    '#name'              => 'sitemap',
    '#title'             => t('Upload Site Map (xml)'),
    '#upload_location'   => 's3://private/sitemap',
    '#field_suffix'      => 'XML format supported',
    '#upload_validators' => [
      'file_validate_extensions' => ['xml'],
    ],
    '#required'          => TRUE,
    '#validated'         => TRUE,
  ];

  $form['submit'] = [
    '#type'       => 'submit',
    '#value'      => t('Save configuration'),
    '#attributes' => [],
    '#validated'  => TRUE,
  ];

  return $form;
}

```

# Answer
> 1 votes
I have stopped the managed\_file auto uploading this way. This is like a workaround. But this works. You better put this in the `$(document).ready` in the js file.

```
(function($) {
    $(document).ready(function() {
        /*Drupal has a hidden submit button for upload the file
          automatically. This will remove the button so Drupal won't auto upload for the given managed_file field*/
        $("input[name*='name_of_the_button']").remove();
    });
}(jQuery));

```

note - make sure you find the correct button. This is not your upload file button. This is the button that drupal creates automatically to do the file upload. This button is not visible in the page. So you need to go the inspect element and find this button. The button has the class `js-hide button js-form-submit form-submit`. So you won't miss !

# Answer
> 4 votes
Try overriding the #attached library on the managed file field:

```
$form['sitemap'] = [
'#type'              => 'managed_file',
'#name'              => 'sitemap',
'#title'             => t('Upload Site Map (xml)'),
'#upload_location'   => 's3://private/sitemap',
'#field_suffix'      => 'XML format supported',
'#upload_validators' => [
  'file_validate_extensions' => ['xml'],
],
'#required'          => TRUE,
'#validated'         => TRUE,
'#attached'          => [
   'library' => [],
 ]

```

\];

---
Tags: 8, forms, files
---


title: Change field label used in node display

text:
# Question
Title: Change field label used in node display
I have a custom content type in Drupal 8.6.x. I want to be able to change the text used for a field label based on the value of a taxonomy term reference in the node.

For example, I want to change the field label used for the body field, to display "Description" or "Definition" or "Introduction", etc. based on the value in the taxonomy reference field. This is when rendering the node - I don't need to change the field label on the form. I'll need to alter the label in the full and teaser display modes, and just for the custom content type. I don't need to change any of the text in the body field, just what label is shown above it.

# Answer
> 4 votes
You can do this by implementing `hook_entity_view_display_alter()` in a custom module, for example using code similar to the following one. (Replace *mymodule* with the machine name of the module containing this function.)

```
function mymodule_entity_view_display_alter(EntityViewDisplayInterface $display, array $context) {
  if ($context['entity_type'] == 'node' && $context['bundle'] == 'CUSTOM_CONTENT_TYPE') {
    if (in_array($context['view_mode'], ['full', 'teaser'])) {
      foreach ($display->getComponents() as $name => $options) {
        if ($name == 'text' && isset($options['label'])) {
          $node = \Drupal::routeMatch()->getParameter('node');
          $options['label'] = $node->FIELD_TERMS->entity->label();
          $display->setComponent($name, $options);
        }
      }
    }
  }
}

```

---
Tags: 8, nodes
---


# Question
Title: How can I programatically add the default AJAX throbber to a form submit?
I'm trying to add the AJAX throbber in core to a form submit button, specifically the Private Message module new message page.

Here is my code:

```
function MYMODULE_form_privatemsg_new_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#ajax'] = array(
'callback' => 'MYMODULE_submit_throbber_callback',
  );
}

function MYMODULE_submit_throbber_callback($form, $form_state) {
  return;
}

```

Here's what I have done so far.

First, I looked at the Page Throbber module for ideas, but this does everything in `hook_init()`, and it doesn't use the throbber included in core. If possible, I want to avoid replicating what is already in core for a single form.

Next, I looked in the Examples module, specifically the AJAX example that includes an AJAX submit example. However, this is for adding a callback to do something else, but all I want to do is get the pager, which appears to happen automatically if you add any kind of callback.

So I added a dummy callback that just returns. This gives me a throbber, but it breaks the submit functionality of the form. **How do I get the throbber without breaking the form submit?**

# Answer
> 1 votes
It should be easily done like this:

```
$form['submit']['#ajax'] = [
  'callback' => 'MYMODULE_submit_throbber_callback',
  'progress' => [
    'type' => 'throbber',
    'message' => NULL,
  ],
];

```

And then return `$form` in the callback;

# Answer
> 0 votes
If you want to show a throbber on the submit button without coding, you can use the Hide Submit module.

My question is about doing it programatically, but I'm listing this as an answer for people who don't want to code.

---
Tags: 8, forms, ajax
---


# Question
Title: Why is $form array empty when extending FormBase or NodeForm
Why is $form not upcast with the requested bundle's fields for the default Form Mode for GET requests; and with the entities' values for other method requests?

My form:

```
namespace Drupal\tam_api\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

use Drupal\node\NodeForm;
// use Drupal\Core\Form\FormBase; i've tried all of these as well...
// use Drupal\Core\Entity\ContentEntityForm;
// use Drupal\Core\Entity\EntityForm;
// Drupal\node\Form\NodeDeleteForm

class TamForm extends NodeForm {

  public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL) {
    $form = parent::buildForm($form, $form_state);
    $res = array('fields'=>json_encode($form, TRUE));
    return new JsonResponse($res);
  }

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

  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm();
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $module_data = system_rebuild_module_data();
  }

}

```

My route:

```
namespace Drupal\tam_api\Routing;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class TamRoutes {

  protected $formMap = array(
    'node' =>array(
        'tracks'=> array(
         'default'=>'/node/tracks',
         'add'=>'/node/tracks',
         'delete'=>'/node/tracks/{node}',
         'edit'=>'/node/tracks/{node}',
       )
     ) // and other entity types...
  );

  public function routes() {
    $route_collection = new RouteCollection();

    foreach($this->formMap as $entity_type=>$bundles) {
      foreach($bundles as $bundle=>$routes) {
        foreach($routes as $verb=>$path) {
          $route = new Route('/forms'.$path);

          $perms = array('_access'=>'TRUE'); // TEMP while testing

          $opts = array(
            '_format' => ['json'],
            '_auth' => ['oauth2']
          );

          if ($verb != 'add') {
            $opts['parameters'] = array(
              $entity_type => array('type'=>'entity:'.$bundle)
            );
          }

          $defaults = ['_form' => '\Drupal\tam_api\Form\TamForm'];
          if ($entity_type == 'node') {
            if ($bundle === 'tracks') {
              $defaults = ['_entity_form' => 'node.tracks'];
            }
          } else if ($entity_type == 'group_content') {
            $perms['_group_member'] = 'TRUE';
            if ($verb != 'add') {
              $opts['parameters']['group_content'] = array('type'=>'entity:group_content');
            }
          }

          $route->setDefaults($defaults);
          $route->setRequirements($perms);
          $route->setOptions($opts);

          if ($verb === 'add') {
            $route->setMethods(['POST', 'GET']);
          } else if ($verb === 'edit') {
            $route->setMethods(['PATCH', 'GET']);
          } else if ($verb === 'delete')  {
            $route->setMethods(['DELETE', 'GET']);
          } else {
            $route->setMethods(['GET']);
          }

          $route_collection->add($entity_type.'.'.$bundle.'.'.$verb, $route);
        }
      }
    }
    return $route_collection;
  }

}

```

My module:

```
function tam_api_entity_type_build(array &$entity_types) {
  tam_api_module_entity_type_alter($entity_types); // _alter isn't seeming to fire by itself?
}
function tam_api_module_entity_type_alter(array &$entity_types) {
  $form_modes = \Drupal::service('entity_display.repository')->getAllFormModes();
  foreach ($form_modes as $entity_type => $display_modes) {
    if ($entity_type !== 'node') {
      continue;
    }
    $node_type = $entity_types[$entity_type];
    foreach ($display_modes as $machine_name => $form_display) {
      $default_handler_class = '\Drupal\tam_api\Form\TamForm';
      $node_type->setFormClass($machine_name, $default_handler_class);
    }
  }
}

```

ERRORS are as follows:

GET: /forms/node/playlists/31694?\_format=json: (which routes through `_entity_form`) `Error: Call to a member function getEntityTypeId() on null in
Drupal\Core\Entity\EntityForm->getBaseFormId() (line
79 of
core/lib/Drupal/Core/Entity/EntityForm.php.`

GET: /forms/node/tracks/32434?\_format=json: (which routes through `_form`) `Argument 1 passed to Drupal\Core\Entity\EntityForm::setEntity() must implement interface Drupal\Core\Entity\EntityInterface, string given, called in /Users/user/Developer/trackauthority/tam-d8/web/core/lib/Drupal/Core/Entity/HtmlEntityFormController.php on line 74 in Drupal\Core\Entity\EntityForm->setEntity()`

GET /forms/node/tracks?\_format=json (which routes through `_form` `Missing bundle for entity type node in Drupal\Core\Entity\ContentEntityStorageBase->doCreate() (line 86 of core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php). >Drupal\Core\Entity\EntityStorageBase->create(Array) (Line: 381)`

# Answer
When you return a response instead of a Form API array

```
  public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL) {
      ...
    return new JsonResponse($res);
  }

```

the form is reduced to a request/response pattern of a controller. It is no longer possible to use it as a Drupal form.
> 0 votes

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


# Question
Title: How to programmatically build a page and a form in the same page
What I'd like to do is build a page with two things:

* On one half of the page, custom markup with data from Drupal.
* On the other half, a custom form also submitted to Drupal.

There are a lot of tutorials on how to programmatically build pages in D8 (create route, extend controller, return render array, etc.). There are also a lot of tutorials on how to programmatically build forms on D8 (create route, extend form base, return render array, etc.). However, I could not find any resource on how to build *both* onto the same page.

How would I go about doing this?

# Answer
You must use the `formBuilder`, like this:

```
$render = [];
$render['elememt1'] = [
  '#type' => 'markup',
  '#markup' => t('Test'),
];
$render['element2'] = \Drupal::formBuilder()->getForm('Drupal\MY_MODULE\Form\MyFormClass');// The destination of your form.

return $render;

```
> 4 votes

# Answer
Not sure if it fits to your project.

As a themer, I would create a form with `Form Api` in a custom module.

The I would create a custom block for this form :

```
src/Plugin/Block/HelloBlock.php

```

See here for a example :https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-blocks/create-a-custom-block

I would then create a twig template for the page (what you call "custom markup with data from Drupal"). And Then I would integrate the custom block with the form.
> 1 votes

---
Tags: 8, forms, page-controller
---


# Question
Title: Add CSS class to view image_field in twig
In my custom view fields twig file `views-view-fields--search--product_result.html.twig` I try to theme my view item.

```
{{ fields.field_images.content }}
<h5 class="card-title">{{ fields.title.content }}</h5>

```

How do I add a CSS class to my image field `{{ fields.field_images.content }}`?

# Answer
This is what worked for me: It's a preprocess function in the .theme file. I wish there was a way to do this directly into the template. This would apply that class everywhere the field appears.

```
/**
 * Implements hook_preprocess_field().
 * Adds a class to a People image.
 */
function themename_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_machine_name') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['content']['#item_attributes']['class'][] = 'my_class';
    }
  }
}

```

`themename`, `field_machine_name`, and `my_class` are placeholders for your values.

This produces:

```
<img class="my_class" src="/your/image/location.png" alt="Your alt text." typeof="foaf:Image" width="458" height="354">

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Webform element validation custom module
I want to add a custom validation to text input, I followed the instruction provided in https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element

I have a requirement which needs to verify an id entered into a text box, by making a REST API call to another system, the issue is to make that REST API call, I need another text parameter which is also inputed into the webform. I have written a custom handler which makes that rest call, but that custom handler work on webform post save option only, how can I pass more than 2 fields to the validate function mentioned in the example given.

```
function onboarding_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
    // check for desired element
   if (isset($element['#webform_id']) && $element['#webform_id'] === 'register_account--surname'){
     $surname= $element['#default_value'];
    $form_state->setValue('SOME_NAME', $surname);
   }
   if (isset($element['#webform_id']) && $element['#webform_id'] === 'register_account--proda_id') {

        $element['#element_validate'][] = array(
            'Drupal\dhs_vendor_onboarding\Validate\DhsValidateConstraint',
            'validate'
        );
    }
}

```

In the validate function:

```
public static function validate(array &$element, FormStateInterface $formState, array &$form) {
        ksm($formState->getValue('SOME_NAME'));
        $webformKey = $element['#webform_key'];
        $value = $formState->getValue($webformKey);
        $surname= $formState->getValue('SOME_NAME');
        }

```

I am not getting any value for surname

# Answer
i was able to get the value of surname from the Formstate, the form state had surname in surname field itself.

```
public static function validate(array &$element, FormStateInterface $formState, array &$form) {
    $webformKey = $element['#webform_key'];
    $value = $formState->getValue($webformKey);
    $surname= $formState->getValue('surname');
}

```

this did the trick.
> 0 votes

---
Tags: 8, forms
---


title: How to run tests in my contrib module?

text:
# Question
Title: How to run tests in my contrib module?
I'm writing a contrib module but I can't find the documentation to run the tests - unit and functional. I know that I'm supposed to use PhpUnit, but I can't find examples of PhpUnit configuration files and more importantly, there is no resource on how to execute functional tests - i.e. having the module tested against a running Drupal instance.

I've been looking at some famous contrib modules like Paragraphs and there is nothing about running tests in their documentation - and no phpunit dependency at all. Which doesn't make sense to me since there are some functional tests implemented.

How are we supposed to provide tests for contrib modules?

# Answer
You have to include phpunit/phpunit package in composer, alredy done if you took default drupal installation :

```
composer require phpunit/phpunit --dev

```

A file should be filled which describe yours testsuites, generally phpunit.xml

It looks like this `./phpunit.xml` :

```
<phpunit bootstrap="web/core/tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">

<php>
  <ini name="error_reporting" value="32767"/>
  <ini name="memory_limit" value="-1"/>
  <env name="SIMPLETEST_BASE_URL" value="http://drupal-8.localhost"/>
  <env name="SIMPLETEST_DB" value="mysql://drupal-8:drupal-8@localhost/drupal-8"/>
  <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/var/www/sites/default/simpletest"/>
</php>
  <testsuites>
    <testsuite name="testname1">
      <directory>web/modules/custom/your_module/tests</directory>
    </testsuite>
    <testsuite name="testname2">
      <directory>web/modules/custom/your_module2/tests</directory>
    </testsuite>
  </testsuites>
</phpunit>

```

In this example, drupal is located in `./web/` directory with `./vendor/`, both in root path (`./`) .

You can add test for contrib module, but they are already tested (if they contain tests) when authors are pushing their sources to drupal.org ( https://www.drupal.org/pift-ci-job/1339317 ) :

```
<testsuite name="toolbar">
    <directory>./web/modules/contrib/admin_toolbar/tests/src/FunctionalJavascript</directory>
</testsuite>

```

Then you can run tests with :

```
./vendor/phpunit/phpunit/phpunit

```

To use a specific description file :

```
./vendor/phpunit/phpunit/phpunit -c phpunit-other.xml

```

To run a specific testsuite :

```
./vendor/phpunit/phpunit/phpunit --testsuite=testname1

```
> 2 votes

---
Tags: testing
---


# Question
Title: Conditional field on checkbox is not woking
If the checkbox is checked then it will show the textbox else not, for this purpose i've written this code. But it is not working, even the textfield is not showing.
what do i need to change in this code ?

```
      $form['details'] = array(
       '#type' => 'fieldset',
       '#title' => $this->t('Details'),
      );

      $form['details']['field_type'] = array(
       '#type'    => 'checkbox',
       '#default_value' => 0,
       '#title'   => t('Choose entry type.')
      );

     $form['details']['text'] = array(
      '#type'          => 'textfield',
      '#title'         => t('Enter the text'),
      '#states'        => array(
         'visible'      => array(
           ':input[name="field_type"]' => array('checked' => TRUE),
         ),
       ),
    );

```

# Answer
Please try this code ... It works !!

```
$form['field_type'] = array(
  '#type'    => 'checkbox',
  '#default_value' => 0,
  '#title'   => t('Choose entry type.')
);

$form['text'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Enter the text'),
  '#states'        => array(
     'visible'      => array(
       ':input[name="field_type"]' => array('checked' => TRUE),
     ),
   ),
);

```
> 5 votes

# Answer
Attribute #states does not work with some types such as date / datetime.

You have to add your field into a container and apply the #states to this container.

```
$form['filters']['start-do'] = array(
  '#type' => 'checkbox',
  '#title' => t('Filter by start date'),
);
$form['filters']['container'] = array(
  '#type' => 'container',
  '#states' => array(
    'invisible' => array(
      'input[name="start-do"]' => array('checked' => FALSE)
    )
  )
);
$form['filters']['container']['start'] = array(
  '#type' => 'date',
  '#title' => t('Start Date'),
  '#description' => t('Show hours that started after this date.'),
);

```
> 0 votes

---
Tags: 8, javascript
---


title: Run validation callback before ajax

text:
# Question
Title: Run validation callback before ajax
The submit element on my form uses an ajax callback which sends out an email.

I have a validation callback which I've added to this form, but it gets run after the ajax callback and so the email will be sent out even if the form doesn't validate.

I can't add the validation to the ajax callback itself because it gets used on lots of other forms on my site.

Is there any way to run my validation callback before ajax is run?

# Answer
Actually, you will pass through your validateForm() method, whether you are using Ajax or not.

In the validateForm(), you have to set the appropriate errors on your fields which do not validate. Then, as Charles Bamford stated, you need to handle the error management in your submit callback.

So basically, you would end up with some kind of the following structure:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#prefix'] = '<div id="my-ajax-target-element"></div>

  $form['my_field'] = [
    '#type' => 'textfield',
    '#title' => $this->t('My field title'),
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Submit'),
    '#ajax' => [
      'callback' => '::myAjaxCallback',
      'wrapper' => 'my-ajax-target-element',
      'method' => 'replace',
    ],
 ];

 return $form;

}

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  // I set error on my field here, but due to Ajax, the display
  // of error messages will be handled in the Ajax callback
  if($values['my_field'] != 'my expected value') {
    $form_state->setErrorByName('my_field', $this->t('This is my error message'));
  }
}

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  // If $form_state contains errors, populate the ajaxResponse content with the error messages
  if($form_state->hasAnyErrors()) {
    $errors = $form_state->getErrors();
    $command_content = $errors['my_field'];
  }
  else {
    // Happily proceed to the submission of your form
  }

  $response->addCommand(new HtmlCommand('#my-ajax-target-element', $command_content));
  return $response;
}

```
> 2 votes

# Answer
If the validation callback is not being called, you can call it manually at the top of the ajax callback with $callback($form, $form\_state).

That said, the validation is probably being called, but the ajax callback doesn't know how to handle it. This is how I'm handling ajax callbacks on some forms I have.

At the top of the ajax callback:

```
$messages = \Drupal::messenger()->messagesByType('error');
if ($form_state->hasAnyErrors() || !empty($messages)) {
  // If the form has errors, reload it.
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand($css_form_id, $form));
  return $response;
}

```

This checks for any validation errors, and reloads the form. My form also has a status messages element at the top

```
$form['status_messages'] = [
  '#type' => 'status_messages',
  '#weight' => -100,
];

```

So that when it is reloaded, the status messages appear on it.
> 0 votes

---
Tags: 8, forms, ajax
---


# Question
Title: Unable to add Quantity in Stock in Drupal Commerce 8 using Commerce Stock Module
I have enabled Commerce Stock Modules and its submodules 1. Commerce Stock API
2. Commerce Stock Field
3. Commerce Stock Local Storage
4. Commerce Stock UI

Created a Product Type ABC and added a field field\_stock(field type Stock Level ) under fields section of Product Type ABC
Under Commerce \>\> Configuration \>\> Stock
I have set the default configuration for STOCK SERVICES as - Use Default -
and default value is set to **Local Stock**

and when I edit the products I see it as

What am I missing I have added a field but it does not show the text value
where I can add quantity for a product ?

# Answer
> 1 votes
You need to configure the Stock Services found at `/admin/commerce/config/stock/settings` and choose `Local Stock` for your product variation.

Related topic can be found here.

**EDIT**: reading your question again and it seems that you added the field to the product itself, instead of adding it to the product variation. Stock field needs to be attached to the stock variation entity.

---
Tags: 8, commerce
---


title: How to create a Tour on the homepage?

text:
# Question
Title: How to create a Tour on the homepage?
I created a Tour with the Tour UI module and I was unable to activate the tour on the homepage.

The homepage of my site is the default view of drupal 8 with the machine name frontpage

How to activate the tour on the homepage ?

# Answer
Every time a page is rendered, the Tour module load all guided tours for this one. Those tours are added at the end of the DOM (with hook\_page\_bottom) with a css 'hidden' class. Then the Tour JS script (tour.js) handles those hidden elements by watching a triggering html element targeted by the id **toolbar-tab-tour**. If any tour is registered for the current page, that **toolbar-tab-tour**element will also be hidden by tour.js. I did this thing for showing a student role tour. I simply created a plugin block within my module:

namespace Drupal\my\_module\Plugin\Block;

```
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'StudentTourBlock' block.
 *
 * @Block(
 *  id = "student_tour_block",
 *  admin_label = @Translation("Student tour block"),
 * )
 */
class StudentTourBlock extends BlockBase {

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

    if (\Drupal::currentUser()->hasPermission('access tour') && !\Drupal::currentUser()->hasPermission('access toolbar')) {

      $build = [
        'tour_button' => [
          '#type' => 'html_tag',
          '#tag' => 'button',
          '#value' => '<span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span> ' . $this->t('Help'),
          '#attributes' => [
            'id' => 'toolbar-tab-tour',
            'class' => ['btn btn-success btn-xs hidden-sm hidden-xs']
          ],
          '#cache' => [
            'contexts' => [
              'user.permissions'
            ]
          ],
          '#attached' => [
            'library' => [
              'tour/tour',
            ],
          ],
        ]
      ];
      return $build;
    }
    else
      return [];
  }

}

```

Don't forget to attach the **tour/tour** library :)
> 0 votes

---
Tags: 8
---


# Question
Title: How to add domain access to custom entity?
Trying to do this for a custom entity, but it seems like Domain Access doesn't have its own entity to reference, and I'm not quite sure what method to use. I'm still looking into it, but since I couldn't find a question on it yet, I thought I'd post this ahead of time in case anyone else has done this.

# Answer
> 0 votes
You can override the access handler.

You have to add the handler path in the entity anotation and create an access class extending EntityAccessControlHandler. Inside you can manage the entity access using the rules that you want.

You can copy for learning the Node access Handler: https://api.drupal.org/api/drupal/core%21modules%21node%21src%21NodeAccessControlHandler.php/class/NodeAccessControlHandler/8.2.x

# Answer
> 0 votes
The module https://www.drupal.org/project/domain\_entity can be used, the only requirement is that your custom entity is fieldable.

---
Tags: 8, domain-access
---


# Question
Title: Code inside attached behavior not executed
I nested jQuery code inside a behavior. I don't understand, why the code does not execute. I would be appleased if you could give me a hint on what I probably did wrong.

**My code:**

```
$(function (){
    Drupal.behaviors.block_sidebar_register_buttons = {
        attach: function (context, settings) {
            var element = $('#block_register_buttons');
            //...
        }
    };
});

```

# Answer
> 3 votes
Drupal disables the `$` namespace for jQuery, to avoid potential conflicts with other libraries. Therefore the wrapping `$()` DOM-ready-function will neither be executed, nor can the `$('#something')` selector be used inside. Wrap your behavior with this instead:

```
(function ($, Drupal) {
  //inside the wrapper you can use the usual jQuery $ notation
  Drupal.behaviors.block_sidebar_register_buttons = {
    attach: function (context, settings) {
      var element = $('#block_register_buttons');
      //...
   }
  }
}(jQuery, Drupal));

```

---
Tags: javascript
---


# Question
Title: Showing fields from different bundles that are related
I'm trying to display the fields of one content type while searching on another content type. More specifically... here is my situation:

I have a view based on an index with fields in Organism and fields in mRNA.

Content type: Organism
Fields: order, common name, genus, species

Content type: mRNA
Fields: description, scientific name (Genus species)

I set up search filters for description, order, common name, scientific name. The result should look something like:
link to mRNA page
order | scientific name | common name
description

However, if I actually search by description, nothing shows up for order and common name. I feel like this is the result of an outer join of the two content types.

How would I "inner join" organism on scientific name? I've tried looking into EntityReference module but it seems like I would have to manually fill in the entity reference for every mRNA page I have... which isn't what I want.

Thanks

# Answer
I figured it out using the Views Field View module. It basically gives you the ability make a subquery inside a view using a subview.

First I created a new index on organism with an aggregated field called Scientific Name that combines Genus and species. Then I made a view on that index with a contextual filter with Scientific Name (display empty text when filter value not in url; specify validation criteria). Then I made the other view which uses the previously made view as a subview.

Well here's an intro tutorial for the module anyways: https://www.ostraining.com/blog/drupal/views-field-view/
> 0 votes

---
Tags: views
---


title: What does the term 'Bootstrap' mean?

text:
# Question
Title: What does the term 'Bootstrap' mean?
Referring to https://www.drupal.org/project/health\_check

I am confused as to what 'If Drupal fails to bootstrap' means.

What is term 'bootstrap' referring to? Does it make a database call? From what I have read bootstrap can mean from the Drupal core.

So if the healthcheck module fails is it because it cannot see the database, will the module render a 200 or some other response code?

# Answer
> 5 votes
In computing, "bootstrapping" refers to software getting to a state to where it can perform the task being requested.

In the context of Drupal, it means the code starts and does everything up to the point where it generates the page. It more-or-less includes

* connecting to the database
* reading configuration
* loading modules

The bootstrap process is pretty much the same for everything request; what happens when a page gets rendered and sent to the browser differs page-to-page.

So, when "Drupal fails to bootstrap", it means that it wasn't able to get to a point to figure out what to do, and is considered a Fatal Error. In my experience nine times out of ten when it happens in a production environment, it is because there was a problem connecting to the database.

---
Tags: bootstrapping
---


# Question
Title: How can you display the current user's name in the header region?
I created a new user. When they logs in, they should to see their user name in the header region.

I can create a block for header but I am not sure how to create a block that displays the username of the logged in user.

# Answer
Using `php filters` is not recommended.

Instead create a User view for it.

**Steps to creating a user view:**

1. Go to Admin -\> Structure -\> Views
2. Click on "Add new View"
3. Now simply create a User view.

4. Click on Continue and edit button.
5. Add a contextual filter for **uid**.

6. Click on apply button. And the filter value as "User Id from logged in user".

7. Click on Apply button.
8. In the field, add the name of the user as the field to display. If you want to show more things just add more fields to it.

9. Save the view and place the block in the header region.
> 3 votes

# Answer
I agree with @Nitesh, using php filters is not recommended, here is another aproach by creating a custom block by code named 'Display user name', it will work only for authenticated users, place block in propper region, make a custom module named 'hello\_user\_block', and place this code inside hello\_user\_block.module

```
<?php
/**
*implements hook_block_info
*/
function hello_user_block_block_info() {
  // This example comes from node.module.
  $blocks['user_name'] = array(
    'info' => t('Display user name'),
    //'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}

/**
*implements hook_block_view
*/
  function hello_user_block_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {

    case 'user_name':
      $block['subject'] = t('');
      //$block['type'] = 'markup';
      $block['content'] = user_name_function();
      break;
  }
  return $block;
}

/**
*implements function block content
*/
function user_name_function() {
  global $user;
  $output = '';
  if($user->uid!=0){
    $output = 'Hello '.$user->name;
  }

  return $output;
}

```

EDIT: this code makes 2 blocks, first block just output same as before: 'Hello user-name', second block output: 'Good monrnig user-name', or: 'Good afternoon user-name', or: 'Good evening user-name' depending on time of day, you can use either block.

```
    <?php
/**
*implements hook_block_info
*/
function hello_user_block_block_info() {
  // This example comes from node.module.
  $blocks['user_name'] = array(
    'info' => t('Display user name'),
    //'cache' => DRUPAL_NO_CACHE
  );

  $blocks['user_name_greetings'] = array(
    'info' => t('Display user name & greetings'),
    //'cache' => DRUPAL_NO_CACHE
  );

  return $blocks;
}

/**
*implements hook_block_view
*/
  function hello_user_block_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {

    case 'user_name':
      $block['subject'] = t('');
      //$block['type'] = 'markup';
      $block['content'] = user_name_function();
      break;

    case 'user_name_greetings':
      $block['subject'] = t('');
      //$block['type'] = 'markup';
      $block['content'] = user_name_greetings_function();
      break;
  }

  return $block;
}

/**
*implements function block content
*/

function user_name_function() {
  global $user;
  $output = '';
  if($user->uid!=0){
    $output = t('Hello ').$user->name;
    $output = "<div class='float-right'>$output</div>";
  }
  return $output;
}

function user_name_greetings_function() {
  global $user;
  $output = '';
  $day_term = '';
  if($user->uid!=0){

    $hour = date('H');

    if ($hour>11 && $hour<19) {
      $day_term = t('Good afternoon');
    }

    if ($hour>18 && $hour<=24) {
      $day_term = t('Good evening');
    }

    if ($hour>=0 && $hour<12) {
      $day_term = t('Good monrning)';
    }

    $output = $day_term.' '.$user->name;
    $output = "<div class='float-right'>$output</div>";
  }
  return $output;
}

```

it adds a class 'float-right', add this code in your custom css file.

```
.float-right {
 text-align: right;
 color:rgba(121, 121, 121, 1);
 font-size: 12px;
 font-style: italic;
 position: relative;
 top:-10px;
 }

```

placed in 'top bar' region it will otuput something like this, sorry, my img example is in spanish: Hola root, buenas tardes! --\> Hello root, good afternon!
> 2 votes

# Answer
The `user` object contains the current user properties. The following properties of the user object is available.

So in order to print the user name,enable the `PHP Filter` module, Add a block and then you need to select PHP as the text format for that block, as this picture shows

and then in the block body write

```
global $user;
print $user->name;

```

Now assign the block at any where you want
> 1 votes

---
Tags: 7, users
---


title: Overriding radio button rendering

text:
# Question
Title: Overriding radio button rendering
I have a List (text) field on a comment type. This field is required and only one option may be chosen, so a radio button is how it will be rendered. I would now like to change the way the radio buttons are rendered to allow for additional necessary styling. I have never done this before.

Currently each element is styled as such:

```
<div id="edit-field-list" class="form-radios"><div class="js-form-item form-item js-form-type-radio form-type-radio js-form-item-field-list form-item-field-list">
  <input data-drupal-selector="edit-field-list-1" type="radio" id="edit-field-list-1" name="field_list" value="1" class="form-radio">
  <label for="edit-field-list-1" class="option">Item #1</label>
</div>

```

But, let's say that I wanted to add an HTML element inside this `<div>` or move one around. I have created a module which adds a widget for this field type. Once this widget is selected, I have tried modifying the field using a number of different methods, but to no avail. I have been making sure to regularly clear the cache since I have been using the `.module` file and a template.

I've tried using a template file, `radios.html.twig` and adding it using various hooks, such as `hook_theme_registry_alter()` and `hook_theme()`. I've tried using `hook_form_alter()`.

I have never modified the rendering of an element like this before and the documentation all seems to be different enough from what I am trying to do so as to only add confusion.

Could anyone please tell me how to accomplish this? I'm happy to add clarification as needed.

Additionally, is using a Field Widget the best way to accomplish this? It seems the correct way to me, since I only want it to affect the input element on the comment creation/edit form, but I'm open to being wrong.

# Answer
> 0 votes
> Additionally, is using a Field Widget the best way to accomplish this?

I would say yes, it's more work than a hook, but it makes things configurable most times hidden in a form alter hook. The result is the same. You can add to the form array additional render elements like div containers or attributes to the input element itself. Based on this add a theme suggestion, in case you want to add more markup in a template. See this answer from @Kevin.

---
Tags: 8, theming
---


# Question
Title: How to implement a text field formatter that renders a URL as the image?
If a node has a text field with the url of an image as its value, how can I render this field as the image?

The image does exists it will be given the image url. I have to write that url into the text field.

Now using this url the value of this field should be an image when the node is viewed. But should be again editable textfield when editing the node.

And if in case the image doesn't exits a string can be shown "no image available".

# Answer
> 1 votes
You can follow the Drupal.org example on creating a custom Field Formatter. Inside the viewElements function, you can add an if statement to check if the remote file exist. If it does, assign the url to the markup. If not, assign some text:

```
viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
        $file = $item->value;
        $file_headers = @get_headers($file);
        if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
            $url = Url::fromUserInput($file);
            $markup = "<img src={$url->toUriString()} \>";
        }
        else {
            $markup= "File Not Found";
        }
      // Render each element as markup.
      $element[$delta] = ['#markup' => $markup];
    }

    return $element;
  }

```

Part of this answer is from stackoverflow.
I have not tested this, but it should be close.

# Answer
> 0 votes
Use a view to display this content type. Then set the view to display fields.

You can then add the text field and then add a template for this specific field.

You can technically override the output of the field and put the html there, but it's bad practice to put html into the database. So I would stick with doing it with a view template file. Then you can also put in an alt tag from the title field or wherever. The only issue is you won't have the image height/width which is best practice to include, you could use some fancy javascript to do this but it may not be worth the cost.

Drupal.org documentation on views template naming: https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views\_templates/8.2.x

---
Tags: 8, hooks
---


# Question
Title: Is there a field tpl for body and/or title fields?
I need to add some data- attributes and I am hoping to change it for the body and title fields on article content types. Do the title/body have tpl's that I can modify to add these? Or another method I could try? I've tried adding a field--body--article.tpl.php and it doesn't appear to work.

NOTE: This needs to be done in PHP as the search engine we're using needs it to be done server side.

# Answer
> 1 votes
Title does not use a template, but is rendered directly in page.tpl.php by default.

Display Suite can be used to override this behavior. Many examples available. Here's one for D8, but the principal is the same in D7: https://www.webwash.net/using-display-suite-drupal-8-how-to-use-display-suite-fields/

You may also find using preprocess hooks in template.php to be useful.

https://www.drupal.org/docs/7/theming/overriding-themable-output/setting-up-variables-for-use-in-a-template-preprocess-and

Proprocess hooks give you control over the entire render pipeline, so it's hard to give better guidance without knowing more specifics of your use case.

---
Tags: 7, theming
---


# Question
Title: How do I delete custom entity instances?
I've create a custom entity content with Drupal console,

```
 drupal generate:entity:content

```

Now I want delete (remove) it completely, how can I achieve it with drupal console or drush ?

my drupal version is **8.1.8** and my drupal console is 1.0 beta 5

**update** I have serveral Entity in my module and I want to only remove one Content type, uninstalling module cause all Entity Database table dropped.

I know I can looking for entity table in database remove it and all related file manually **I looking for a method with Drupal console or Drush**

# Answer
Drush 9+ supports deleting custom entities `drush entity:delete my_custom_entity`
> 11 votes

# Answer
1. You can use drush genc 0 —kill –types=article but you need to install devel\_generate.
2. You can also install Drush Delete All module available for drupal 8 module link
> 3 votes

# Answer
## Delete all *custom entities* of a type:

Using Drupal Console (best method):

```
drupal entity:delete custom_type --all

```

Download and install Drush Delete All module and do:

```
drush delete-all-entity custom_type

```

which is the same as `drush dae custom_type`

## Delete all *nodes* of a type:

**Option 1:** Using Drupal Console (best method):

```
drupal entity:delete node --all

```

**Option 1:** Download devel module and install devel\_generate submodule You can then use drush (as per @shreya's answer) or the UI:

```
drush genc 0 —kill –types=article

```

**Option 2:** Download and install Drush Delete All module and do:

```
drush delete-all article

```
> 2 votes

---
Tags: 8, entities
---