# Question
Title: how to include external php file in drupal 8
I want to merge two xlsx file and download merged file in drupal 8. So i used a PHPExcel library for doing so.

But i am not able to include a PHPExcel.php file in custom controller for that. I used require\_once, module\_load\_include() but does not work for me.

How can i include it . please help.

```
require_once DRUPAL_ROOT.'/'.drupal_get_path('module','custom').'/src/Controller/PHPExcel.php';

or

module_load_include('php', 'custom', 'src/Controller/PHPExcel');

$file1 = 'ford.xlsx';
$file2 = 'toyota.xlsx';
$objPHPExcel1 = PHPExcel_IOFactory::load($file1);
$objPHPExcel2 = PHPExcel_IOFactory::load($file2);

foreach($objPHPExcel2->getSheetNames() as $sheetName) {
$sheet = $objPHPExcel2->getSheetByName($sheetName);
$sheet->setTitle($sheet->getTitle());
$objPHPExcel1->addExternalSheet($sheet);
}

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="ford-toyota.xls"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1,
'Excel2007');
$objWriter->save('php://output');
exit;

```

and error is :

```
Fatal error: Class 'Drupal\custom\Controller\PHPExcel_IOFactory' not found

```

# Answer
I am not sure from your question which phpexcel library you are using, so there are potentially different answers, here is one:

**1. On Packagist**

If like in the case of mvlabs/mvlabs-phpexcel you would do the following:

on the command line:

```
composer require mvlabs/mvlabs-phpexcel

```

Then in the file where you are wanting to use it you can simply add a "Use" statement (as per this answer):

```
use ExternalPackage\namespace\Foo;

```

Drupal 8 does an auto-include and is "aware" of all the PHP libraries inside the vendor folder.
> 6 votes

---
Tags: external-scripts
---


title: How to make node title translatable?

text:
# Question
Title: How to make node title translatable?
I have a content type in D8 that requires translation, however at the moment I appear to be only able to translate the individual fields and not the title.

The language selector is available on the content type edit page, but there seems to be no way of selecting to translate the title:

Other fields have a checkbox that allows them to be translatable:

Any ideas? Thanks in advance!

# Answer
The title is set as translatable by default (in the entity definition). Somehow you've disabled translation for this field. You can check the translatable fields for content entities here:

```
/admin/config/regional/content-language

```

This includes all fields, also the base fields, which you can't configure in *Manage Fields* of the content type.
> 4 votes

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


# Question
Title: Composer shows "nothing to update" but there is a new version of the module
I am managing a Drupal 8 site in Composer. Commerce 2.0 was just released; I currently have 2.0-rc2 installed on my site.

This is my `composer.json`

```
"drupal/commerce": "^2.0@RC",

"minimum-stability": "dev",
"prefer-stable": true,

```

To update, I ran `composer update drupal/commerce --with-dependencies`, which gave me this result:

```
Gathering patches for root package.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating optimized autoload files
Warning: Ambiguous class resolution, "Drupal\Component\Utility\Random" was found in both "$baseDir . '/web/core/lib/Drupal/Component/Utility/Random.php" and "/mnt/c/Users/x/d/mysite/vendor/drupal/drupal-driver/src/Drupal/Component/Utility/Random.php", the first will be used.
Removing packages services cache file:
/mnt/c/Users/x/d/mysite/vendor/drupal/console/extend.console.uninstall.services.yml
Creating packages services cache file:
/mnt/c/Users/x/d/mysite/vendor/drupal/console/extend.console.uninstall.services.yml
> DrupalProject\composer\ScriptHandler::createRequiredFiles

```

So Commerce does not get updated to 2.0 (I already updated all the dependencies to their latest versions.)

I thought it might be a caching issue so I ran `composer clearcache` and then attempted to update commerce again, but I got the same result (nothing to update).

I thought it might be an issue with the composer module list being out of date, but Commerce 2.0 was released more than 48 hours ago. So what can I do to get composer working in this case?

**EDIT**

My repo is based on the Drops 8 Composer repo from Pantheon, which is in turn based on `drupal-composer/drupal-project`.

Deleting the `/vendor` directory and running `composer update` gives me this error:

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

```

Changing `composer.json` to `"drupal/core": "^8.4@RC"` `"symfony/css-selector": "~3.2"` also results in the same error.

But, running `composer install` or running `composer update drupal/modulename` allows me to install the site and update individual modules (except Commerce) without any problem.

# Answer
Thanks to @Neograph734 for pointing me in the right direction.

I needed to require Drupal 8.4-rc2 and drush 9, and then Commerce 2 arrived automatically.

Drush 9 appears to be a requirement for the 8.4 core update.
> 0 votes

---
Tags: updating, composer
---


# Question
Title: How to set which entities a workflow for Content Moderation applies to?
On Drupal 8.3, I enabled the Content Moderation and Workflow modules.

This provides an example **Editorial Workflow** by default.

The Content Moderation documentation states:

> Once your moderation workflows are established, you can apply the workflows to different entity types. Out of the box Content Moderation can be added to Block Content and Content (Node) entities. The "select" button will allow you to select which types should use this workflow.

However, there is no "select" link on the workflow edit page. The screenshot on the documentation page shows *This workflow applies to*, but out of the box that information is not displayed.

**Where can I select which types of entities a workflow applies to?**

# Answer
> 1 votes
This is supported from Core 8.4, so you have to upgrade your site. Then it shows up in the UI normally.

---
Tags: 8, entities, workflows
---


# Question
Title: Getting CSS content above the fold and I'm not quite sure why
I am getting this error for Page Speed insights, but I have followed the instructions I saw here to a T, and also tried messing around with it a bit.

Here's the link to the instructions.

I'm still getting CSS content above the fold - with 10 files on the mobile version and 17 on the desktop. What would be causing this? I'm now using 7.x-2.26 as opposed to 7.x-2.19. Trying to load the CSS in the footer doesn't help me out, nor anything else I'm doing.

What's a way to ensure that CSS is only loaded in such a way that page speed insights doesn't hate the site?

Instructions can be module-driven or technical, as I can write any custom code.

# Answer
> 0 votes
The answer was that if you have `base_path().path_to_theme()` as the location of your CSS, which the theme I was modifying did, it will not aggregate cleanly with either Drupal's standard aggregation nor with AdvAgg's aggregation.

---
Tags: 7, theming
---


title: MAMP database upload problem

text:
# Question
Title: MAMP database upload problem
I completely removed Acquia Dev Desktop & XAMPP and installed MAMP.

Plain vanilla Drupal 8 that I downloaded which is works. Now I want to import the database dump created by ADD, but keep getting an error message saying the file is too big. I believe the problem centers around php.ini. I can find no php.ini in the WAMP folder. I found php.ini-development & php.ini-production. I increased the parameters in both files relating to maximum file size upload, but they had no effect. I then copied php.ini-development & renamed it php.ini. I restarted the server, but it had no effect. Got any ideas as to how to fix this problem? i want to uploaded my new drupal website to this url https://www.kvtech.ae please help me to fix this problem.

Parameters changed - max\_execution\_time = 30 to 1200

Changed post\_max\_size=8M to 128M max\_execution\_time = 60 to 90000 upload\_max\_filesize=2M to 128M

Versions -

MAMP 3.2.0

Apache 2.2.27 Nginx 1.7.5 MySQL 5.5.41 PHP 5.3.23 & 5.4.1 & PHP 5.4.40 & 5.4.45 & 5.5.0 & 5.5.24 & 5.5.29 & 5.6.0 & 5.6.8 & 5.6.13 & 7.0.0 OpenSSL 1.0.2e APC 3.1.13 APCu 4.0.4 & 4.0.7 eAccelerator 1.0 XCache 3.0.4 & 3.1.0 OPCache 7.0.4 Python 2.7.6 mod\_wsgi 3.4.0 Perl 5.16.1 mod\_perl 2.0.8 phpMyAdmin 4.2.7 SQLiteManager 1.2.4 phpLiteAdmin 1.9.4.1 Freetype 2.4.10 curl 7.36.0 libpng 1.5.18 ImageMagick 6.8.9-1 Imagick 3.1.2 gd 2.1.0 zlib 1.2.7 libxml2 2.9.1 gettext 0.18.1.1 iconv 1.14 mcrypt 2.5.8

# Answer
Here's my preferred way of importing large databases.

I log in with mysql command line:

```
/Applications/MAMP/Library/bin/mysql -uroot -proot

```

Then I create the database:

```
drop database mysite_local;
create database mysite_local;
use mysite_local;

```

Then to import the large database command by command use:

```
source ~/Downloads/mysite_local.sql

```

Then exit the mysql client:

```
exit;

```

You can also set up your drush to jump right into your database. Since you'll be using the MAMP mysql instead the default on, you'll want to set up a symlink so that you can type mysql instead of the path to MAMP's mysql:

```
ln -s /Applications/MAMP/Library/bin/mysql /usr/local/bin/mysql

```

To get the terminal to recognize MAMP's php, you can add the correct php to your path variable in your bash profile. For example:

```
export PATH=$PATH:/Applications/MAMP/bin/php/php7.1.1/bin

```

To refresh the terminal so it uses the new path, type:

```
source ~/.bash_profile

```

At this point go to the site directory, for example, /Applications/MAMP/htdocs/web/sites/mysitefolder/ and type:

```
drush sql-cli

```

If you've set things up properly, you should be able to jump right into your database.

Or if you have a zipped file, you could do this to import the database:

```
gunzip ~/Downloads/dump-file.sql.gz | drush sqlc

```
> 0 votes

# Answer
I assume you are trying to import this via phpMyAdmin and that the file is an standard DB dump.

I would recommend either doing this via drush or the mysql command line. E.g.:

```
drush @mysite sql-cli < \backup\my-dump.sql

```

Note: drush @mysite status should show db schema and user name.

or

```
mysql -u user -p d8-database-schema-name < \backup\my-dump.sql

```

Another alternative would be to use the MySQL Workbench Tool. Excellent GUI tool that runs on any OS and can even access databases via SSH. Set up a connection to your DB, then load the dump as a script. Make sure your target database schema is selected as default.
> 1 votes

---
Tags: database
---


# Question
Title: How to stop a Views block from displaying to administrators, such as user/1?
I created a view and put an access role of anonymous user. When I log in with normal user account I don't see it, but when I log in with my admin account I see the view.

I would like to not see it. Is there a way to stop it from displaying to admins?

BTW, I tried un-checking `Bypass views access control` in the permissions, but it didn't work.

# Answer
> 5 votes
Below is an answer to what I think this question is really about, i.e. "***I would like to not see it. Is there a way to stop it from displaying to admins?***". And to make the challenge a bit tougher, not for a user with role "Administrator", but assuming "*... you are talking of the user with ID equal to 1 ...*".

My short answer to it is "Yes you can" ... read on for more details ...

# Part 1: Rules block visibility

You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the actual user who's using the site, i.e. if it is **YES** or **NO** (a boolean, right?) the user with `uid = 1`.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the **K**eep**I**t**S**uper**S**imple concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `1`.

With that, we're coming close to an actual answer to your question. But note that, as a variation, you could also have used a rules condition like "does this user yes or no have a role like administrator".

# Part 3:

Head over to the "Block" settings for the block you want to hide for the user with `uid = 1`. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2

**Notes**:

* It doesn't matter what type of block it is (created by a view, or something else), it works in all cases.
* This answer applies to D7.

# Answer
> 4 votes
The *Bypass views access control* permission is indeed the one that should not be given, to avoid users bypass the access control for a view, but the user account created when installing Drupal (whose ID is 1) is granted all the permissions, by design. In fact, `user_access()` uses the following code.

```
global $user;
if (!isset($account)) {
  $account = $user;
}

// User #1 has all privileges:
if ($account->uid == 1) {
  return TRUE;
}

```

Future Drupal releases will not grant every permissions to user #1, once Remove the special behavior of UID#1 is marked as *Fixed*. (On June 2, 2023, that issue is still marked as *Needs work*.)

# Answer
> 1 votes
This is quite simple you are using views so why not filter on the role.

In your view:

1. Select `*Contextual filters*`
2. Global: `*Null*`
3. Provide default value: `*User ID from logged in user*`
4. Select: `*When the filter value IS in the URL or a default is provided*`
5. With the Specify validation criteria of `*USER*`, `*Allow both numeric UIDs*` and `*string usernames*` and `*Restrict user based on role*` (Select your roles you DO want to access your view)
6. Select `Action to take if filter value does not validate` and Select *show page not found* or another Validation.

# Answer
> 0 votes
A little late, but you could do with PHP filter.

In the block settings, go to "Pages on which this PHP code returns TRUE (experts only) and write:

```
if ($account->uid == 1) {
  return TRUE;
} else {
  return false;
}

```

# Answer
> 0 votes
Just in case you're looking for something similar in D8, you may want to try using the Block Visibility Groups module. Some details about it (from its project page):

> ... allows the site administrator to easily manage complex visibility settings that apply to any block placed in a visibility group. The visibility settings for all blocks in the group can be edited on one administration form.
>
> This module works in conjunction with the Drupal 8 core's block administration system. It is a simpler alternative to modules like Panels.
>
> The following modules provide additional conditions that can be used with Block Visibility Groups:
>
> * CTools: Provides various conditions including bundle for each entity type.
> * Menu Condition provides a condition based on menu position. For example, you can use it to specify that a block should only show for a particular menu item and all its children.
> * Term Condition provides a simple Condition plugin which checks to see if the current node has a specific taxonomy term.
> * Token Conditions creates a simple Token matching condition plugin. Vocabulary Condition provides a vocabulary visibility condition.

---
Tags: views, blocks
---


# Question
Title: How to alter node url or toUrl function output?
How do we alter what's returned from $node-\>url()? or $node-\>toUrl()?

There are many entity reference fields that don't allow referencing more than one entity type or a custom route, such as entity queue or entity reference fields. For this purpose, so that we can create entity queues that reference other entities other than nodes, I am attempting to create a node with the bundle "redirect", and when the node referenced on the site, it would display the link to the referenced item on a field on that entity field\_path (which is a link field).

The problem is that $node-\>url() or $node-\>toUrl() is tightly integrated into the node object. In Drupal 7 we had hook\_url\_outbound\_alter which made this kind of thing easy. I would like a Drupal 8 equivalent. So that whenever a url or link to my redirect node is displayed, it is replaced with the value of field\_path. Not just that node/ redirects, but that it displays the redirect.

So how do we alter $node-\>toUrl() if $node-\>bundle() == 'redirect'?

I have found I can fix this most places on the site using two hooks:

```
/**
 * Implements hook_entity_view().
 *
 * Gets the output for extra fields.
 */
function mymodule_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'redirect') {
    if (!$variables['node']->field_path->isEmpty()) {
      $redirect = $variables['node']->field_path->getValue()[0]['value'];
      $variables['url'] = $redirect;
    }
  }
}

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {
  if (empty($variables['options']['external']) && !empty($variables['options']['entity'])) {
    $entity = $variables['options']['entity'];
    if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'redirect') {
      if ($variables['url']->getRouteName() == "entity.node.canonical" && !$entity->field_path->isEmpty()) {
        $redirect = $entity->field_path->getValue()[0]['value'];

        if ($new_url = URL::fromUri('internal:'.$redirect)) {
          $variables['url'] = $new_url;
        }
      }
    }
  }
}

```

But this doesn't help if someone calls the -\>url() function without the link wrapping it.

# Answer
> 4 votes
Path outbound processing still exists: OutboundPathProcessorInterface, check the implementations, like path alias handling. It's a tagged service.

That said, not sure if that's the approach that I'd take, I usually implemented something like that simply by overriding the necessary node templates/preprocess.

# Answer
> 3 votes
You can set uri callback function for an entity and for each bundle of an entity. This way, when code calls $node-\>url(), or $node-\>toUrl() you can have complete control of the output.

For the node content type, the tricky part is that you have to unset the link template for the canonical link in order for a uri callback to be used instead of the link template. By unsetting the link template for the entity, you have to set a uri callback for all bundles as well as for your specific bundle. So you need two functions, or one function that can handle all the bundles. Below is an example where for the "redirect" content type I use one uri callback and then for all the other bundles, I use another uri callback.

```
use Drupal\node\NodeInterface;
use Drupal\Core\Url;

/**
 * @file
 * Contains mymodule.module.
 */

/**
 * Implements hook_entity_type_alter().
 */
function mymodule_entity_type_alter(array &$entity_types) {

  // Unset the canonical link template for node content type and
  // replace with a uri callback.
  // Unsetting the uri template is necessary for the uri callbacks to work.
  $entity_types['node']->setUriCallback('mymodule_node_uri');
  $links = $entity_types['node']->get('links');
  unset($links['canonical']);
  $entity_types['node']->set('links', $links);
}

/**
 * Implements hook_entity_bundle_info_alter().
 */
function mymodule_entity_bundle_info_alter(&$bundles) {

  // Set the uri callback for the redirect content type.
  if (isset($bundles['node']['redirect'])) {
    $bundles['node']['redirect']['uri_callback'] = 'mymodule_redirect_uri';
  }
}

/**
 * Bundle URI callback for redirect content type.
 */
function mymodule_redirect_uri(NodeInterface $node) {
  if ($node->field_redirect->isEmpty() === FALSE) {
    return $node->field_redirect[0]->getUrl();
  }
  return new Url('entity.node.canonical', ['node' => $node->id()]);
}

/**
 * Bundle URI callback, all other content types outside of "redirect".
 */
function mymodule_node_uri(NodeInterface $node) {
  return new Url('entity.node.canonical', ['node' => $node->id()]);
}

```

To understand the order of operations that requires you to unset the link template, you can look at the toUrl() function on the Entity class: /core/lib/Drupal/Core/Entity/Entity.php

```
if (isset($link_templates[$rel])) {
  // uses link template . . . .
}
else {
  // checks for bundle specific uri callbacks and then entity specific uri callbacks.
}

```

---
Tags: 8, redirection
---


# Question
Title: Rules fatal error during update: Call to undefined method stdClass::events()
What I have tried:

> 1. Clear Cache.
> 2. Disabled module and enabled it.
> 3. Try with `registry_rebuild`, `module_missing_message_fixer`, `variablecheck` modules.

Still getting the below error when I try to run `update.php`.

> Notice: unserialize(): Error at offset 668 of 1298 bytes in \sites\all\modules\entity\includes\entity.controller.inc on line 261
>
> Warning: Creating default object from empty value in \sites\all\modules\rules\includes\rules.core.inc on line 57
>
> Fatal error: Call to undefined method stdClass::events() in \sites\all\modules\rules\includes\rules.plugins.inc on line 767

# Answer
> 2 votes
Debugging is the art of eliminating all possible causes for your problem. Below are some attempts to help you to find the real cause of your issue ...

### 1. Enable Rules debugging

Something that might help you find the answer to your question, is to have a look at Rules **debugging** ... Within the Rules **settings**, experiment a bit with the debugging facilities that come with Rules. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

For way more details about Rules **debugging**, refer to the answer to "How can I display the value of a variable inside a condition?".

### 2. Disable all active rules and re-enable them one by one

Instead of "disable" of the Rules module (which will possible resolve your issue until you enable it again), try to leave it enabled. But start with a *disable* of all Active (enabled) rules.

If it is some custom rule that is causing your problem, if none of your rules are active, the problem should have disappeared also after you disabled all active rules. If that's the case, re-enable your rules again, one by one, do some test to ensure the rule you enabled did execute. Keep doing this until you hit the custom rule that makes the issue come back again. Then disable that rule again, and check if there are other remaining rules that also make the problem show up again. In the end, try to adapt the rule(s) that seem to cause the issue so that the problem no longer shows up. If you cannot solve it, do not re-enable that rule anymore and think of some alternative.

### 3. Special watchdog entries

Make sure to also check for any unexpected watchdog entries, it may help to get a clue about what is happening

# Answer
> 1 votes
Try to re-download Rules module and re-try again. So basically remove *Rules* folder and re-download it again manually or use `drush` command, e.g.:

```
drush -y dl rules

```

For 2.x-dev version, add `--dev`.

After that clear you caches. If you're using any external caching such as *Memcached* or *Redis*, clear it as well. Then re-try again

Source: Error at time of installation of Call to undefined method stdClass::events().

---

If above won't help, the `unserialize()` notice suggests that your configuration data is corrupted. As per PHP docs:

> In case the passed string is not unserializeable, `FALSE` is returned and `E_NOTICE` is issued.

So basically you need to identify the table of your entity (`$this->entityInfo['base table']`/`$schema['fields']`) and which row it refers to (`fields` column). Ideally by setting up the breakpoint or manual code right after `unserialize()` call.

In other words, edit `includes/entity.controller.inc` file, find `load()` method and modify something like below:

```
  $record->$field = unserialize($record->$field);
  if ($record->$field === FALSE) { // Check if field is unserializeable.
    var_dump($record->$field, $record, $field); // Or use dpm(), dd(), etc.
    // exit(); // Optional exit to improve the formatting.
  }

```

If you've found some certain pattern, find the corrupted row by:

```
drush sql-dump --ordered-dump | grep some_unique_field_pattern

```

Then either correct the corrupted serialized data, restore from the backup or remove the corrupted field data.

---
Tags: 7, entities, rules, updating
---


# Question
Title: In Views, how can I show a blank end date if no value is entered?
A date field in views allows you to show a start date and/or an end date. If the end date is optional, and not filled out by the user, views doesn't show a blank field if it is empty-it's show the start date for some reason.

This issue is similar to How can I rewrite a date field "End Date" to be "present" if no value is entered?

I have tried messing around with the code in the above issue to meet my needs but it's not working.

I have views php installed and I need to add php code to show the field label and date but leave the date portion as blank, if empty. e.g. End Date: 2017-09-20 or if empty End Date:

These are my available variables

$row-\>field\_start\_date: Content: Position start/end date (Set to display only **start** date)

$row-\>field\_start\_date\_1: Content: Position start/end date (Set to display only **end** date)

# Answer
To answer my own question:

I used the Views Conditional module and set it up as follows:
> 2 votes

---
Tags: views, datetime
---


# Question
Title: An error upon trying to execute Drupal Console
I installed Drupal 8 into on my localhost, working under Windows 7 with OpenServer. After it I tried to install Drupal Console using Composer. Namely, this way

```
composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader

```

It installed without errors. But when I'm trying to execute Drupal Console (with command "drupal"), there is an error on the console:

```
Fatal error: Cannot use Drupal\Console\Core\Bootstrap\DrupalConsoleCore as DrupalConsoleCore because the name is already in use in D:\OpenServer\domains\palomniki.local\vendor\drupal\console\src\Bootstrap\Drupal.php on line 11

```

Could you clarify me, how to solve this problem ?

Frankly speaking, I managed to find answers of the error, where they advice to reinstall Drupal Console, but I don't know what they means. I tried to do remove this package, then to reinstall it, but I wasn't able to fix the error.

# Answer
> 0 votes
Drupal console global executable is not at the same version as your current project

go outside any drupal project and and execute: drupal self-update

# Answer
> 0 votes
Run "drupal self-update" as administrator or whatever the windows equivalent to sudo is.

---
Tags: 8, console
---


title: How do I add a custom region?

text:
# Question
Title: How do I add a custom region?
How do I add a custom region in the bootstrap theme using Drupal 8?

I have installed a Bootstrap theme and now I want to add a custom region before the *Header* region. What should I add in the theme .info file? How do I render it in the page template?

# Answer
1. In your sub-theme's .info.yml file add the new region alongside the existing ones, e.g.

```
regions:
  header: Header
  content: Content
  sidebar_first: 'Sidebar first'
  footer: Footer
  custom_region: 'Custom region'

```
2. Then in your page.html.twig file render it like so:

```
{{ page.custom_region }}

```
3. Visit the Block layout admin page and assign some blocks to the region so it displays on the page.
> 2 votes

---
Tags: 8, theming, bootstrap-theme
---


# Question
Title: How to link/add custom CSS to bootstrap theme in Drupal 8
I am new to Drupal 8 and want to link a custom CSS file in my bootstrap subtheme. There is no way to link the CSS file in the theme.info.yml file. however, I was able to link my custom CSS in theme.info in Drupal 7. Guide me on how to add custom CSS in the Drupal 8 bootstrap subtheme.

# Answer
> 3 votes
Bootstrap is designed for you to add extra CSS to a subtheme, not the main theme.

The Bootstrap documentation says this:

> Warning You should never modify any theme or sub-theme that is packaged and released from Drupal.org, such as Drupal Bootstrap. If you do, all changes you have made will be lost once that theme is updated. Instead, you should create a subtheme from one of the provided starterkits (this is considered a best practice). Once you've done that, you can override CSS, templates, and theme processing.

Bootstrap even provides starter kits so you can easily make the theme yourself, plus step-by-step documentation.

# Answer
> 1 votes
Don't do on main theme instead create a sub-theme and change what you like. Here are some links that can help you set up Bootstrap sub-theme

You can use either SASS or LESS starterkit. Hope this helps you.

# Answer
> 1 votes
Though it's not a good idea to add your own CSS to a base-theme, you need to add it to `bootstrap.libraries.yml`

---
Tags: theming, bootstrap-theme
---


# Question
Title: Page title with substitution on views page
I have a view page that requires a dynamic page title. It is a simple substitution of the label field.

If I use `{{ label }}` it works fine for the title displayed on the page, but it doesn't substitute the label for the actual page title (in meta)

I was able to fix this by using `hook_views_post_render` using the following code

```
// Set the route title.
$route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
$route->setDefault('_title', $title);

$view->setTitle($title);

```

However, the title only works if the page is not cached. For the cached pages, the page title is missing. This feels like a bug in drupal, but I am hoping that there is a simple way to get this done.

# Answer
> 3 votes
You can't change the route object in a hook. Use a RouteSubscriber to add a dynamic `_title_callback` to the view route.

Otherwise `setTitle()` should work. The bug you've described is not a bug. It's about caching in general. When you add dynamic data you also have to add the cache metadata, which defines what kind of dynamic data this is.

For example if the dynamic title depends on the node 123:

```
$output['#cache']['tags'][] = 'node:123';

```

---
Tags: views, 8
---


# Question
Title: Dompdf returns PDF on Controller function but not on Submit Form function
I'm using Drupal's Form api to create a form which returns some values inside a PDF document based on some selected inputs. I'm importing the form like so:

```
public function content(){
    $form = \Drupal::formBuilder()->getForm('Drupal\custom_module_name\Form\ContributeForm');
    ...
    ... and so on

```

In my ContributeForm::submitForm I have this code:

```
public function submitForm(array &$form, FormStateInterface $form_state)
{
    $dompdf = new Dompdf();
    $dompdf->loadHtml('<h1>hello world</h1>');
    $dompdf->setPaper('A4');
    $dompdf->render();
    $dompdf->stream("example.pdf", array("Attachment"=>0));
    if ($dompdf){
        drupal_set_message("DOMPDF");
    }
    foreach($form_state->getValues() as $key => $value){
        drupal_set_message($key . ': ' . $value);
    }

```

and I don't get a pdf doc on the reloading of the page, though I do get the contents selected in the form returned to me in the drupal\_set\_message call.

Now to sanity check, I created a dummy module with only a controller (no form import) and this one DOES return the PDF with the content inside ::loadHtml:

```
public function content(){

    $domp = new Dompdf();
    $domp->loadHtml('<h1>Hi</h1>');
    $domp->setPaper('A4');
    $domp->render();
    $domp->stream('example.pdf');

    return array(
        //'#type' => 'markup',
        '#markup' => $this->t('Hello World yall'),
    );

}

```

Am I missing something on the form return? Am I adding an unnecessary layer of complications by importing the form into the controller, and should I just have the form load to it's own url?

# Answer
By default after form submit drupal makes a redirect, if there is no redirect defined intentionally allways will go to current url. To prevent this, you need call to *disableRedirect()* method from FormState at the final of *submitForm()*.

Example:

```
public function submitForm(array &$form, FormStateInterface $form_state)
{
    $dompdf = new Dompdf();
    $dompdf->loadHtml('<h1>hello world</h1>');
    $dompdf->setPaper('A4');
    $dompdf->render();
    $dompdf->stream("example.pdf", array("Attachment"=>0));
    if ($dompdf){
        drupal_set_message("DOMPDF");
    }
    foreach($form_state->getValues() as $key => $value){
        drupal_set_message($key . ': ' . $value);
    }
    // Prevent form redirection to print PDF.
    $form_state->disableRedirect();
}

```

Source: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AdisableRedirect/8.2.x

Other option, more dirty, is call to exit() method from PHP (http://php.net/manual/es/function.exit.php) also at the final of the function.
> 1 votes

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


# Question
Title: Importing external resources via REST as nodes or other entities
I'm just getting my feet wet with Drupal 8, having written a decent amount of modules for various projects for Drupal 6 and 7. We are trying to leverage Drupal as a CMS add-on to our club management software. A lot of our customers have asked us both how we would integrate into an external system and also how we could provide customer websites. We've decided to try and leverage Drupal 8 to provide a hosted CMS to our customers.

We are developing a REST API for our product that will expose various resources such as Events, Equipment items, Equipment Reservations, etc... What we want to do is have those available in Drupal, preferably as full-fledged entities so that customers could add additional information to these items that is stored with Drupal. For an example, we would provide an Event object via our API and then a customer could add a "photo gallery" field in Drupal to add photos to the event.

We'd also show an events and equipment usage calendars using data from our product, likely as blocks.

What I'm somewhat stuck on is how to define an Entity without storing it in the SQL database. We want our system (via REST) to be the canonical source with addons and UI provided by Drupal.

Can anyone point me in the right direction as to how I could create an entity type with its core storage outside of Drupal and linked via an API?

I should note, I already found the External Entities module, but I don't see how it exposes the external entities as viewable or fieldable objects. Perhaps I'm just missing something here?

Thanks in advance!

# Answer
> 3 votes
I haven't looked at that module yet, but pretty much everything that involves the storage of an entity goes through the storage handler of a given entity type.

Drupal 8 provides to real implementations, `SqlContentEntityStorage` for content entities stored in the database and `ConfigEntityStorage` for config entities stored in configuration. And a few test and example implementations too.

So the first thing you need to implement is your own storage. Do whatever you want in the relevant methods like load()/save()/delete(), see `EntityStorageInterface`.

Additionally, you will have to implement a entity query, so you can create lists with conditions, sorts and so on. That also comes from storage (getQuery()), initialized based on a given service name, see for example `entity.query.sql` and `entity.query.config`. That's a factory that returns the actual query object and in there, you can again do whatever you want. For content entities, it's transformed to an SQL query while config entity queries are actually mostly implemented in PHP, with some optimizations and lookups.

If you also want to use views, you have to write a backend for that too, since it doesn't use entity query (yet). There's https://www.drupal.org/project/efq\_views, not sure how far it is for Drupal 8.

# Answer
> 0 votes
If you just want the external data to be read and display in your site then you can use this module, View xml Backend, Views will have the external data.

---
Tags: 8
---


# Question
Title: Drupal 7 appending class in uc attribute option radio button
I have this code inside **mymodule\_form\_alter**:

```
     foreach ($form['attributes'] as $att) {
        foreach ($att['#options'] as $option => $value) {
  // Get the name of the option without the price or price adjustment -> string before coma
            $optionName = explode(",", $att['#options'][$option], 2)[0];
            if (strpos($optionName, '+') !== false) {
                $att['#options'][$option]['#attributes'][] = array('class' => array('my_class'));
            }
        }
    }

```

Unfortunately

> $att\['#options'\]\[$option\]\['#attributes'\]\[\] = array('class' =\> array('my\_class'));

Displays unexpected error, I tried different syntax but no success. Any help much appreciated

> Update 27/09/2017

I tried to do this by using **after\_build** I get no errors but it isn't working

```
// Inside hook_form_alter
 $form['attributes']['#after_build'][] = 'addToCartFormEditQuantity_after_build';

 function addToCartFormEditQuantity_after_build(&$element, &$form_state)
{
    // Each renderable radio element.
    foreach ($element as $attribute) {
        foreach (element_children($attribute) as $option) {
            var_dump($attribute[$option]);
      // Get the name of the option without the price or price adjustment -> string before coma
            $optionName = explode(",", $attribute['#options'][$option], 2)[0];
            if (strpos($optionName, '+') !== false) {
                $attribute[$option]['#atrributes']['class'] .= 'single-double';
            }
        }
    }

    return $element;
}

```

# Answer
> 0 votes
I managed to get what I wanted inside **theme\_uc\_attribute\_add\_to\_cart** by using:

```
foreach (element_children($form) as $aid) {
     foreach (element_children($form[$aid]) as $option) {

        $form[$aid][$option]['#prefix'] = '<div class="row single-double">';
        $form[$aid][$option]['#suffix'] = '</div>';

      }
    }

```

But I really don't want to mess with uc\_attribute.theme.inc is there any other way?

---
Tags: hooks, ubercart
---


# Question
Title: How to load a CSS file on a specific page, not on the entire site
I have a CSS library that I need to load on a particular page because loading on unnecessary pages reduces the performance of my site. I know to load it for all pages like.

`global-styling: css: theme: css/style.css: {}`

But I want to know how to load this on a particular page. where to add and how to call it on the required page.
`css/gall.css: {}`

# Answer
> 1 votes
Here is an example in (your\_custom\_sub\_theme.libraries.yml)

```
global-styling:
  css:
    component:
      css/my-custom.css: { weight: 220 }
      css/my-custom2.css: { weight: 221 }
      css/my-custom3.css: { weight: 222 }

  js:
    js/my-custom.js: {}
    js/my-custom2.js: {}

```

Do NOT change the indents.

(the weight is optional)

In your\_custom\_sub\_theme.info.yml you need:

```
# Defines libraries group in which we can add css/js.
libraries:
  - your_custom_sub_theme/global-styling

```

---
Tags: 8, theming
---


title: Get all comments

text:
# Question
Title: Get all comments
How do I get all the comments posted for a node? The REST API seems not to return them in a usable manner.

```
    {
  "_links": {
    "self": {
      "href": "http://localhost:8080/drupal8/node/3?_format=hal_json"
    },
    "type": {
      "href": "http://localhost:8080/drupal8/rest/type/node/article"
    },
    "http://localhost:8080/drupal8/rest/relation/node/article/uid": [
      {
        "href": "http://localhost:8080/drupal8/user/1?_format=hal_json",
        "lang": "en"
      }
    ],
    "http://localhost:8080/drupal8/rest/relation/node/article/revision_uid": [
      {
        "href": "http://localhost:8080/drupal8/user/1?_format=hal_json"
      }
    ]
  },
  "uuid": [
    {
      "value": "5326216b-0e65-454b-8a48-720b6e6e2402"
    }
  ],
  "type": [
    {
      "target_id": "article"
    }
  ],
  "langcode": [
    {
      "value": "en",
      "lang": "en"
    }
  ],
  "title": [
    {
      "value": "Testing Post Article",
      "lang": "en"
    }
  ],
  "_embedded": {
    "http://localhost:8080/drupal8/rest/relation/node/article/uid": [
      {
        "_links": {
          "self": {
            "href": "http://localhost:8080/drupal8/user/1?_format=hal_json"
          },
          "type": {
            "href": "http://localhost:8080/drupal8/rest/type/user/user"
          }
        },
        "uuid": [
          {
            "value": "e7f777b9-8bd7-4f87-a100-d1784d6ed1bc"
          }
        ],
        "lang": "en"
      }
    ],
    "http://localhost:8080/drupal8/rest/relation/node/article/revision_uid": [
      {
        "_links": {
          "self": {
            "href": "http://localhost:8080/drupal8/user/1?_format=hal_json"
          },
          "type": {
            "href": "http://localhost:8080/drupal8/rest/type/user/user"
          }
        },
        "uuid": [
          {
            "value": "e7f777b9-8bd7-4f87-a100-d1784d6ed1bc"
          }
        ]
      }
    ]
  },
  "status": [
    {
      "value": "1",
      "lang": "en"
    }
  ],
  "created": [
    {
      "value": "1490939860",
      "lang": "en"
    }
  ],
  "changed": [
    {
      "value": "1490939860",
      "lang": "en"
    }
  ],
  "promote": [
    {
      "value": "1",
      "lang": "en"
    }
  ],
  "sticky": [
    {
      "value": "0",
      "lang": "en"
    }
  ],
  "revision_timestamp": [
    {
      "value": "1490939860"
    }
  ],
  "revision_translation_affected": [
    {
      "value": "1",
      "lang": "en"
    }
  ],
  "default_langcode": [
    {
      "value": "1",
      "lang": "en"
    }
  ],
  "body": [
    {
      "value": "article",
      "format": null,
      "summary": null,
      "lang": "en"
    }
  ],
  "comment": [
    **{
      "status": "2",
      "cid": "3",
      "last_comment_timestamp": "1490944700",
      "last_comment_name": "",
      "last_comment_uid": "1",
      "comment_count": "2",
      "lang": "en"
    }**
  ]
}

```

As can be seen it gives a count but not the Ids of the Comments..

I am using **Drupal 8.0.2**

# Answer
I got a solution.

1. Create a view with rest export with below settings. VIEW SETTINGS: show = **comments** and type = **all**
2. After view is created the change the **entity** with **fields** in format settings
3. Then add the required fields in view, also select content type field so that you can differenciate between comments.
4. Add contexual filter with **id**, add change path with **{yourpath}/%**
5. Check output on Postman or any other app.

This is working for me,and becuase of this I can able to get the comments related to individual content.

If you want comment related to article content type then you can add the filter criteria.

Hope this will work for you!
> 1 votes

---
Tags: comments
---


title: Dependent Term Reference Autocomplete

text:
# Question
Title: Dependent Term Reference Autocomplete
I want to make the options for a (secondary) term reference autocomplete field dependent on the values chosen in another (primary) autocomplete term reference field. How can I limit the options in the secondary term reference field?

I have two vocabularies called chapter and sub-chapters. In the sub-chapters vocabulary, I have an additional term reference field linking each sub-chapter to the chapter in the chapter vocabulary. (I wanted to use two separate vocabularies, rather than a single hierarchical vocabulary to make it easier to use separate exposed views filters).

On my main content form, I want to limit the sub-chapters available in the autocomplete field to the values chosen in the primary chapters autocomplete field.

I have looked at many different modules for achieving this and haven't found any that will work with my scenario so need to write some code to achieve this. I need to use autocomplete fields as there are so many terms to choose from for both the primary and secondary fields. I have been using the autocomplete deluxe widget for the primary field but I can just use the standard autocomplete widget if this makes it easier.

Can anyone give me a rough outline of the basic code I would need to write in order to achieve this?

I guess there will need to be an update of the options of the secondary term reference field whenever the values are altered in the primary term reference field using AJAX?

# Answer
The basic process would be to make the 2nd field an Ajax (AHAH) created field. Then in this method, set the #autocomplete render element to a URL that uses the first field's value. Something like:

```
function simple_ahah_select($form_state) {
if ($form_state['storage']['content']['simple_select_parent']) {
  $element = array(
    '#type' => 'textfield',
    '#size' => '60',
   // Define a autocomplete_path depend on the value selected on the parent select field
    '#autocomplete_path' => 'simple/autocomplete/' . $form_state['storage']['content']['simple_select_parent']
  );
  }
}
return $element;

```

The Autocomplete URL can probably be a view if you don't want to write code. But code would be faster.

See this d.o page for some more details
> 0 votes

---
Tags: 7, taxonomy-terms, ajax
---


# Question
Title: Solr, Merge Facet from two taxonomy type fields
I am trying to create an advanced facet from a solr implementation.

A searchable content type (Book) has 2 fields (grade level min) and (grade level max) Grade level is a (Taxonomy Term) Pre-K - 12th.

I would like to create a facet called 'Grade' that when a user selects an option the search will use the grade min and max fields to filter this correctly. Example: (User clicks 6th Grade, the system will show all books whose min max values include 6th grade)

I am confident with providing the logic, I just don't know what hook, hooks, or UI options I can use to customize a facet to this degree. I am not new to Drupal but I am new to solr.

My initial thoughts are to either:

1. Add an aggregate field to store in the database
2. Create an advanced facet that can handle the min-max situation
3. Provide a hook before solr is accessed to modify my search
4. Provide a hook after solr returns results to modify my search.

Any help would be greatly appreciated.

# Answer
I was able to get this to work by creating a new entity property in a custom module. This was kind of close to my 1st thought.

```
/**
 * Implements hook_entity_property_info_alter().
 */
function advanced_search_entity_property_info_alter(&$info) {
    $info['node']['properties']['supported_grades'] = array(
        'type' => 'list<taxonomy_term>',
        'label' => t('Supported Grades'),
        'description' => t("Full Grade Level list that this resource has."),
        'sanitized' => TRUE,
        'getter callback' => 'advanced_search_get_supported_grades_callback',
    );
}

function advanced_search_get_supported_grades_callback($item) {
     // Logic that uses the $item values to return an array of tids.
}

```

Once I did this I was able to access the new field as usual when indexing and to create facets.

Hope this helps someone else out there.
> 0 votes

---
Tags: search
---


# Question
Title: Where does the search form come from and how to access it
I am trying to change the search bar that is displayed on my Commerce Kickstart installation.

When inspecting the website code, the form is build like this:

```
  <form class="contextual-links-region" action="/commerce_kickstart/products" method="get" id="views-exposed-form-display-products-page" accept-charset="UTF-8"><div><div class="views-exposed-form">
  <div class="views-exposed-widgets clearfix">
  <div id="edit-search-api-views-fulltext-wrapper" class="views-exposed-widget views-widget-filter-search_api_views_fulltext">
  <div class="views-widget">
  <div class="form-item form-type-textfield form-item-search-api-views-fulltext">
       <input placeholder="Search" type="text" id="edit-search-api-views-fulltext" name="search_api_views_fulltext" value="" size="26" maxlength="128" class="form-text">
    </div></div></div>
    <div class="views-exposed-widget views-submit-button">
    <input type="submit" id="edit-submit-display-products" name="" value="Apply" class="form-submit">
   </div></div></div></form>

```

My first question is: Where is this HTML coming from? I kind of know the basics of Drupal theming but I have no idea where this piece of code is coming from.

And now I am trying to access it. For example, I would like to edit the Placeholder "Search" into something else. But I have no idea how to do that.

I tried something like this in my themes template.php:

```
function mytheme_form_views_exposed_form_alter(&$form, &$form_state) {
    $form['views_exposed_form_display_products_page']['#attributes']['placeholder'] = t('Test');
    drupal_set_message('Test');

```

Test gets printed, but nothing happens to the search box.

I have also tried:

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form_display_products_page') {
    $form['views_exposed_form_display_products_page']['#attributes']['placeholder'] = t('KLSDFNSELfhsdfk');
    drupal_set_message('Test');
  }
}

```

Test is not shown and obviously nothing happens. Is that even the correct id? I also tried using `views-exposed-form-display-products-page` since that is what is used as 'id=' in the form but nothing happened either.

# Answer
I don't know how to do this from the .theme php file, But I did do this before by overwriting the input.html.twig file.

In your themes folder, " THEME \> templates \> form \> input.html.twig ", If you are building a new theme, this directory might not be there, You will have to create it in the same order and naming in this case.

Note that "THEME" is the root folder for your theme.

Just do something like this in the input.html.twig file

```
<input {{ attributes }} placeholder="How can we help you?" />{{ children }}

```

---

Please note that this way will alter every input tag used by a form initialization from drupal ( Basically the input tags generated by the modules )
> 0 votes

---
Tags: theming, forms
---


# Question
Title: How do I programmatically retrieve the inputs from a form?
I am implementing a hook\_form\_alter in my custom module and I want to get all the inputs from the $form variable.

So, if for example there is a textarea, a radio button and a checkbox, I want to grab these elements and put them in a clean array for later use. What I basically want to do down the road is create a dropdown list and have these inputs as the options in the list.

Is this a clean way to do that through the FAPI?

# Answer
You can use the `element_children()` function to grab all of the child elements within a particular element (including a form element). The thing with Drupal forms is that often all elements are not on the same level of the array, so you'll need to make a recursive function to get them all reliably. This is untested but should give you a place to start:

```
function _element_children_recursive(&$element) {
  $names = array();

  foreach (element_children($element) as $element_key) {
    $names[] = $element_key;
    $names = array_merge($names, _element_children_recursive($element[$element_key]));
  }

  return $names;
}

$all_element_names = _element_children_recursive($form);

```

There's even one further caveat to this...since form elements can be on different levels you might well end up with two identically named keys. This is perfectly valid in Drupal so you'll probably want to do a bit of checking in the recursive function to avoid duplicates.
> 3 votes

# Answer
Do you want the FAPI representation of the elements or the user-inputted values?

I think that you are asking about the values input to the form elements by the user. These are available in the variable $form\_state\['values'\] when the form has been submitted.
> 1 votes

# Answer
I think the accepted answer is the best, but I wanted to mention you can also get the field names by doing `drupal_retrieve_form('form_id', $form_state)`. You get an array with the form element names as keys, and the build attribute array of each field as the contents.

Note: you have to create a dummy `$form_state` by doing `$form_state['build_info']['args'] = array();`
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Search API: sorting with Scandinavian alphabet
We're using the search API something like this, and returning results in alphabetical order:

```
// Set up
$search_api_index = $this->entityTypeManager->getStorage('search_api_index');
$index = $search_api_index->load($name);
$search_id = 'restful_search_' . uniqid();
$query = $index->query([
  'limit' => $limit,
  'offset' => $offset,
  'search id' => $search_id
]);

// Add some conditions
$query->addConditionGroup($conditionGroup);

// Add sort directive
$query->sort('title', SORT_ASC);

```

This is working, and the results are coming back in alphabetical order. However, we'd like the sort according to the Finnish/Swedish alphabet.

So instead of things being sorted like "ÄBC", we'd like them sorted like "BCÄ". That is, those beginning with Å, Ä and Ö etc. should come last, not first.

Is it possible to tell the Search API to return results which meet this order?

# Answer
> 0 votes
I believe your question is more tailored to Solr rather than Drupal persay.

I'm using Solr, but not with any special language semantics for Sorting required.

It appears as though solr can be configured to support the kind of alphabetical sorting you requested via a Plugin and a special field type. See the section entitled `Unicode Collation` on this reference page: https://cwiki.apache.org/confluence/display/solr/Language+Analysis

Once your Solr instance is configured to support the `ICUCollationField` field type. You then need to tell Drupal to make use of that field for analysis/sorting. So either in D8 you need to implement some of the below modifications:

* alter the Solr Field type that fulltext searches are indexed with to use the `ICUCollationField` instead of the default fulltext field supplied by Search API using the Search API hooks.
* OR, use the `copyfield` technique described in the Solr reference page under *Sorting Text for Multiple Languages*, and use the Search API copy field functionality to clone the default fulltext into this collation aware field.
    + then alter every search performed by your site using Search API hooks to override the Sort parameter to use the collation field.

Your request will likely require a full Solr re-index of all your Nodes, and if you use copyfield be aware the index may be much bigger.

These are some general approaches you can attempt using Search API and Solr. I'm not 100% sure they'll work, but they're the 2 approaches I'd try if I was setting this up.

Any feedback, success or failure is welcome to your original post once you've figured it out.

---
Tags: 8, search
---


# Question
Title: Drupal 8: Node form submit/update - how to redirect to a custom page with an code-based approach different than hook_form_alter()
I have Drupal 8 installation, with a custom content type. I would like to redirect to a specific page after node form submission.

**What I have tried so far:** Using hook\_form\_alter() and it works, but that's not the point here.

**What I want to achieve:** Delivering the same functionality in a new OOP code based way.

**What I have found so far:** https://www.thirdandgrove.com/redirecting-node-pages-drupal-8

This example shows the replacement for the old hook\_init().

Update 1: Rules module can achieve the desired functionality.

Update 2: Node\_save\_redirect module can achieve the desired functionality.

Update 3: A possible answer https://www.foreach.be/blog/how-manipulate-forms-drupal-8 can someone with enough D8 experience actually confirm if that's actually the official way of doing things ?

Regards, Oleg

# Answer
> 3 votes
While the other solution is perfectly valid, I mark this answer as accepted since it comes closer to what I was looking in first place - the new way to alter forms.

Eventually the solution can be found right here: https://www.foreach.be/blog/how-manipulate-forms-drupal-8

In summary (quoted from the article): 1 ) The first step is to write a service that intercepts the original UserLoginForm and directs to the adapted form

2) Changed the route to return the adapted NewUserLoginForm instead of the original UserLoginForm

3) The new form extends the old form and inside the buildForm method you add in the beginning

```
$form = parent::buildForm($form, $form_state);

```

This step was missing in the example tere

# Answer
> 4 votes
A route subscriber doesn't work so well because the route 'entity.node.edit\_form' uses an entity form.

One approach would be to use hook\_entity\_type\_alter to change the edit form:

```
function mymodule_entity_type_alter(array &$entity_types) {
  $handlers = $entity_types['node']->get('handlers');
  $handlers['form']['edit'] = 'Drupal\mymodule\Form\CustomNodeEditForm';
  $entity_types['node']->set('handlers', $handlers);
}

```

Then you could override the save function of the node.

```
namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeForm;

class CustomNodeEditForm extends NodeForm {

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    parent::save($form, $form_state);

    $node = $this->entity;

    if ($node->id()) {
      if ($node->access('edit')) {
        $form_state->setRedirect(
          'entity.node.edit_form',
          ['node' => $node->id()]
        );
      }
      else {
        $form_state->setRedirect('<front>');
      }
    }
  }

}

```

This is heavy-handed and risks conflicts with other customizations, but it assures that the redirects are set in the same place they're set as the node edit form, and are therefore fired before other handlers added by other modules.

A simpler approach is to simply to add another submit handler in form alter.

# Answer
> 2 votes
This functionality can easily be implemented using rules. This will ensure your Drupal installation to be upgrade proof.

Start off with installing this module. Once installed, create a new rule to trigger on Node \> After saving new content of type {your custom content type}. Set action to System \> Page redirect and supply the url and you're done.

---
Tags: 8, forms, redirection
---


# Question
Title: How to perform a redirect to custom page after node save or delete?
What I'm trying to do doesn't work, I still get redirected to /node/{id}:

```
function hook_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'callback_set_redirect';
}
function callback_set_redirect($form, FormStateInterface $form_state) {
  $form_state->setRedirect('custom.landing.page');
}

```

# Answer
Basically the code will work for submit action alone, but drupal node save form have many actions, I think you would have logged in as admin and trying it, then follow the code below.

if you want this to be work for other actions too, That means login as admin and see the node save button, you will have select option "save and publish" , "save and unpublish". as mentioned

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

//hook_form_alter
function hook_form_alter(&$form, $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'callback_submit';
    }
  }
}

function callback_submit($form, FormStateInterface $form_state) {
  $form_state->setRedirect('custom.page');
}

```
> 10 votes

# Answer
Using hook\_form\_alter, you'll need to do two things

1) make sure that it's a node form 2) add a custom submit handler to each submit button.

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

  if (isset($form['#entity_type']) && $form['#entity_type'] == 'node') {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'mymodule_node_form_submit';
      }
    }
  }
}

```

Then for the submit function, you can use whatever logic you want. You can compare with NodeForm::save, where it sends you either to the canonical node page or to the front page based on the current user's access permissions.

If you wanted to change this behavior so that it stays on the current node form, you could do this:

```
function mymodule_node_form_submit($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->id()) {
    if ($node->access('edit')) {
      $form_state->setRedirect(
        'entity.node.edit_form',
        ['node' => $node->id()]
      );
    }
    else {
      $form_state->setRedirect('<front>');
    }
  }
}

```

If you want to use your custom landing page, you just replace the redirect with the code you're already using:

```
$form_state->setRedirect('custom.landing.page');

```

Note that this won't override when there is a "destination" $\_GET parameter, such as at the /admin/content page.

To remove the destination parameter from the /admin/content page, you'll want to uncheck "destination" checkbox under "Content: Operations links (Operations)" in that views fields.
> 5 votes

# Answer
I had success using Symfony RedirectResponse:

```
function callback_set_redirect($form, FormStateInterface $form_state) {
  $url = Url::fromRoute("custom.landing.page")->toString();
  $response = new RedirectResponse($url);
  $response->send();
}

```
> 0 votes

# Answer
I can't find anything wrong with the original code so something else is probably amiss. It works fine for me.

However, `custom.landing.page` must be a defined route and parameters (if there are any) need to be passed in like so:

```
  $form_state->setRedirect("custom.landing.page", [
    'parameter1' => 42,
  ]);

```

See FormState::setRedirect() for details.
> 0 votes

# Answer
I always use the Node Save Redirect module for this functionality. It adds an option to a content type that says "what to do after saving new content".

> **What is this?**
>
> This module provides a method of specifying a location to take the user after saving a piece of content.
> 0 votes

---
Tags: 8, redirection
---


# Question
Title: Split commerce cart to multiple orders per product
What's a solution in Drupal Commerce to create an order per product in cart during the checkout?

**The cart looks like this:**

* Product A, Quantity: 2, $100
* Product B, Quantity: 1, $199

Total: $399

**The order-output should be:**

* Order #1: Product A, Quantity: 2, $100, Total: $200
* Order #2: Product B, Quantity: 1, $199

So instead of the usually created single order that contains all products in the cart, the goal is to create an order per product in the cart.

Could a checkout rule solve this? Or a custom module, and if, how?

# Answer
As you now,by default drupal add to cart form add all products to the same order.

Looking at the code of commerce\_cart.module, the base and unique behaviour of commerce\_cart module, it doesn't works in other way. When a product is add to cart, the order associated will be the same order or a new order.

If you want to decouple the line items in two different orders in cart page you will have to code a module based in commerce cart with that feature.

You can take a look to this module, it maybe helps you https://www.drupal.org/project/commerce\_cart\_multiple
> 0 votes

---
Tags: 7, commerce, rules
---


# Question
Title: How to show a block on specific pages using the Node ID instead of an URL?
Using the "Show block on specific pages" on a block configure field, is it possible to use the Node ID in lieui of URL.

I.E.

`412` instead of `about/contact-us/`

# Answer
If you just want use the node id you can use node/\[id\]. Example: node/1

It will works even you are using a path alias, because that route is allways avaiable for any node.
> 3 votes

# Answer
If you're willing to consider using "Rules", then there is a solution for this question, as further explained below.

# Part 1: Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the node id of the current page, i.e. if it is **YES** or **NO** (a boolean, right?) the node with `nid = 412` (as in your question).

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_show_block_only_for_nid_412" : {
    "LABEL" : "Show block only for nid 412",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false },
      "node" : { "label" : "Node", "type" : "node" }
    },
    "IF" : [
      { "data_is" : { "data" : [ "node:nid" ], "value" : "412" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the node's nid is YES or NO equal to `412`.

With that, we're coming close to an actual answer to your question.

# Part 3:

Head over to the "Block" settings for the block you want to only show for the node with `nid = 412`. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How do I set up a More Link in a View's Pager?
I have a View and am using the Pager to display a specific number of items, limited to 4. I want to create a "More" link to link to the rest of the items.

I've set my view up as such:

But no More link is appearing, even though I have more than 4 items and even though the helper information says:

> This will add a more link to the bottom of this view, which will link to the page view. If you have more than one page view, the link will point to the display specified in 'Link display' section under advanced. You can override the url at the link display setting.

I've looked through the HTML to ensure the link is not hidden by anything else. It's simply not present.

Would anyone know how to get this working?

# Answer
> 0 votes
You need to make display as page then only more will work. For more details https://www.drupal.org/node/450736.

You can also create block and activate ajax for better functionality. Show more/load more modules implements this sort of functionality. You can follow that.

---
Tags: 7, views
---


# Question
Title: Is there a way to use wildcards in block restrictions first?
I know that for restricting blocks to only certain pages you can do a path such as: blog/\*

I'd like to know if anyone knows a way to do a path such as: \*/blog

Basically, due to views not being able to use contextual links as the first URL argument (www.example.com/%/events is not a valid URL but www.example.com/events/% is) - I would like to be able to have an * first since I plan on having multiple contextual views that would have different first terms, but the same second term. It would just allow me to write one line of restrictions vs. a line or 5 for each view.

Anyone know if this is possible in a Drupal 7 environment?

Thanks!

# Answer
> 1 votes
You can use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on those pages that have a path **ending with** "`/blog`").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_blog_pages" : {
    "LABEL" : "Show block on selected blog pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "\/blog",
          "operation" : "ends"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

---
Tags: 7, views, blocks, path-aliases
---


# Question
Title: No release history was found for the requested project
When I try to download registry\_autoload via `drush dl registry_autoload` I get this error:

> No release history was found for the requested project

Is this an issue with the module's .info file, or something I'm doing wrong? How can I get this module using Drush, and if that is impossible can I just download and install the latest release? I don't want to install it if there's an error with the code.

# Answer
> 1 votes
According to release updates.drupal.org, the module has release candidates for Drupal 7.x as per:

So try the following suggestions:

* Make sure your IP is not blocked by going to https://updates.drupal.org/
* Make sure your Drush recognise your Drupal root as 7.x (check `drush status`) and whether Drush can access the above endpoint by:

```
drush ev 'echo file_get_contents("https://updates.drupal.org/release-history/registry_autoload/7.x");

```

There could be a case that you are behind the firewall or corporate proxy, therefore the certificate could be not valid, so you'll have to configure your PHP's `curl` library either by importing the right certificate and mark it as trusted, ignoring it (not recommended) or use the non-secured connection to check for the new releases.

---
Tags: 7, drush
---


# Question
Title: What's the best practice to show a node's fields in different regions?
In D7 we used to create a view for nodes, with each field having an own display. Each display creates a block to place in any region of the site. But of course, Views are SQL-heavy.

Now, Drupal 8 is all fancy. What's the Drupal 8 way of showing a node's fields in different regions of the page?

Edit: my current attempt is to create a custom module which provides a block for each specified field.

# Answer
Not exactly sure why you want to have every single field as a separate block? That's pretty inefficient, if nothing else.

To have one or two additional blocks, you can use an Entity view block provided by ctools module. It will take the current node and display it in a certain view mode. Of course that will be painful to maintain if every field is separate, but I don't really see why you would want to do that?
> 4 votes

# Answer
Ctools in D8 comes with an experimental module called **Chaos tools blocks** that will let you do this in any page manager variant layout.

This is very useful if you are creating a node variant to display a content type.

After you enable it you can add any field from the node being viewed. You will see a full list of the fields available under "Content" when you click on add block.

The downside, the module is experimental and there is not much documentation available.

Here is an active thread about it https://www.drupal.org/node/2809213

Module page https://www.drupal.org/project/ctools

I've tried it myself and it works just fine.

Hope this helps you or anybody looking for a solution for this kind of scenario.
> 4 votes

# Answer
> Whats best practice to show a node's fields in different regions in Drupal 8?

I think, there is no best practice for that, maybe not even a good practice, but its not impossible to do, follow a couple of options

For me this is best option: You can create a block that load current node and show your desired node\_field. This way, and you can manage via UI easily (Your block with 'node\_type' select and 'field\_name' select is easy and fast to do that).

---

**Begin Edit 1**
Here my implementation of that block, test and please comment the results

```
<?php
/**
 * @file
 * Contains \Drupal\ module_name\Plugin\Block\NodeFieldBlock.
 */

namespace Drupal\module_name\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\field\Entity\FieldConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Provides a Filter by vocabulary terms block.
 *
 * @Block(
 *   id = "node_field_block",
 *   admin_label = @Translation("Node Field")
 * )
 */
class NodeFieldBlock extends BlockBase implements ContainerFactoryPluginInterface {
  /**
   * The Entity Type Manager.
   *
   * @var Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The Entity Field Manager.
   *
   * @var Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The Entity Display Repository.
   *
   * @var Drupal\Core\Entity\EntityDisplayRepository
   */
  protected $entityDisplayRepository;

  /**
   * Dependency injection through the constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_type_manager
   *   The Entity Type Manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The Entity Field Manager.
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
   *   The Entity Display Repository.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition,
  EntityTypeManagerInterface $entity_type_manager,
  EntityFieldManagerInterface $entity_field_manager,
  EntityDisplayRepositoryInterface $entity_display_repository) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->entityDisplayRepository = $entity_display_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('entity_field.manager'),
      $container->get('entity_display.repository')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return array(
      'node_type' => array_keys(node_type_get_names())[0],
      'view_mode' => 'default',
      'field' => '',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $types = node_type_get_names();
    $config = $this->configuration;
    if ($node_type = $form_state->getValue(array('settings', 'node_type'))) {
      $config['node_type'] = $node_type;
    }

    $form['node_type'] = array(
      '#title' => $this->t('Content type'),
      '#type' => 'select',
      '#options' => $types,
      '#default_value' => $config['node_type'],
      '#ajax' => array(
        'callback' => array(get_class($this), 'updateFieldList'),
        'wrapper' => 'edit-node-wrapper',
      ),
    );

    $form['options'] = array(
      '#type' => 'container',
      '#prefix' => '<div id="edit-node-wrapper">',
      '#suffix' => '</div>',
    );

    $form['options']['view_mode'] = array(
      '#title' => $this->t('View mode'),
      '#type' => 'select',
      '#multiple' => FALSE,
      '#options' => $this->getViewModes($config['node_type']),
      '#default_value' => $config['view_mode'],
    );

    $form['options']['field_list'] = array(
      '#title' => $this->t('Field list'),
      '#type' => 'select',
      '#multiple' => FALSE,
      '#options' =>  $this->getFieldList($config['node_type']),
      '#default_value' => $config['field'],
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['node_type'] = $form_state->getValue('node_type');
    $this->configuration['view_mode'] = $form_state->getValue(array('options', 'view_mode'));
    $this->configuration['field'] = $form_state->getValue(array('options', 'field_list'));
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->configuration;
    $build = array();
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      if ($config['node_type'] == $node->getType()) {
        if ($field = $node->get($config['field'])) {
          $build['field'] = $field->view($config['view_mode']);
        }
      }
    }
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
    } else {
      return parent::getCacheTags();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
  }

  /**
  * Função que cria uma lista de fields de um node type.
  *
  * @param string $node_type
  *   O id do node type.
  * @return array
  *   Retorna a lista de campos do node type.
  */
  protected function getFieldList($node_type) {
    if (!empty($node_type)) {
      $list = $this->entityFieldManager->getFieldDefinitions('node', $node_type);
      foreach ($list as $id => $field) {
        if ($field instanceof FieldConfig) {
          $list[$id] = $field->label();
        } else {
          unset($list[$id]);
        }
      }
      return $list;
    }
    return array();
  }

  /**
  * Função que cria uma lista de view modes de um node type.
  *
  * @param string $node_type
  *   O id do node type.
  * @return array
  *   Retorna a lista de view mode do node type.
  */
  protected function getViewModes($node_type) {
    return $this->entityDisplayRepository->getViewModeOptionsByBundle('node', $node_type);
  }

  /**
   * Handles switching the node type selector.
   */
  public static function updateFieldList(&$form, FormStateInterface &$form_state, Request $request) {
    return $form['settings']['options'];
  }
}

```

**End Edit 1**

---

Or... get your field in `preprocess_region` and load in a var (this is easy to demonstrate).

```
function THEME_preprocess_region(&$variables) {
  //TODO: change for you region name
  if ($variables['region'] == 'sidebar_right') {
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      //TODO: change for you node type
      if ($node->getType() == 'article') {
        //If you need a flag for this type
        $variables['is_article'] = TRUE;
        //Here is your field
        $variables['node_field'] = $node->get('field_descricao')->view();
      }
    }
  }
}

```

And use in your twig file

```
{% if node_field %}
  {{ node_field }}
{% endif %}

```

**CAUTION:**
In the future you can't remove this field, if you remove, will break your page. Explanation: `$node->get('field_descricao')` will evaluate no null then `null->view()` = broke page. Even you take care of this, someone or even you can forget about this and will be a headache why that information not show anymore.
> 3 votes

# Answer
> for instance, we have a field "sidebar" for nodes. of course, that field's content should be rendered outside of the normal "content", in a different region. \- Alex 18 hours ago

Instead of using the theme's layout and side bar region, you could use the one of the following modules and create a panel or display suite layout with a side bar region. Then you can insert the node fields and other blocks you need on the sidebar and on other regions that you create.

### Panels

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

### Display Suite

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files.
> 1 votes

# Answer
The Field Block module does pretty much what you are asking. It enables any field in any entity type / bundle to be displayed as a block in the region of your liking.
> 1 votes

# Answer
If you want to use Quick Edit feature you may create and use different View Modes via UI (under Structure/Display Modes/View Modes). I.e. you are not limited to only, say, Teaser and Full view modes. And you may use your custom view modes in Views as well. And content rendered in such a way will have all the required contextual links.
> 0 votes

# Answer
In Drupal 7 I used to do exactly the same as Alex: Create views to place content in blocks. I found this thread looking for a way to make QuickEdit work.
Display Suite and ViewModes seems to be the answer.

This seems like the cleanest way to me: Using the Drupal 8 version of Display Suite, you can add fields from nodes to blocks.
Full instructions are on https://www.drupal.org/node/2754967. This method saves creating a bunch of views, and allows inline editing.
> -1 votes

---
Tags: views, 8, blocks, entities
---


# Question
Title: WYSIWYG editor on Paragraphs text field?
How do I enable the WYSIWYG editor on a paragraphs text field in Drupal 8?

Currently, adding a text field (of any type) displays a single line input box. I'd like this field to be at least a multi line textarea, with preferably, a WYSIWYG editor. Is there a setting or module I can use to change this ?

EDIT: I should add that the editor works fine in a field on a content type or block. It does not load for any text type in a paragraphs field.

# Answer
If you want to have a multi line textarea with an WYSIWYG editor, you'll have to create, for your paragraph type, a field of type "Text (formatted, long)" and while editing your field, you should choose "Full HTML" as "Text format". Hope this works for you.
> 1 votes

# Answer
The field type needs to be "Textarea (formatted, long) with summary" when creating the paragraph type.
> 0 votes

---
Tags: entities, paragraphs
---


# Question
Title: How do I save session data for the anonymous users?
In my last project for Drupal 6, I did save the data using code similar to the following one:

```
$_SESSION['xxx'] = serialize($data);

```

In Drupal 7, it doesn't work.

How should I save the session data for the anonymous users, in Drupal 7?

# Answer
> 4 votes
It because drupal save session with key, this mean you should do something like

```
  $_SESSION['yourkey']['xxx'] = serialize($data);

```

You can try this.

```
function lists_session($key, $value = NULL) {
  global $user;

  static $storage;

  // If the user is anonymous, force a session start.
  if(!user->uid) {
    drupal_session_start();
  }

  if ($value) {
    $storage[$key] = $value;
    $_SESSION['lists'][$key] = $value;   // I use 'lists' in case some other module uses 'type' in $_SESSION
  }
  else if (empty($storage[$key]) && isset($_SESSION['lists'][$key])) {
    $storage[$key] = $_SESSION['lists'][$key];
  }
  return $storage[$key];
}

```

So, to save a variable in Session:

```
lists_session("xxx", serialize($data));

```

And to retrieve the value, just use:

```
$myVar = lists_session("xxx");

```

and aslo as MOLOT mentions sometimes session not stareted for anonymous users then you should `drupal_session_start()` manually.

# Answer
> 2 votes
According to the docs, that is all you should need to do.

Which means that there is either a bug, or your pages are being cached for anon users so the session data is not being read. I would check your caching settings in the first instance.

# Answer
> 2 votes
Drupal 7 sometimes does not automatically start sessions for anonymous users. To use sessions for them, you may need to force session started with drupal\_session\_start to be able to use `$_SESSION`.

# Answer
> 1 votes
After you saving data by following:

```
$_SESSION['xxx'] = serialize($data);

```

Need another function:

```
drupal_session_start();

```

Due to the Session table needs a record with id=0, you could manually insert a record with id=0.

# Answer
> 0 votes
create a user with uid=0 in users table because drupal always uses that uid for anonymous users

---
Tags: 7, sessions
---


# Question
Title: How can I disable specific layouts provided by contrib modules via the layout API?
For example, the Bootstrap Kit module provides many layouts that I'm not using. Is it possible to only enable the specific layouts that my theme needs?

# Answer
> 1 votes
Kind-of. With IPE you could use the patch in https://www.drupal.org/node/2849219.

---
Tags: theming, 8
---


# Question
Title: Migrate row data into text formatted long multiple
I would like to import 3 different row values into a multiple text formatted long field.

This is my migrate (plus) map yml:

```
  ...
  field_mytext_formmated:
    plugin: get
    source:
    - dataValueA
    - dataValueB
    - dataValueC
  ...

```

The data is being migrated but the main problem is that the format property is not being filled so the HTML content is not interpreted. I don't figure out how to set the format to full\_html for all fields.

I've seen that for just one field I should use something like:

```
'body/value': example_matched_field

```

https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/migrate-process-overview

But it doesn't seem to work with multiple values.

Thanks!

# Answer
There is a plugin named iterator which allows iterate a list of associative fields to a compound field. Example: `field_formatted:
 plugin: iterator
 source:
 - fieldA
 - fieldB
 process:
 value: value
 format:
 plugin: default_value
 default_value: 'full_html'`

In this case the fields should have this structure `[
 'fieldA' => [
 'value' => 'Chicken',
 ],
 ]`

Can you fields you adapt your source fields to use iterator plugin in this way?
> 0 votes

---
Tags: 8, entities, migrations
---


title: Adding field input to a field

text:
# Question
Title: Adding field input to a field
I am creating a custom content type with the following fields:

> * Name
> * Offices(can be many)
> * Address(offices address)

Question is, how can I be able to add address field to each office names?

# Answer
> 1 votes
Sounds like you want Paragraphs or Field Collection.

Basically, the idea with these modules is to group two fields (office + address) as a set within an entity and then embed that entity in your content type.

For Drupal 8, Field Collection recommends using Paragraphs, so that's the module I would use. For Drupal , I would use Field Collection.

---
Tags: 8, entities
---


# Question
Title: Module's optional field config not imported on install
I've got a module which contains a `config/optional` folder which has the content:

```
paragraphs.paragraphs_type.my_paragraph_id.yml
field.field.paragraph.my_paragraph_id.field_my_field.yml
field.storage.paragraph.field_my_field.yml
core.entity_form_display.paragraph.my_paragraph_id.yml
core.entity_view_display.paragraph.my_paragraph_id.yml

```

These files have been exported from an existing installation without uuid's. When I enable the module, the config does not import since the module `paragraphs` has not yet been enabled. When I enable `paragraphs` the paragraph type `my_paragraph_id` is created as expected. The field storage for `field_my_field` is also created, since I can create a new field based on the existing field `field_my_field`. Though, the field is not created on the paragraph itself.

I've tried moving the config files to `config/install` and then it simply works as expected; the field gets created on the paragraph just fine. But the module `paragraph` should be optional and only then the config should be created, therefor, I want it to be optional.

Why does the `config/optional` not install the field?

# Answer
> 7 votes
Optional config is only installed if it has an explicit dependency on a module that is being installed right now. Otherwise that configuration would be re-installed every time you install a module, even if it is something you chose to delete on a specific site.

The downside of that is that there are some grey areas of config that depends on config that depends on a module being installed that isn't found by this. Although that *should* also work but apparently does not in this case.

As a workaround, you can add an enforced dependency on the paragraphs module on those configurations that aren't being imported, then it should work. See https://www.drupal.org/node/2404447

---
Tags: 8, configuration, paragraphs
---


# Question
Title: How to use kpr() or dsm() when i am not logged in
I need to access my login form array using kpr() and dsm() functions but it's not working when I logged out from the site. How to debug and access the login form array as logged out.

# Answer
You need to grant the *Access developer information* permission to the anonymous user role.

Be sure to revoke it again before releasing the site, it's an easy way to leak sensitive information.
> 7 votes

---
Tags: users, debugging
---


# Question
Title: What is the difference between KPR() and DSM()
I am learning advanced theming for which I am using *Devel* Module kpr() and dsm() functions to print the arrays on the page for finding variables. So I want to know, What is the main difference between kpr() and dsm() functions? And which one is the best for which condition.

# Answer
In Devel there are various formatters you can use to dump variables. But the main difference of `dsm()` is, that it uses `drupal_set_message()`, which displays the output in the message array via a session, so that the information is preserved between different requests of the same user. This is helpful for debugging code, which doesn't result in a html page to display a normal var dump, for example a form submit. The disadvantage is, that `dsm()` sometimes produces the output asynchron, not when you expect it, which can lead to false conclusions.
> 2 votes

---
Tags: debugging
---