# Question
Title: Passing values in view block to contextual filter on Panelized Node
I have a view set up with a contextual filter for year (select list field). I want to have the ability to have one view and pass the year to the view.

Now I have panelized nodes that I add the views to and I want to pass different years to each view. In Drupal 7 I used to be able to do this with View Panes. Is this not possible in Drupal 8?

# Answer
There is a patch that may add this functonality: How to manually pass an argument to a views block through interface.
> 0 votes

---
Tags: views, 8, panels
---


# Question
Title: Views exposed filter with selected tags/terms
I am importing RSS content with Feeds Module that is tagged with the Atom standard category-tag. I would like to give the user the opportunity to filter the content in a view, but only by some selected tags (as the tags imported are too many and I am not able to assign them to different vocabularies). I tried to achieve it with grouping, but only received empty results. Is it possible to offer filters that only offer some selected tags?

# Answer
I found the answer by myself: Sometimes it is so easy and obvious and you too are blind to see it:

* Choose selection type dropdown
* select terms
* check "Limit list to selected"
> 0 votes

---
Tags: views
---


# Question
Title: Have can I have a view grouped by nested hierarchy?
I have a nested taxonomy as follows:

Some forms will only have the taxonomy of "Basic Forms", some will have taxonomy of "overtime forms", etc. So I want my Forms view to look like this example:

How can I get my view to recognize my nested taxonomy?

EDIT TO ADD: I have made some progress and what I have is repeating the parent taxonomy:

Forms\_IT is the parent term-I'd like to start at the next one but can't seem to figure that part out either.

General & Quincy are on the same level. OT Approval is a subcategory to General but it is not appearing as such and it is repeating the parent and child taxonomy when it lists out the nodes.

This is how I want it:

Any ideas on this? Is it simply a sorting issue?

**7/25 - Edited again to add a pic of my setup and group by.**

# Answer
> 1 votes
* Create a list of all nodes that you want in your Views,
* add the field for their taxonomy terms to show where they belong,
* add the Parent relatinship for your taxonomy reference field to your Views. You may need to first add the relationship to the taxonomy reference field first, to get the Parent one to show as an option, in which case you'll en up with two relationships, the second one set to use the first one.
* Add the Taxonomy Name field and set it to use the Parent Relationship. This field will show the parent term of the one the node is tagged with
* Under Format use the "Group by field" option and set the first one to the Parent Field, and the second "Group by field" to the (sub-term) regular taxonomy field.

This should get you fairly close, I can't predict OTOMH where the nodes that have been tagged with only the parent taxonomy.

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


title: Calling a public function

text:
# Question
Title: Calling a public function
Over time, I have created some contributed module projects for D7. With D7 EOL not too distant in the future, I need to convert those to D8.

I've just started out doing this, and I've found the OO-style of D8 very different from the procedural style of D7.

For instance, I want to call the public function `getTopics()` that is part of the **Advanced Help** project. It can be found inside a file `src/AdvancedHelpManager.php`, and looks like this:

```
class AdvancedHelpManager extends DefaultPluginManager {
  …

  /**
   * Search the system for all available help topics.
   * @todo check visibility of the method.
   */
  public function getTopics() {
    $ini = $this->parseHelp();
    return $ini['topics'];
  }
  …
}

```

I want to call it from my module, in order to get hold of the list of topics I expect it to return.

So far, I've tried:

```
$foo = new AdvancedHelpManager();
$bar = $foo->getTopics();

```

but this returns the error "Error: Class 'AdvancedHelpManager' not found.

I guess I need to put some sort of "use"-statement on top of the file I try to use it, to make the class visible, but I am currently unable to figure out what that statement should be.

# Answer
> 1 votes
Your current code doesn't work because of namespaces, but even so, that's not the right way to approach your requirement.

`AdvancedHelpManager` is a plugin manager, which is a service, so you should get the instance of it like so:

```
$plugin_manager = \Drupal::service('plugin.manager.advanced_help');
$topics = $plugin_manager->getTopics();

```

(as always, if you're in a context where DI is available, inject the service instead of calling the static `\Drupal` method).

If any of this doesn't make sense it would be a very good idea to read the Services and dependency injection docs, which help to explain the architecture behind Drupal 8.

---
Tags: 8
---


# Question
Title: how to get the bid ( id from multi-instances of block )?
is it possible to get and render the bid from a plugin block class build method ?

```
class HalPublicationBlock extends BlockBase implements BlockPluginInterface
{

  /**
   * {@inheritdoc}
   */
  public function build()
  {
        //do contain id but not bid
        $config = $this->getConfiguration();
        //$bid=$this->get->?

```

EDIT : i'd like to pass the bid (or values that will be used by drupal as block css indentifier) to JS object and or twig templates , along with the same bloc instance configuration values

# Answer
> 2 votes
You receive the block id via a form value in the blockSubmit function, so if you save it as configuration, you can use it in the build() function. Seems a bit weird to save the block id as another config value, but otherwise you can't access it. Also note that it is possible to use a block plugin without an actual block entity, see https://drupal.stackexchange.com/a/181458/11500

```
/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $block_id = $form['id']['#default_value'];
  $this->configuration['block_class'] = $block_id;
}

```

You should probably add it to the BlockBase::defaultConfiguration() function as well. Because this changes the configuration, you will have to save the blocks manually once (to activate the change).

# Answer
> 0 votes
A reliable way to get the entity object (block in this case) attached to a plugin form is from the form\_state object.

```
$formObject = $form_state->getFormObject()

```

This will return an instance of a FormInterface. From there you can get the entity object:

```
/** @var \Drupal\block\BlockInterface $block */
$block = $formObject->getEntity();

```

So if you have a Block Plugin with a block instance tied to it you can use the approach above to get the instance of the $block entity.

The good thing about this is you can use it in any of the functions that utilize the FormStateInterface object (functions like blockForm,blockSubmit, etc..)

So, to put it all together:

```
public function defaultConfiguration() {
     return ['block_id' => NULL] + parent::defaultConfiguration();
}

public function blockForm($form, FormStateInterface $form_state) {

    $block = $form_state->getFormObject()->getEntity();
    if (empty($config['block_id'])) {
        $this->setConfigurationValue('machine_name', $block->id());
    }
}

public function build(){
  $config = $this->getConfiguration();
  $bid = $config['block_id'];

  // Put code here to build your render array with the necessary information.
}

```

Please use the necessary precautions to account for null values. Block plugins don't necessarily have a block instance attached to them.

---
Tags: 8, blocks
---


# Question
Title: `drush uli` generates correct link but results in 'Access Denied'
I have set up a *Drush* alias for my website (hosted on a shared hosting), the alias works correctly, because commands like `drush status`, `drush cc all`, etc. work. The problem comes with `drush uli`. It generates the one-time login link, the domain is correct, everything looks all right, but when entered into a browser, it results in *standard* Drupal

> Access Denied

page.

*Part of setting up the alias and some interesting issues around `path-alias`-es, relations to database settings, it's usage and relevancy the aliases is originally discussed in Drush issues page on GitHub.*

Technical information:

* This is a clean Drupal 7 installation, without contrib modules.
* I can log in using password (even using password set via `drush upwd` using the same alias).
* I have checked all possible sources (like truncating `sessions` table, etc.) discussed in similar but yet different issue on StackExchange.
* I have tried different browsers and cleared browser caches and cookies as suggested in various similar discussions on Drupal.org, all without luck.

---

Drush alias:

```
$aliases['myalias'] = array(
  'uri' => 'mysite.com',
  'root' => '/home/mysite.com/web',
  'path-aliases' => array(
    '%drush' => '/home/.composer/vendor/drush/drush',
   ),
  '%files' => '/home/mysite.com/web/sites/mysite.com/files',
);

```

The alias works correctly for other commands like clearing caches and `drush status` confirms that Drupal is bootstrapped correctly.

# Answer
> 2 votes
I'm not exactly sure why the `drush uli` gets to *Access Denied*. I suspect it's something with validation/generation of the one time links and/or incorrect timestamp in the *users* table.

The solution was deleting the password in the database. (Changing it via `drush upwd` or directly in Drupal didn't work.) After deleting the user's password I was able to run `drush uli`.

# Answer
> 16 votes
This can happen when the user is blocked. Setting the status to 1 in the Users table may resolve it.

# Answer
> 5 votes
Just ran across this in a local dev setup.. turned out to be the `$cookie_domain` setting that was committed in `settings.php`... if this is set to the production URL, you will *not* get a valid cookie, and therefore access will never be granted. Overriding `$cookie_domain` to match the local dev environment in `local-settings.php` did the trick!

# Answer
> 3 votes
Also check the flood table. Its possible there are records that are failed attempts by IP address that are blocking access.

---
Tags: 7, drush
---


# Question
Title: How to get nid and title from a node array
```
use Drupal\node\Entity\Node;

function abc($v) {
  $node = \Drupal\node\Entity\Node::load($v);
  print_r($node);
}

```

The array structure of $node is as given below

> ```
> Drupal\node\Entity\Node Object (
> [in_preview] =>
>
> [values:protected] => Array
>     (
>
>
>    [nid] => Array
>         (
>             [x-default] => 166
>         )
>
>     [vid] => Array
>         (
>             [x-default] => 180
>         )
>
>     [type] => Array
>         (
>             [x-default] => sections
>         )
>
>     [uuid] => Array
>         (
>             [x-default] => 7759efc9-cfff-4d58-b392-8d60b9903323
>         )
>
>     [langcode] => Array
>         (
>             [x-default] => en
>         )
>
> ```

# Answer
As mentioned in the comment of @Hudri `Node` is an object not an array.

In Drupal 8 there are two ways to get the value of a field.

1. `$node->field_name->value`
2. `$node->get("field_name")->getValue()`

In your case you can get the `nid` and `title` like below:

```
$nid = $node->id();
$title = $node->label();

```

or

```
$title = $node->getTitle();

```

To read about objected-oriented programming conventions In Drupal 8 check this blog article: Drupal 8 API: objected-oriented programming conventions.
> 7 votes

# Answer
you can get the node id like this :

```
$nid = $node->id();

```

and for the title :

```
$title = $node->label();

```
> 2 votes

# Answer
You can get the node id and node title values by using Node::load function.

use Drupal\node\Entity\Node;

function abc($v) {

```
$node = Node::load($v);

$strNodeId =  $node->nid->value;

$strNodeTitle = $node->title->value;

echo 'Id: '.$strNodeId;

echo 'Title: '.$strNodeTitle;
exit();

```

}
> 0 votes

# Answer
For Drupal 8 media items (e.g. Remote Video), use `getName()`
> 0 votes

---
Tags: 8, nodes
---


title: Looking for core Drupal table DDLs

text:
# Question
Title: Looking for core Drupal table DDLs
My Drupal 7 installation has a handful of tables that have been corrupted. Attempts to repair them have not been successful so my best chance of being able to move forward is to recreate them.

I have not been able to find the DDLs for the tables that are corrupt so my question is, where might I find the DDLs for the core Drupal tables so I may recreate them?

The 2 tables that seem to be giving me the most grief because they are not available are `field_data_field_files` and `field_revision_field_files`.

# Answer
> 2 votes
Those tables are generated dynamically by the field API, and as such don't have a pre-built DDL. This is essentially because fields can be added through the UI/programmatically after installation. Rather than keeping a monolithic registry of those fields and values, the architectural decision was made to split them out into dynamically-created tables with a conventional structure.

If you have corrupt field tables it's a bit...awkward. Drupal will already think the field exists because it'll still be listed in `field_config` and `field_config_instance`, so trying to add it again with the API/UI isn't going to work unless you also prune those records.

Those records may also be referenced elsewhere (possibly in serialised PHP strings, no less), and there's no referential integrity of any sort here anyway, so you'd have to be able to work out what types of referenced record you could have, be able to identify them all, and nuke them. Not exactly easy.

The easiest approach will probably be a bit of a hack job; get the DDL of another field table, and twist it to match the table you've lost:

```
mysqldump -d -uroot -p <dbname> field_data_body

```

Give us

```
DROP TABLE IF EXISTS `field_data_body`;
CREATE TABLE `field_data_body` (
  `entity_type` varchar(128) NOT NULL DEFAULT '' COMMENT 'The entity type this data is attached to',
  `bundle` varchar(128) NOT NULL DEFAULT '' COMMENT 'The field instance bundle to which this row belongs, used when deleting a field instance',
  `deleted` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'A boolean indicating whether this data item has been deleted',
  `entity_id` int(10) unsigned NOT NULL COMMENT 'The entity id this data is attached to',
  `revision_id` int(10) unsigned DEFAULT NULL COMMENT 'The entity revision id this data is attached to, or NULL if the entity type is not versioned',
  `language` varchar(32) NOT NULL DEFAULT '' COMMENT 'The language for this data item.',
  `delta` int(10) unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields',
  `body_value` longtext DEFAULT NULL,
  `body_summary` longtext DEFAULT NULL,
  `body_format` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`entity_type`,`entity_id`,`deleted`,`delta`,`language`),
  KEY `entity_type` (`entity_type`),
  KEY `bundle` (`bundle`),
  KEY `deleted` (`deleted`),
  KEY `entity_id` (`entity_id`),
  KEY `revision_id` (`revision_id`),
  KEY `language` (`language`),
  KEY `body_format` (`body_format`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Data storage for field 7 (body)';

```

Replace the table name and comment. Remove `body_value`, `body_summary`, and `body_format` columns, and the `body_format` index. These are specific to the body field type, the rest is boilerplate and common to all field types.

It seems likely your field type was a file reference, so you need to find the columns for that field type's schema. These are in `file_field_schema()`; mix these into your edited DDL:

```
`field_files_fid` INT(10) unsigned NOT NULL,
`field_files_display` TINYINT(3) unsigned NOT NULL DEFAULT 1,
`field_files_description` TEXT DEFAULT NULL

```

(add comments if you wish)

And an index for the file ID:

```
KEY `field_files_fid` (`field_files_fid`)

```

Repeat for the revision table (using `field_revision_body` as a starting point), and you should have your table structure back in place. At this point it would be a good idea to restore the data to these tables from a backup, as they reference entities in the `file_managed` table (and can have references elsewhere throughout the system).

---
Tags: 7, database
---


# Question
Title: Error when viewing list of taxonomy terms
I'm getting an "unexpected error" when I try to view a list of taxonomy terms. I recently updated to 8.7, though I have a feeling the problem has been around since before the update. Here's the error as it appears in watchdog:

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AS expression FROM tfr INNER JOIN tr ON tfr. = tr. AND tr. = 0 INNER JOIN (S' at line 1: SELECT tfr.tid AS tid, MAX(tfr.) AS expression FROM {} tfr INNER JOIN {} tr ON tfr. = tr. AND tr. = 0 INNER JOIN (SELECT t.tid AS tid, t.langcode AS langcode, MAX(t.) AS expression FROM {} t WHERE t. = :db\_condition\_placeholder\_0 GROUP BY t.tid, t.langcode) mr ON tfr. = mr. AND tfr.langcode = mr.langcode GROUP BY tfr.tid; Array ( \[:db\_condition\_placeholder\_0\] =\> 1 ) in Drupal\taxonomy\TermStorage-\>getTermIdsWithPendingRevisions() (line 404 of /Applications/MAMP/htdocs/libnews/core/modules/taxonomy/src/TermStorage.php).

And I don't know if this related, but I am also getting an error when I try to update my database via drush:

> Error: Call to a member function getKey() on null in system\_update\_8702() (line 2278 of /Applications/MAMP/htdocs/libnews/core/modules/system/system.install) #0

This is outside my area of expertise, so I'm pretty stumped.

# Answer
> 2 votes
I got a similar error on my server too. I had to change the function in TermStorage.php to get it to work.

Just a warning, this core hack and should be reverted once it is fixed in core. Replace getTermIdsWithPendingRevisions() with the following:

```
  public function getTermIdsWithPendingRevisions() {
$table_mapping = $this->getTableMapping();
$id_field = $table_mapping->getColumnNames($this->entityType->getKey('id'))['value'];
$revision_field = $table_mapping->getColumnNames($this->entityType->getKey('revision'))['value'];
$rta_field = $table_mapping->getColumnNames($this->entityType->getKey('revision_translation_affected'))['value'];
$langcode_field = $table_mapping->getColumnNames($this->entityType->getKey('langcode'))['value'];
$revision_default_field = $table_mapping->getColumnNames($this->entityType->getRevisionMetadataKey('revision_default'))['value'];

$query = $this->database->select($this->getRevisionDataTable(), 'tfr');
$query->fields('tfr', [$id_field]);
$query->addExpression("MAX(tfr.$revision_field)", $revision_field);

$query->join($this->getRevisionTable(), 'tr', "tfr.$revision_field = tr.$revision_field AND tr.$revision_default_field = 0");

$inner_select = $this->database->select($this->getRevisionDataTable(), 't');
$inner_select->condition("t.$rta_field", '1');
$inner_select->fields('t', [$id_field, $langcode_field]);
$inner_select->addExpression("MAX(t.$revision_field)", $revision_field);
$inner_select
  ->groupBy("t.$id_field")
  ->groupBy("t.$langcode_field");

$query->join($inner_select, 'mr', "tfr.$revision_field = mr.$revision_field AND tfr.$langcode_field = mr.$langcode_field");

$query->groupBy("tfr.$id_field");
return 0;
//return $query->execute()->fetchAllKeyed(1, 0);

```

}

# Answer
> 0 votes
I have Drupal core version 8.7.2 and `drush updb -y` fixed the error:

> taxonomy module : Update taxonomy terms to be revisionable. Remove the 'hierarchy' property from vocabularies.

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


# Question
Title: View that filters content based on current page
I'm in the middle of a Drupal 6 to 8 migration and am attempting to recreate a view. This view would appear on pages of the content type "People" and would show the "Publications" that this person is associated with. The "Publications" has a field of type "Entity reference" that references each of the "People" titles.

How do I configure the view block to only show Publications that have the entity reference of the current "People" page? I figure this has something to deal with contextual filters, but I'm a bit lost on how to filter this correctly.

Thank you in advance.

# Answer
Recreating Drupal 6 Views in Drupal 8 should be quite straightforward. What got you confused?

You need to create a list of all "Child" nodes (Publications) and add the Contextual filter for the Entity reference field that references the "parent". Configure that filter to use the "**Provide default value**", "**Content ID from URL**". Adjust all the other options in the filter to your specific needs.

When you add the Block to a region in your theme you also have to set the option again (in the Block settings) for the Contextual filter to use the Content ID from URL.
> 0 votes

---
Tags: views
---


# Question
Title: How to add multiple values to file/image fields while creating node programmatically?
I have multiple images coming dynamically in array. But while adding those images to node only last file get attached in field and other images only saved in file directory. I have tried everything but didn't find any solution. Please help. Please review the code and suggest me the solution.

```
$node = Node::create(['type' => 'my_contentType']);
$node->set('title', $item['name']);
$node->set('field_author_name', $item['author']);
foreach ($FilePaths_keys as $path){
$digitalFile_path = $item['bitstreams'][$path] ['retrieveLink'];
$get_data_contents = file_get_contents($digitalFile_path);
$file = file_save_data($get_data_contents, 'public://'.$item['bitstreams'][$path]['name'], FILE_EXISTS_REPLACE);
$Dfiles = [
        'target_id' => $file->id(),
        'alt' => $item['bitstreams'][$path]['name'],
        'title' => $item['bitstreams'][$path]['name']
      ];
$node->set('field_book_image', $Dfiles);
}
$node->enforceIsNew();
$node->save();

```

Running this code will save all images in directory but only last image got attached with node. How all the images get attach in "field\_book\_image" unlimited field.

# Answer
> 3 votes
Just change your code:

```
$Dfiles = [];
foreach ($FilePaths_keys as $path){
  ....
  $Dfiles[] = [
        'target_id' => $file->id(),
        'alt' => $item['bitstreams'][$path]['name'],
        'title' => $item['bitstreams'][$path]['name']
      ];
}
$node->set('field_book_image', $Dfiles);
$node->enforceIsNew();
$node->save();

```

---
Tags: 8, nodes, media
---


# Question
Title: How do I render a form from a controller?
Render form in Drupal 8.

**In modulename.routing.yml**

modulename.fp:

```
path: '/formpage'

defaults:

_controller: '\Drupal\modulename\Controller\*Controller::formpage'

```

**Write code in controller.php**

public function formpage() {

```
$form = '';

$form = 'Form Title';

$form .= \Drupal::formBuilder()->getForm('\Drupal\modulename\Form\fp');

return [

  '#type' => 'markup',

  '#markup' => $form,

];

```

}

and write form code in modules\modulename\src\Form\fp.php.

but showing **Form Title** Array

how to render form.

# Answer
> 2 votes
First of all why use a \_controller if all you need to do is print a form? Instead it should have \_form something like this: Drupal\example\Form\DefaultForm in the routing definition.

Here is a simple guide on how to create a form in drupal 8 https://www.valuebound.com/resources/blog/step-by-step-method-to-create-a-custom-form-in-drupal-8

And if you really want to embed a form in a controller response check this out How do I embed a form in a controller response?

---
Tags: forms
---


title: Create form via a controller

text:
# Question
Title: Create form via a controller
I have a template in which I've manually built a form. It renders some variables that come from a controller.

I've looked over the Form API and I think I should build the form using that. But I'm not quite sure how to go about it.

I'm relatively new to Drupal 8 and to be perfectly honest the Documentation is good, if one knows what to look for. It's not the case here.

Basically what I'm asking, is it possible(or rather advised) to somehow grab the form in the controller, and instead of passing the variables to the template, simply pass the created form to the template?

I'm assuming it would be better to do that, although I'm note quite sure that's the case.

# Answer
> 2 votes
This is definitely possible (and preferable). There are a few ways to do this, but I think the preferred approach is to first specify your form in your routing entry (`mymodule.routing.yml`)

```
mymodule.some.route:
  path: '/foo/bar'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
    _title: 'My form title'

```

The routing system will automatically build your form for you. The class `\Drupal\mymodule\Form\MyForm` should implement `FormInterface`. An easy starting point is to extend `\Drupal\Core\Form\FormBase`.

There are several examples of this in core. For instance, the `entity.user.admin` and `user.admin_permissions` routes in `users.routing.yml`.

# Answer
> 0 votes
Too late but incase someone stumbles across this:-

Here is a simple guide on how to create a form in drupal 8 https://www.valuebound.com/resources/blog/step-by-step-method-to-create-a-custom-form-in-drupal-8

And if you want to embed a form in controller check this out:- How do I embed a form in a controller response?

To theme your form. You need to implement hook\_theme() in your .module file to define a new theme implementation. Something like this:-

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

       //Your code
       $form['#theme'] = 'a_b_c';

       return $form;
}

```

And then in your .module file attach

```
function example_theme() {
  return [
    'a_b_c' => [
      'render element' => 'form', // here 'form' is a variable name and can be anything you want.
    ],
  ];
}

```

And then you can print your variables in templates/a\_b\_c.html.twig something like:

```
{{ form.name }} //if name is your form element.

```

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


# Question
Title: How to change the field label in an API response
How to change `field_canonicalurl` to `canonicalUrl` and `field_teaser` to `Teaser`?

Below is my API output from my View:

```
[{"field_canonicalurl":"","title":"This is the title ","field_teaser":"\u003Cp\u003EIn this is the teaser \n" }]

```

# Answer
Go to field settings of the Rest export view, add Alias for each field, Save. That's it. You're done
> 2 votes

---
Tags: views, 8
---


# Question
Title: How can I have the language-specific 'enabled' Boolean of menu items being respected?
I'm trying to translate the 'enabled' field of menu items in Drupal 8. So far I have written this code in `MYMODULE.module` file:

```
function MYMODULE_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'menu_link_content' && !empty($fields['enabled'])) {
    $fields['enabled']->setTranslatable(TRUE);
  }
  return $fields;
}

```

This works fine and I am able to set the enabled field differently for different languages. eg: for the same menu item, I can check the 'enabled' field for English, but uncheck the 'enabled' field for French.

But it does not work as expected. It hides the menu item for all languages. Should I use `hook_preprocess()` or `hook_preprocess_menu()` or some other hook for the menu item to show/hide based on 'enabled' field in different languages? Can someone give me some hints on this?

# Answer
> 2 votes
For what you are trying to achieve I found out you can use the Menu Manipulator module. This module initially aimed to fix \[Issue\] Untranslated menu items are displayed in menus.

> ### Notes
>
> This module initially aims to fix this core issue with unstranslated menu items.

---

Having this module installed only menu items that are available in the current language will be displayed. If there's a menu item you don't need in a certain language, remove it or remove its translation.

To make this work properly, ensure that your menu, the menu title and "Show language selector on create and edit pages" is enabled for your menu under https://example.com/admin/config/regional/content-language.

* Having a menu item you want only to be shown on the French site, select French as its language, and don't translate it.
* Having a menu item to be shown only on the English site, select English as its language, and don't translate it.
* Having a menu item to be shown on both sites, add it in one language and simply translate it.

# Answer
> 0 votes
Adding this code in Drupal/core/modules/menu\_link\_content/Plugin/Menu/MenuLinkContent.php made the functionality work exactly as expected. (Menu items were disabled in one language but enabled in another)

```
public function isEnabled() {

        if ($this->languageManager->isMultilingual()) {
          return $this->getEntity()->isEnabled();
        }
        return $this->pluginDefinition['enabled'];
    }

```

But Im not sure of how to extend this class in my custom module and make it visible to drupal.. Any ideas on that?

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


# Question
Title: How can I load comment IDs using the comment type?
I know how to load comment ids for a particular node by following code

```
$entity_manager = \Drupal::entityTypeManager();
$cids = $entity_manager
    ->getStorage('comment')
    ->getQuery('AND')
    ->condition('entity_id', '25364')
    ->condition('entity_type', 'node')
    ->execute();

```

But I need one more condition to add on because this node might have multiple comment type linked. I know the machine name , but I don't know exactly what should be the first parameter to be passed in condition.

# Answer
> 0 votes
I itself got the answer i just guessed the name to be passed in condition.

```
$cids = $entity_manager
    ->getStorage('comment')
    ->getQuery('AND')
    ->condition('entity_id', '25364')
    ->condition('entity_type', 'node')
    ->condition('comment_type' 'post_trp_comments')
    ->execute();

```

---
Tags: 8, comments
---


# Question
Title: Remove node_access check from content revisions view
For the 'content' Views one can simply check tickbox 'Disable access checks' in UI under Advanced =\> Query, and the View returns all the records regardless of the node\_access check.

However, in the 'content revisions' Views this tickbox is not available.

How can I make 'content revisions' Views to bypass the access\_check?

# Answer
> 1 votes
In the `hook_views_query_alter` is possible to alter the query tags. Unfortunately, the method tag\_remove is not present, but the `$tags` variable is public, which allows us to do:

```
function yourmodule_views_query_alter(&$view, &$query) {

    // Disable Node Access check for myview
    if ($view->name == 'myview') {
        $view->query->tags = [];
    }
}

```

I hope this will help somebody who needs unrestricted Views (e.g. for Services).

---
Tags: 7, views
---


# Question
Title: Stop displaying content of subpaths for invalid URLs
I have views set up, with following paths: www.example.com/news www.example.com/projects

If a user goes to www.example.com/projects/not-a-url or www.example.com/news/not/a/real/url it displays the content of /projects or /news accordingly.

Is this a core function? I would prefer it to either 404 or preferably redirect completely.

I have disabled Paths, Pathauto, Redirect, and Global Redirect but it still shows the content for the views when it should be a 404.

# Answer
> 0 votes
This can be achieved through views contextual filter.

As per wesleymusgrove's asnwer on drupal.org support "Under "WHEN THE FILTER VALUE IS NOT IN THE URL", tell it to "Display all results for the specified field". This allowed me to still see the list of all articles at the views path: example.com/articles

And under "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" check "Specify validation criteria", Validator "Content", Content type "Blog post" or "Article" - whatever content type it is. This allowed me to still see a valid post at example.com/articles/my-page, but invalid links like example.com/articles/mypage respond with 404

---
Tags: 7, views
---


# Question
Title: How to add library if Ajax is enabled for view?
We have a view, myview, where Ajax is disabled. We created a custom library that would override the load more button's indicator so that we can use our own. However, we would only like to add this library conditionally if `myviews->Use Ajax->Enabled`, but when it is disabled then do not add the library. I know how to conditionally add the library, but not sure how to check if `myviews->Use Ajax` is set to enabled.

**How can we detect if `myview->Use Ajax->enabled`?**

mytheme.libraries.yml

```
mytheme-custom-indicator:
  version: 1.0
  js:
    /path/to/js/custom-indicator.js: { attributes: { defer: true }}
  dependencies:
    - core/drupal
    - core/drupal.ajax
    - core/jquery

```

custom-indicator.js

```
 /**
   * Infinite scrolling progress indicator.
   *
   * @type {{attach: Drupal.behaviors.progressIndicator.attach}}
   */
  Drupal.behaviors.progressIndicator = {
    attach: function (context, settings) {
      Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
        this.progress.element = $('<div class="myclass"> </div>');
        $('body .pager').after(this.progress.element);
      };
    }
  };

```

**What we tried**

```
/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
}

```

**Goal**

```
/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  if($view->hasAjax) {
    $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
  }
}

```

# Answer
> 3 votes
Found my answer after doing `ksm($view)`

```
/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  if($view->ajaxEnabled()) {
    $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
  }
}

```

---
Tags: views, 8, javascript, ajax
---


# Question
Title: Drupal 8: Multi-sites in subdirectories not working
I followed this tutorial(*Drupal 7*) but it not worked for me(*Drupal 8*):

This is my enviroment:

* CentOs 7 with SELinux(*mode: enforcing*)
* Varnish 4.0.3
* Apache 2.4.23
* Drupal 8.2.4

I need to create the next structure of sites:

* / \<-- First site
* /site2 \<-- Second site
* /site3 \<-- Third site

In the file **sites/sites.php** i have:

```
$sites['localhost.site2'] = 'site2';
$sites['localhost.site3'] = 'site3';

```

In the directory **sites/** i have:

* default/
* site2.localhost
* site3.localhost

In the root of the drupal o have the next symlinks to **.**:

* site2 -\> .
* site3 -\> .

In my **.htaccess** file i have:

```
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} ^/site2/(.*)$
  RewriteRule ^(.*)$ /site2/index.php [L,QSA]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} ^/site3/(.*)$
  RewriteRule ^(.*)$ /site3/index.php [L,QSA]

```

When i tried to access to each subsite, he shows me the default. What is wrong?

# Answer
* Download latest D8 version.
* Extract and navigate into the directory: /drupal/sites/
* Create `sites.php` duplicating `example.sites.php`
* Add the code to sites.php

`$sites = array(
 'dogs.multisite.local' => 'dogs',
 'multisite.local.cats' => 'cats',
 );`
* Create two folders named 'cats' and 'dogs' on the sites folder.

```
/drupal/sites/dogs/
/drupal/sites/cats/

```
* The **/drupal/sites/default**/ site will have default files we need to copy into each of our sites. Copy these files using the cp command in the sites directory:

```
cp default/default.settings.php dogs/settings.php
cp default/default.settings.php cats/settings.php
cp default/default.services.yml dogs/services.yml
cp default/default.services.yml cats/services.yml

```
* Setup virtualhost

**hosts**

```
 127.0.0.1  multisite.local

```

**httpd-vhosts.conf**

```
<VirtualHost *:80>
ServerAdmin webmaster@multisite.local
DocumentRoot "/opt/lampp/htdocs/drupal"
ServerName multisite.local
ServerAlias    *.multisite.local multisite.local.*
ErrorLog "logs/multisite.local-error_log"
CustomLog "logs/multisite.local-access_log" common
</VirtualHost>

```
* Once it is done, you can start the installation of your new website in a multisite context from the urls:

```
   http://dogs.multisite.local/
   http://multisite.local.cats/

```
> 1 votes

# Answer
**I suggest you to use drush**. It will make your life way easier:

```
$ drush site-install --db-url=mysql://db_user:db_password@127.0.0.1/sample_site_db --sites-subdir=sample.subsite.com --yes

```

Please note that drush will generate all the proper config for you. Then you can check how it is actually when you want to go "manual".

And here you have **a full list of steps to setup a Multisite on Drupal 8**: https://evolvingweb.ca/blog/drupal-8-configuration-management-multi-site
> 0 votes

# Answer
If you really want to make your life easy, use Aegir. It does all of this automatically via point and click. From the official Drupal documentation on multisite:

> It should be noted, however, that using the Aegir hosting system is preferred. It does all of the heavy lifting for you using secure best practices including automatically configuring virtual hosts for both Apache and Nginx, adding HTTPS support, running Composer commands, etc. See the documentation for setting up a "platform", Aegir-speak for a multisite codebase.

For your use case, you'll need to enable the (Site) Subdirectories module, which ships with core Aegir.

*No command-line work is necessary at all* as this is all done for you in the back-end.
> 0 votes

---
Tags: 8, multi-sites, .htaccess
---


# Question
Title: How can I programmatically create a media object and a new file and associate the file with the media object?
I am trying to programmatically create a media object and a file, and then associate the file with the media object. The first part works--I can successfully create the media object and file. But the second part fails--the media object has no file associated with it.

Here is my code:

```
//Begin handling file uploads
$file = file_save_data('hey dude', 'public://2019-07/my_example.txt', FILE_EXISTS_REPLACE);

$media_arr = [
  'bundle' => 'file',
  'langcode' => 'en',
  'uid' => '0',
  'name'=> 'Test Name',
  'created' => date('U'),
  'changed' => date('U'),
  'moderation_state' => 'published',
  'file' => [
    'target_id' => $file->id(),
  ],
];

$drupalMedia = Media::create($media_arr);

$drupalMedia->setName('Test Media Object')
  ->setPublished(TRUE)
  ->save();

```

my\_example.txt is created in the files directory, and the media object "Test Media Object" is also created, and I'm able to attach it to a node. But there is no file in the new media object! Am I missing something here?

# Answer
Ah, I always figure it out after I say I can't do it. Once I specified the document type, it worked:

```
$media_arr = [
  'bundle' => 'file',
  'langcode' => 'en',
  'uid' => \Drupal::currentUser()->id(),
  'created' => date('U'),
  'changed' => date('U'),
  'moderation_state' => 'published',
  'field_file_document_type' => 1409, //1409 is the id for pdf
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
];

```

Edit: I should mention that 1409 is the id we use for pdfs, yours will be different. The field\_file\_document\_type just needed to have a value in it to work.
> 1 votes

---
Tags: 8, media
---


# Question
Title: How do I add a view mode to a simple custom entity?
I have created a super-simple drupal 8 custom entity. We now need a custom view mode for this entity. What do I need to add to my definition to make my entity appear as an option on the 'Add View Mode' page: /admin/structure/display-modes/view/add ?

My super-simple entity definition is

```
 * @ContentEntityType(
 *   id = "schedulecal",
 *   label = @Translation("ScheduleCalendar"),
 *   base_table = "scheduler_entity_calendars",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )

```

I can't find this info anywhere in doc.

# Answer
You need a view builder class in the handler section:

```
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",

```

and a field UI route:

```
 *   field_ui_base_route = "my_entity.settings",

```

pointing at the config form for the settings of your entity type. If you don't have settings return at least a #markup element:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['my_entity_settings']['#markup'] = 'Settings form for My Entity entities. Manage field settings here.';
    return $form;
  }

```
> 10 votes

---
Tags: 8, entities
---


# Question
Title: How can I force the user to register/login first before being redirected back to the current URL?
I'm displaying a form using the Form API under a given URL. User gets this URL and accesses it. But before the user fills out the form, they need to be registered or logged in.

How can I send the user to the login page, or present the login form, then subsequently direct them back to the form under the given URL?

This is not a Webform -- I'm using the Form API.

# Answer
Redirect to the login page and provide a destination query parameter to the current route to redirect back after login:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect(
          'user.login',
          [],
          ['query' => ['destination' => Url::fromRoute('<current>')->toString()]]
      );
    }

    // build form

    return $form
  }

```

Don't forget to add a `use Drupal\Core\Url;` statement to the class.
> 5 votes

---
Tags: 8, users, forms
---


# Question
Title: How to add Checkbox Fields to User Accounts?
Is it possible to add multi-choice checkbox fields to a Content Type or the fields of a User Type? Hoping it is possible to create the following when a User is registering for an account. They should be able to choose multiple check boxes when registering.

**Desired output in user registration form:**

```
<input type="checkbox" id="checkbox1" name="checkbox1" value="first-choice">
<label id="checkbox1-label" for="checkbox1">First Choice</label><br>

<input type="checkbox" id="checkbox2" name="checkbox2" value="second-choice">
<label id="checkbox2-label" for="checkbox2">Second Choice</label><br>

<input type="checkbox" id="checkbox3" name="checkbox3" value="third-choice">
<label id="checkbox3-label" for="checkbox3">Thrid Choice</label><br>

```

# Answer
You can add checkbox list from Account Settings

Go to Configuration \>\> People \>\> Account settings - http://example.com/admin/config/people/accounts/fields

Add Field \>\> Add a new field of List(text)

Add options and select options as unlimited (for multiple select)

Save and go to Manage Form display (/admin/config/people/accounts/form-display) change the checkbox widget to checkboxes/radio buttons.

That's it you can see the check boxes in user account form like this
> 2 votes

---
Tags: 8, users
---


# Question
Title: Drupal 7 Views: Display a Taxonomy term as its Term-ID number for a node
I have a View that displays Nodes. Each of the nodes have a taxonomy term applied to it.

I would like this taxonomy term to be display as it's Term-ID number. How can I do this?

---

# Steps I have tried

1. In relationships, I have added "Content: Taxonomy terms on node". This is the only option for taxonomy terms in a node View. But it doesn't have options for accessing the term ID.
2. In fields, you can add a field to display the term on a Node. I have checked "Rewrite the results". There is a token called Raw, but it only displays "Raw Text" as opposed to a number.

# Answer
Here are few things you need.

1. In relationships, add **Content: Taxonomy terms on node**.
2. In Filter Criteria(I think this is the one you are missing), add **Content: has taxonomy term** and check the "**is not empty(NOT NULL)**".
3. In Fields: Add **Taxonomy term: Term ID**

PS: in step 2, you may pick other operator based on what you need.
> 3 votes

# Answer
In the majority of Views you indeed can use relationships (see CocoSkin's answer), but in some Views, like revisions, it doesn't work (you get only the last revision of the field). The best approach in such a case is to create a new field formatter in your private module:

```
/**
 * Implements hook_field_formatter_info().
 */

function yourmodule_field_formatter_info() {
  return array(
    'yourmodule_termid' => array(
      'label' => t('Show TermID'),
      'field types' => array('taxonomy_term_reference'),
    )
  );
}

/**
 * Implements hook_field_formatter_view().
 */

function yourmodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

  if (!in_array($entity_type, array('node', 'field_collection_item'))) {
    return $element;
  }

  switch ($display['type']) {

    case 'yourmodule_termid':

      foreach ($items as $delta => $item) {
        foreach ($item as $key => $val) {
          if ($key == 'tid') {
            $element[] = array(
              '#markup' => $val,
            );
          }
        }
      }

      break;
  }

  return $element;
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Output referenced entity in correct language
The following code outputs referenced entities in the original language they were created.

```
{% for story in node.field_stories %}
  {{ story.entity.label }}
{% endfor %}

```

I want it to render in the current language (translation) instead. How can I achieve this?

# Answer
Do not use the raw field value, use the render array of the field instead:

```
{{ content.field_stories }}

```

This will automatically use the correct language.

NOT RECOMMENDED:
If you have to go the custom, raw value route you can do something like

```
{% for story in node.field_stories %}
  {% if story.entity.hasTranslation('iso2_langcode') %}
    {{ story.entity.getTranslation('iso2_langcode').label }}
  {% else %}
    {# fallback default lang #}
    {{ story.entity.label }}
  {% endif %}
{% endfor %}

```
> 4 votes

---
Tags: nodes, i18n-l10n
---


# Question
Title: How to disable max length validation on an entity form?
How do I disable the #maxlength **validation** on a field I've added to the user entity form?

Let me explain: I want my field to be 10 characters long in the database, so I've set a max length of 10 at the field UI. However, at the form level I want it to have a formatting mask that makes it be 14 characters long.

Even though I could disable its #maxlength property via `hook_form_alter` and get to enter more than 10 characters, the validation for such property is still up when I submit the form.

Since I don't want to remove the mask via JS by the time the form gets submitted, my intention was to to bypass form validation **only for the max length property of this field** (or even for the whole field) and then at a `presave` hook I'd remove the mask and store only the original 10 characters to the database.

Hope I've made it clear.

Thank you.

# Answer
> 1 votes
You didn't give an explanation of your rules for your input, but for an example, imagine that the format of the required value is XXX-XXXXXXXXXX, where X is a numeral, and the hyphen is always at position 4.

1. Change the maxlength on the HTML input to allow more characters. Add your own validation handler to be run before the default validation handlers. Add your own submit handler to be run on submission.

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

function HOOK_form_alter(array $form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'some_form_id') {
    if (isset($form['some_field'])) {
      // Change the HTML max length to 14.
      $form['some_field']['#maxlength'] = 14;

      // Insert a custom validation handler to be run BEFORE
      // the default handlers.
      array_unshift($form['#validate'], 'my_module_FORM_ID_validate');

      // Add your own submit handler to deal with the submitted values:
      $form['actions']['submit']['#submit'][] = 'my_module_FORM_ID_submit';
    }
  }
}

```
2. In the validation handler, parse the value in this handler, replacing the value in the field with the 10-character value, so it can pass validation. Store the other 4 characters in the $form\_state

```
function my_module_FORM_ID_validate(array &$form, FormStateInterface $form_state) {
  if ($value = $form_state->getValue('some_field')) {
    // Check that the submitted value is in the right format, and
    // parse the value into $matches.
    if (preg_match('/(\d{3})-(\d{10})/', $value, $matches)) {
      // Store the 10-digit value in the field, to be passed through
      // default submit handlers.
      $form_state->setValueForElement('some_field', $matches[2));

      // Store the other three digits in the $form_state.
      $form_state->set('some_key', $matches[1]);
    }
    else {
      // The submitted value was not in the correct format.
      $form_state->setError($form['some_field'], t('Some Field must be in the format XXX-XXXXXXXXXX where the Xs are numeric'));
    }
  }

```

}
3. Use the values as necessary in the submit handler.

```
function my_module_FORM_ID_validate(array &$form, FormStateInterface $form_state) {
  $key1 = $form_state->get('some_key');
  $key2 = $form_state->getValue('some_field');
  // Do what you need with these values.
}

```

---
Tags: forms
---


# Question
Title: Pauthauto breaking for one specific page
I have a Drupal 8.7 site with a content type for which I have just activated automatic URLs via pathauto.

We have a number of pages using this content type, and all of them worked perfectly when I activated the alias... except for one, which remained stuck as `/node/9669`.

I investigated this, and it turned out that the content editor who created the page had unticked the 'Generate automatic URL alias' checkbox on this particular page, hence why it didn't pick up the new pathauto alias.

So I thought it would be a simple thing to tick the box and it would work.

I ticked the checkbox and saved the page, but what actually happened is that it now gives me a browser error saying "page isn't redirecting properly" (Firefox) or "too many redirects" (Chrome).

I have tried regenerating the aliases, manually changing the alias, deleting the alias, recreating it... but nothing I do is getting the page back.

My guess is that there's something that's gotten saved in the pathauto database tables for this which is broken, but isn't showing up in the admin panel.

Can anyone please help me understand what's going on under the hood here and fix this alias.

Thank you.

# Answer
> 2 votes
The redirect issue described here is pretty common for sites where the Redirect module (drupal.org/project/redirect) is enabled. The module has a default config setting that creates a redirect anytime the url on the node is edited (this includes through bulk operations such as a pathauto alias generation process).

This setting can lead to the infinite redirect issue when a user changes an alias and then changes it back, resulting in a circular reference/infinite redirect.

I highly recommend disabling this setting for sites under construction (where urls are in flux) and enabling once deployed to production. You can toggle it at /admin/config/search/redirect/settings (it's the very first setting on the page, shown in the partial screenshot below)

For production sites, be wary of changing a url multiple times- check/manage the list of redirects associated with the node on the node edit form as shown below

You can also check/manage redirects from the full list of redirects assigned in Drupal at /admin/config/search/redirect

---
Tags: 8, path-aliases
---


# Question
Title: EntityQuery, query by referenced entity value,
I am getting an empty array when I query by the value of a referenced field.

I have the following:

```
$result = \Drupal::entityQuery('node')
  ->condition('type', 'custom')
  ->condition('status', 1)
  ->condition('field_category.entity:taxonomy_term.name', 'somevalue', '=')
  // ->condition('field_category.%delta', 'somevalue');
  ->execute();

```

Using `->condition('field_category.%delta', 'somevalue');` returns way too many results (nids) than expected.

using `->condition('field_category.entity:taxonomy_term', 'somevalue', '=')`: returns an empty array.

Am I using an incorrect syntax to query by a related field?

# Answer
> 2 votes
As mentioned here it seems like you only need `.entity` like this:

```
->condition('field_category.entity.name', 'somevalue', '=');

```

---
Tags: 8, entities
---


# Question
Title: Load all configuration that has a particular config dependency?
I want to load all entity form display configuration that has a particular, DIRECT, config dependency. I feel like this is something that should be doable with an entity query but I haven't been able to figure it out. Any thoughts on how to go about this?

# Answer
Figured it out. You need to use wildcards and pass an array of potential matching values.

```
$form_displays = \Drupal::entityQuery('entity_form_display')
  ->condition('dependencies.config.*', ['field.field.paragraph.call_to_action.field_cta_text'])
  ->execute();

```
> 3 votes

---
Tags: 8
---


title: Multiple Images from external WEB URL

text:
# Question
Title: Multiple Images from external WEB URL
My problem is simple though multiple solutions touch upon it but none address it directly. Hence posting this question.

1. Problem: I have multiple servlet urls (hosted at external web server) that returns a single image in response stream. My task is to embed images from these (precisely 6) URLs in my drupal site. How can I do that.
2. Attempts: I tried using Media Module, Embedd Media Module, Custom formatters but none worked for me (may be because I'm a beginner). If anyone can help me with some sort of link of steps to achieve this.

# Answer
> -1 votes
I achieved it in a work-around. I am downloading images inside my drupal accessible folders with the fixed names. Updating these images with fixed names using a background script. Applied cache buster techniques so that images with same names are updated.

---
Tags: media
---


# Question
Title: How can I have a second alias for a node to be displayed in a different view mode?
I have nodes whose content type is *X* that I would like to render differently based on the node path. I'd like to use the default view mode for a path alias and a custom view mode for the other path alias. These aliases were created using the Pathauto module; both of them point to the same node.

* /url/alias1/path =\> /node/123 (default view mode)
* /url/alias2/path =\> /node/123 (custom view mode)

I tried using mymodule.routing.yml to do this, but it does not appear to be picked up by the route system.

```
mymodule.program:
  path: '/url/alias2/path'
  defaults:
    _controller: '\Drupal\mymodule\Controller\RoutesController::setViewMode'
  requirements:
    _access: 'TRUE'

```

When I click on the alias with the custom view mode, I get the default view mode. I put a logger statement in the routes controller setViewMode function and it is not reached. This suggests that the routing is not being 'tripped'.

Am I missing something or trying to do something Drupal 8 cannot handle?

I looked at Routing and path aliases but that doesn't quite address my question.

# Answer
There are many approaches in aliasing and routing, but I think splitting the task between both is the most effective:

Add an internal node route for the second view mode:

```
mymodule.custom_node:
  path: '/node_custom/{node}'
  defaults:
    _entity_view: 'node.custom_view_mode'
  requirements:
    _access: 'TRUE'

```

Then change the source path to /node\_custom/123 before Pathauto saves the second alias in `hook_pathauto_alias_alter()`.
> 1 votes

# Answer
The above approach was too complex for the time crunch so I went back to my first solution which was to create a new content type that contains a field that is an entity reference to the 'original' content type that has the information to be rendered. This made it much easier to have the right view mode, title, alias, menu link, etc. I created a cron job that will periodically check to see if new content of the original content type was created and create a content of the new content type with the entity reference pointing to the original. From there I can create a new menu link and pathauto alias.
> 0 votes

# Answer
OK, so you got your node created and added a second alias using Pathauto. Now you can use `hook_entity_view_mode_alter()` to simply switch the view mode depending on the current URL pattern. And the node will be displayed in a different view mode under this URL.

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  if ($entity->getEntityTypeId() === 'node' && $entity->bundle() === 'page') {

    // Get the current URL and cut in parts you can later check more easily.
    $current_uri = \Drupal::request()->getRequestUri(); // '/url/alias1/path'
    $current_uri = ltrim($current_uri, '/'); // 'url/alias1/path'
    $arg = explode('/', $current_uri); // array

    // Check URL to match a certain pattern, and switch the view mode.
    if ($arg[0] === 'url' && $arg[1] === 'alias2' && $arg[2] === 'path') {
      $view_mode = 'teaser';
    }
  }
}

```

You could even automate multiple path alias creation using `hook_entity_insert()` like shown in this answer.
> 0 votes

---
Tags: 8, entities, path-aliases
---


# Question
Title: Same module with different versions in several places
This the directory structure of my drupal 8 installation:

```
├── composer.json
├── composer.lock
├── drush
├── LICENSE
├── load.environment.php
├── phpunit.xml.dist
├── README.md
├── scripts
├── vendor
└── web
    ├── autoload.php
    ├── core
    ├── index.php
    ├── modules
    │   └── custom
    │       └── xyz (version 1.0)
    ├── profiles
    │   └── custom
    │       └── qwer
    │           └── modules
    │               └── custom
    │                   └── xyz (version 1.1)
    ├── robots.txt
    ├── sites
    │   └── example.com
    │       └── modules
    │           └── custom
    │               └── xyz (version 1.2)
    ├── themes
    ├── update.php
    └── web.config

```

Which version of `xyz` module "win" in this structure ? For example: \- A site installed with `qwer` profile (sites/example.com). \- A site installed without `qwer` profile (sites/example.com). \- Another option ?

I would like to know the preference that Drupal has when it have the same module with different versions in several places

# Answer
> 2 votes
If each copy of the module in the directory structure is in fact a different version (***the module's .info file must specify a version number***), you can inspect the version listing either via Drush or on the modules listing (install) page.

**Version Listing from the Modules Listing page**

1. Navigate to /admin/modules
2. Find module "xyz" and expand the description section to reveal which version is being detected/loaded.
3. Refer to the example screenshot below, where Activity Tracker has been expanded.

**Version Listing via Drush**

1. Run 'drush pm-list --no-core --status Enabled' to show a list of all modules other than those included with Drupal Core.
2. Scroll through the list to find your custom module and note the version number in the right column.
3. Refer to example screenshot below.

**What if there are no version numbers, or they are all the same version?**

1. Temporarily modify the version number in the info file.
2. Push the updated code to your server (if not a local copy of the site).
3. Flush Drupal Cache, rebuild the registry.
4. Follow the instructions above to detect which one is used.
5. Reset the version number and push the updated code to your server (if not a local copy of the site).

***Drupal Multisite Note***:

If you are running Drupal Multisite, each site with the custom module enabled may be referencing it from a different path (depending on where the module was located at the time the site was being built).

1. In this situation, check the versions on each site using the instructions above.
2. Find the most updated version being used so that you can consolidate all the other sites to use the same version/instance.

**Consolidating duplicate instances of the module**

Since this is a custom module, **be sure to check that the functionality provided between versions is in fact the same and that there is an upgrade path between them before consolidating**. *Sometimes, lesser experienced developers will copy a custom module and completely overhaul its functionality for use on a similar or different site without understanding best practices.*

1. Backup your code and databases, just in case you need to rollback.
2. Remove older versions/unused copies, ideally keeping/moving your one copy of the module in /web/modules/custom/.
3. Push the updated codebase to your server.
4. Clear caches and rebuild the registry.
5. Run update.php or drush updatedb to ensure any update hooks for the module are applied.
6. Test the functionality the module provides on each site (for some custom modules, you may need to edit/resave the configuration settings for the module to properly function).
7. If all is working, it's recommended to create a new restore point backup; otherwise troubleshoot until you get it working or rollback.

---
Tags: 8
---


# Question
Title: How to keep checkbox checked after form submit
I am trying to keep checkbox "checked" after form submit and page load. I have following simple code from .module file.

```
    <?php

function my_module_menu() {
  $items = array();

  $items['examples/my_module'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('my_module_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return $items;
}

function my_module_form($form, &$form_state) {

$form['terms'] = array(
        '#type' => 'checkbox',
        '#title' => t('Your checkbox'),
    );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}

function my_module_form_submit($form, &$form_state) {
  $form['terms']['#default_value'] = 1;
  }

?>

```

How can I achieve this?

# Answer
> 1 votes
First you need to specify #default\_value to your element, Then if you are going to save your data in some place, then load it and use it as your element default\_value, if you are not going to save it then you can use form\_state on that but remember to set $form\_state\['form\_rebuild'\] as TRUE in submit handler, a sample code will be like this :

```
function my_module_form($form, &$form_state) {

  $form['terms'] = array(
    '#type' => 'checkbox',
    '#title' => t('Your checkbox'),
    '#default_value' => isset($form_state['values']['terms']) ? $form_state['values']['terms'] : array(),
  );
  $form['submit_button'] = array(
   '#type' => 'submit',
   '#value' => t('Click Here!'),
  );

  return $form;
}
function my_module_form_submit($form, &$form_state) {
  $form['terms']['#default_value'] = 1;
  $form_state['rebuild'] = TRUE;
}

```

---
Tags: 7, forms
---


title: Create a node using the REST API

text:
# Question
Title: Create a node using the REST API
I am trying to create a node from a different server via REST API, utilizing the Drupal 8 REST API and the Poster plugin for the browser. I posted the request as shown below, and I got the following output.

```
{
    "message": ""
}

```

I already enabled the service end\_point to create, retrieve, update, and delete the content in the REST API configuration.

What is happening? Is it the right way of doing it?

# Answer
Okay, I am going to Explain you in a very simple way using a Postman Software.
1. Enable the restui Module.
2. Add the basic\_auth authentication.
3. Get the X-CSRF-Token from /rest/session/token.
4. Follow things by this image:

5. Add the following text into your Body.

And hit the Send Button Its **Done!**
> 2 votes

# Answer
Drupal officially support 2
Authentication providers

1. Cookie
2. Basic\_auth

( Note ) Personally, I recommend ‘Cookie’,
because it is useful for mobile and third-party developers.

================= Login ==================
How can Login Drupal’s APIs in PostMan ?
Method: Post
URL : http://localhost/drupal\_8\_bs4\_theme\_01/user/login
Parameters: Key=value ---\> ?\_format=json
Headers : Content-Type = application/json
Body : Raw → application/Json
`{
"name": "test",
"pass": "test"
}`

Response :
`{
 "current_user": {
 "uid": "25",
 "name": "test"
 },
 "csrf_token": "-Cgh_1vMeVvFn3E5KePfXKWPeVg2Rhf6kURcnVEQbwA",
 "logout_token": "PxfO3uR4gUWFn5hWXgvKBr-4gsB8HMOdT4v5okrZxC8"
}`

======== Create Node Using Cookie Auth ======
After Login How can You Create Node ?
Method: Post
URL : http://localhost/drupal\_8\_bs4\_theme\_01/entity/node?\_format=json
Headers :
Content-Type = application/json
X-CSRF-Token = 8km8Kh5enGfT1\_fpYGg6q6g3BWUhjMa3L3EijUphJu8
Body:
`{
 "type":[{"target_id":"page"}],
 "title":[{"value":"Hello World 221"}],
 "body":[{"value":"How are you?"}]
}`

======== Create Node Using Basic Auth ======
Method: Post
URL :- http://localhost/drupal\_8\_bs4\_theme\_01/entity/node
Query Params :
Key = \_format
Value = hal\_json
Authorization:
Basic Auth: u -\> admin and password -\> admin
Headers:
X-CSRF-Token = Token Which you get like CVieBUrFLSjUsXLGLJ-xW6krdKdAcOkpJK0WP6rzK\_0
Content-Type = application/hal+json
Accept = application/hal+json

Body:
`{
 "type":[{"target_id":"page"}],
 "title":[{"value":"Hello World 221"}],
 "body":[{"value":"How are you?"}]
}`

==================== LogOut =======================
How can Logout Drupal’s APIs in PostMan ?
Method: Post
URL: http://localhost/drupal\_8\_bs4\_theme\_01/user/logout
Parameters: Key=value ---\> ?X-CSRF-Token=-Cgh\_1vMeVvFn3E5KePfXKWPeVg2Rhf6kURcnVEQbwA

(Note) I Think Body is Optional

Body : Raw → application/Json
`{ "csrf_token": "hU2BZsfvXjcT92rWvxQyiZ1wOD-bMtOkG2Mlj2pSPuw", "logout_token": "UUiitmj854Qm_UpuVZq-PK_0FOXQA9wMIqhVLbXBbFM" }`

Response :
Redirect to URL

For Details Visit Following Links
https://www.drupal.org/docs/8/modules/jsonapi/get-post-patch-and-delete
https://www.drupal.org/node/2806623
https://www.drupal.org/docs/8/core/modules/rest/javascript-and-drupal-8-restful-web-services
> 2 votes

# Answer
My plan was first make it work using the **`postman client`** and port the same using **`curl`** request . So first i made a curl request from command line as

```
curl --include --request POST --user username:password --header 'Content-type: application/hal+json' http://192.168.1.243/node --data-binary '{"_links":
{"type":{"href":"http://192.168.1.243/rest/type/node/article"}}, "title":[{"value":"My first page"}],"body":[{"value":"How are you?"}]}'

```

And that was worked (created the node in **`192.168.1.243`**) . Then i made the **`curl`** request from php as follows :

```
$data = '{"_links":
{"type":{"href":"http://192.168.1.243/rest/type/node/article"}}, "title":[{"value":"My first page"}],"body":[{"value":"How are you?"}]}';

        $url = "http://192.168.1.243/node";
        $curl_connection = curl_init($url);
        curl_setopt($curl_connection, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
        curl_setopt($curl_connection, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
        curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
        curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl_connection, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl_connection, CURLOPT_HTTPHEADER, array('Content-type: application/hal+json'));
        curl_setopt($curl_connection, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($curl_connection, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

```

And that was all . The **`node created`** in the remote server .

In postman client cant set the **`HEADER`** as **`'Content-type: application/hal+json'`** . I think that may caused the issue . Any insights welcome .
> 0 votes

---
Tags: 8
---


# Question
Title: Display a message to user for empty user fields
User's have a field called "Location" (uses the Address module).

I would like to show a message (or enable a block) to users that have not filled out this field.

Specifically, this message should be shown when they log in, view their profile, or when they view their dashboard.

I am attempting to do this with Rules, but no luck yet. Any guidance would be appreciated.

# Answer
> 4 votes
This solution may be less performance happy than preprocessing (or not, it's difficult to say depending on caching etc), but I thought I'd be good to throw it out there since it's a "no-code" solution.

1. Create a Views with Block display listing users
2. Filter according to Location field `Is empty` to show only users who don't have it filled in
3. Add a Contextual filter for the user ID and set it to the current user, Hide Views if it doesn't validate
4. Add `Custom text` field and enter your message to be shown
5. Add the `No results behaviour`, this may need some thinking around how to handle the cases when the uses do have the Location field filled in
6. Place the block in as many regions of your theme as you need, and configure each Block visibility so it makes sense for your cases
7. Don't forget to also configure the Block contextual filter settings

# Answer
> 2 votes
Two possible ways I can think of.

First, via a preprocess hook. Maybe `template_preprocess_page()` or `*_html` as they are being called on every page request. But you need to ensure to add `user` to the cache contexts to get a user-specific version of the cached page and to have changes to the user profile bubbling up. This works but still might not be good for cache performance, to have every single page cached user-specifically.

```
/**
 * Implements template_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {

  // Add the current user to the cache contexts.
  $variables['page']['#cache']['contexts'][] = 'user';

  if (\Drupal::currentUser()->isAuthenticated()) {

    // 1. Get the current user.
    /** @var $user \Drupal\user\UserInterface */
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    // 2. Check if field exists.
    if ($user->hasField('field_location')) {

      // 3. Get field.
      $location = $user->get('field_location');

      // 4. Check if field is empty.
      if ($location->isEmpty()) {

        // 5. Trigger message.
        \Drupal::messenger()->addMessage('Hello World!');
      }
    }
  }
}

```

Second, via a custom block and `hook_block_access()` implemented from a custom module. Have core's `block_content` (Custom Block) module enabled, add a custom block type (maybe "User Message"), create a custom block, remind its machine name (it's the block ID) and add it to the region you wanna have the message displayed. Then implement the following.

```
/**
 * Implements hook_block_access().
 */
function MYMODULE_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {

  if ($operation == 'view' && $block->id() == 'BLOCK_MACHINE_NAME') {

    if ($account->isAuthenticated()) {

      /** @var $user \Drupal\user\UserInterface */
      $user = \Drupal\user\Entity\User::load($account->id());

      if ($user->hasField('field_location')) {

        $location = $user->get('field_location');

        // Hide if location field is not empty anymore.
        return \Drupal\Core\Access\AccessResult::forbiddenIf($location->isEmpty() === FALSE)
          ->addCacheableDependency($block);
      }
    }
  }

  return \Drupal\Core\Access\AccessResult::neutral();
}

```

---
Tags: 8, status-messages
---


# Question
Title: How to add a region block to the custom template contact form page?
I trying to add a region block to custom template Contact Form page: "contact-message-feedback-form.html.twig"

Define a region (like: contact\_info) to theme-name.info.yml and add {{ page.contact\_info }} in contact-message-feedback-form.html.twig

Contact form rendered successful but when add block to the region not display block in this region.

theme-name.theme:

```
/**
 * Implements hook_theme().
 */
function crown_ui_theme($existing, $type, $theme, $path) {
  return [
    'contact_message_feedback_form' => [
      'render element' => 'form',
    ]
  ];
}

```

theme-name.info.yml:

```
regions:
  contact_info: 'Contact Info'

```

contact-message-feedback-form.html.twig:

```
<div class="col-sm-3">
{{ page.contact_info }}
</div>

```

# Answer
> 1 votes
I used twig\_tweak module to load and render a block on any where in Drupal. Read more on the module docs:

https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak

---
Tags: 8, theming, forms
---


title: How do I use a term page display?

text:
# Question
Title: How do I use a term page display?
In Drupal 7, the module taxonomy\_display allowed me to insert a **content view** via **views display options** under the taxonomy manage display. I am working on rebuilding my Drupal 7 views for Drupal 8, and the way they are built in 7, they depend on this function.

We are using a (term) view to display parent terms as links to navigate to:

* **either** a child term view (parent/% path) displaying child terms as links to the content view when the content is ascribed to the child term.
* **or** our content view (also parent/% path) when the content is ascribed directly to the parent. We accomplish this in our content view by using no results behavior/global view area to inject the child term view when there is no content ascribed.

With the taxonomy\_display module, you then simply go to the term page display and set that to the content view. It will show child terms when there is no content ascribed, and it will show content when there is content ascribed.

The module documentation for taxonomy\_display for D7 says that the core function of this has been included into Drupal 8, and refers you to this issue for more information, but there I didn't find information there on how this function is implemented in Drupal 8. It seems that they are referring to the taxonomy/term view in now in core.

My question is, can i still accomplish this structure without the taxonomy\_display module merely by what is provided by the taxonomy/term view in core?

Or can I ignore the taxonomy/term view all together and accomplish it a better way? I'm new to D8, so any help would be appreciated!

# Answer
Both of the modules mentioned (Taxonomy display and TVI) that make Taxonomy term pages easier to configure rely on Views, so you do need to have the Views sorted out before you can assign different Views to different Vocabularies. These modules don't replace the "Views magic".

If you don't use these modules that override how term pages are displayed the "Taxonomy term" Views that comes out-of-box handles all of the terms equally. BTW "Taxonomy term" Views is of the content type (not the taxonomy term type, the name can be confusing a bit).

But the "Taxonomy term" Views can be changed to handle different Vocabularies differently. This change can be made in the Contextual filter in the validation settings. Then you can clone that page, give it a different path, and adjust the contextual filter validation to a different Vocabulary.

Both of your cases can be handled with the modified "Taxonomy term" views. Using the "Summary" option in the contextual filter for the Taxonomy reference field will list the terms present in the views results. When you click through those links you see the content listed. Although your "No results behavior" solution also works.

You can get the Parent info into your path through another Contextual filter (Taxonomy Name), that you can get after adding the Relationship for the parent term in your Views.

It's all in the Contextual filters and perhaps some Relationships to create your cases. There are a lot of answers here relating to those so you can search and learn from them.

It is also mentioned in the comments you can use the theme templates to override how Term pages are displayed, when you're not using the Views to build those pages, but you'll probably still use Views to build blocks to put in those templates, unless you know SQL and can create better queries manually.
> 2 votes

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


# Question
Title: Does extending a class include the namespace of the extended class?
For the following example, does `ColourSprayTrap:timer()` collide with the `timer()` function that exists in the weapons module?
More generally, does a namespace need to be re-declared for a class that extends a class with a namespace?

If I have a function declared somewhere in the code.

```
/* In weapons module. */
function timer() { /* Function definition. */ }

```

I have a class with a namespace.

```
/* In traps module */
namespace Traps;

class Trap { /* Some class definition. */ }

```

I extend that class.

```
class ColourSprayTrap extends Trap {
/* Start of class defnition. */
  public function timer($time) {
    /* Function defnition. */
  }
/* Rest of class defnition. */

```

# Answer
To answer the question in the title: **no**, extending a class does not inherit the namespace of the extended class.

Your class namespace must be declared for each class or your class will be placed in the global namespace.

A little bit more on namespaces since if you don't declare one your code will be placed in the global namespace. Since PHP 5.3 if you don't declare a namespace then the class will belong to the global namespace. From the manual here:

> Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

As this applies to you, if you don't put a class in a namespace it will simply belong to the global namespace thus it wouldn't clash with a class with the same name in another namespace.

In general, functions without a class won't interfere with functions with the same name in a class. The reason being is that you need a class object to call a function declared inside a class.
> 0 votes

---
Tags: 7
---


title: sql:sync not working

text:
# Question
Title: sql:sync not working
I'm using drush 9 on a remote server and I'm trying to perform a sql:sync.

This is my alias:

```
live:
  host: www.mysite.com
  paths:
    drush-script: '/home/wodby/drush-wrapper.sh'
    files: files
  root: /var/www/html/web
  ssh:
    options: '-p 9191 -o "AddressFamily inet" -o "StrictHostKeyChecking=no"'
  uri: www.mysite.com
  user: wodby

```

The "drush-wrapper" is a script (on remote server I've docker, so I use ssh to connect into the container. The wrapper is this:

```
export PATH=$PATH:/usr/local/bin
/home/wodby/.composer/vendor/drush/drush/drush.php $@

```

This alias works (for commands like drush cr or cim) but doesn't work the sql:sync command.

If I try to run drush sql:sync @d8.live @self I obtain:

```
 Error: no database record could be found for source @d8.live

```

How should I add this configuration about database?

# Answer
I just had a similar issue and found out I needed to edit the database login-information on my remote site as it had the local site's info in it since that's where the files came from.

Maybe that's the case on your site too?

In short: Check that the remote site's settings.php-file has the database information from the remote site and not the local site.
> 0 votes

---
Tags: drush
---


title: Update a field type with hook_update()

text:
# Question
Title: Update a field type with hook_update()
My module provides config that creates a field:

field.storage.paragraph.field\_accordion\_section\_title.yml

```
langcode: en
status: true
dependencies:
  module:
    - paragraphs
    - text
id: paragraph.field_accordion_section_title
field_name: field_accordion_section_title
entity_type: paragraph
type: text_long
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

I would like to update the field to use `string_long` instead of `text_long`. I would like to handle this via hook\_update() since the module was already installed on multiple sites. I tried the following:

```
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

/**
 * Updates accordion section title to string type.
 */
function my_module_update_8001() {
  if ($fields = \Drupal::entityTypeManager()->getStorage('field_storage_config')->loadByProperties(array('field_name' => 'field_accordion_section_title'))) {
    foreach ($fields as $field) {
      $new_field = $field->toArray();
      $new_field['type'] = 'string_long';
      $new_field = FieldStorageConfig::create($new_field);
      $new_field->original = $field;
      $new_field->enforceIsNew(FALSE);
      $new_field->save();
    }
  }
}

```

I get the following error when updating: **Failed: Cannot change the field type for an existing field storage.**

# Answer
> 6 votes
As the error message says, this is not supported. There is no API that will do it for you.

There was a similar question recently but I can't find it right now, just this one: How do I change the type of a field attached to a content entity?

In short, you have two options:

1. Create a new field, write a script to move over all your data, then delete the old field.
2. Manually alter the database schema and low-level config data as well as the data that Drupal has stored about the field type and its schema. This is by far the more complicated option.

# Answer
> 1 votes
Expanding on @Berdir answer, I would recommend option 1. Creating a separate field, migrating the data and deprecating the old field (not necessarily deleting it, just in case)

For example, let's say your Paragraphs (can be Nodes) of type "sample" have a field "body" that is currently plain text (plain, long) and you want it to be rich text (formatted, long)

1. Create the new field in Drupal admin
2. Add the update

```
/**
 * Update paragraph body to rich text
 */
function es_updates_update_8117() {
  $paragraphs = \Drupal::entityTypeManager()->getStorage('paragraph')->loadByProperties(['type' => 'sample']);
  foreach ($paragraphs as $paragraph) {
    $paragraph->field_body_rich->value = $paragraph->field_body->value;
    $paragraph->save();
  }
}

```
3. Remember to update your twig templates to reflect the change of field name if needed.
4. Remember to optimize it for authors, such as:
    * Rename the old field (in my case I added "\[DEPRECATED\]" to the label)
    * Move the old field in Form Display to the Hidden section
    * Move the old field in View Display to the Hidden section
5. Finally, once you've proved everything works as expected with the new field, feel free to remove it.

---
Tags: 8
---


# Question
Title: How can I create a product with a single variation for a store?
I am having trouble with creating products for a commerce project with multiple sellers (each with their own store). The products these sellers are selling is a baseball card.

When a user adds a new product to sell, in the form submission I create the form as:

```
// create price...
$price = new Price($vals['price']['number'], $vals['price']['currency_code']);

// init variation
$variation_vals = [
  'type' => 'card_type_baseball',
  'status' => 1,
  'sku' => 'baseball-1',
  'price' => $price,
  'field_card_image' => [$vals['image_fid']]
];
$variant = ProductVariation::create($variation_vals);
$variant->save();

// init product
$product_vals = [
  'uid' => $this->getUID(),
  'title' => $vals['name'],
  'type' => 'card',
  'stores' => [$this->store],
  'variations' => [$variant],
];
$product = Product::create($product_vals);
$product->save();

```

It works, however, when I view the product after creation, I have many copies of image and field values for some reason.

I think I'm missing a concept.

When a user wants to sell their product, and they upload the product image, set the price, and enter the title for that card (through the form I provide via the Form API) I want to create the product that I can display in a view for the front page, or under their store on their store pages (which I can display via Views).

Every card has the same properties: an image, title, and a price. Examples,

1 - Barry Bonds, $20.00 (with img) 2 - Mark McGuire, $15.00 (with img)

Am I missing something in relation to creating products?

# Answer
> 1 votes
The code in my example was fine. In my product variation's display I was rendering the product entity, and in my product entity I was rendering my variant. If anyone encounters multiple copies of their product rendered, check how the fields are rendered in the display.

---
Tags: 8, commerce
---


# Question
Title: How to install with composer external library that drupal module depends on
Module bootstrap\_languages depends on external library of same name how do we ask composer to require the external library that needs to go to `libraries/bootstrap_languages` folder

The project's `composer.json` already includes *installer-paths* but how can I make use of them ?

```
    "installer-paths": {
        "core": [
            "type:drupal-core"
        ],
        ....
        "libraries/{$name}": [
            "type:drupal-library"
        ]

```

NOTE: the module itself has not taken care of this dependency

# Answer
You should be able to include this package via composer by adding some repository info.

Add a package definition to your `repositories` section in your composer.json. The resulting `repositories` section may look like this:

```
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "package",
        "package": {
            "name": "usrz/bootstrap-languages",
            "type": "drupal-library",
            "version": "dev-master",
            "dist": {
                "url": "https://github.com/usrz/bootstrap-languages/archive/master.zip",
                "type": "zip"
            }
        }
    }
]

```

Then you can just use composer require like:

```
composer require usrz/bootstrap-languages

```

This will add a new line to your `require` section in composer.json like

```
"usrz/bootstrap-languages": "dev-master"

```

Normally I would try to use this approach with a release tag of a package, rather than the master branch, but no tag exists for this repository.
> 12 votes

# Answer
You can do this by using Asset Packagist. Add **repository** and **installer-types**, **installer-paths** to your `composer.json`

```
"repositories": [
    {
        "type": "composer",
        "url": "https://asset-packagist.org"
    }
],
"extra": {
    "installer-types": ["bower-asset", "npm-asset"],
    "installer-paths": {
        "docroot/libraries/{$name}": ["type:drupal-library", "type:bower-asset", "type:npm-asset"]
    },

```

Then you can add package

```
composer require bower-asset/bootstrap-language

```
> 6 votes

# Answer
Don't forget to add **Composer Installers Extender** by `oomphinc` for the installer paths to work.

```
composer require oomphinc/composer-installers-extender

```
> 4 votes

---
Tags: 8, installation, composer, bootstrap-theme
---


title: Enable translation for theme settings

text:
# Question
Title: Enable translation for theme settings
Theme settings are not translatable in core. Is there a way to make them translatable? I have some additional theme settings which needs to have different values per language.

I'm trying to achieve something like this - How do I translate theme settings?

What I have so far -

mytheme/config/schema/mytheme.schema.yml

```
mytheme.settings:
  type: theme_settings
  label: 'My theme settings'
  mapping:
    custom_textarea:
      type: text_format
      label: 'Additional settings'

```

mytheme/config/install/mytheme.settings.yml

```
custom_textarea:
  value: "<p><sup>*</sup>this is an additional settings.</p>\r\n"
  format: full_html
langcode: en

```

mytheme/mytheme.config\_translation.yml

```
mytheme.settings:
  title: 'my theme settings'
  base_route_name: system.theme_settings
  names:
    - mytheme.settings

```

theme-settings.php

```
/**
 * Implements hook_form_system_theme_settings_alter().
 *
 * Form override for theme settings.
 */
function mytheme_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {

  $custom_textarea = theme_get_setting('custom_textarea');
  $form['custom_textarea'] = [
    '#type'          => 'text_format',
    '#title'         => t('custom textarea'),
    '#format'        => 'full_html',
    '#default_value' => $custom_textarea['value'],
  ];

}

```

When I navigate to admin/config/regional/config-translation it shows the 'my theme settings' but when I click on Translate it navigates to admin/appearance/settings/translate and returns Access Denied.

I also tried updating the base\_route\_name in mytheme.config\_translation.yml to system.theme\_settings\_theme but when I navigage to admin/appearance/settings/mytheme/translate it throws a fatal error.

Looking forward for any suggestions.

# Answer
in schema change field type to text and add translatable: true

```
mytheme.settings:
  type: theme_settings
  label: 'My theme settings'
  mapping:
    custom_textarea:
      type: text
      label: 'Additional settings'
      translatable: true

```

You may also face this problem later https://www.drupal.org/project/drupal/issues/2719553 (my reply there is the last from current date)
> 3 votes

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


# Question
Title: Set the message field as not required in a custom contact form
I have tried many things to set the message field as not required.

1-The more obvious in form\_alter

```
$form['message']['widget'][0]['value']['#required']=false;
$form['message']['widget'][0]['#required']=false;
$form['message']['widget']['#required']=false;
$form['message']['#required']=false;

```

2-Set a white space as a value (if field is empty) in form\_validate

```
$msg= $form_state->getValue('message');
if(!isset($msg['value'])){
    $form_state->setValue('message',
        [
            'value' => '  '
        ]
    );
}

```

3-Set not required in after build

```
function alter_contact_ds(&$form, FormStateInterface $form_state, $form_id)
{
    $form['#after_build'][] = '_remove_msg_required';
    ...
}
function _remove_msg_required($element){
    $element['message']['widget'][0]['value']['#required']=false;
    $element['message']['widget'][0]['#required']=false;
    $element['message']['widget']['#required']=false;
    $element['message']['#required']=false;
    return $element;
}

```

4- In form\_alter, I have used the #state to set the required property

```
$form['message']['#states'] = ['required' => ['select[id="edit-object"]' => [
    'value' => 'info'
]]];
//Note that ['select[id="edit-object"]' => ['value' => 'info']]]
//is used succesfully on another field (but not the requied part)

```

The best I could get is not having the **regular** behavior explaining that the field must be completed (and no red asterix near the field to mark it as required)

But each time I press on the submit button, I get a `drupal_set_message("This value could not be null",error)` \[freely translated from french\]

**SOLUTION:**

Following the idea of Alireza Tabatabaeian, I could solve this problem by

1-Set the field as not required in form alter

```
$form['message']['widget'][0]['value']['#required'] = false;

```

2-Set my validation function de first one in form\_alter

```
$form['#validate'] = ['my_validate_contact','::validateForm'];

```

3-In my validate function set the value of the field equal to a space if the field is empty (it is not really nice, but I could accept it)

```
$msg = $form_state->getValue('message');
if (! isset($msg['value'])) {
    $form_state->setValue('message', [
        [
            'value' => '  '
        ]
    ]);
}

```

# Answer
I've solved this issue this way:

```
function hook_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'contact_message') {
    if (isset($fields['message']) && $fields['message'] instanceof BaseFieldDefinition) {
      /* @var BaseFieldDefinition $field */
      $field = &$fields['message'];
      $field->setRequired(FALSE);
    }
  }
}

```
> 2 votes

# Answer
As many form in drupal are manageable in drupal (like node forms, user registration form, webforms and ...) the first attempt to alter form can be took using UI.

Hence in some cases the form cant be altered using UI and in this situation we need to use hook\_form\_FORM\_ID\_alter.

to make a field required or non-required two different steps should be took

one step is to remove or add client side verification, this can be done using form #states property, a sample code could be :

```
$form['ELEMENT']['#states'] = ['required' => [Array of conditions]];

```

see some examples here

as this element is required by another module there must be a validation function which wont allow submission of empty value, so the next step is to add our custom validation function to form in a manner that our function being called before any other validation function, in that function a non empty value can be assigned to element, so the codes can be something like below :

in hook\_form\_alter :

```
$form['#validate'] = ['my_validate_contact','::validateForm'];

```

and in validation function :

```
$msg = $form_state->getValue('message');
if (! isset($msg['value'])) {
  $form_state->setValue('message', [
    [
        'value' => '  '
    ]
  ]);
}

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Alter the wrapper of radios buttons in a custom module
In a custom module, I have created a custom form. In this form, I need to alter the markup of the radio buttons wrapper and add a new attribute. After reading many posts and testing, I can alter all the form elements (form-item, first fieldset...) except this wrapper.

This is the markup I am outputting.

```
<fieldset ...>
  <legend>Mylegend</legend>
    <div class="fieldset-wrapper">
      <div id="edit-myfield"> <!-- < I need to alter the attributes of this div -->
        <div class="form-item js-form-item form-type-radio js-form-type-radio...">
    ...
        </div>
        <div class="form-item js-form-item form-type-radio js-form-type-radio...">
          ...
        </div>
      </div>
    </div>
  </fieldset>

```

I see that the related system template is radios.html.twig. I tried to copy and paste this template in the *templates* directory of my module without success. I tried to use `theme => 'my custom theme'` in the definition of my field. I tried to use a preprocess function in my module.

What is the simpler method to alter this wrapper?

# Answer
You can do this directly in the form.

Add this to the radios element:

```
'#attributes' => [
  'attribute_name' = 'attribute_value'
],

```
> 0 votes

---
Tags: theming, forms
---