# Question
Title: How to pass a Date as Contextual Filter?
I have a custom content entity 'service' created with Drupal Console (drupal generate:entity:content). I added my own fields to the standard ones created by DC. Of which 'additiondate':

```
$fields['additiondate'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Addition Date'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))
  ->setReadOnly(TRUE);

```

Doing this way stores the date in YYYY-MM-DD string format.
I created an Embed View on this custom content entity to be used with `views_embed_view()`.
I'd like to use Contextual Filter on the field 'additiondate' in order to have all the services that have been added SINCE the date passed as parameter.
The only way to pass a parameter seems to be '2018-04-26' and the result is all the services that have been added ON this date, as you can see in the Preview of my View with the generated request displayed:  Any idea?

Here is the screen capture of my options when I add the contextual filter:

# Answer
> 0 votes
Finally, I made it work.
I used `mymodule_views_query_alter` replacing the operator of the proper condition:

```
  if ($view->id() == 'services' && $view->current_display == 'embed_2') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'service.additiondate') {
          $condition['operator'] ='>=';
        }
      }
    }
  }

```

---
Tags: views, 8
---


# Question
Title: how to pass param to js for custom page in drupal 8 ?
I want to pass variable to js for my custom page. Tried below code which is working fine with static value. But I m not able do same thing with existing variable of custom template.

```
    function test_theme($existing, $type, $theme, $path) {
        return [
            'test_template' => [
                'variables' => [
                    'nDetails' => null
                ],
            ],
        ];
    }

 function test_preprocess_page(&$variables) {
        print_r($variables['nDetails']); // its showing empty???
        $routeName = \Drupal::routeMatch()->getRouteName();
        if ($routeName == 'test.content') {
            $variables['#attached']['drupalSettings']['test']['data'] = $variables['nDetails'];
    $variables['#attached']['drupalSettings']['test']['dataa'] = "work fine";
        }
    }

class TestController extends ControllerBase {
    public function content() {
        return [
            '#theme' => 'test_template',
            '#nDetails' => "test1"
        ];
    }

```

Is something wrong with above code? Or there is another way to pass variable to drupal setting from controller itself?

# Answer
> 0 votes
You only see the variable in the preprocess hook of the custom template `hook_preprocess_test_template()`. But you don't need a preprocess hook at all, because you can attach the drupal settings in the controller directly:

```
return [
  '#theme' => 'test_template',
  '#attached' => [
    'drupalSettings' => [
      'test' => [
        'data' => 'test1',
      ],
    ],
  ],
];

```

---
Tags: 8
---


title: Custom order processor not being run

text:
# Question
Title: Custom order processor not being run
I have a custom order processor which currently just logs a debug message, so that I know that the order has been processed by it.

For whatever reason, my order processor is never run, I've checked against the docs, looked at how other commerce modules does it (commerce\_promotion and commerce\_tax), none of them show that I am doing anything wrong.

**custom\_commerce.services.yml**

```
services:
  custom_commerce.order_tax_processor:
    class: Drupal\custom_commerce\OrderTaxProcessor
    tads:
      - { name: commerce_order.order_processor, priority: 300 }

```

**OrderTaxProcessor.php class**

```
<?php

namespace Drupal\custom_commerce;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderProcessorInterface;

/**
 * Provides an order processor that adds tax to order if order has adjustments.
 * It does not affect order items.
 */
class OrderTaxProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {
    \Drupal::logger('Custom commerce')->debug('Order processed check');
  }
}

```

Can anyone see what I am doing wrong? Other order processors seem to be running fine, but mine seems to be ignored/not run.

Running Drupal 8.5.3 and Commerce 2.6.0

# Answer
So I found what caused my problem, a silly typo...

Basically, in my *custom\_commerce.services.yml* I had written `tads` instead of `tags`.

I fixed it and it's now running as it should.
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: Webform data tables name change d7 to d8 tables to delete records from
I have converted my d7 webforms to d8 with custom modules ... looks great Previously I pulled data down from the database daily and deleted records from the webform\_submissions and webform\_submitted\_data tables. (worked flawlessly for years) With d8 the names are webform\_submission and webform\_submission\_data. Does anyone know if deleting the records from these two tables affects any other tables? I intend to do as before... read daily, delete daily. Thank you

# Answer
I agree that you should use the 'Entity API' but if you are deleting 1000's of records I understand why you would want to do it using SQL.

Below are all the tables that are used to store webform submission related data.

* webform\_scheduled\_email
* webform\_submission
* webform\_submission\_data
* webform\_submission\_log
> 1 votes

---
Tags: webforms
---


# Question
Title: How do I set an entity base field as NOT NULL?
When creating custom entities in Drupal 8, you define a bunch of fields in `baseFieldDefinitions()` on your entity class, like this:

```
  <?php
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['postal_code'] = BaseFieldDefinition::create('integer')
      ->setLabel('PLZ')
      ->setDescription(t('Postal code.'))
      ->setSetting('unsigned', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'number',
      ])
      ->setRequired(TRUE);

    return $fields;
  }

```

However, these fields, despite being marked required, are defined as nullable in the database.

There’s no `->setNullable(FALSE)` or similar method on `BaseFieldDefinition`. So how else do you make Drupal generate the schema correctly?

# Answer
> 5 votes
There is no API for that at the moment, every field that is specified as a key happens to be set to not null, but that's IMHO actually a bug and I would not rely on that.

Instead, the only thing you can do is provide a storage schema handler and customize the schema there.

See \Drupal\node\NodeStorageSchema::getSharedTableFieldSchema() for example.

---
Tags: 8, entities, database
---


# Question
Title: Drupal 8 - Check if language prefix is present in url or not
Is there a way in the drupal 8 api to figure out if a language prefix is present in the url or not? Cause I need this information in order to display a custom language switcher if no prefix exists in the url. So for language detection I only have the prefix enabled.

Unfortunately this code is not working for me:

```
$languagecode = \Drupal::languageManager()->getCurrentLanguage()->getId();

```

Cause it always returns me a language. When no prefix is present in the url it returns me (as excepted) the fallback language.

Has someone a similar situation or can help me here?

# Answer
There might be something more elegant, but doing it the dirty way is pretty simple:

```
$languagecode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$parts = array_filter(explode('/', \Drupal::request()->getRequestUri()));

$has_prefix = count($parts) && $parts[0] == $languagecode;

```
> 2 votes

---
Tags: i18n-l10n
---


# Question
Title: How to render a region in custom module twig template
I have rendered regions in page.html.twig using `{{ page.region_name }}`. But it doesn't work for the custom modules template. How can I render a region in custom template?

# Answer
I'd recommend to install the Twig Tweak module: It provides (amongst others) an operator for that:
`{{ drupal_region('my_region_name') }}`
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Drush 7 bootstraps DB apparently without error, but still needs higher level
This is a Drupal 7 multi-site (subdirectory based with symlinks) I've migrated to a new server. (Perhaps worth mentioning Drush doesn't work on the old server either). The websites don't have any obvious problems.

Bootstrapping appears to reach level 5 without any error. Debian 9.4, PHP 5.6. I've checked the PHP.ini requirements and I've definitely got the mysql PDO driver.

I *originally* installed Drush 7.x via Ansible (geerlingguy.drush role). I've now switched to Drush 8, installed manually (downloading Drush.phar from GitHub):

drush status (domains redacted):

(Note - if I use `drush status --uri=example.com/subsite1` or `drush status --uri=example.com/subsite2`, then the 'Drupal Settings File' and 'Site path' lines, plus database name etc. are updated accordingly, so the right settings.php file is being read and there doesn't appear to be a problem switching between sites.)

```
 Drupal version         :  7.58
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  redacted
 Database name          :  umbrella
 PHP configuration      :  /etc/php/5.6/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.16
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /var/www/example/htdocs
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

```

Note for others: if Drush can't ever find the settings file, it'll display:

```
Drupal Settings File   :  MISSING

```

drush up --debug

```
Phar detected. Proceeding to drush_main().
Cache HIT cid: 8.1.16-commandfiles-0-dbfc5eac52981945177b460bd5c08987 [0.01 sec, 3.45 MB]                                                                                [debug]
Bootstrap to phase 0. [0.14 sec, 9.3 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [0.14 sec, 9.31 MB]                                                                                [bootstrap]
Drush bootstrap phase : bootstrap_drupal_root() [0.14 sec, 9.69 MB]                                                                                [bootstrap]
Initialized Drupal 7.58 root directory at /var/www/example/htdocs [0.14 sec, 9.69 MB]                                                                                [bootstrap]
Find command files for phase 1 (max=6) [0.15 sec, 7.3 MB]                                                                                [debug]
Cache HIT cid: 8.1.16-commandfiles-1-3f59809f319dc8415f75a4fe9a39c2e1 [0.15 sec, 7.3 MB]                                                                                [debug]
Cache HIT cid: 8.1.16-annotationfiles-1-f59a1308e828ee8afb57dc2e531b4a8b [0.15 sec, 7.3 MB]                                                                                [debug]
Drush bootstrap phase : bootstrap_drupal_site() [0.18 sec, 7.33 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [0.18 sec, 7.33 MB]                                                                                [bootstrap]
Find command files for phase 2 (max=6) [0.18 sec, 7.33 MB]                                                                                [debug]
Drush bootstrap phase : bootstrap_drupal_configuration() [0.18 sec, 7.33 MB]                                                                                [bootstrap]
Find command files for phase 3 (max=6) [0.19 sec, 7.36 MB]                                                                                [debug]
sql-query: SELECT 1; [0.19 sec, 7.48 MB]                                                                                [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_R3Phpd --database=umbrella --host=localhost --port=3306 --silent  < /tmp/drush_T5CkBa
  1
sql-query: SHOW TABLES; [0.2 sec, 7.48 MB]                                                                                [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_XA8Y3i --database=umbrella --host=localhost --port=3306 --silent  < /tmp/drush_lIZBeg
  actions
  apachesolr_environment
  apachesolr_environment_variable
  apachesolr_index_bundles
  apachesolr_index_entities
  apachesolr_index_entities_node

    [... long list of tables ...]

  webform_emails
  webform_last_download
  webform_localization
  webform_roles
  webform_submissions
  webform_submitted_data
  wysiwyg
  wysiwyg_user
Bootstrap to phase 1. [0.22 sec, 7.57 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [0.26 sec, 9.96 MB]                                                                                [bootstrap]
Bootstrap to phase 5. [0.26 sec, 9.96 MB]                                                                                [bootstrap]
Command pm-update needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. [0.26 sec, 9.97 MB]                                                                                [error]
The drush command 'up' could not be executed. [0.26 sec, 9.97 MB]

```

If it's apparently connecting to the DB OK, what else should I be checking?

(Thanks.)

# Answer
This is caused by using database prefixes to share user/permission tables between multiple sites (turns out Drush has never really supported that).

There are a number of stages in the database bootstrapping phase. Although `drush_valid_db_credentials()` succeeds (and hence you can use `drush sql-` commands without issue), `bootstrap_drupal_database_has_table()` subsequently fails, because it's trying to look for a table named like this - "database.table" among a list of tables without any database prefixes.

That list of tables shown in my debug output is actually as part of that test, and the phase fails immediately, it's just not visible in the debug info.

These bootstrap messages…

```
Bootstrap to phase 1. [0.22 sec, 7.57 MB]
Bootstrap to phase 6. [0.26 sec, 9.96 MB]
Bootstrap to phase 5. [0.26 sec, 9.96 MB]

```

…only refer to the **start** of the process - they're not telling you it was completed successfully. In fact what's happening is more like this (with extra debugging added):

```
Bootstrap to phase 1. [0.85 sec, 8.77 MB]
result for 0 = 1
result for 1 = 1
Bootstrap to phase 6. [0.92 sec, 11.11 MB]
result for 0 = 1
result for 1 = 1
result for 2 = 1
result for 3 = 1
fail for 4
Bootstrap to phase 5. [0.92 sec, 11.11 MB]
result for 0 = 1
result for 1 = 1
result for 2 = 1
result for 3 = 1
fail for 4

```

*result = 1 indicates success. Note each phase only actually runs once - the results are cached in a static array to speed things up.*

**Workaround**

With this I can still use Drush, and I don't need to modify the Drush source code, just add a conditional to each `settings.php`:

```
if (defined('DRUSH_VERSION')) {
    // Drush doesn't construct prefixes correctly, remove and use single DB
        // remember to call Drush with correct --uri= value!
    $db_prefixes = [];
} else {
    $db_prefixes = // whatever they usually are
}

$databases = [
...

unset($db_prefixes);

```

We use the Drush constant to detect if Drush is running or it's a webpage. Doing it this way, rather than, for example, checking for the presence of $\_SERVER variables, also ensures things work properly if Drupal code is executed from the command line in other ways without Drush.

You then call Drush and user `--uri` to specify the appropriate settings.php:

```
drush up --uri=www.example.com/
drush up --uri=www.example.com/subsite

```

It's important to remember to use the correct site when you want to edit anything to do with users or roles (i.e. to ensure you're editing the correct set of MySQL tables).

See also:
> 0 votes

# Answer
Looking at the output again, I notice that Drush reports that the site "default" is initialized. Could it be as simple as helping Drush to select the correct site using the URI option - ref http://docs.drush.org/en/8.x/usage/
> 0 votes

---
Tags: 7, drush
---


# Question
Title: install.php displayed instead of update.php
This looks similar to

Drupal 7 keeps returning to install.php and reports no settings.php but it's all there

but I only just registered so can't comment.

This is a single site (still drupal 7.59). free\_access is true, sites/defaults/settings.php is writeable by all (website on local machine to try to figure out solution.) Connection to mysql seems OK.

One clue: if I proceed to install, "Verify requirements" says things like:

> The Drupal installer requires that the ./sites/default/default.settings.php file not be modified in any way from the original download.

yet from within the nginx root directory:

```
# ls -l sites/default/default.settings.php
-rw-r--r--  1 root  users  26250 May  3 15:53 sites/default/default.settings.php

```

so where does drupal look? (I didn't find a mention of the root directory in the database...)

# Answer
The script useful for tracking this down was:

```
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
print_r(getcwd()); echo '<br>';
print_r(conf_path()); echo '<br>';
$settings_path = DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
echo "settings_path: $settings_path<br>";
$ret = realpath($settings_path);
echo "ret: $ret<br>";
?>

```

The clue was that $ret was empty. From the realpath documentation:

> Note: The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Changing

```
drwxr-x---  3 root  users  512 May 16 14:34 default

```

to have world executable permission worked around the problem.
> 0 votes

---
Tags: updating
---


# Question
Title: How do I stop a module from installing optional configuration, or make sure it's installed by the time I want to remove it myself?
I don't want the "Frontpage" view to be installed along with my installation profile.

I tried adding a `hook_install` to a module which does this:

```
\Drupal::entityTypeManager()->getStorage('view')
  ->load('frontpage')
  ->setStatus(FALSE)
  ->save();

```

But during installation that tells me that the frontpage view doesn't exist when my module is being installed. Fair enough, so I added the module that owns the frontpage view config (core node) to my dependencies:

```
dependencies:
  ...
  - drupal:node

```

Still didn't work. Then I realised it's optional config; maybe the module responsible for processing that config (core views) also needs to be a dependency. It would make sense, so my dependencies became:

```
dependencies:
  ...
  - drupal:node
  - drupal:views

```

Still didn't work, same problem - the View simply doesn't exist yet, so it can't be deleted.

So two halves of the same question:

1. How do I stop this config from ever having been installed in the first place (or installed but initially disabled)?
2. If that's not possible, what dependencies do I need to provide to ensure that the View in question is installed by the time my own `hook_install` is executed, so I can remove/disable it myself?

# Answer
> 1 votes
Hmm, have you tried in the .profile file an hook\_install\_tasks?

Or maybe with the hook\_install\_tasks\_alter.

```
/**
 * Implements hook_install_tasks_alter().
 */
function MODULE_install_tasks_alter(array &$tasks, array $install_state) {
  $tasks['install_finished']['function'] = 'CALLBACK_post_install';
}

```

And deactivate the view in the callback.

---
Tags: 8, installation, configuration
---


# Question
Title: Different front page for anonymous users
I am looking to create a custom front page for users that are visiting the site. This is a landing page in a way, which will encourage users to register and has different CSS. Once a user is logged in or registered then they can see the normal website. Trying to do this without any modules.

What I have done so far is change the .htaccess file so it loads the index.html first.

Like so:

DirectoryIndex index.html index.php index.htm

The problem with this method is that users who login in still see the index.html page if they click on any link that points to the Home page. Instead I would like them to see the index.php or the normal Drupal site.

If it possible to do this with preprocess page hook? What code should be used?

I am only trying to present a different front page to the visitor when they hit domain.com. All the other pages such as domain.com/about-us and others should display properly regardless of the user role. In other words, I am NOT trying to hide the whole site for visitors.

# Answer
If the pages are not too different, you could edit the page--front.html.twig and make it something like:

```
{% if not logged_in  %}
  // add your markup for non-registered users here
{% else %}
  {{ page.content }}
{% endif %}

```
> 1 votes

---
Tags: 8, theming
---


title: Performance is notoriously slow

text:
# Question
Title: Performance is notoriously slow
This feels like a repeat post but I can't find an actual answer. I just installed Drupal 8.4.4 on an Azure App Service (S3 Standard 4core 7GB RAM / PHP 7.0.6) and Azure Database for MySQL (Standard 100 computes / v5.6.26.0). I've been told the host isn't the issue.

Out of the box, the admin side is incredibly slow, like 4-5 seconds per click. I enabled page caching, and CSS/JS are aggregating. Dog slow. I worked through this and created my content types, added a couple of extensions, and enabled BigPipe (reported to help but didn't).

What am I missing? How do I improve performance before I ask my content authors to start loading up content?

Status report from Drupal. *(I have since fixed the reported trusted host settings error)*

Performance of the page in Chrome. Looks like 2.8s waiting on the page

I created a test.php file, and queried mysql directly, the key\_value table, and dumped all of that to the page, about 576 rows, and it returned instantly. Appears to be Drupal specifically?

Devel bar on public page 182 DB queries

Devel bar on admin page 233 DB queries

# Answer
It appears Azure's docker container services, which App Services leverages, is the cause of the problem.

Two big pains with Azure's app service (as explained by Azure support):

First, the docker containers are spread out across multiple drives, and PHP/Drupal's nature in using file caching causes it to run slower than it should.

Second, setting PHP settings to setup xdebug for instance, were lost when the service was restart. A "feature" in Azure, the container since it's a PHP image, everything outside of the home directory gets reset. This could be fixed by using an empty container, but then I'd probably still have the first issue.

My solution was to spin up a VM in Azure and manage it there. Runs MUCH faster, more reasonably now.

**THANK YOU ALL**
> 6 votes

# Answer
Odds are you have some code that is doing an external http request. If MySQL is fast, php isn’t that slow; leaves something like an http request. If you don’t know where to look, a cachegrind via xdebug is how to pinpoint the slow part.
> 2 votes

# Answer
One possibility is that Drupal caching will attempt to make use of APCu caching if it is available. Generally not a bad thing since it's fast. However, sometime the host system has this available but it is set to a very small memory size. This can cause problems.

You might try adding the following to your settings file to force Drupal to ignore this:

```
  $settings['cache']['default'] = 'cache.backend.database';

  # Force common chainedfast bin to use database.
    $settings['cache']['bins']['discovery'] = 'cache.backend.database';
    $settings['cache']['bins']['bootstrap'] = 'cache.backend.database';
    $settings['cache']['bins']['render'] = 'cache.backend.database';
    $settings['cache']['bins']['data'] = 'cache.backend.database';
    $settings['cache']['bins']['config'] = 'cache.backend.database';
    $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.database';

```

If you have memcache available, you can change the database part to memcache.

Another thought is to check your opcache size (in php setting via status report). It might be too small and your PhP code is having to be parsed into op codes to run. My servers are using 96MB for D8.

Finally, can you change your PhP version to 7.1? I know that 8.5 has some requirements for it and will not install via composer with 7.0.
> 2 votes

# Answer
There's some sort sub-optimal LAMP/Drupal configuration that's occurring here. As the case with most these types of problems, you run through the common checklist of Drupal slow stack performance problems (e.g. DB caching, app server caching, web server config, etc.) to see if you're hitting one of the common instances that can occur.

Past that, you need to deep dive into all performance profiling tools for your stack to find out where in the web/app/DB request pipeline the bottleneck is occuring. From comment groking (you last mention trying a fresh Drupal install), it sounds like this might be a new stack setup so you might want to consider a freshly provisioned stack & Drupal install on Azure following the practices recommended by MS so you can find a known-to-be-reliable setup on your hosting provider.

That's about the whole scope that you can address from the Drupal perspective since this is more a question about a host environment than it is about the CMS application itself.
> 2 votes

---
Tags: 8, performance
---


# Question
Title: Get select field value inside of a module
I have a taxonomy reference field `field_location_type` with terms: Term A, Term B.

Inside of my custom module, I'm setting up a presave function that will set a hidden field value depending on the term selected in `field_location_type`.

I'm trying to log the current value of the field just to confirm i'm getting the right one, but there are no values displaying, like ...

```
function general_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
    \Drupal::logger('general')->notice('here: ' . $entity->field_location_type->value);
}

```

How do i get the value of the select field `field_location_type`?

# Answer
> 1 votes
Update as @berdir suggested in the comments, the best way to get a field value is:

`$node->get('field_location_type')->target_id`

In addition, you could also use `Field::getValue` method if you want an array representation. Something like:

```
$entity->field_location_type->getValue()[0]['target_id']);

```

In addition if you need the term name (`Option A` ) from the id you can do this:

```
  $tid = $entity->get('field_location_type')->target_id;
  $term = \Drupal\taxonomy\Entity\Term::load($tid);
  // $name should have 'option A' or 'option b'
  $name = $term->getName();

```

Update: one way to figure out what methods are available to you is to use xdebug in PhpStorm. If you set a break point after `$field = $entity->field_location_type;` you can then type `$field->` and then hit ctrl and space the editor will provide suggestions based on the type of `$field` Here is a screen shot:

---
Tags: 8, theming, entities
---


# Question
Title: Where does the value $ds_content come from in display suite templates?
After updating to the newest version of display suite I noticed that in display suite ds-reset.tpl.php the value for $ds\_content is now blank.

```
<?php

/**
 * @file
 * Display Suite reset template.
 */
?>
<?php print $ds_content; ?>
<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

```

Where is this value assigned so I can better troubleshoot what the problem is.

# Answer
Looks like it's set in `ds/includes/ds.registry.inc` in `_ds_ds_layout_info()` which implements a hook `hook_ds_layout_info`
> 0 votes

---
Tags: 7, display-suite
---


# Question
Title: exporting a field from dev to production
My custom module creates a content type which has fields. I want to export config so that other developers/production can use it. I run

```
drush config-export --destination=/tmp/myconfig

```

from `/tmp/myconfig` I take the following files:

```
field.field.node.CONTENT_TYPE.FIELD_NAME.yml   #field instance
field.storage.node.FIELD_NAME.yml   #field storage
core.entity_form_display.node.CONTENT_TYPE.default.yml
core.entity_view_display.node.CONTENT_TYPE.default.yml

```

and copy these files to `modules/custom/mymodule/config/optional`

In the destination machine I run

```
drush config-import  --partial --source=modules/custom/mymodule/config/optional

```

The field instance gets imported (I can see it on the content type) but the storage does not, and no table is being created in the database.

Am I doing anything wrong? Uninstalling and re-installing the module doesn't help.

# Answer
At Drush Commands something similar is mentioned in the comment of Sebastian Contreras:

> --partial and --source "custom directory" are not working at all after upgrading Drupal 8.3 to Drupal 8.4 and Drush8 to Drush9. It does not detect the source with --source and it does not detect the --partial causing lots of removals where they should not happen.

However, did you already try the Configuration Split module? This module allows you to create different sets of configuration stored in multiple directories, and merge them back together when needed/indicated.

I'm using the Configuration Split module mostly to exclude configuration that is only needed in my development environment and not in production (modules such as Devel and Stage File Proxy). If I understand your use case correctly, this module should be able to perform the thing you want.
> 0 votes

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


# Question
Title: How to show a many-to-many relationship in drupal 7? Example: Teachers who guide a certain course
I would like someone to guide me regarding relationships.

I have a many-to-many relationship (Course, Teacher) and I need to show the teachers that guide a certain course. What module or way is recommended to do it? How can I show it in a view or block?

(I have been testing the Relation module but I still can not do it)

# Answer
> 0 votes
It is possible with the use of Entity Reference and View Relationships. I have created an Entity reference type field in my content type, managed to relate it to another type of content. Then, with the use of View Relationships and capturing the node id, I can show the types of content associated with a specific node.

# Answer
> -1 votes
You can use entity module for relationships

---
Tags: views, 8
---


title: List all revison users on a node

text:
# Question
Title: List all revison users on a node
I want to list all the users who have ever contributed to the revisions of a node.

# Answer
**Use The Views Module To Create A Custom Block**

If you're using the Views module you can create a view that will show you what you need.

Create a new view (admin/structure/views/add) and choose 'Content Revisions' as the view type.

Add the 'Node Revision: User' relationship so that you can access the username of the user that made each edit.

Add a 'Node ID' contextual filter to your new view.

When the filter value is not available you should provide a default value. Choose the Content ID from URL.

Add the field 'User: Name' but be sure to select the relationship you created earlier as in the graphic. You may also want to add a link to view the revision or see when the revision was created.

You can optionally sort by "Content revision: Updated date" desc to ensure the block is easy to follow.

The last step is to go to 'admin/build/block' and enable the new block for the appropriate content types.

Lastly, one of my favorite resources for views comes from NodeOne's insanely talented Johan Flak. If you're new to views check out http://nodeone.se/sv/node/20

Also, as @indrock said in his comment, you can also see the history of a node's revisions at `http://your-site-url/node/%nid/revisions` This is a much simpler solution and I wish I would have seen it before I went views crazy.
> 7 votes

# Answer
Try to use `Content revision: Nid` as a contextual filter instead.
> 0 votes

---
Tags: views, users, nodes
---


title: Page cache maximum age

text:
# Question
Title: Page cache maximum age
Please advise me on the correct value to choose for “Page cache maximum age” as a cachin strategy (I’m running a medium Drupal 8.5.3 website).

# Answer
> 3 votes
As others have said, there is no "correct value". But if you are really stuck; a fairly simple way to choose is to consider how often content on your site will change, and then divide that by 2.

So if you expect your content to update every 24 hours: `24 / 2 == 12` hours. So set your cache to 12 hours. If you aren't sure how often content will change, set it to a slightly lower value. Is performance is very important, or if your site will be getting a lot of traffic, set a higher value.

You may also want to look at non Drupal caching options such as Cloudflare, varnish cache & memcache. But that's a whole other thing.

---
Tags: caching
---


# Question
Title: Dynamically adjust argument or filter to views entity reference filter based on value from select list in form
I have a entity reference field that references a taxonomy term from a vocabulary named "fund". Now I'm needing to add a fiscal year field to the fund terms to allow us to have different budget lines for different fiscal years. Some of these funds will have the same name, but be from different fiscal years, so I now need to add a fiscal year dropdown list before the autocomplete entity reference field mentioned above.

Say the dropdown has two values FY17 and FY18, I'd like the views entity reference filter view to receive the selected value for fiscal year, and apply that as a filter to the views entity reference filter. How can I accomplish this? Alternatively is there a better way to accomplish this?

For example:

I looked at Dynamically change views entity reference filter based on current form value but it doesn't **seem** like it quite fits what I'm trying to do. I could be wrong.

# Answer
> 1 votes
The simplest answer ended up being to use Entity Reference View Widget which allowed me to build a view for selecting the entity desired. This was nice because it allowed me to add some additional information and filtering the the approach I was hoping for in my question didn't allow. Unfortunately, it also moves me further from being able to update this site to Drupal 8 because this module doesn't exist for Drupal 8 because the maintainer decided to let another module that isn't released yet, cover this functionality for Drupal 8. I would still welcome answers about how to do this in a more forward compatible way.

---
Tags: 7, views, entities
---


title: Restricting view of content to one role

text:
# Question
Title: Restricting view of content to one role
I know how to change edit and create permissions of a content type to one role.

But what i need is that a user that has the role 'consultant' is the only one that can see the content that was created of the type 'consultant info'.

I can only find a way to watch "own published content" but that isnt enough because their are multiple consult accounts that need to see each-others content.

Ive already looked at modules like content\_Access but they also don't provide this.

# Answer
> 1 votes
Sorry missunderstood your questtion, I think -\>

https://www.drupal.org/project/node\_view\_permissions

is what you are looking for.

---
Tags: 8, nodes, users
---


# Question
Title: How can I add static text into a Views exposed filter block?
I have a views exposed filter block that I'm using as a search form. I'm wondering how I can display static text within the block. Here's what my Block looks like:

Essentially I want to display the title (Find A Venue) to the left of the fields, and then display the word "or" between the two. If somebody knows how to move the block title to the left of the filter fields instead of above, I suppose that that would serve my purpose well enough as well. Although, it would be nice to know how to display the static text regardless.

# Answer
You can do this with Better Exposed Filters.

Enable the module and then navigate to your view edit page. Under **Exposed Form**, click **Basic**, which is next to *Exposed form style*, and change it to *Better Exposed Filters*. Add a **Description** of "or" to your title. This will place the text on the page; you will then need to style it with CSS to place it where you want.
> 2 votes

# Answer
Since an exposed filter is a form you could of course use hook\_form\_alter to tweak the form in any way you want.
> 2 votes

# Answer
I know this is a really old question, but here's what I did for Drupal 8. I hope it helps someone. (This is for a views page with the exposed filters exposed as a block).

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

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  switch ($form['#id']) {
    case 'my_views_exposed_form_id':

      $form['my_text'] = array(
        '#type' => 'item',
        '#markup' => t('This is some custom text'),
        '#weight' => 0, // experiment with negative / positive weights to see what works
        '#wrapper_attributes' => ['class' => ['my_class']],
      );
      break;
  }
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Change Password/Confirm_Password Password Tips
How does one go about changing the Password Tips for the password\_confirm form element?

This one specifically:

```
Recommendations to make your password stronger:
•Make it at least 12 characters
•Add lowercase letters
•Add uppercase letters
•Add numbers
•Add punctuation

```

Into something like:

```
Password should have:
• Minimum of 12 characters
• At least one lowercase letter
• At least one uppercase letter
• At least one number
• At least one special character
• No three consecutive same characters

```

I'm tried using the hook\_element\_info\_alter() hook that calls a method my\_module\_form\_process\_password\_confirm() and followed this template(https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user\_form\_process\_password\_confirm/8.5.x).

But it doesn't seem to be working.

```
/**
 * Implements hook_element_info_alter().
 */
function client_element_info_alter(array &$types) {
  if (isset($types['password_confirm'])) {
    $types['password_confirm']['#process'][] = 'client_form_process_password_confirm';
  }
}

function client_form_process_password_confirm($element){
  if (($key = array_search('user_form_process_password_confirm', $element['#process'])) !== false) {
    unset($element['#process'][$key]);
  }
  $element['#process'] = array_values($element['#process']);

  $password_settings = [
    'confirmTitle' => t('Passwords match DOES IT:'),
    'confirmSuccess' => t('yes'),
    'confirmFailure' => t('no'),
    'showStrengthIndicator' => FALSE,
  ];

  $password_settings['showStrengthIndicator'] = TRUE;
  $password_settings += [
    'strengthTitle' => t('Password strength:'),
    'hasWeaknesses' => t('Password should have:'),
    'tooShort' => t('Minimum of 12 characters'),
    'addLowerCase' => t('At least one lowercase letter'),
    'addUpperCase' => t('At least one uppercase letter'),
    'addNumbers' => t('At least one number'),
    'addPunctuation' => t('At least one special character'),
    'sameAsUsername' => t('Make it different from your username'),
    'weak' => t('Weak'),
    'fair' => t('Fair'),
    'good' => t('Good'),
    'strong' => t('Strong'),
    'username' => \Drupal::currentUser()->getUsername(),
  ];

  $element['#attached']['library'][] = 'user/drupal.user';
  $element['#attached']['drupalSettings']['password'] = $password_settings;

  return $element;
}

```

# Answer
> 4 votes
so I managed to tinker enough to get something to work and I'm sharing it in case other people need it or something. Of course, I dunno if this is optimal or follows standards or shouldn't even be done in the first place but please feel free to add your input. It's in the my\_module.module file, by the by. Oh and don't mind the text, was just kinda testing this out and all that jazz.

Without further ado, here's the code:

```
/**
 * Implements hook_form_alter().
 */
function <my_module>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === <my_custom_form_id>) {
    // Note that this isn't actually a hook
    $form['#after_build'][] = '<my_module>_confirm_password_after_build';
  }
}

function client_confirm_password_after_build($element) {
  $drupal_settings = $element['pass']['#attached']['drupalSettings']['password'];

  $drupal_settings = [
    'confirmTitle'          => t('Do the passwords match?'),
    'confirmSuccess'        => t('Yeah'),
    'confirmFailure'        => t('Nope'),
    'showStrengthIndicator' => TRUE,
    'hasWeaknesses'         => t('Password Suggestions:'),
    'tooShort'              => t('Make it at least 50 characters'),
    'addLowerCase'          => t('Add 7 lowercase letters'),
    'addUpperCase'          => t('Add 8 uppercase letters'),
    'addNumbers'            => t('Add 8 numbers'),
    'addPunctuation'        => t('Add 10 punctuations'),
    'sameAsUsername'        => t(''),
    'weak' => t('Forgettable'),
    'fair' => t('Meh'),
    'good' => t('Almost'),
    'strong' => t('You got it'),
    'username' => '',
  ];

  $element['pass']['#attached']['drupalSettings']['password'] = $drupal_settings;
  return $element;
}

```

# Answer
> 0 votes
You can use enter link description herepassword\_policy

If you wonder why your code isn't working then you should include the code in your question.

---
Tags: 8, forms
---


# Question
Title: Unable to fetch image after using Content Import and IMCE module
I am trying to import content for custom content type fields using csv, in content I have images fields as well and using the Content Import Module for CSV import and IMCE module for image upload. After import CSV all content showing but images not showing. The path for images also storing in **file\_managed** table I have set the permission of the folder still its now showing the images

Also place the image in the /sites/default/files/artist/hero Please help with this problem?

# Answer
Your folder path should be "`CONTENT-TYPE MACHINE NAME/images`" not artist/hero and set permissions to 777 as per Content Import Module. And also change `File directory` path under that field as "`CONTENT-TYPE MACHINE NAME/images`".
> 1 votes

---
Tags: views, theming, nodes, media
---


# Question
Title: default_content import error field content_translation_source is unknown
I've exported a custom block content using default content module, when trying to import, I'm getting error

```
[ERROR] Field content_translation_source is unknown.

```

I've all 4 language modules enabled.

# Answer
> 0 votes
Content translation module was enabled but content translation was not enabled for custom block. Enabling it fixed the error.

---
Tags: blocks, importing-exporting
---


title: hook for maintenance mode

text:
# Question
Title: hook for maintenance mode
I would like to send an email to some users, when i put my Drupal-7 website in maintenance mode. Are there any hooks that allow me to do this? I could not figure it out for myself.

# Answer
> 2 votes
As @Clive said you can use hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() and add extra submit handler to send email notifications.

```
function YOURMODULE_form_system_site_maintenance_mode_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'email_system_settings_form_submit';
}

function email_system_settings_form_submit($form, &$form_state) {
  // Add your email code here
}

```

---
Tags: 7, maintenance-mode
---


# Question
Title: D8 - Cannot make Custom EntityType translatable
When I am trying to make a custom entity translatable I get the following error message:

```
The Redirect entity entity type cannot be translatable as it does not define a translatable "langcode" field. in <em class="placeholder">Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions

```

After checking other modules and the drupal docs I have to define 2 things:

1.) I need to create a translatable "langcode" field 2.) I need to set the entityType annotation to translatable

Still I receive this error.

My annotation of the entityType:

```
@ContentEntityType(
 *   id = "email_confirm_redirect",
 *   label = @Translation("Redirect entity"),
 *   admin_permission = "administer email confirm redirect entity",
 *   base_table = "email_confirm_redirect",
 *   revision_table = "email_confirm_redirect_revision",
 *   data_table = "email_confirm_redirect_field_data",
 *   translatable = TRUE,
 *   handlers = {
 *     "list_builder" = "Drupal\email_confirm_redirect\Entity\Controller\RedirectListBuilder",
 *     "form" = {
 *       "add" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "edit" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "delete" = "Drupal\email_confirm_redirect\Form\RedirectDeleteForm",
 *     },
 *     "access" = "Drupal\email_confirm_redirect\RedirectAccessControlHandler",
 *   },
 *   list_cache_contexts = { "user" },
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "title",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "edit-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/edit",
 *     "delete-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/delete",
 *     "collection" = "/admin/structure/email_confirm_redirect/list"
 *   },
 * )

```

The field declaration in my baseFieldDefinition() function:

```
//langcode
        $fields['langcode'] = BaseFieldDefinition::create('language')
            ->setLabel(t('Language'))
            ->setTranslatable(true)
            ->setDescription(t('The redirect language code.'))
            ->setDisplayOptions('form', array(
                'type' => 'language_select',
                'weight' => 2,
            ));

```

# Answer
> 4 votes
I think you also need to add it to the entity keys:

```
entity_keys = {
  "id" = "id",
  "label" = "title",
  "uuid" = "uuid",
  "langcode" = "langcode"
}

```

Also make sure you're running `drush entity-updates` and clearing cache when making changes to base fields/annotations.

---
Tags: entities
---


title: Error when translatable

text:
# Question
Title: Error when translatable
When I save my Custom Entity Type I get an error. I tried several different things. The code looks valid to me.

> Error: Cannot unset string offsets in Drupal\Core\Field\WidgetBase-\>extractFormValues() (line 367 of core/lib/Drupal/Core/Field/WidgetBase.php).

This is my annotation.

```
/**
 * @ContentEntityType(
 *   id = "email_confirm_redirect",
 *   label = @Translation("Redirect entity"),
 *   admin_permission = "administer email confirm redirect entity",
 *   base_table = "email_confirm_redirect",
 *   translatable = TRUE,
 *   handlers = {
 *     "list_builder" = "Drupal\email_confirm_redirect\Entity\Controller\RedirectListBuilder",
 *     "form" = {
 *       "add" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "edit" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "delete" = "Drupal\email_confirm_redirect\Form\RedirectDeleteForm",
 *     },
 *     "access" = "Drupal\email_confirm_redirect\RedirectAccessControlHandler",
 *   },
 *   list_cache_contexts = { "user" },
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "title",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode",
 *     "admin_name" = "admin_name",
 *   },
 *   links = {
 *     "edit-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/edit",
 *     "delete-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/delete",
 *     "collection" = "/admin/structure/email_confirm_redirect/list"
 *   },
 * )
 */

```

This is the code I am using.

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  // Standard field, used as unique if primary index.
  $fields['id'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('ID'))
    ->setDescription(t('The ID of the redirect entity.'))
    ->setReadOnly(TRUE);

  // Standard field, unique outside of the scope of the current project.
  $fields['uuid'] = BaseFieldDefinition::create('uuid')
    ->setLabel(t('UUID'))
    ->setDescription(t('The UUID of the redirect entity.'))
    ->setReadOnly(TRUE);

  $fields['langcode'] = BaseFieldDefinition::create('language')
    ->setLabel(t('Language'))
    ->setTranslatable(true)
    ->setDescription(t('The redirect language code.'))
    ->setDisplayOptions('form', array('type' => 'language_select', 'weight' => 2));

  $fields['admin_name'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Administrative Name'))
    ->setDescription(t('The name for the redirect (shown just in admin)'))
    ->setRequired(TRUE)
    ->setSettings(['max_length' => 255, 'text_processing' => 0])
    ->setDefaultValue(NULL)
    ->setDisplayOptions('form', ['type' => 'string_textfield', 'weight' => -5])
    ->setDisplayConfigurable('form', FALSE)
    ->setDisplayConfigurable('view', FALSE);
}

```

I also don't see the language selector on the edit/add form.

# Answer
> 0 votes
I had to set the fieldWidget to hidden.

```
 //langcode
        $fields['langcode'] = BaseFieldDefinition::create('language')
            ->setLabel(t('Language'))
            ->setTranslatable(true)
            ->setDescription(t('The redirect language code.'))
            ->setDisplayOptions('form', array(
                'type' => 'language_select',
                'weight' => 2,
            ));

```

Also I used Drupal's language configuration settings to enable the multilanguage feature for the entity.

The only missing bit is the language translation interface that you can use with nodes.

---
Tags: entities
---


# Question
Title: Is it fine to use hook_entity_view_mode_alter() to intercept an entity view to change the view mode based on an attached field value?
Basically I want to let the content creator choose an arbitrary view mode. For example, be able to choose a gallery that is a FlexSlider slideshow, a Masonry jQuery plugin type image gallery, or an image gallery that displays metadata below each image.

On the entity there would be a field called field\_view\_mode which is an options list. The options are flex slider, masonry, and full images with text. Depending on the option they get the images and other fields formatted differently in different templates.

I'm thinking about defining 5 different arbitrary view modes. One more view mode would be custom\_view\_mode.

```
function hook_entity_view_mode_alter(&$view_mode, $context) {
  // For nodes, change the view mode when it is teaser.
  if ($context['entity_type'] == 'node' && $view_mode == 'custom_view_mode') {
    $view_mode = 'use entity metadata wrapper to pull field_view_mode value here';
  }
}

```

I don't want to use the Template Field module because it seems like overkill. I'm not sure if the Display Suite module does this but that seems like overkill too. I just want different view modes to be available. Has anyone done this before?

# Answer
I know it's been a while since you asked...

As far as I can say, if you want use your own module, and not a contributed one, you have to define the view modes using hook\_entity\_info\_alter, for example:

```
function mycustommodule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['mycustommode'] = array(
  'label' => t('My custom view mode'),
  'custom settings' => FALSE, //Or true if you want to allow a certain role to modify it
  );
}

```

After that, you can use the hook\_entity\_view\_mode\_alter from your custom module (not working if you are trying to use in from your template.php in your theme). Hope that helps to anyone coming here from search as I did.
> 2 votes

---
Tags: theming, entities
---


title: Default 404 page not working

text:
# Question
Title: Default 404 page not working
In a Drupal `8.5.3` installation I have set up the following configuration:

* I created a basic page, its node path is `/node/42`.
* Under *Administration » Configuration » System » Basic site settings* (`/admin/config/system/site-information`) I have set the **Default 404 (not found) page** to `/node/42`.

Now I expect a non-sensical URL to show the contents of `/node/42` for the 404 page. However, I still only get the generic 404 page.

The theme we are using does not have a custom 404 template or anything like that. What other reasons could there be, that the default 404 page is not the one set in the config?

# Answer
> 0 votes
It was due to the multi-domain setup. I did not realize that you can/have to assign a different 404 page for each domain.

---
Tags: 8
---


title: How to render a link as a button

text:
# Question
Title: How to render a link as a button
I am using Drupal 7 and I would like to render a link (anchor tag) the same as a submit button. Does Drupal 7 allow for this (say by using the button type) or do I have to use CSS to accomplish this?

# Answer
> 2 votes
You need to, and should, use CSS to style this.

```
.buttonize {
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
  padding: .5em;
  /* whatever other styles you want */
}

```

I added a jsfiddle.

You can look this up, but I'll note that `appearance` is different on OS's

# Answer
> 0 votes
If you are using bootstrap, add 'btn' class to anchor tag. So simple!

# Answer
> 0 votes
If you are using a Drupal default theme, you can try these classes:

**Add button**

button button-action button--primary button--small

**Save button**

button button--primary js-form-submit form-submit

**Form submit button**

button js-form-submit form-submit

You can use an element inspector on other admin pages to see what button classes can work for you, but these cover the most common cases for Bartik and Seven in D8. For Bootstrap, go with Sujith's answer about the btn classes. Here are the relevant links:

https://getbootstrap.com/docs/3.3/css/#buttons

https://getbootstrap.com/docs/4.1/components/buttons/

---
Tags: 7, forms, navigation
---


# Question
Title: Vendor directory vs. Modules directory. What are the key differences?
I've seen articles that instruct developers to add docroot/vendor to the .gitignore but if I require a module with composer and push up that module, will that cause a huge error on the site I'm pushing up to?

Does my composer.json file have to include all of the modules in my modules directory?

If I were to copy and paste the composer.json file into another install and run `composer install` would that automatically give me all of the dependencies I need?

As you can tell, I'm pretty new to Drupal 8. The team I work with uses Acquia and I'm finding a ton of issues when trying come up with a good workflow using compser, drush, git, and config management.

Thanks

# Answer
> 1 votes
\[Assuming you are using composer in this answer\]

The vendor directory contains non-Drupal dependencies that core and/or contributes modules require. This is typically fully managed by composer.

The modules directory contains your Drupal modules. It can be managed by composer if you are using drupal-composer/drupal-project or something similar where the install paths can be set.

Committing composer managed dependencies or now, like vendor or modules (if you are doing so), is a nuanced subject. There is no 100% correct answer.

I tend to not commit, even when I am not using a full CI deployment, because the composer dev dependencies should not be deployed on a production server. So, on the live server I want do do a `composer install --no-dev`.

---
Tags: drush, composer
---


# Question
Title: How to convert the drupal-entity tag into an img tag?
I have a content type with a text field that uses CKEditor, in the editor is possible to add a media entity image, once the image is inserted inside the text the html tag for it is:

```
<p>Document</p>\r\n\r\n<drupal-entity alt=\"Luz\" data-embed-button=\"media_browser\" data-entity-embed-display=\"media_image\" data-entity-embed-display-settings=\"{"image_style":"","image_link":""}\" data-entity-type=\"media\" data-entity-uuid=\"4076130e-9ccb-43f1-a4d9-dc8176271ffa\" title=\"Luz\"></drupal-entity>\r\n

```

I have in the site a webservice that need to provide the text field with all the information, but I need to convert the drupal-entity tag into an img tag to provide a tag that can be used from the applications that use the webservice.

I made a search inside the CKEditor configurations and in the media module but I can't find any related to this, how can I convert the drupal-entity tag into an img tag?

# Answer
> 1 votes
Basically you'll want to get the field's value and do a str\_replace(), but where?

I haven't done this myself yet, but I believe you'll have to create a normalizer.

Serialization API overview (good read).

I think you can achieve it by doing the following Changing the way Serializer handles entities.

There is more indepth info here Using Normalizers to Alter REST JSON Structure in Drupal 8.

---
Tags: media, wysiwyg, 8
---


title: Drupal Bootstrap - Regions Placement

text:
# Question
Title: Drupal Bootstrap - Regions Placement
I'm making my first attempt at creating my own Sub-Theme of the Bootstrap theme. I've got the theme installed, the sub-theme created and working, I've added some new regions and populated them. The situation I'm encountering is, the regions just display one under the other, where I want (at least certain ones) to display side by side. I've added "float: left;" code, but that doesn't seem to make any difference. I'm guessing that I need to "float" the region, rather than the block inside of it. However, I'm not sure how to do that. I've searched Google, I've searched YouTube, I've searched Drupal.ORG, I've searched the Drupal Bootstrap site documentation, and I'm not finding anything. Someone on Drupal.ORG told me that such modifications could be made via CSS, however, I've searched the bootstrap-theme.min.css file, and I find no mention of *any* of the regions. I would appreciate some pointers on how to do this correctly.

I'm using Drupal 8.5.3 and Bootstrap theme version 8.x-3.11

# Answer
> 0 votes
With Bootstrap you can have two regions side by side wrapping them with a row and adding a col-size-number class to them, like this:

```
<div class="row">
  <div class="region region-name-left col-md-6">
    ...
  </div>
  <div class="region region-name-right col-md-6">
    ...
  </div>
</div>

```

You have to do that in the page.html.twig file.

---
Tags: theming
---


# Question
Title: What causes EntityMetadataWrapperException: Unknown data property?
I have added new field to my bundle in one of entity type. I used the Group audience as field type and Group Audience as widget type. This is to make the field to select multiple records.

While adding the new record with all the values it gives following error:

> EntityMetadataWrapperException: Unknown data property og\_membership. in EntityStructureWrapper-\>getPropertyInfo() (line 354 of /var/www/vhosts/test1.3blmedia.com/httpdocs/sites/all/modules/entity/includes/entity.wrapper.inc).

I am not getting where it is wrong. Any hints?

# Answer
> 2 votes
Please login to admin and go to following page. You need to add field for your bundle. It will resolve above error.

Home » Administration » Configuration » Group Organic groups field settings

For more details please visit following link. https://www.drupal.org/node/2023721

# Answer
> 0 votes
If it is a custom field that you have defined in your module (using `hook_field_info()`) then you need to add a `property_type` to your field info. See https://www.drupal.org/docs/7/api/entity-api/property-info-for-fields for an example and https://www.drupal.org/node/905580 for a full list of possible types.

If your field is a complex (multiple value) data structure you may also additionally need to include `property_callbacks` as well. See http://d7.thecarneyeffect.co.uk/describe-field-properties-make-custom-fields-work-entity-metadata-wrappers for a good example of this.

---
Tags: 7, organic-groups, entities
---


# Question
Title: Why am I getting the error "Unknown data property" when the field exists?
I am trying to grab all of the fields of a node (which I am doing by using array\_keys). At this point, I want to feed them all to `entity_metadata_wrapper()`, and grab their values.

I will then, if they are strings, print them to a PDF document using TCPDF's `Text()` function.

Everything looks like it will work correctly; however, certain fields give an error as such:

> EntityMetadataWrapperException: Unknown data property field\_grade. in EntityStructureWrapper-\>getPropertyInfo()

The field exists in my node, though.

```
'field_grade' =>
    array (size=13)
      'default_value' => null
      'description' => string '' (length=0)
      'display' =>
        array (size=4)

```

This is the code I am using.

```
$wrapper = entity_metadata_wrapper('node', $node);
$trip_fields = field_info_instances('node', 'trip');
$trip_fieldskeys = array_keys($trip_fields);
$margintop = 0;

foreach($trip_fieldskeys as $item) {
  $value = $wrapper->$item->value();
  if (gettype($value) == "string") {
    $pdf->Text(0, $margintop, $value, false, false, true, 0, 0,
       '', false, '', 0, false, 'T', 'M', false);
    $margintop = $margintop + 25;
  }
}

```

# Answer
If it is a custom field that you have defined in your module (using `hook_field_info()`) then you need to add a `property_type` to your field info. See https://www.drupal.org/docs/7/api/entity-api/property-info-for-fields for an example and https://www.drupal.org/node/905580 for a full list of possible types.

If your field is a complex (multiple value) data structure you may also additionally need to include `property_callbacks` as well. See http://d7.thecarneyeffect.co.uk/describe-field-properties-make-custom-fields-work-entity-metadata-wrappers for a good example of this.
> 3 votes

# Answer
PHP fatal errors when calling `$wrapper->field_foo->value()` on an empty $wrapper. You need check that node have this field before call `$wrapper->field_foo->value()`. That Exception handling, be careful with `EntityMetadataWrapper`. And you can try with:

```
$wrapper = entity_metadata_wrapper('node', $node);// you need sure with varibale $node
foreach ($wrapper->getPropertyInfo() as $key => $val) {
    $value = $wrapper->$key->value();
    if (gettype($value) == "string") {
   $pdf->Text(0, $margintop, $value, false, false, true, 0, 0,
       '', false, '', 0, false, 'T', 'M', false);
   $margintop = $margintop + 25;
   }
  }

```
> 1 votes

# Answer
I have used FPDI Library for PDF Creation for Particular Content Type Node

```
    /* PDf Creationg Start */
    $pdf=new PDF_HTML_Table();
    $pdf->AddPage('L');
    $pdf->SetXY(10.0,5.0);
    $pdf->SetDisplayMode('fullwidth');
    $pdf->SetLeftMargin(4.0);
    $pdf->SetTitle('Your Title',false);
    $pdf->SetFont('Arial','',7);
    $pdf->SetFontSize(12);
    $title_page = 'Dated : '.date('jS F Y');
    $pdf->Text(10,28,$title_page);
    $pdf->SetFontSize(7);
    $header=array('your_field_no1','your_field_no2','your_field_no_n..');
    $rows = array();

  /* Get Node Content */
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'your_content_type_name')
  ->propertyCondition('status', 1, '=')
  ->propertyOrderBy('created','DESC')
  ->fieldCondition('field_name', 'value', $_GET['mname'],'=');
  $results = $query->execute();

    if (isset($results['node'])) {
      $nodes = node_load_multiple(array_keys($results['node']));
       $counter = 0;
      foreach($nodes as $row) {
          $data = array();
        if(sizeof($row->your_field_no1) > 0)
            {
                $your_data_array[] = $row->your_field_no1['und'][0]['value'];
            }

       if(sizeof($row->your_field_no2) > 0)
            {
                $your_data_array[] = $row->your_field_no2['und'][0]['value'];
            }
         // and so on..
         $rows[] = $data;
      }

    }
   $pdf->Ln(35);
        $pdf->SetFont('Arial','',9);
        $pdf->SetWidths(array(40,40,40,40,40,40,50));
        $pdf->SetAligns('C');
        $pdf->FilterRow($data_header);
        $pdf->SetWidths(array(40,40,40,40,40,40,50));
        $pdf->FilterRow($data);
   $filename = "your_desired_name_plus_".date('jS-F-Y-h-i-s').'.pdf';
   $pdf->Output($filename,"D");

```

and it's working on my site... hope this helps
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Check if the current user has permission to edit current node
I'm using Nodeaccess module to add permissions on specific nodes. in my `.theme` file I want to Check if the current user has permission to edit the current node.

# Answer
> 11 votes
I've found it and working great.

```
  $node = \Drupal\node\Entity\Node::load(NID);
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $check = $node->access('update', $user);

```

---
Tags: 8, nodes, users
---


# Question
Title: Set value for new field automatically based on another field
I want to add a new date field to an existing content type, and set the new field automatically for existing nodes to be equal to another date field from that content type.

For example, if the new field is called 'Event date', and there is an existing field 'Publication Date', I want the 'Event date' field to contain the date from the 'Publication date' field for all existing nodes, without assigning each one manually.

Is this possible?

# Answer
> 0 votes
It is possible and the best way to do it is in a custom module. Here's how:

* Assume you have a module called mymodule.
* Inside mymodule.install create a function called mymodule\_update\_N where N is a number starting at 7100. See the API documentation for hook\_update\_N for details but this is what runs when you run update.php
* Inside your mymodule\_update\_7100, load the nodes you want to act on and then iterate over them, setting your newly created field to the value from Event Date.

If you have a lot of nodes, you'll want to look to the Batch API system to batch the nodes one by one so you don't run out of PHP memory or run up against the timeout. If it's not a ton of nodes, you don't need to worry about that usually.

And last, but not least, you should use an EntityFieldQuery to get the nodes you want to act on.

Hope that helps. Good luck!

# Answer
> 0 votes
I have done this with Rules.

1. Set up a rule that fires before the content type is saved
2. Have the rule set the value of the new field to the value of the existing field.
3. Then, install Admin Views and Views Bulk Operations
4. Filter the content list to show just that content type
5. Select them all
6. Choose Save Content from the Bulk Operations dropdown and follow the steps from there.
7. Check that the field has populated correctly. If not, check your rule.

If the Save Content option is not available, you can edit the Bulk Operations field in the Content view to enable it.

---
Tags: 7, entities, nodes
---


title: How to change this to D8

text:
# Question
Title: How to change this to D8
How to change this to Drupal 8 and attach css file to it.

```
$output = theme_table(array('header' => $header, 'rows' => $rows, 'attributes' => array('width' => '100%', 'id' => 'stockapi-table'), 'sticky' => TRUE, 'caption' => t('All available stock quotes.'), 'colgroups' => array(), 'empty' => t('No stock quotes available.'))) . theme("pager");

```

# Answer
This requires two steps:

The first is a render array that contains three elements. The first will be the table, the second the pager, and the third an attached library.

```
$output = [
  'table' => [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No stock quotes available.')
  ],
  'pager' => [
    '#type' => 'pager',
  ],
  '#attached' => [
    'library' => 'mymodule/mylibrary',
  ],
];

```

Next, you need to create the library that was attached in the render array.

### mymodule.libraries.yml

```
mylibrary:
  css:
    theme:
      css/path_to_my_file.css: {}

```
> 2 votes

---
Tags: 8
---


title: Two sites on the same server don't work

text:
# Question
Title: Two sites on the same server don't work
I have a Drupal 8 site installed in a root directory(/var/www/html). I then installed another Drupal 8 site in another folder(/var/www/html/myFolder).

The homepage is working fine. If I try to log in, the first Drupal 8 server returns a 404 error.

Is there is any way to solve this issue?

# Answer
Check both site's `.htaccess` files and find the lines where it says `RewriteBase` etc.

Your first site's `.htaccess` needs:

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

```

And your seconds site's `.htaccess` needs:

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /myFolder

```

---

Apart from that your vhost file should have the following directives included.

```
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com *.example.com

    ServerAdmin webmaster@example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        Options -Indexes
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog /var/log/apache2/example_com_error.log
    LogLevel warn
    CustomLog /var/log/apache2/example_com_access.log combined
</VirtualHost>

```
> 3 votes

# Answer
As said previously, check your HTACCESS on both sites, and your apache virtual host. In theory, you can imbricate websites... But it's not recommended and not easily maintainable.

But the simpler and far more recommended way will be to reorganise your sites/folders : If you want to keep 2 Drupal separately :

* /var/www/html/SiteNAME1
* /var/www/html/SiteNAME2

If you are interested in multi site architecture, please check https://www.drupal.org/docs/8/multisite
> 2 votes

# Answer
First of all: You might want to **check the logs**: both **sites logs + server logs + db logs**. There got to be some **error code** somewhere.

Here's a list of things you can try:

* Use **different admin users** for both sites
* Check the **redirect rules** in your htaccess. Especially the www redirect, maybe there is something wrong in your declaration that can confuse the redirection
* Make sure the 2 sites have clearly **2 differents domain declaration** in your vhost, and that both declarations are **pointing to the right folder**
* Make sure your directory declaration for each site contains the **full path** (`<Directory /var/www/html/site1>`), here is an example:
`<Directory /var/www/html/site1>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>`
* Make also sure you have nicely declared your **bind zone** (zone declaration in named.conf.local and creation of your db.domain.com). If one of them is a subdomain, hopefully you should have made a subdomain declaration in the main domain.
* And check again your **settings**, especially the base\_url and trusted host patterns, that can help too.

For each drupal change, clear the caches of the site that was edited, and eventually the second just for peace of mind. For every change made on the web server configuration (vhost), restart it (apache2/nginx). For each change in your bind zone, restart the bind service, and the webserver for peace of mind.

As you can see there might be quite a few sources to your issue. You may want to make more comparing tests of use cases what happens to one site if I trigger this in the second **and vice versa**. Hope this can help.
> 2 votes

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


# Question
Title: Use image from taxonomy term as exposed filter option
I created a view which has an exposed filter for taxonomy terms. Now the next step is to theme the options. I tried the module "Better exposed Filters" but I wasn't satisfied. I would like to have images to click on instead the standard filter. I already have stored the images in the taxonomy fields, so every term has it own image.

I tried to create a template file for the filter, but I don't have any access to the fields, where the image is stored. I could do some hardcoded stuff, but I want it as generic as possible.

Has anyone an idea how to achieve it?

# Answer
Use "Better exposed Filters" and choose its Display setting as Checkbox
Now you have to do form alter like this

```
function THEMENAME_form_views_exposed_form_alter(&$form, &$form_state) {
  foreach ($form['TAXONOMY_ELEMENT']['#options'] as $tid => &$name) {
      $term = taxonomy_term_load($tid);
      $name = '<img src="' . file_create_url($term->IMAGE_FIELD_NAME['und'][0]['uri']) . '" />';
  }
}

```

In my case ::
TAXONOMY\_ELEMENT = field\_type\_tid
IMAGE\_FIELD\_NAME = field\_term\_image
> 1 votes

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


title: Drupal 8 reset session each request

text:
# Question
Title: Drupal 8 reset session each request
I have create a EventSubscriber like this:

```
<?php

namespace Drupal\custom_session\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class SessionInitial.
 */
class SessionInitial implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['setSession'];

    return $events;
  }

  /**
   * This method is called whenever the kernel.request event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function setSession(Event $event) {
    // Start request.
    kint($_SESSION['page']);
    $route_name = \Drupal::routeMatch()->getRouteName();
    if ($route_name == 'view.frontpage.page_1') {
      $_SESSION['page'] = 'Home page';
    }
    else {
      $_SESSION['page'] = 'Other page';
    }
    // End logic.
    kint($_SESSION['page']);
  }

}

```

Every request I'll check prev **$\_SESSION\['page'\]** and process logic.

But each request **$\_SESSION\['page'\]** all has same value **Other page**.

Test step by step:

**1, Go to home page (router name is \**view.frontpage.page\_1**)\**

**2. Refesh browser with url home page but debug result is the same:**

Also last request was set **$\_SESSION\['page'\]** to **Home Page**. I don't know why. Someone can help me. Thanks!

# Answer
> 1 votes
With @4k4's suggestion, I found the problem. After each request has a ajax request. The request has route name is quickedit.attachments and method post. So I edited code like that:

```
public function setSession(Event $event) {
    $route_name = \Drupal::routeMatch()->getRouteName();
    if (!$event->getRequest()->isXmlHttpRequest()) {
      if ($route_name == 'view.frontpage.page_1') {
        $_SESSION['page'] = 'Home page';
      }
      else {
        $_SESSION['page'] = 'Other page';
      }
    }
  }

```

Now it's working good. Thanks!

---
Tags: 8, sessions
---


title: Address Module 8.x-1.3

text:
# Question
Title: Address Module 8.x-1.3
I am trying to run address field on my web page, but I get an error

> The website encountered an unexpected error. Please try again later.

So I checked the logs and get

> Error: Class 'CommerceGuys\Addressing\LocaleHelper' not found in Drupal\address\Plugin\Field\FieldFormatter\AddressDefaultFormatter-\>getValues() (line 286 of /var/www/mywebsite/modules/contrib/address/src/Plugin/Field/FieldFormatter/AddressDefaultFormatter.php)

I checked my composer.json file and have the following required

```
 "drupal/address": "~1.0",
 "commerceguys/addressing": "1.x-dev",

```

ran

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

```

from https://www.drupal.org/project/address but still getting the same error, I believe the error is commerceguys/addressing, but composer update says there is nothing to be updated. Any directions to my problem will help a lot, thanks.

# Answer
I have deleted

```
"commerceguys/addressing": "1.x-dev",

```

and reran

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

```

and it works now. I had a unstable beta and commerceguys came out with a stable version that updated their code.
> 1 votes

---
Tags: commerce, composer, 8
---


# Question
Title: What's the equivalent of cache_clear_all()?
What's the equivalent of `cache_clear_all()` in Drupal 8?

# Answer
You can use Cache api. It would be somthing like

```
\Drupal::cache('bin')->invalidateAll();

```

Or if you want to remove the entries and not just invalidate them:

```
\Drupal::cache('bin')->delete('variables')

```

where bin is a valid cache bin such as menu, render, page ...etc.
> 1 votes

---
Tags: 8, caching
---


title: D8 - Entity Load Cache

text:
# Question
Title: D8 - Entity Load Cache
First of all. Are

```
$ent = Drupal\custom_entity\Entity\MyEntity::load(1);

```

and

```
 $ent = \Drupal::entityTypeManager()->getStorage('custom_entity')->load(1);

```

the same?

Also I know that \Drupal::entityTypeManager()-\>getStorage('custom\_entity')-\>load() is getting cached.

When I talk directly to the class's load function also?

Thanks

# Answer
> 2 votes
> First of all. Are ... and ... the same?

Assuming your entity type class doesn't override `Entity::load` to do something different, yes they are the same. If you look at that method you can see it uses exactly the same op:

```
public static function load($id) {
  $entity_type_repository = \Drupal::service('entity_type.repository');
  $entity_type_manager = \Drupal::entityTypeManager();
  $storage = $entity_type_manager
    ->getStorage($entity_type_repository
    ->getEntityTypeFromClass(get_called_class()));
  return $storage
    ->load($id);
}

```

So `Entity::load` is simply a shortcut to loading the entity via the manager service.

> When I talk directly to the class's load function also?

They're identical operations, so yes, they share the same caching.

---
Tags: entities, caching
---


title: Where do I insert code into the header?

text:
# Question
Title: Where do I insert code into the header?
I recently updated my Drupal 'Newsflash' theme but one of my javascripts stopped working. I contacted the writer of the js script and he suggested that my head section has lost the markup for importing the overlibmws.js file, and that I should put it back.

```
<script type="text/javascript" src="/files/overlib.js"></script>

```

Where do I go in Drupal 7 (Im guessing it is a tpl file) to insert this code into the header?

# Answer
What you are looking for is html.tpl.php which by default is part of the `system` module. Copy the file to the location of your theme and add your code. The copy should take precedence over the default .tpl file.

Warning: Do not hack the core! I.e. if you add this change directly to the `system` module file it will be overwritten with the next update. In fact even adding the file to the third party theme is not a very clean solution (for the same reasons).

Consider using drupal\_add\_js() instead (requires custom code).
> 1 votes

---
Tags: 7, theming, javascript
---


# Question
Title: Can't declare uniquely named class.. because it's "in use"
I'm trying to figure out how to make a processor for facets in Drupal 8.3. I've got this, but I have a couple issues. The first is a fatal error I get after activating the module, and navigating to a page with the facet on it:

Fatal error: Cannot declare class Drupal\facets\_change\_labels\Plugin\facets\processor\transform\_labels, because the name is already in use in Drupal/modules/custom/facet\_change\_labels/src/Plugin/facets/processor/TransformLabels.php on line 22

It doesn't make sense, because this is the only place in the entire site that transform\_labels or transformLabels is used. As an experiment, I changed the function to a completely random name, and the issue persisted.

What am I missing, or not understanding?

The code:

```
<?php

namespace Drupal\facets_change_labels\Plugin\facets\processor;

use Drupal\Core\Form\FormStateInterface;
use Drupal\facets\FacetInterface;
use Drupal\facets\Processor\BuildProcessorInterface;
use Drupal\facets\Processor\ProcessorPluginBase;

/**
 * Provides a processor for transforming labels.
 *
 * @FacetsProcessor(
 *   id = "transform_labels",
 *   label = @Translation("Transform labels"),
 *   description = @Translation("Transform labels"),
 *   stages = {
 *     "build" = 35
 *   }
 * )
 */
class transform_labels extends ProcessorPluginBase implements BuildProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function build(FacetInterface $facet, array $results) {
    $config = $this->getConfiguration();

    /** @var \Drupal\facets\Result\Result $result */
    foreach ($results as $result) {
      if ($result->getRawValue() == 'shape') {
        $result->setDisplayValue("leaf shape");
      }
      elseif ($result->getRawValue() == 'type') {
        $result->setDisplayValue("leaf type");
      }
      elseif ($result->getRawValue() == 'color') {
        $result->setDisplayValue("leaf color");
      }
    }

    return $results;
  }
}

```

# Answer
For PS4 class autodiscovery to work, your file name needs to be the same as your class name. From reading the error message, it appears that your file name is TransformLabels.php, but you've named your class transform\_labels. You need to change your class name to TransformLabels:

```
class TransformLabels extends ProcessorPluginBase implements BuildProcessorInterface {

```

One other question I have is, did you create the facets processor plugin type? Or was it a 3rd party?
> 5 votes

---
Tags: search
---


# Question
Title: Drupal 8 group filter conditions using views query filter
I'm facing an issue while applying filter in drupal 8 views.

I have created a view of records where i showed content using filter conditions. Basically, I want to add a filter using AND/OR conditions in views filter.

Currently, There are multiple AND/OR conditions in our views filter. If i chang any Condition from AND to OR, subsequent conditions are also getting changed to the same.

Requirement is: Condition Between first & second group will be 'AND' . Condition from second & third will be OR.

How to do it in views?

Check screenshot for more reference:

# Answer
> 0 votes
Instead of clicking to add a new filter, click on the little arrow that brings down more options: and/Or Rearrange. Choose that one and you can set up the logic kind of like in this image below:: *use highlighted area :: Create new filter group*

---
Tags: hooks, views
---


# Question
Title: How can I limit the allowed quantity in the cart to one item?
I am using Drupal 8/Commerce 2. How do I limit the quantity in the cart to one item so that users can't order more than one item per order.

# Answer
Drupal 8 / Commerce have field "Default quantity to add to cart", so you can add default quantity for product is 1 and hide it from product page. After that user can't change quantity of products. Problem is solved!
> 0 votes

# Answer
Views \>\> Cart form \>\> Remove field... (order\_items: Order Item) Order item: Quantity text field (Quantity)

This was a editable quantity field.

You can now add (order\_items: Order Item) Order item: Quantity (Quantity) Which is a display only version of the quantity field.

For your Order item type \>\> manage display \>\> purchased entity \>\> rendered as cart.

The same item can still be added 1 at a time to the cart. To best solve solve this problem it would depend on your situation.

(1) Is your product a 'one off' unique item? then best solved by a stock strategy -or- (2) Is only one item of a certain sku allowed in a cart -or- (3) Must each sku in a cart be unique?
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: Is there a way to make a keyboard shortcut for Save on the node edit page?
It would save a lot of time not having to scroll to the bottom of the page to save edits to a node.

Are there modules which achieve this?

# Answer
Keyboard Shortcut module might be the one you are looking for , Project page says

> The Keyboard Shortcut Utility module enables you to create keyboard shortcuts on your website. You can create a shortcut to go to a page (internal or external) or call a JavaScript function.
> 2 votes

# Answer
Hotkeys for Save module allow to use keyboard shortcut for Save on the node edit page:

> Do you often edit content or other site data? Do you get tired of scrolling endless down to the Save button? If so, this module allows you to use hotkeys Ctrl+S (Win) and Cmd+S (Mac) instead of clicking on the Save button.
> 1 votes

---
Tags: nodes
---


# Question
Title: Is it possible to get render a field for a paragraphs field in the parent twig template
My use case requires that I get a fields values in the parent paragraph template file.

So to be more clear I have a paragraph type (wrapper) which itself has a field referencing to another paragraph type (nested).

I am trying to get the values of a field (like title) from the child paragraph (nested one) in the parent twig template.

Hope for some help with this.

# Answer
> 4 votes
in your `node.html.twig` file you can traverse up the element array like this

```
{{node.field_parent.entity.field_paragraph.entity.field_text.value}}

```

where

* `field_parent.entity` is the parent paragraph
* `field_paragraph.entity` is the child paragraph attached to parent
* `field_text` is a text field attached to child paragraph

OR inside your `paragraph.html.twig`

```
{{paragraph.field_paragraph.entity.field_text.value}}

```

NOTE: its actually better to put this code in a `paragraph--parent.html.twig` file otherwise this template is going to be used also for the child `text` paragraph which does not have `field_paragraph` and its going to lead to error.

# Answer
> 0 votes
I have eventually gotten this to work, this is how I accessed the field from the parent paragraph template

field\_product is the paragraph field on my parent paragraph type. field\_title is the field I was trying to get the value of which belonged to the child paragraph type

```
{{ content.field_product.0['#paragraph'].field_title.0.value }}

```

---
Tags: theming, paragraphs
---


title: Field weight ignored on buildForm()

text:
# Question
Title: Field weight ignored on buildForm()
I need to set the $form\['langcode'\]\['#weight'\] to -251.

I tried also to access the widget weight. But the position weight still remains on bottom of the form.

Why is that? I tried:

```
//form field sort ('#weight')
$form['langcode']['#weight'] = "-251";
$form['langcode']['widget']['#weight'] = "-251";
$form['langcode']['widget'][0]['#weight'] = "-251";
$form['langcode']['widget'][0]['value']['#weight'] = "-251";
$form['langcode']['#weight'] = -251;
$form['langcode']['widget']['#weight'] = -251;
$form['langcode']['widget'][0]['#weight'] = -251;
$form['langcode']['widget'][0]['value']['#weight'] = -251;

```

Also on the hook\_form\_alter I cannot change the weight.

# Answer
> 1 votes
Sometimes these arrays will have a `#sorted` key that needs to be set to `FALSE` for the array to be sorted (again) and your weight changes to have an effect. Here it would be at `$form['#sorted']`.

---
Tags: entities
---


# Question
Title: How to display a form in controller method
I have a form defined in mymodule/src/Form/myForm.php

```
namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class myForm extends FormBase {

/**
 * Specify the form ID.
 */
public function getFormId() {
  return 'mymodule_myform';
}

  /**
   * Build the actual form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Form API code here...

```

Originally, this routing worked fine and the form displayed at the correct path:

```
mymodule.single_tab:
  path: '/node/{node}/edit/performance'
  defaults:
    _form: '\Drupal\mymodule\Form\myForm'
    _title: 'Add performance'

```

Then I needed to add a custom access check, restricting to a specific content type:

```
mymodule.single_tab:
  path: '/node/{node}/edit/performance'
  defaults:
    _title: 'Add performance'
    _controller: '\Drupal\mymodule\Controller\mymoduleController::content'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\mymoduleController::checkAccess'

```

The access check works fine. Now I think I have to display my form in the controller:

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\Entity\Node;

/**
 * Controller for Add Performance single tab.
 */
class mymoduleController extends ControllerBase {

  /**
   * Returns the add single performance form.
   */
  public function content() {
    $form = $this->formBuilder->getForm('Drupal\mymodule\Form\myForm');
        return [
          '#type' => 'markup',
          '#markup' => $form
        ];
  }

```

This fails to display the form, and I get:

```
Call to a member function getForm() on null

```

I tried defining my form builder class inside the controller instead, but same result. What am I doing wrong?

# Answer
> 0 votes
Thanks to Kevin's comment, I realised that I can just return the form AND still use the custom access check reference to a controller method:

```
mymodule.single_tab:
  path: '/node/{node}/edit/performance'
  defaults:
    _form: '\Drupal\add_performance\Form\myForm'
    _title: 'Add performance'
  requirements:
    _custom_access: '\Drupal\add_performance\Controller\mymoduleController::checkAccess'
  options:

```

---
Tags: 8, forms
---


# Question
Title: How to specify radio buttons in baseFieldDefinitions?
In the baseFieldDefinitions method of my custom entity, I see I can provide a checkbox list with code like...

```
$fields['my_field'] = BaseFieldDefinition::create("list_string")
      ->setSetting('allowed_values', $$my_options)
      ->setLabel('My Field')
      ->setRequired(FALSE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', array(
        'type' => 'options_buttons',
        'weight' => 5
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

```

But how would I specify radio buttons so the user can make only one selection from the list?

# Answer
> 3 votes
The radios/checkboxes are displayed based on the field's ***cardinality***:

* If the field can store ***more than one*** (e.g., unlimited: `->setCardinality(-1)`, or 2,3,etc. `->setCardinality(2)`, `->setCardinality(3)`, etc.), it will be displayed as ***checkboxes***.
* If the field can store ***only one*** (i.e. `->setCardinality(1)`), it will be displayed as ***radio buttons***.

---
Tags: 8, entities
---


# Question
Title: How to update old CAPTCHA to use reCAPTCHA V2
I am very new to drupal I am trying to update a drupal site to reCAPTCHA V2 but I can't figure out how to. I know I need a new site key and secret key which I have gotten; but how do I actually make the CAPTCHA module update so I can put in my new keys. And so I can get the new reCAPTCHA check boxes instead of the images. I am using Drupal 7. Thank you for any help.

# Answer
> 1 votes
Just update module via update modules page: Your\_site/admin/reports/updates/update

Follow steps and update DB.

Go to modules page and check configuration for recaptcha, there you'll put your new keys (got from https://www.google.com/recaptcha)

Note: If you update module files using FTP, remember to run update.php script.

---
Tags: 7, captcha
---


# Question
Title: How to solve the error " Could not determine command name from tag @command" with Drush?
I'm installing drush v9 on the server as well as I try to port my command. I did several things but now get the error:

```
drush status

In BespokeDocBlockParser.php line 65:

  Could not determine command name from tag @command

```

I really have no idea where to look. I googled for the php file but could not even find it :-(

Any suggestion is appreciated. ...

I removed the drush.services.yml and rebuild the cache. Drush status is now giving normal feedback so probably it is sometiming in the drush command.

My drupal.services.yml

```
services:
  tb.commands:
    class: \Drupal\tb\Commands\TbCommands
    tags:
      - { name: drush.command }

```

My generated php template

```
<?php

namespace Drupal\tb\Commands;

use Drush\Commands\DrushCommands;

/**
 * A Drush commandfile.
 *
 * In addition to this file, you need a drush.services.yml
 * in root of your module, and a composer.json file that provides the name
 * of the services file to use.
 *
 * See these files for an example of injecting Drupal services:
 *   - http://cgit.drupalcode.org/devel/tree/src/Commands/DevelCommands.php
 *   - http://cgit.drupalcode.org/devel/tree/drush.services.yml
 */
class TbCommands extends DrushCommands {

  /**
   * Start data collecting for the traderbot
   *
   * @param $para
   *   parameters in case i need this
   * @validate-module-enabled tb
   *
   * @command
   * @aliases tb,traderbot
     */

    public function traderbot($para) {
      // See bottom of https://weitzman.github.io/blog/port-to-drush9 for details on what to change when porting a
      // legacy command.

    tb_log(3,'Start runnning traderbot from drush');

    tb_log(3,'End runnning traderbot from drush');

    }

}

```

The composer.json

```
{
    "name": "org/tb",
    "description": "This extension provides new commands for Drush.",
    "type": "drupal-drush",
    "authors": [
        {
            "name": "Author name",
            "email": "author@example.com"
        }
    ],
    "require": {
        "php": ">=5.6.0"
    },
    "extra": {
        "drush": {
            "services": {
                "drush.services.yml": "^9"
            }
        }
    }
}

```

function tb\_log is part of the custom tb drupal module.

What is wrong?

# Answer
> 1 votes
The comment on the `traderbot` method is incorrect:

```
   * @command
   * @aliases tb,traderbot

```

There is no value after `@command`. I believe you want:

```
   * @command traderbot
   * @aliases tb

```

See: Porting Commands to Drush 9

Clear the cache after the change and try again.

---
Tags: drush
---


# Question
Title: How do I print a twig variable inside a JavaScript in a twig file
I have a twig file of a custom module. It has a `<script></script>` section and I need to print a twig variable inside that section. How do I do this?

```
{{ set twigVariable = '123456' }}

<script>
    function myFunc() {
        var myJsVar = {{ twigVariable }};
    }
</script>

```

The variable does not print when I write like above.

# Answer
> 7 votes
I'll spare to tell that it's a bad practice to add custom script blocks to templates, and just point out the error(s):

(1) To set the variable content, you have to wrap `set` into a `{% %}` block, not `{{ }}`.

(2) You most probably want the value as JavaScript string, so don't forget to wrap it in `" "`.

This sums up to

```
{% set twigVariable = '123456' %}

<script>
  function myFunc() {
    var myJsVar = "{{ twigVariable }}";
  }
</script>

```

Which should be working just fine.

---
Tags: 8, theming, javascript
---


# Question
Title: How to modify add to cart form in detail
Currently add to cart form can be modified from the "manage form display" of the line item. But this place shows all the attributes as a single entry.

Where is the best place to modify the sorting of attributes, inject other elements to the form between attributes etc?

For example I want to show an image field (from product) just before "add to cart" button. Should I use form\_alter or is there a twig file that I can readily use?

# Answer
I realise this answer may be a little late, but for those that end up here looking for a way to display the product variation fields (price, add to cart buttons, etc) separately, you can do it through the commerce-product.html.twig template using something like this:

```
<article{{ attributes }}>
  {{ product.title }}
  {{ product.body }}
  {{ product.variation_price }}
  {{ product.variations }} //show add to cart button
</article>

```
> 1 votes

---
Tags: 8, commerce
---