# Question
Title: How do I override the base URL for private files?
Why in Drupal 8 is possible to override the base\_url for public files using the `file_public_base_url` but not for private files? There are scenenarios where Drupal is installed behind a reverse proxy. The private files point to the hostname where the backend server is, instead of pointing to the frontend server.

Perhaps a workaround is to use the mod\_substitute module (http://httpd.apache.org/docs/2.4/mod/mod\_substitute.html) but I don't know if it's the best on.

# Answer
> 1 votes
> The private files point to the hostname where the backend server is, instead of pointing to the frontend server.

Private files are not directly served to the user. Public files are served directly to the user. With a public file, when a file is requested, PHP is never executed, and therefore Drupal is never executed. By virtue of the files being public, they do not require any access checks, and so there is no reason to bootstrap Drupal. Instead, the server (apache, windows etc) serves the files directly to the user. The proxy can then cache that response, since the response for that file will always be the same for everyone.

Private files on the other hand require access checks. By definition, they are meant to have access checks performed upon them before they are served to the user. With private files, the request for a file is made to a php script (index.php - from which every Drupal request begins). This script (which is Drupal) runs access checks on the requested files. If the the access checks are passed, Drupal reads the data from the actual file, then sends a binary file response to the browser (rather than an HTML response, which would be a webpage). This binary file response is the file, which the browser either then renders or offers to the user as a download, depending on the file type and their browser settings.

An analogy to these files systems is to consider public files to be like wanting a cola, and going to the fridge to get it, while private files are like wanting a beer, asking a server for it, who then checks your ID and if you are old enough, gets it from the fridge, and brings it to you.

So private files by their definition cannot be directly accessed, as a script (Drupal) first needs to check whether the user should have access. As such, private files cannot be cached by the proxy, as the proxy has no means of checking access. This is why the base URL cannot be overridden.

---
Tags: 8, files
---


# Question
Title: How can I get likert element title and descriptions of the questions in webform submission handler?
How can I get likert element title and descriptions of the questions in custom webform submission handler? getData() gives only questions and answers, is there another method?

Webform 8.x-5.2

# Answer
> 0 votes
You can get the title & description with:

```
$webform_submission->getWebform()->getElementsDecoded()['key_name']['#questions']['question value'];

$webform_submission->getWebform()->getElementsDecoded()['key_name']['#answers']['answer value'];

```

For Example:

```
$webform_submission->getWebform()->getElementsDecoded()['test']['#questions']

```

Will give:

Notice that the title & description are together. If you want them separate just explode them

```
  $question_text_desc = $webform_submission->getWebform()->getElementsDecoded()['test']['#questions']['Band Name'];
  $question_array = explode(" -- ", $question_text_desc);
  $question_text = $question_array[0];
  $question_desc = $question_array[1];

```

Obviously the above example is hard coded, in reality you'll prob want to do a loop

```
$questions = $webform_submission->getWebform()->getElementsDecoded()['test']['#questions'];
$question_info = [];
foreach ($questions as $question_value => $question_text_desc) {
  $question_array = explode(" -- ", $question_text_desc);
  $question_info[]['text'] = $question_array[0];
  $question_info[]['desc'] = $question_array[1];
}

```

---
Tags: webforms
---


title: Print a view inside a block

text:
# Question
Title: Print a view inside a block
In Drupal 7, I use the following code to print more than one view inside a block.

```
<?php print views_embed_view('view_name', 'display_name'); ?>

```

In Drupal 8, it doesn't work and it returns *Array*. Although the documentation for `views_embed_view()` says it's the same as in Drupal 7, it doesn't work in blocks using the *PHP filter* module.

# Answer
> 2 votes
First of all, **it is bad practice to use the PHP Filter** that comes with core in D7 and the contributed module for D8. PHP Filter was removed from D8 core to prevent new Drupal devs from falling in this bad practice trap. Unfortunately, some evil genius decided to make a contrib module for D8.

Have a read at What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc? to learn why it's bad.

---

Now to answer your question:

* You could simply place the View blocks by clicking the `place block` button in the Manage Blocks UI and perhaps utilizing Block Group if you have lots of blocks.
* Another option is to Create a block via the UI and then print your View in a your block's template file.

+ You do this by coping /core/modules/block/templates/block.html.twig and renaming it to **block--block--\[block-id\].html.twig** which you then move & place it in your theme's /templates folder. See How to embed a view in a specific node?. for printing the block in the template file.

# Answer
> 5 votes
I can't help with the PHP filter and I don't think it is safe to use it in D8 by looking at the project's page.

There are better solutions. You could for example add a Views Reference Field to the block type or use Twig Tweak in a template. You can also try to embed the View in the WYSIWYG text area, which is a bit more work to set up, but then should give you all options you have now in D7. See Views entity embed.

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


title: Programmatically attaching files

text:
# Question
Title: Programmatically attaching files
I have created the "Gallery" content type, and added two fields: "photo," and "document." I then used the following code for uploading a file in the "document" field:

```
$file = file_save_upload('document', array(
    'file_validate_extensions' => array('txt doc'), // Validate extensions.
));

// If the file passed validation:
if ($file) {
// Move the file, into the Drupal file system
if ($file = file_move($file, 'public://')) {
  $file->status = FILE_STATUS_PERMANENT;
 // $file->file_display = 1;
  $file = file_save($file);

} else {
  $output = t('Failed to write the uploaded file the site\'s file folder.');
}
 } else {
$output = t('No file was uploaded.');
 }

```

I am attaching this file to the node using the following code:

```
$customNode->field_document[$customNode->language][0] = (array)$file;

```

When I call `node_submit()` function, I get the following error:

> Integrity constraint violation: 1048 Column 'field\_document\_display' cannot be null

Does anybody know what I am doing wrong?

# Answer
I usually don't throw the `(array)$file` line because really the only thing the field data needs is the fid, description and display. So I usually do the following:

```
$node->field_image[LANGUAGE_NONE][] = array(
  'fid' => $file->fid,
  'display' => 1,
  'description' => '',
);
node_save( $node );

```

This way if the display is required, I don't get an error. But that's just me...
> 29 votes

# Answer
Your solution is almost right; however, in some cases it requires that you also set display and description.

To make your code work do this:

```
$file = file_save_upload('document', array(
    'file_validate_extensions' => array('txt doc'), // Validate extensions.
));

// If the file passed validation:
if ($file) {
// Move the file, into the Drupal file system
if ($file = file_move($file, 'public://')) {
  $file->status = FILE_STATUS_PERMANENT;
 // $file->file_display = 1;
  $file = file_save($file);
  //set the extra values needed to make node_save work
  $file->display = 1;
  $file->description = "";
} else {
  $output = t('Failed to write the uploaded file the site\'s file folder.');
}
 } else {
$output = t('No file was uploaded.');
 }

```
> 7 votes

# Answer
I think the key here are those lines

```
$file->display = 1;
$file->description = "";

```

as Eric van Eldik pointed out. I was struggling with the exact same issue, adding just

```
$file->display = 1;

```

didn't help, but

```
$file->description = "";

```

made my day.
> 2 votes

# Answer
For adding file programmatically to node you can use

```
$managed = TRUE; // Whether or not to create a Drupal file record
$filename = 'public://imdb-cast-' . time() . '.jpg';
$iamge_file = system_retrieve_file($url,$filename , $managed);
if($iamge_file){
$file = file_load(db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField());
$node->field_image['und'][0] = (array) $file;
  }
}

```
> 0 votes

# Answer
Just going to paste my solution here as well, I needed to create a new node, and upload an image programmatically.

```
$filepath = variable_get('file_public_path') . '/xmas_banner.jpg';
$file_temp = file_get_contents($filepath);
$file_temp = file_save_data($file_temp, file_default_scheme() . '://' .'xmas_banner_nl.jpg', FILE_EXISTS_RENAME);

$node = new stdClass();
$node->type = 'carousel'; // custom content type
$node->title = 'XMAS NL';
$node->field_banner_image['und'][0] = (array) $file_temp;
$node->uid = 1;
$node->status = 0;
$node->active = 0;
$node->promote = 0;
node_save($node);

```
> 0 votes

# Answer
Attach multiple files programmatically in Drupal 8:

```
foreach ($fileIds as $fid) {
  $node->field_images[] = [
    'target_id' => $fid,
    'alt' => 'ALT TEXT',
    'title' => 'TITLE TEXT'
  ];
}
$node->save();

```
> 0 votes

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


title: Conditional change row colors

text:
# Question
Title: Conditional change row colors
Say I have a content type "task" with one field "status", which is output by views. Now I want when the status is "finished", the color of that row will be red, when the status is "failed", the color of that row will be yellow, when the status is "ongoing", the color of that row will be green. Is there any way to realize this? BTW, I know very little about code.

# Answer
> 6 votes
There are 2 ways to do this, but you should do this the Drupal way.

1. You can use JavaScript to iterate through each `<tr>` adding a class to the `<tr>` if it finds finished in the last column.
2. You can do it the Drupal way in views. I assume you are using the table view to output your data since that's what you are showing us.

Under your edit view mode, you'll see "Format" and then "Format:Table | Settings".

Click on Settings. Under settings you should see an option that says "Row Class".

You want to set your row class equal to the value of the status field. To do this. Look under Fields to find the field that is displaying your status column and click to edit it. Once there, select "Rewrite results" and then click the "Override the output of this field with custom text" checkbox.

This will open a textbox with an option below it stating "Replacement Patterns." when you click this, you should see some options inside of `{{ }}`. There will likely be one that looks something like `{{ status }} == Status`.

The `{{ status }}` part is your replacement pattern. Copy it and paste it into the row class field under table settings.

What this will do is add a class to your `<tr>` in your view.

Example of what the view output will then look like:

```
<tr class="finished">
  <td>3/5/19>
  <td>write article</td>
  <td>finished</td>
</tr>

```

After completing this step, you need to add a bit of CSS to your stylesheet in your theme.

Something like:

```
tr.finished td { color: red; }
tr.ongoing td { color: green; }
tr.failed td { color: yellow; }

```

So you end up changing the row class to be the replacement pattern of your status field and adding 3 lines of CSS code to your theme's style sheet.

---
Tags: views
---


# Question
Title: Additional actions when logging using watchdog
Is there a way to perform additional actions every time watchdog logs something? For example, I wanted to record, parse, and compile logs with additional information elsewhere, but still have watchdog perform its default function.

Is there any hook I could use?

# Answer
In Drupal 7, you would use `hook_watchdog()` to achieve the task, which is exactly the hook implemented by dblog.module, the module that shows in admin/reports/dblog the messages added with `watchdog()`.

In Drupal 8, you need to implement a service that is invoked everytime a message is logged, for example with the following code.

### mylog.services.yml

```
services:

  logger.mylog:
    class: Drupal\mylog\Logger\MyLog
    tags:
      - { name: logger }

```

### src/Logger/mylog.php

```
namespace Drupal\mylog\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

class MyLog implements LoggerInterface {
  use RfcLoggerTrait;

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = array()) {
    // Log the message, for example writing it in a file.
  }

}

```

The key is how the service is tagged. Without `tags: [{ name: logger }]`, the service would not be used to log the message.

The example code is taken from hook\_watchdog() and watchdog() removed. For an example of code implemented from Drupal core, see SysLog.php, which logs the messages in the Syslog server.

```
class SysLog implements LoggerInterface {
  use RfcLoggerTrait;

  /**
   * A configuration object containing syslog settings.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * The message's placeholders parser.
   *
   * @var \Drupal\Core\Logger\LogMessageParserInterface
   */
  protected $parser;

  /**
   * Stores whether there is a system logger connection opened or not.
   *
   * @var bool
   */
  protected $connectionOpened = FALSE;

  /**
   * Constructs a SysLog object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory object.
   * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
   *   The parser to use when extracting message variables.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LogMessageParserInterface $parser) {
    $this->config = $config_factory
      ->get('syslog.settings');
    $this->parser = $parser;
  }

  /**
   * Opens a connection to the system logger.
   */
  protected function openConnection() {
    if (!$this->connectionOpened) {
      $facility = $this->config
        ->get('facility');
      $this->connectionOpened = openlog($this->config
        ->get('identity'), LOG_NDELAY, $facility);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = []) {
    global $base_url;

    // Ensure we have a connection available.
    $this
      ->openConnection();

    // Populate the message placeholders and then replace them in the message.
    $message_placeholders = $this->parser
      ->parseMessagePlaceholders($message, $context);
    $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders);
    $entry = strtr($this->config
      ->get('format'), [
      '!base_url' => $base_url,
      '!timestamp' => $context['timestamp'],
      '!type' => $context['channel'],
      '!ip' => $context['ip'],
      '!request_uri' => $context['request_uri'],
      '!referer' => $context['referer'],
      '!severity' => $level,
      '!uid' => $context['uid'],
      '!link' => strip_tags($context['link']),
      '!message' => strip_tags($message),
    ]);
    $this
      ->syslogWrapper($level, $entry);
  }

  /**
   * A syslog wrapper to make syslog functionality testable.
   *
   * @param int $level
   *   The syslog priority.
   * @param string $entry
   *   The message to send to syslog function.
   */
  protected function syslogWrapper($level, $entry) {
    syslog($level, $entry);
  }

}

```

Notice that in Drupal 8, as in Drupal 7, it is possible to have different loggers active at the same time, so the log messages can be recorded in different ways at the same time.
> 5 votes

# Answer
Drupal 8 uses PSR3 compatible logging API. In order to implement additional logger behavior you can create and register a custom logger service.

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

You can create a logger service with the `drush generate logger` command.

Note that at this moment there is no an easy way to alter logged messages in Drupal 8. https://drupal.stackexchange.com/a/222123/433
> 0 votes

# Answer
In Drupal 8 :

```
// Logs a notice
\Drupal::logger('my_module')->notice($message);
// Logs an error
\Drupal::logger('my_module')->error($message);

```

In Drupal 7 :

```
// Logs a notice
watchdog('my_module', $message, array());
// Logs an error
watchdog('my_module', $message, array(), WATCHDOG_ERROR);

```
> 0 votes

---
Tags: 8, log-messages
---


# Question
Title: Set value on a new term based on a vocabulary custom field
I want to set the value of a field of a term based on a custom field set on the vocabulary. Basically if the vocabulary `promote_to_index` field is checked I want to the `field_index_page` of the term checked.

I understand I have to write a hook like but I don't understand how to get the value of the vocabulary custom field

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

  switch ($form_id) {

    case 'taxonomy_term_category_form':
    case 'taxonomy_term_article_type_form':
    case 'taxonomy_term_main_purpose_form':
    case 'taxonomy_term_tags_form':
    case 'taxonomy_term_content_partnership_form':
    case 'taxonomy_term_traffic_source_form':
    case 'taxonomy_term_client_form':
      $form['field_index_page']['widget']['value']['#default_value'] = true;
  }
}

```

# Answer
> 1 votes
You can add an extra validation step to those forms that checks and changes the value accordingly like so.

```
function polaris_drupal_taxonomy_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_term_category_form':
    case 'taxonomy_term_article_type_form':
    case 'taxonomy_term_main_purpose_form':
    case 'taxonomy_term_tags_form':
    case 'taxonomy_term_content_partnership_form':
    case 'taxonomy_term_traffic_source_form':
    case 'taxonomy_term_client_form':
      $form['#validate'][] = '_polaris_drupal_add_field_index_page';
  }
}

function _polaris_drupal_add_field_index_page(&$form, FormStateInterface $form_state) {
  $promote_to_index = $form_state->getValue('promote_to_index');
  if ($promote_to_index['value']) {
    $form_state->setValue('field_index_page', [ 'value' => TRUE ]);
  }
  else {
    $form_state->setValue('field_index_page', [ 'value' => FALSE ]);
  }
}

```

This will check the field **promote\_to\_index** of the form and set the field **field\_index\_page** before executing the submit handlers of the form.

---
Tags: 8, forms, hooks
---


# Question
Title: When I going to Disable Twig template cache , Fatal error
When I going to Disable Twig template cache , Fatal error . i.e

> The website encountered an unexpected error. Please try again later. Error: Unsupported operand types in Drupal\Core\Template\TwigEnvironment-\>\__construct() (line 69 of core\lib\Drupal\Core\Template\TwigEnvironment.php).

I followed below steps :

1.Copy and rename the file from sites/example.settings.local.php to sites/default/settings.local.php 2.Open settings.php file in sites/default and uncomment these lines:

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

```

3.Uncomment these lines in settings.local.php

```
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```
4. Open development.services.yml in the sites folder and add the following code

```
 parameters:
twig.config:
debug: true
auto_reload: true
cache: false
```
5. Rebuild the cache and your good to go

My development.services.yml code :

`parameters:
 http.response.debug_cacheability_headers: true
 twig.config:
 debug: true
 auto_reload: true
 cache: false
services:
 cache.backend.null:
 class: Drupal\Core\Cache\NullBackendFactory`

# Answer
> 2 votes
The least hassle way is to install Drupal Console

Then run the command `drupal site:mode dev` (turns off caching and turns on twig debug)

Once you're done, run `drupal site:mode prod` (turns off twig debug, turns caching back on).

---
Tags: theming
---


# Question
Title: Get value of programmatically (form_alter) added fields at form submit
I'm altering a node creation form using the form\_alter hook in a custom module. In this particular case, I'm adding an email field **which is not part of the content type structure.** At the node creation, I need to send an email to the address entered in the field. Using the hook entity\_presave or entity\_insert I have access to the entity field that are part of its structure, but not to the programmatically added email field. How can I get that value at the form submit?

# Answer
A field added in the form\_alter hook is not created on the entity. Therefore you cannot retrieve the value in either hook\_entity\_presave or hook\_entity\_insert.

What you want however you can do by creating an additional submit handler for the form.

```
function _MODULE_NAME_custom_submit_handler($form, FormStateInterface $form_state) {
  $email = $form_state->getValue('email_field_name');
  // send email.
}

```

You can also get the saved entity (which does not have the email field) using `$form_state->getFormObject();`
> 1 votes

# Answer
So you added this MY\_EMAIL\_FIELD to the form with form\_alter. Add the following as well:

```
$form['actions']['submit']['#submit'][] = 'MYMODULE_node_form_send_email';

```

Add another function to your file:

```
function MYMODULE_node_form_send_email($form, FormStateInterface $form_state) {
  $email = $form_state->getValue('MY_EMAIL_FIELD');
  // send email here
}

```

In this way, the email data won't get lost and you are able to send the email to the correct address.
> 1 votes

---
Tags: 8, forms, hooks
---


# Question
Title: Set entity reference target_id in migration yml
I migrate Drupal 6 to Drupal 8. In Drupal 8 I have content type that has field with type `Entity reference` that reference specific taxonomy dictionary. I can't find out how to set `Entity reference` field `target_id` in `yml` migration file. I have tried:

```
field_my_field:
  plugin: iterator
  source: field_my_field
  process:
    target_id:
      plugin: default_value
      default_value: 19

```

I would expect that code above set Entity reference (`field_my_field`) to reference term with id `19` (that already exists). There is no error (or message) and `default_value` plugin is called correctly a returns `19`. But in migrated content is not reference set.

I tried to set reference manually and then dump it and result was:

```
[field_my_field] => Array
  (
    [x-default] => Array
      (
        [0] => Array
          (
            [target_id] => 19
          )
      )
  )

```

I have tried lot of other ways how to set entity reference `target_id` but nothing actually work. Do anybody know how to set entity reference `target_id` in migration yml file?

# Answer
> 3 votes
Old question, but I'm guessing you need to add the array for the item list. I was successful with: `field_something/0/target_id: YOUR_VALUE_HERE`

I haven't found documentation on the slash in the field id, but it is an array notation. The above is equivalent to something like: `$destination_values['field_something'][0]['target_id'] = YOUR_VALUE_HERE`

# Answer
> 1 votes
Is 19 the tid of an already-existing Drupal 8 term in the vocabulary that field\_my\_field is configured to reference? If so, I don't really see where the example using default\_value would be going wrong...

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


# Question
Title: Calling Drupal Form from non-Drupal 3rd Party Website
I have an existing non-Drupal 3rd party site and I am trying to submit a form request to a site written in Drupal. For some reason, the request does not process. I'm not familiar with Drupal and would appreciate any help that can be offered.

An expected response would be:

> "No match found for AMA 123456 and last name smith. Please verify."

# Answer
you'll probably need to post some sort of code to help us understand whats going on.

* What version of Drupal are you on?
* What HTTP status code is coming back from Drupal?
* if its a status 200, Are there any errors, messages etc being returned?

but at a high level, Drupal protects against CSRF and the 3rd party site submitting a form on the Drupal site would run afoul of this protection.

potential solutions:

* You can disable the CSRF (not recommended).
* you can embed the form as an iframe
* you can create a REST resource and use that to submit the submission from the 3rd party (bypass the form)

read more https://www.drupal.org/docs/7/security/writing-secure-code/create-forms-in-a-safe-way-to-avoid-cross-site-request-forgeries
> 1 votes

---
Tags: forms
---


# Question
Title: Unable to save content language configuration
My Drupal 8 website is multilingual and has many entity type bundles for nodes, taxonomy terms, paragraphs, media et cetera. This leads to a content language settings form (admin/config/regional/content-language) with more than thousand translatable-checkboxes.

Currently I'm not able to save this form. In the first place the form seemed to be successful submitted but changes have not been saved. This was caused by insufficient php setting value for `max_input_vars`, which could be solved by setting it to `6000`. Now I'm struggling with a timeout. After submitting the form the request fails after some minutes.

Here are the php settings of my Drupal VM:

```
php_version: "5.6"
php_memory_limit: "1024M"
php_realpath_cache_size: "1024K"
php_opcache_enabled_in_ini: true
php_opcache_memory_consumption: "192"
php_opcache_max_accelerated_files: 4096
php_max_input_vars: "6000"
php_max_execution_time: "720"
php_post_max_size: '64M'

```

How can I get around this issue? Which resource bottleneck could cause this?

# Answer
> 0 votes
I tried the max\_input\_vars fix and that didnt work (i have alot of custom entities on the page and was hoping this would work). I had to check the entity, pretend it was called MyCustomEntity in 'Custom language settings' at the top... but also scroll down to the individual MyCustomEntity settings further down on the page, and also check that checkbox. When I saved, now it worked

# Answer
> 0 votes
Today I had to struggle again with this problem and could solve it by disabling Xdebug. So to sum up this could help:

* increase `memory_limit` and `max_execution_time`
* update to latest PHP version (at least 7.1)
* make sure Xdebug is not enabled when saving the settings form (e.g. via browser extension or general xdebug settings on server/vm)

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


title: Entity getOwner()

text:
# Question
Title: Entity getOwner()
In what table does an entity "foo" get its metadata stored? In Drupal 7, there are tables for all the fields for a content type and the node table had some metadata stored, but most data for a content type were in other tables. I think I understand that configuration is what metadata is required for an entity. But I cannot figure out which tables would store an association between node/100 and user/10. Using breakpoints I'm trying to troubleshoot where in the node object this info resides and try to deduce its definitions to backtrack where metadata like author/owner is stored.

# Answer
In Drupal 8 all that stuff is stored as YAML files in your config directory.

If you don't have a custom path to that directory it's usually located in `sites/default/files/config......` where .. is a long randomly generated hash key.

There you will find config files for all entities and fields and configuration settings.

**EDIT:** To get a node's asociation with it's author you'll have to look in the `node_field_data` table, the UID field there is the author's user ID.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Is the front page considered in_active_trail?
I'm learning Drupal 8, so still very new to it. I'm working on customizing the main menu. I've been able to add Twitter Bootstrap to my custom theme. I've made a custom menu--main.html.twig file.

I'm trying to change the "is-active" class to "active" using what Drupal has available. I see when I click to my About page that they About link is highlighted with the active link class. Great!

What I can't seem to figure out is how do I get the Home page to get the active class too? It looks like it is being treated differently.

I tried adding a new page called Homepage, but that didn't work either.

Here is my twig file, which i took pieces from another theme that use twitter bootstrap to try to compile it together.

```
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('nav navbar-nav mr-auto') }}>
    {% else %}
      <ul class="navbar-nav mr-auto dropdown-menu">
    {% endif %}
    {% for item in items %}
    {%
      set classes = [
        menu_level ? 'dropdown-item' : 'nav-item',
        item.is_expanded ? 'menu-item--expanded',
        item.is_collapsed ? 'menu-item--collapsed',
        item.in_active_trail ? 'active',
        item.below ? 'dropdown',
      ]
    %}
    <li{{ item.attributes.addClass(classes) }}>
      {%
          set link_classes = [
            not menu_level ? 'nav-link',
            item.in_active_trail ? 'active',
            item.below ? 'dropdown-toggle',
            item.url.getOption('attributes').class ? item.url.getOption('attributes').class | join(' '),
          ]
        %}
        {% if item.below %}
          {{ link(item.title, item.url, {'class': link_classes, 'data-toggle': 'dropdown', 'aria-expanded': 'false', 'aria-haspopup': 'true' }) }}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% else %}
          {{ link(item.title, item.url, {'class': link_classes}) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  </div>
  {% endif %}
{% endmacro %}

```

Update: I went into Views in my admin panel and edited the Frontpage. I noticed that it was not assigned to any menus. I changed that by adding it to the main menu. Looked at my homepage and the Home link is now highlighted as the active page.

So, what worked is adding it through the view page. What did not work was adding the homepage from the "menu" screen where you build the menu. Clearly the homepage is treated differently from other pages in the menu and if you add it via the menu panel, it is not considered as part of in\_active\_trail. I don't totally understand so I am hoping that someone can explain this to me.

Now, my question is did i do this right?

Update #3 I check my "Home" link in my main navigation. The original "Home" link says "This link is provided by the Standard module. The title and path cannot be edited." This link will not add the active class when I use "in\_active\_trail".

I had manually added a link via the Menu -\> Main Navigation -\> Add New Link. I gave it a title called "Homepage" and the link "". This link did not accept the "active" class either.

From what I can gather, the only way to get it to repsect "in\_active\_trail" is y using the Views -\> Front page and then configure the menu setting. That did the trick.

# Answer
As mentioned on Active on home menu item not working, it could happen because you are using `""` as menu link instead of `<front>`.

The Menu Trail By Path module could resolve your issue. That module sets the menu item to active if it's for the page you are currently on.

> Menu Trail By Path sets the active trail on menu items according to the current URL. For example, if you are at https://example.com/blog/category1/article1, menu items with the following paths will get the *active-trail* class on them and expand accordingly.
>
> * blog
> * blog/category1
> * blog/category1/article1
> 0 votes

---
Tags: 8, theming, navigation
---


# Question
Title: How to Create and Retrive a product programmatically in Drupal commerce 2.x
I have created the store in Drupal commerce 2.x. I have added a product for the product type from the dashboard. Now i want to create Product grammatically in my custom module. how this can be done Drupal 8 for Drupal commerce 2.x

# Answer
To create a product is similar to how you'd create a node:

```
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

$variation1 = ProductVariation::create([
  'type' => 'default',
   'sku' => '123',
   'price' => new Price('14.50', 'USD'),
]);
$variation1->save();

$variation2 = ProductVariation::create([
  'type' => 'default',
   'sku' => '1234',
   'price' => new Price('10.00', 'USD'),
]);
$variation2->save();

$product = Product::create([
   'type' => 'default',
   'title' => t('Product Title'),
    'variations' => [$variation1, $variation2],
]);
$product->save();

```
> 1 votes

# Answer
It seems duplicate of https://stackoverflow.com/a/56225927/7528823 or please see the documentation --- Creating Products
> 0 votes

---
Tags: commerce
---


title: Composer update failure

text:
# Question
Title: Composer update failure
I am trying to update a site to Drupal 8.7 and getting a weird set of errors. Can someone point me to how to best diagnose and fix the problem?

Here are the steps that I am taking:

1. When I try to update Drupal I use: `composer update drupal/core webflo/drupal-core-require-dev --with-all-dependencies`

This results in

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

  Problem 1
    - drush/drush 9.6.2 requires chi-teck/drupal-code-generator ^1.28.1 -> satisfiable by chi-teck/drupal-code-generator[1.x-dev].
    - drush/drush 9.6.2 requires chi-teck/drupal-code-generator ^1.28.1 -> satisfiable by chi-teck/drupal-code-generator[1.x-dev].
    - drush/drush 9.6.2 requires chi-teck/drupal-code-generator ^1.28.1 -> satisfiable by chi-teck/drupal-code-generator[1.x-dev].
    - Conclusion: don't install chi-teck/drupal-code-generator 1.x-dev
    - Installation request for drush/drush (locked at 9.6.2, required as ^9.0.0) -> satisfiable by drush/drush[9.6.2].

```
2. results of `composer why-not drupal/core 8.7.0`:

webflo/drupal-core-require-dev 8.6.15 requires drupal/core (8.6.15) drupal/core 8.7.0 requires egulias/email-validator (^2.0) drupal-composer/drupal-project - requires egulias/email-validator (^1.0)
3. Contents of composer.json:

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "chi-teck/drupal-code-generator": "dev-master",
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6.5",
        "drupal-composer/drupal-scaffold": "^2.5",
        "drupal/admin_toolbar": "^1.25",
        "drupal/chosen": "^2.6",
        "drupal/ckeditor_a11ychecker": "^1.0",
        "drupal/ckeditor_balloonpanel": "^1.1",
        "drupal/ckeditor_div_manager": "^1.0",
        "drupal/ckeditor_liststyle": "^1.3",
        "drupal/ckeditor_uploadimage": "^1.7",
        "drupal/console": "^1.0.2",
        "drupal/core": "^8.6",
        "drupal/devel": "^2.0",
        "drupal/entity_reference_integrity": "^1.0@RC",
        "drupal/eva": "^1.3",
        "drupal/imce": "^1.7",
        "drupal/inline_entity_form": "^1.0@RC",
        "drupal/ldap": "^3.0@beta",
        "drupal/markup": "^1.0@beta",
        "drupal/masquerade": "^2.0@beta",
        "drupal/migrate_plus": "^4.1",
        "drupal/migrate_source_csv": "^2.2",
        "drupal/migrate_tools": "^4.1",
        "drupal/module_filter": "^3.1",
        "drupal/readonly_field_widget": "^1.2",
        "drupal/serial": "1.x-dev",
        "drupal/taxonomy_access_fix": "^2.6",
        "drupal/token": "^1.5",
        "drupal/uuid_extra": "1.x-dev",
        "drush/drush": "^9.0.0",
        "egulias/email-validator": "^1.0",
        "vlucas/phpdotenv": "^2.4",
        "webflo/drupal-core-require-dev": "^8.6",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3"
    },
    "require-dev": {
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/{$name}": ["type:drupal-drush"]
        },
        "drupal-scaffold": {
            "initial": {
                ".editorconfig": "../.editorconfig",
                ".gitattributes": "../.gitattributes"
            }
        }
    }
}

```
4. Results from `composer outdated`:

```
alchemy/zippy                      0.4.3              0.4.9
chi-teck/drupal-code-generator     dev-master 8209866 dev-master 4960fe0
dflydev/dot-access-data            v1.1.0             v2.0.0
drupal/core                        8.6.15             8.7.0
egulias/email-validator            1.2.15             2.1.7
league/container                   2.4.1              3.2.2
paragonie/random_compat            v2.0.18            v9.99.99
phar-io/manifest                   1.0.1              1.0.3
phar-io/version                    1.0.1              2.0.1
phpdocumentor/type-resolver        0.4.0              0.7.1
phpunit/php-code-coverage          5.3.2              7.0.3
phpunit/php-file-iterator          1.4.5              2.0.2
phpunit/php-timer                  1.0.9              2.1.1
phpunit/php-token-stream           2.0.2              3.0.1
phpunit/phpunit                    6.5.14             8.1.3
phpunit/phpunit-mock-objects       5.0.10             6.1.2              Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
ralouphie/getallheaders            2.0.5              3.0.3
sebastian/comparator               2.1.3              3.0.2
sebastian/diff                     2.0.1              3.0.2
sebastian/environment              3.1.0              4.2.1
sebastian/global-state             2.0.0              3.0.0
sebastian/resource-operations      1.0.0              2.0.1
stecman/symfony-console-completion 0.9.0              0.10.0
symfony-cmf/routing                1.4.1              2.1.0
symfony/config                     v3.4.27            v4.2.8
symfony/console                    v3.4.27            v4.2.8
symfony/css-selector               v3.4.27            v4.2.8
symfony/debug                      v3.4.27            v4.2.8
symfony/dependency-injection       v3.4.27            v4.2.8
symfony/dom-crawler                v3.4.27            v4.2.8
symfony/event-dispatcher           v3.4.27            v4.2.8
symfony/filesystem                 v3.4.27            v4.2.8
symfony/finder                     v3.4.27            v4.2.8
symfony/http-foundation            v3.4.27            v4.2.8
symfony/http-kernel                v3.4.27            v4.2.8
symfony/phpunit-bridge             v3.4.27            v4.2.8
symfony/process                    v3.4.27            v4.2.8
symfony/routing                    v3.4.27            v4.2.8
symfony/serializer                 v3.4.27            v4.2.8
symfony/translation                v3.4.27            v4.2.8
symfony/validator                  v3.4.27            v4.2.8
symfony/yaml                       v3.4.27            v4.2.8
twig/twig                          v1.40.1            v2.9.0
typo3/phar-stream-wrapper          v2.1.0             v3.1.0
vlucas/phpdotenv                   v2.5.2             v3.3.3
webflo/drupal-core-require-dev     8.6.15             8.7.0
zendframework/zend-diactoros       1.8.6              2.1.2

```

Per suggestion from @fgrep, I removed composer.lock and vendor/. The result was even more errors: (see File linked as question was getting too long)

# Answer
> 0 votes
The problem turned out to be that the composer.json had a requirement for `"egulias/email-validator": "^1.0"` and 8.7 requires 2.0. I could not find any reason why 1.0 was in the requirements. When I removed that requirement, the update proceeded without any problem.

# Answer
> 1 votes
I fixed it by deleting composer.lock and vendor:

```
rm -Rf composer.lock vendor/

```

Then I ran a composer update:

```
composer update

```

---
Tags: 8, composer
---


# Question
Title: In code, only create a revision if a field is changed
I have a custom revisionable entity with a few dozen fields. I'm importing data about the entity on a periodic basis. If the entity has changed, I'd like to save it and create a new revision.

```
$dogs = \Drupal::entityTypeManager()
  ->getStorage('my_entity')
  ->loadByProperties(['my_entity_id' => $my_entity_id]);

$dog = reset($dogs);

$dog->set('name', $record['TheName']);
$dog->set('birth_date', $record['Dog Birth Date']);
// Lots more ->set happening here.
$dog->set('notes', $record['Notes']);
if ($dog->someMagicComparisonFunction()) {
  $dog->setNewRevision(TRUE);
  $dog->save();
}

```

I searched for the `someMagicComparisonFunction` but didn't find it. Does it exist?

# Answer
> 2 votes
This may do the trick in a `hook_entity_presave()`, or get you close:

```
$old_dog = clone $dog;
update_the_dog($dog);

// Use == to allow for out of order keys.
$same = $dog->toArray() == $old_dog->toArray();

```

This is kinda of cheating, and you may want to filter the arrays for just the fields and not the properties. It also isn't multilingual-safe.

To do it properly, start reading `ContentEntityBase::hasTranslationChanges()` and `FieldItemList::equals()`. The code above makes a lot of assumptions about fields and storage, which `ContentEntityBase()` does properly.

---
Tags: 8, entities
---


# Question
Title: How to use hook_prepare to modify a field of a node before it is edited
I want to modify the contents of a field of an Article node just before it comes up for editing. I have read the documentation at http://api.hostdog.gr/api/drupal-8/drupal%21core%21modules%21node%21node.api.php/function/hook\_prepare/8, which states that hook\_prepare will "Act on a node object about to be shown on the add/edit form." I've read lots of other stuff too.

I've tried lots of ways of naming the function:

```
MyModule_article_prepare()
MyModule_article_node_prepare()
MyModule_prepare_article()
MyModule_prepare_node_article()
and on and on

```

But the function is never called. I've tried putting these functions in both the MyModule.module file and in the MyTheme.theme file. I've read countless posts. Nothing has caused my function to be invoked (I output to the error log to tell it got called).

I simply want to look at one field in the node and possibly modify it just before it comes up in the add/edit form for the user to edit it. I feel really dumb; this has got to be dead simple and I'm just not getting it.

# Answer
The code that is provided by the page that you linked to is wrong. While this hook exists in D7 and while it is possible that during early D8 core development, in alpha or beta, it existed at one point. In D8 there is no such thing as `hook_prepare`.

As per the list of all D8 core hooks, it looks to me that hook got replaced with a newcomer hook called hook\_ENTITY\_TYPE\_prepare\_form

```
/*
 * Implements hook_ENTITY_TYPE_prepare_form
 */
function mymodule_node_prepare_form(\Drupal\node\NodeInterface $node, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($node->getType() == 'article') {
    // your code goes here
  }
}

```

and as always, anytime you implement a new hook, for the first time, clear the cache so it gets picked up by Drupal.
> 2 votes

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


title: Aggregator with custom RSS field

text:
# Question
Title: Aggregator with custom RSS field
I have a simple RSS feed I am importing via core Aggregator module in Drupal 8.5. One specific field in the Item can't be accessed by Views, and it's critical for display. I'm relying on hacky approach right now, but would love to do it right.

What's the process in getting a specific ATOM Rss field registered so that it appears in Views UI? Can't find any info on building custom Aggregator plugins for fetcher/parser/processors.

Anyone have other thoughts on how to approach?

Thanks in advance for all insight.

PTG

# Answer
Aggregator offer the possibility to add custom fetch/parser/process to update/override/remove actions on the global process.

For example I managed to make aggregator deal with enclose url image. Their are several ways to do it with Drupal 8. I used a very simple one : **Annotation**.

```
/**
 * Defines a default parser implementation.
 *
 * Parses RSS, Atom and RDF feeds.
 *
 * @AggregatorParser(
 *   id = "xxxxx_aggregator",
 *   title = @Translation("XXXX parser"),
 *   description = @Translation("Custom parser for RSS enclosure tag.")
 * )
 */
class CustomParser extends DefaultParser {

  /**
   * Override default parser to add the enclosure attribute to feed item
   * {@inheritdoc}
   */
  public function parse(FeedInterface $feed) {

    parent::parse($feed);
    // your code...
  }

}

```

In this given example, using `@AggregatorParser`, I allow Aggregator to detect and use another **PARSER**, my custom, which is extending the aggregator's default.

Do not forget to add it in the correct needed path. Here its : `namespace Drupal\xxxxx_aggregator\Plugin\aggregator\parser;`

You will be able to see and enable it on the aggregator feed admin page.

For deeper informations you can analyse the aggregation process throught the module's files, this contrib module use plugin management and hooks api. `AggregatorPluginManager.php`
> 1 votes

---
Tags: 8, feeds, plugins
---


title: How to print the URL of a title field?

text:
# Question
Title: How to print the URL of a title field?
I'm trying to print out the url path from the title in my twig template however I haven't been successful so far.

Printing out the title containing the link works fine using:

```
{{content.title}}

```

However, I would like to seperate the URL from the title so I can use it in other areas of my twig template. For example:

```
<a href="{{ content.title.0.url }}">Example text</a>

```

I've tried various combinations and suggestions from stackexchange/drupal forums but to no avail. e.g. {{ url }}, {{ uri }} etc.

Any ideas?

# Answer
> 1 votes
If the content that you refer to is a node then you can use the twig path function as follows:

```
<a href="{{ path('entity.node.canonical', {'node': content.id}) }}">{{ 'Example text'|t }}</a>

```

---
Tags: 8, theming, nodes, uri
---


title: Custom Page routing

text:
# Question
Title: Custom Page routing
I created a custom page type called 'Angular page' and a custom twig template for it which loads my angular scripts and prints the `<app-root>` tag.

I set the page URL to `/angularpage` and the page will display the data correctly.

The issue is - my angular app supports routing so I want all the angular routes also to load the same node:

For example:

```
/angularpage/route1
/angularpage/route2
/angularpage/route2/step2

```

Does anyone know of a way in which I can take the URL alias the user filled and use it as a base for my page so that all routes that start with it lead me to the same node?

(Drupal 8)

Thanks Yaron

# Answer
You should be able to accomplish this with use of a custom route and controller.

Let's assume you have a custom module `angular_router`. You'll want to create a controller file, which should be located at `angular_router/src/Controller/AngularPageController.php`:

```
<?php

namespace Drupal\angular_router\Controller;

use Symfony\Component\HttpFoundation\Request;

/**
 * AngularPageController class.
 */

class AngularPageController {

  /**
   * Creates the response for the angular page.
   *
   * @param string $user
   * @param Request $request
   * @return array
   */
  public function content($param, Request $request) {
    // This is a hardcoded node ID, you'll probably want to load
    // this from config, or something.
    $nid = 3;
    $entity_type = 'node';
    $view_mode = 'default';

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $node = $storage->load($nid);
    $build = $view_builder->view($node, $view_mode);
    return $build;
  }

}

```

As noted, this example is hardcoding node ID of '3'. You could create a Form that could store a configurable value, and load this up here. But the point is, this will render the given node ID in the specified view mode, "default" in this case, but again, this could be configurable.

Now that you have a controller, you'll just have to wire it up to your path. So create a routing yml file - the path should be `angular_router/angular_router.routing.yml`. You can wire up the route by adding this to the file:

```
angular_router_page:
  path: '/angularpage/{param}'
  defaults:
    _controller: '\Drupal\angular_router\Controller\AngularPageController::content'
  requirements:
    _permission: 'access content'

```

Note the `_controller` points to the controller created above. The `{param}` is just an arbitrary placeholder for an expected user provided parameter. This should serve as the "wildcard", so that going to `/angularpage/foo`, `/angularpage/bar`, etc. should all point at this controller, which you have now setup to *only* ever serve the specified node output.

Hopefully, I've understood what you're wanting to do, and this will work out for your implementation. I can't say that I've verified it against Angular or anything, but I think this answers your question.
> 2 votes

---
Tags: nodes, routes, uri
---


# Question
Title: How to create unique banner for each node and views page?
What I am trying to achieve:

I want the unique banner image for each node and the views page, where the site administrator can simply upload the image and description to upload the banner for each node.

What I have done so far:

I have created the custom paragraph (https://www.drupal.org/project/paragraphs type) with image and description field and attached it to the content type.

Then I have hidden the paragraph field from manage display and then I installed field as block module(https://www.drupal.org/project/fieldblock) to display my attached field, particularly attached with the node from block layout in the custom banner region.

Problem: With this approach I successfully created a unique banner for content type; however, I am not sure how to achieve this in views page. Any other approach I could achieve this?

# Answer
I'd suggest to use core's Custom content blocks to create blocks (similar to your banner paragraph for nodes). Then you've got two options:

You can either use Block Layout to place the blocks, but limit visibility of the block to certain pages/URLs. Pro: You can directly place the block in any region. Con: It will clutter up your Block layout page if you've got a lot of views.

Or you can go to Views UI and place the block in the header of the view (middle column, below Page settings). Pro: Block and View are tied together in the same part of the Admin UI, no clutter in Block Layout. Con:The block will not be placed in your banner region
> 2 votes

---
Tags: views, theming
---


title: CIDRAM on Drupal 7

text:
# Question
Title: CIDRAM on Drupal 7
Has anyone installed CIDRAM (access management to block undesirable IP addresses) on Drupal 7.

It requires adding a "php require" statement to a file that is executed on every attempt to access the web site, and I do not know which file to use. Any advice gratefully received.

Frank

# Answer
I think that the ip\_ranges module is a lot more used and easier to setup.

Try to install that module, should be quite easy to configure.

Good luck.
> 1 votes

# Answer
I have placed the line

```
require DRUPAL_ROOT . '/pah_to_file/loader.php';

```

in the index.php file at the top level of the drupal files.

It works well!!
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: override view Use administration toolbar
i have a view that using administration toolbar. Problemis theme suggestion is not showing the template names that should override the template. i guess because its using the administration toolbar .. What i am trying to acheive is showing the whole comment body, when the edit link is clicked  , instead of going to an other page. How can i force drupal to show suggestion view templates. And is there a better idea.

# Answer
I found out that i need to do a custom module then do theme hook suggestion.

```
function my_module_theme($existing, $type, $theme, $path) {
    return array(
    'views_view__comments'=> [
        'template' => 'views/views-view--comments',
    ]);
 }

```

And then template in yout admin theme , or in your custom module. In my case in module forlder templates/view.
> 0 votes

---
Tags: comments
---


title: Delete a block of all layouts

text:
# Question
Title: Delete a block of all layouts
I am using Layout Builder (Drupal 8.7.1)

I have a block in several Layouts. How can I programmatically remove all instances of this block and update all layouts without the message "This block is broken or missing. You may be missing content or you might need to enable the original module." ?

# Answer
here it is, tried it with a custom content block and a views block

i executed the code in php/devel from devel\_php module

```
$storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
foreach ($storage->loadMultiple() as $display) {
  foreach ($display->getSections() as $section) {
    foreach ($section->getComponents() as $component) {
      // Custom views block
      // $to_delete_plugin_id = 'views_block:my_news-block_1';
      // Custom block
      $to_delete_plugin_id = 'block_content:fb4ad848-0f3c-4296-a6ba-1a9da886335b';
      if ($component->getPluginId() == $to_delete_plugin_id) {
        $section->removeComponent($component->getUuid());
        $display->save();
      }
    }
  }
}

```

for a particular node :

```
// This can be adapted to be used for a set of nodes
$node = node_load(42);
$display = $node->layout_builder__layout;

foreach ($display->getSections() as $section) {
  foreach ($section->getComponents() as $component) {
    // Custom views block
    // $to_delete_plugin_id = 'views_block:my_news-block_1';
    // Custom block
    $to_delete_plugin_id = 'block_content:fb4ad848-0f3c-4296-a6ba-1a9da886335b';
    if ($component->getPluginId() == $to_delete_plugin_id) {
      $section->removeComponent($component->getUuid());
      $node->save();
    }
  }
}

```

Hope this helps :)
> 11 votes

# Answer
Assuming you're using Layout Builder on a Node, and you're using "overrides" to allow each content to have it's own unique layout, the data you're looking for is in the `node__layout_builder__layout` table. You can look there and see that it stores a reference to the "ID" of the entity, and the UUID of the content. So, in the case of a block, because you may have deleted the instance, it will fail to find the UUID of this block content, and display the warning message.

I figured this would make a good contrib project, so I've created "Layout Builder Block Sanitizer", and released a dev version that allows you to go to a form, type in a node ID, and it will scan each section on that node automatically for "block\_content" that no longer exists, and remove it. Let me know if this helps out. As I've noted on the project page, this could definitely scale up and improve quite a bit from the current state, but should possibly help you out in this situation.

Check out the project here: https://www.drupal.org/project/layout\_builder\_block\_sanitizer
> 5 votes

---
Tags: 8, blocks, layout-builder
---


# Question
Title: Use a Twig filter to resize / crop images in templates
I want to use a twig filter to resize/crop images in Drupal 8 templates for responsive images, I know I can generate responsive images with Image Style and Responsive Image styles, but that requires too much clicking in 3 different configuration pages.

I would prefer something like:

```
<img
srcset="{{ image_url|crop(1000, 1000) }} 1000w, {{ image_url|crop(500, 500) }}
500w,"
sizes="..."
src="{{ image_url|crop(1000, 1000) }}"/>

```

Or something like LiipImagineBundle https://symfony.com/doc/master/bundles/LiipImagineBundle/basic-usage.html

Does somebody know if it's possible to use it with Drupal 8

# Answer
> -3 votes
After some research I found this is possible using Image Styles and Twig Tweak

I created 2 image styles scale and crop:

* scale\_crop\_1000\_1000
* scale\_crop\_500\_500

It is something like this:

```
<img srcset="{{ node.field_image.entity.uri.value | image_style('scale_crop_1000_1000') } 1000w,
{{ node.field_image.entity.uri.value | image_style('scale_crop_500_500') } 500w",
sizes="..."
src="{{ node.field_image.entity.uri.value | image_style('scale_crop_1000_1000') }" />

```

---
Tags: 8, theming
---


title: Add link for each column

text:
# Question
Title: Add link for each column
I'm working on tripal with drupal 7.x I have created new view. i had chosen the fields and i have this table.

i want to add the link for each row of the column map Name. i put this tag but i want to change the ID (85) for each row it correspondd to the ID of the map. How can i do? Thank you

# Answer
It seems you're trying to override output of a field in Views using information from one of the fields.

If you turn on the option to Output the field as a link, you shouldn't include the anchor HTML `<a href="...`, Drupal does that on its own when you turn this option.

If you want to control the HTML you shouldn't use the Output as link option. Instead enter your HTML into the Text area of the Rewrite field.

Or, if you want to use the Overwrite as link option only enter the HREF **value** into that field.

If we assume that the ID is a separate field then it needs to be added to the Views.

You can use the `Exclude from display` option if you don't want that field to be visible, but it must be present if you want to be able to use it.

Rearrange the order of the fields so the ID field is **above** the Map name field.

If the ID number is a part of the Map name field then you have the ID information already available as a token under Replacement patterns.

Edit the Map name field and open the Rewrite results option, then open the Replacement patterns under it. You will see a token for all fields available for that field. One of them will be the ID field. Copy that token and paste it into your HTML override, or the Link href (depending on which option you're using).

Save and check that your token is evaluated correctly and that the link/href is working as expected.
> 0 votes

---
Tags: views
---


# Question
Title: Drupal maintenance over several environments
I have a production environment for a Drupal 7 site.

This environment is replicated to a staging environment, which we use for testing updates to modules and drupal core (same major version).

We would like to sync this environment with the production one everytime we want to test an update, and then replicate the changes.

The way I envision the process is the following:

1. rsync everything from production to staging, getting the updated content from production and crushing any staging changes, deleting any files from staging that do not exist in production
2. replicate database from production to staging, so we can test pages and functionalities on production content replica
3. perform updates on the staging environment
4. rsync from staging to production, not deleting in production content that might not exist in staging

Question #1: Do updates make changes to the database? Or are these file only changes? Will rsync be enough to get the production in sync with staging after the updates?

Question #2: Is there a better, more robust way to achieve this?

Question #3: Should I set the site into maintenance mode while doing #4? Can this be done by setting maintenance mode programatically in a config file, rsync that file and everything else, then reset the maintenance mode and rsync that file? (I am looking to build a script to automate this)

# Answer
> 0 votes
> Question #1: Do updates make changes to the database? Or are these file only changes? Will rsync be enough to get the production in sync with staging after the updates?

Updates will most likely do changes to the database. That's where most of the fun comes in when doing updates :D

> Question #2: Is there a better, more robust way to achieve this?

Syncing production to the staging system every now and then is a good idea, I'm not sure if you need it everytime you want to test something. I'm assuming your deployments go through that staging system as well, so your content there will already be something you can test with. As far as I know there is no way to be 100% sure you're not going to kill your production environment. That's why you back up the database and the code and everything, before doing any change to production.

> Question #3: Should I set the site into maintenance mode while doing #4? Can this be done by setting maintenance mode programatically in a config file, rsync that file and everything else, then reset the maintenance mode and rsync that file? (I am looking to build a script to automate this)

You can set the maintenance mode using drush. https://drupal.stackexchange.com/a/32/47426 To disable maintenance mode, run the same command with 0/FALSE instead of 1/TRUE. And don't forget about the cache clear.

---
Tags: 7, database, updating, maintenance-mode
---


title: Is there a better way to style fields?

text:
# Question
Title: Is there a better way to style fields?
I'm learning twig and using it to format and style my fields. The problem I am running into is that I need to create a new twig template for each individual field.

In the example picture, I have `field--parent-task.html.twig`which allows me to edit 1 field (or the first field), but I will need to create 6 more templates with identical code structure, just to style and move the fields around.

Is there a more efficient way to do this? In the end, I will have 7 templates just to target different fields, but yet they are all on the same page. I know I can target classes, say `field__label`, but that is not what I need, since I will be moving these fields around, giving them unique positions on the page.

If it cannot be done and this is how it is in D8, that is fine, I will deal with it. But if not, is there a better approach? So I don't end up having a endless list of field templates just to add/tweak a few css styles?

# Answer
> 2 votes
I had a project that needed some specific markup for different fields, using field.html.twig only at least saved managing multiple files.

**field.html.twig:**

```
{%
  set themeGroupOne = [
    'first_field',
    'second_field',
  ]
%}

{%
  set themeGroupTwo = [
    'third_field',
    'fourth_field',
  ]
%}

{# field markup option #}
{% if field_name in themeGroupOne %}

  {% for item in items %}
    {{ item.content }}
  {% endfor %}

{# field markup option #}
{% elseif field_name in themeGroupTwo %}

  {% for item in items %}
    {{ item.content }}
  {% endfor %}

{# Final option, default field template #}
{% else %}

{% if label_hidden %}
<span{{ attributes.addClass('field', field_type | clean_class, field_name | clean_class) }}>
  {% if multiple %}
    {% for item in items %}
      <span{{ item.attributes.addClass('field-item', field_type | clean_class ~ '-item', field_name | clean_class ~ '-item') }}>{{ item.content }}</span>
    {% endfor %}
  {% else %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% endif %}
</span>
{% else %}
<label{{ title_attributes.addClass(field_type | clean_class, field_name | clean_class) }}>{{ label }}</label>
<span{{ attributes.addClass('field', 'with-label', field_type | clean_class, field_name | clean_class) }}>
  {% if multiple %}
    {% for item in items %}
      <span{{ item.attributes.addClass('field-item', field_type | clean_class ~ '-item', field_name | clean_class ~ '-item') }}>{{ item.content }}</span>
    {% endfor %}
  {% else %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% endif %}
</span>
{% endif %}

```

\*Note that the two fields:

* `field.field.paragraph.paragraph_type.field_h2`
* `field.field.node.node_type.field_h2`

will both register as `field_name == 'field_h2'` in **field.html.twig**, making it even easier to theme fields across your site.

---
Tags: 8, theming
---


# Question
Title: How to use managed_file to upload many files
I'm looking for a way to upload many files by means of the `managed_file` form API element. I would like it be like while uploading for node where is 'add new item' button. How to do it?

# Answer
You may want to use plupload form element instead. Install Plupload integration module and then use something like:

```
$form['my_element'] = array(
  '#type' => 'plupload',
  '#title' => t('Upload files'),
  '#description' => t('This multi-upload widget uses Plupload library.'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt  ods odp'),
    'my_custom_file_validator' => array('some validation criteria'),
  ),
  '#plupload_settings' => array(
    'runtimes' => 'html5',
    'chunk_size' => '1mb',
  ),
);

```
> 1 votes

# Answer
I used below Solution. Its worked for me. Click Here
> 0 votes

---
Tags: forms, files
---


# Question
Title: How to add file extensions while creating a field (type file) through the module installer.yaml?
I need to add 4 fields to an existing content type in Drupal 8 website, 2 of them is text another 2 is file type, I have a multisite setup and have 30 country-specific sites so I need to add for every locale site, Now I have created a module and created installer file, right now I am able to create the fields but I am unable to add the file extension to the file type field. can anyone please help with this?

I have followed this below documentation to create the filed.

https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type

# Answer
> 2 votes
Really, that's a task for the Features module. And even if you decide against fully using Features in the end, you could at least use it locally to export your content type and fields and see in the resulting installer files how the allowed file extensions needs to be defined in your own module then. As Features exports its config into ready-made modules. But going for fully using Features also will enable you to constantly **sync** certain config (content types, fields, image styles etc.) pretty easily **across all your multisite instances**.

1. Take one of your multisite instances where you have the content type like you want it to be on all other sites.
2. Go through Features' UI and create a features module from it (that's called "package", usually that goes under `/modules/features/my_package`).
3. Activate the resulting package (module) on all other instances.

---

Leaving the Features module and your package module activated on all instances now allows you to sync all following changes to your content type by a certain set of commands:

```
# In the site_foo instance export changes into its package module.
drush -y features:export my_package -l site_foo

# In the site_bar instance import the changes.
drush -y features:import:all --bundle my_bundle -l site_bar

# In the end export config as usual.
drush -y config:export -l site_foo
drush -y config:export -l site_bar

```

---

To have a file field install sample yaml:

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.paragraph.field_dlbox_files
    - paragraphs.paragraphs_type.dlbox
  module:
    - file
id: paragraph.dlbox.field_dlbox_files
field_name: field_dlbox_files
entity_type: paragraph
bundle: dlbox
label: Files
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  file_directory: paragraphs/dlboxfiles
  file_extensions: 'pdf doc docx'
  max_filesize: ''
  description_field: true
  handler: 'default:file'
  handler_settings: {  }
field_type: file

```

---
Tags: files, multi-sites
---


# Question
Title: How to print the URL path of a referenced node using paragraphs?
I'm trying to print out the url path of a node from a referenced entity paragraph field in my twig template however have not had any success so far. I have tried various common twig functions but with no luck.

Any ideas?

# Answer
Use the Twig path() function and build a node route with the target id of the reference field:

*paragraph.html.twig*

```
{% if paragraph.field_example.target_id %}
  <a href="{{ path('entity.node.canonical', {'node': paragraph.field_example.target_id}) }}">{{ 'View node page'|t }}</a>
{% endif %}

```

See https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates
> 4 votes

---
Tags: 8, theming, paragraphs
---


# Question
Title: Are changes to the user status stored somewhere?
I've made a pretty serious error of judgement creating a view for a client that shows users created before a date AND still active. The error was adding a date filter.

This was meant to be used at the end of each month, and it was, with an email of users sent to the client. Now, after many users have been blocked, they're showing back on the view I created.

With quarterly billing, this is an issue as new users get counted fine, but any old users who have been blocked since don't show. A year from now, this period could actually show zero users.

The accounts were blocked using the editable\_fields module.

# Answer
> 3 votes
Core doesn't store revisions/changes for the User entity type (the functionality simply isn't available out of the box).

So unless you have something like the User Revision module installed, or some custom functionality storing that data, you're unfortunately out of luck.

If you take regular backups, you might be able to fudge something together using those, but it would be a very manual process.

---
Tags: 7, users
---


# Question
Title: Using ImageStyle with dependency injection
Is there a way to use the *ImageStyle* class with dependency injection instead of a static call?

I am struggling to find an example.

At the moment I have a block which is importing the class with

```
use Drupal\image\Entity\ImageStyle;

```

And then calls the *load* method with

```
ImageStyle::load('machine_name')->buildUrl($path);

```

But I am wondering if there's a better way to do this?

# Answer
> 8 votes
Yes, inject the `entity_type.manager` service and load it that way:

```
$url = $this->entityTypeManager
  ->getStorage('image_style')
  ->load('machine_name')
  ->buildUrl($path);

```

---
Tags: 8
---


# Question
Title: Twig whitespace controls have no effect on fields
I am trying to iterate over a Paragraph field and apply a comma after each Paragraph item.

In the field template that outputs the Paragraph, I am trying:

```
{%- for item in items %}
  {{ item.content }}{{ not loop.last ? ', ' }}
{% endfor -%}

```

This puts the comma out, but there is a ton of whitespace all over:

I have tried many whitespace control combinations and none seem to have any effect.

How can I remove this sort of behavior entirely? The paragraph field is an entity reference, that renders a view mode, so I don't want to install field delimeter plugin.

edit: Tried the solutions mentioned here:

How remove whitespace on field in twig?

and here:

https://craftcms.stackexchange.com/questions/2789/whitespace-created-when-using-if-statements

as well as in the documentation.

The structure is as follows:

Node -\> Paragraph field -\> Paragraph (Entity) -\> User Reference + Plain text field + rich text

In this context, only the user field is being rendered, and I want to put a comma at the end of each linked name.

# Answer
Although the whitespace control modifier is supposed to work for all `{{ … }}` prints, `{% … %}` statements and `{# … #}` comments I'd expect to make your sample work it needs to be put directly into the print like that:

```
{% for item in items %}
  {{- item.content -}}{{- not loop.last ? ', ' -}}
{% endfor %}

```

Alternatively you could try to use the `{% spaceless %}` tag. But again, I'd expect this only works right when placed inside the loop:

```
{% for item in items %}
  {% spaceless %}
    {{ item.content }}{{ not loop.last ? ', ' }}
  {% endspaceless %}
{% endfor %}

```

> As of Twig 1.38, use the `|spaceless` filter instead.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How can I add folders to my template directory and have Twig find them?
I was listening to a Drupal Developer on youtube and one of the suggestions he has, is that when you go into a template folder, create some subdirectories for easier management, like this:

```
Templates
->Blocks
->Fields
 ->YourField.html.twig
->Nodes

```

So I want to do the same thing for my template folder, however when I do that, I get this error:

> Twig\Error\LoaderError: Template "modules/custom/task/templates/field--expire-date.html.twig" is not defined.

Now granted, I learned with Drupal that Twig + Theming Templates is different than Twig + Module Templates. I am using my own module.

Is there a way for me to tell Twig there is another subdirectory (Ex: Fields Folder), so it can find the code?

# Answer
In your "task" module you must have a task\_theme function where you've defined your templates. In there you'll need to update with your new paths too. e.g.

This

```
'template' => "field--expire-date.html.twig"

```

becomes:

```
'template' => "fields/field--expire-date.html.twig"

```
> 4 votes

---
Tags: 8, theming
---


# Question
Title: How do I fix missing input fields in panels
The site I am working on is Drupal7 site, built of panels and pages, panelizer. Typical steps to edit, admin logs in, click on the "customize this page" button, various panels open up, click on the gear of the panel you want to edit, edit screen opens, make your updates, click finish then slick save, and all is right with the world.

Yesterday one of the editors, following the steps above, attempted to edit, but the panels input box, for some reason, the actual area where you would add the content is collapsed/gone.

**It should look something like similar to this**:

Anyone have any idea on what is causing this or where should I even start checking to see why all the fields are not displaying?

Any and all suggestions would be appreciated.

Thanks in advance.

# Answer
Just a reference for those who come along after this.

Try to find out if anyone else has touched your code specifically .js or .CSS and CSS was the issue here. ONe of the content editors added some css into a block: `fieldset{display:none;}` well that closed the fieldsets in that popup window and I am sure in other places on the site that we had not run into yet.
> 0 votes

---
Tags: panels
---


# Question
Title: ThemeNegotiator not working for admin pages
I'm trying to use the ThemeNegotiator to change the theme of the add and edit pages of one content type. I've followed the following very extensive posts/blogs.

Don't use admin theme for adding editing specific content type

Dynamic theme switching in Drupal 8

Soft launching your new drupal theme

Choose your theme dynamically Drupal 8

I have a user that is allowed to see the Admin theme `seven`, but for one content type `documenten` I want him to see the front-end theme `svds`. I'm able to get this to work for front-end pages but not for admin pages. What I think is that the `applies` part doesn't match on the add and edit pages. So it doesn't know it's on a `documenten` content type. Does anyone has an idea on how to solve this?

Module structure:

```
theme_switcher
--src
----Theme
------SwitcherNegotiator.php
--theme_switcher.info.yml
--theme_switcher.services.yml

```

theme\_switcher.info.yml:

```
name: Theme Switcher
type: module
description: 'Switch theme for specific Content Type'
package: SVDS
core: 8.x

```

theme\_switcher.services.yml:

```
services:
    theme.negotiator.theme_switcher:
        class: Drupal\theme_switcher\Theme\SwitcherNegotiator
        tags:
          - { name: theme_negotiator, priority: -50 }

```

SwitcherNegotiator.php:

```
<?php
/**
 * @file
 * Contains \Drupal\theme_switcher\Theme\SwitcherNegotiator
 */

namespace Drupal\theme_switcher\Theme;

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;

class SwitcherNegotiator implements ThemeNegotiatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function applies(RouteMatchInterface $route_match)
    {
        // Use this theme on a certain route.
        $node = $route_match->getParameter('node');
        if (!is_null($node) && $node instanceof \Drupal\node\Entity\Node) {
            return $node->getType() == 'documenten';
        }

        // apply default theme
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function determineActiveTheme(RouteMatchInterface $route_match)
    {
        // Here you return the actual theme name.
        return 'svds';
    }
}

```

# Answer
The admin theme negotiator is tagged with a priority of -40:

*user.services.yml*

```
  theme.negotiator.admin_theme:
    class: Drupal\user\Theme\AdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -40 }

```

So you have to use at least -39, since the first negotiator returning a theme name wins and on an admin page this core service will return the admin theme.
> 2 votes

---
Tags: 8, theme-negotiation
---


# Question
Title: Why return AccessResult::allowed() ends up with "Access denied"?
I'm having a strange behaviour while trying to use hook\_node\_access in Drupal 8 (Lightning to be more precise) and I can't figure out why is doing this. Let's suppose that I want to always allow people to edit a certain content type (I know I can setup role permissions to achieve this, but I'm just trying to understand why it's not working):

```
function mymodule_node_access($node, $op, $account) {
  $type = $node->bundle();
  if($type == 'service' && $op == 'update') {
      return AccessResult::allowed();
  }
}

```

I always get "access denied" while trying to edit a "service" node.

This is what I've tried to do in order to debug it:

* in reports \> status reports there are no node access permissions in use;
* the current user does not have "bypass content access control" permission;
* hook\_module\_implements\_alter doesn't return any other module using hook\_node\_access.

Is there anything I'm missing?

# Answer
Although I've checked for other modules using hook\_node\_access, I forgot to check for hook\_entity\_access as well. It turned out that the "content moderation" module is denying access. Thanks @4k4 for making me revisit this!

Just for the record, if you need to see which other modules are using a certain hook, you can use something like this:

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if($hook == 'node_access') {
    //do whatever you need to do (e.g. use kint($implementations) to see what other modules are using this hook)
  }
}

```
> 5 votes

---
Tags: 8
---


# Question
Title: Override view-list and get items properties
I'm currently working on Bartik theme and i'm trying to create a custom template for the Content-Recent block available in Drupal 8 For your information, i would like to create the following block view :

For that, I've followed these steps :

* In Drupal 8 back-office, I've added the block view "Recent content" (Machine name : views\_block\__content\_recent\_block\_1)
* In my source code, I've created a new file in my templates folder and named : views-view-list--content-recent--block-1.html
* I've added a static text : "Hello world", just to check if the template has been override, and it's OK for this part.

But now, I'm stuck because I don't know how to retrieve item properties (Title, Date, Description) I've tried to find some informations with `kint()` and `dump()` but I'm bit lost :/

# Answer
This is the default template for a views-view-list.html.twig. Basically you've overwritten this template when you've created views-view-list--content-recent--block-1.html.

```
{#
/**
 * @file
 * Default theme implementation for a view template to display a list of rows.
 *
 * Available variables:
 * - attributes: HTML attributes for the container.
 * - rows: A list of rows for this list.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's contents.
 * - title: The title of this group of rows. May be empty.
 * - list: @todo.
 *   - type: Starting tag will be either a ul or ol.
 *   - attributes: HTML attributes for the list element.
 *
 * @see template_preprocess_views_view_list()
 *
 * @ingroup themeable
 */
#}
{% if attributes -%}
<div{{ attributes }}>
    {% endif %}
    {% if title %}
        <h3>{{ title }}</h3>
    {% endif %}

    <{{ list.type }}{{ list.attributes }}>

    {% for row in rows %}
        <li{{ row.attributes }}>{{ row.content }}</li>
    {% endfor %}

</{{ list.type }}>

{% if attributes -%}
    </div>
{% endif %}

```

What you could do is try adding something like this inside your "for" loop:

```
{% set item = row.content['#view'].style_plugin.render_tokens[ loop.index0 ] %}
{{ item['{{ title }}'] }}
{{ item['{{ field_date }}'] }}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to show contextual links / quick edit links for blocks
I'm building a Drupal 8 template/theme from scratch, and it is not showing the contextual editing options for my blocks when I view a site page. I.E., the little circles that are clicked to see options like "edit view," "configure block," etc.

I cloned the block.html.twig from the Bartik theme, so it has the attributes token that I thought was enough, like this:

```
<div{{ attributes.addClass(classes) }}>
 {{ title_prefix }}
 {% if label %}
   <h2{{ title_attributes }}>{{ label }}</h2>
 {% endif %}
 {{ title_suffix }}
 {% block content %}
   <div{{ content_attributes.addClass('content') }}>
     {{ content }}
   </div>
 {% endblock %}
 </div>

```

I can confirm the Contextual links module **is** active.

I have global access, so it shouldn't be a permissions issue.

Is there something more I need to do for this feature to be added in?

# Answer
Per 'No Sssweat's comment above, this was due to a small syntax error in a custom javascript file, viewable in console. Once corrected, the contextual links worked as intended.
> 0 votes

---
Tags: 8, theming
---


title: Hook for Node Add Field?

text:
# Question
Title: Hook for Node Add Field?
For my use case, this question revolves around the entities `node` and `paragraph`.

Fields in my projects are created under the following structure:

* content\_h2
* paragraph\_h2
* content\_p
* paragraph\_p
* ...

etc...

For example, I'd like to create `field_name` on a node, check if it exists in paragraph entity storage and if not create it. And the other way around.

I've had some success but it seems like more coding than needed.

**Does a hook exist for node add field?**

Example form class: `field-ui-field-storage-add-form`.

# Answer
By the way, all the hooks are listed here there doesn't appear one that fits the task tho.

You can always add a custom validation to the field add form.

```
/*
 * Implements hook_form_FORM_ID_alter()
 */
function mymodule_form_field_ui_field_storage_add_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['#validate'][] = 'mymodule_custom_add_field_validation';
}

/*
 * Custom Validate Callback
 */
function mymodule_custom_add_field_validation(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // the code that performs the check
  // if (......) {
  //   $form_state->setErrorByName('label',
  //     t('This field already exists in another entity'));
  // }
}

```
> 1 votes

---
Tags: 8, hooks
---


title: How to add the view name as body class

text:
# Question
Title: How to add the view name as body class
```
function THEMENAME_preprocess_views_view(&$variables){
        $view = $variables['view'];
      if($view->name == "YOUR_VIEW_NAME" && $view->current_display == "MACHINE_NAME_OF_VIEW"){
        $variables['attributes']['class'][] = 'page-'.$view->name;
    }

```

For some reason this does not work. Any ideas?

# Answer
> 0 votes
this one worked:

```
function THEMENAME_preprocess_html(&$variables) {
  //view name as body class
  $variables['view_title'] = '';
  $route = \Drupal::routeMatch()->getRouteObject();
  if ($route) {
    $view_title = $route->getDefault('_title');
    $variables['attributes']['class'][] = 'view-' . Html::cleanCssIdentifier($view_title);
  }
}

```

---
Tags: views, 8
---


title: How do I render a form?

text:
# Question
Title: How do I render a form?
What is the alternative to `drupal_get_form('user_login')`. in Drupal 8?

I am using the following code in theme\_name.theme, but it doesn't work.

```
// Include namespace for userLoginForm.
use \Drupal\Core\core\modules\user\src\Form;

function MYTHEMENAME_preprocess_page(&$variables) {
  $form = UserLoginForm::create();
}

```

# Answer
`drupal_get_form()` has been replaced by the form builder service, e.g.:

```
$form = \Drupal::formBuilder()->getForm(\Drupal\user\Form\UserLoginForm::class);

```

See the Change Record for more details.

Actually, don't - that change record is incorrect. It'll tell you to pass the form ID, when in fact you need to pass the class string.
> 36 votes

# Answer
You can create a form under form folder . And then you can call your form anywhere and pass the paramater as shown.

**Drupal 7** : `$form = drupal_get_form('form_id',$parameter);`

**Drupal 8** : `$form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomModuleForm',$parameter);`
> 15 votes

# Answer
There are two options to return(D8) or render(D7) a form. These are `\Drupal::formBuilder()->getForm` and `Drupal::formBuilder()->buildForm`. I use **`\Drupal::formBuilder()->getForm`** as below.

Use this if **you are not passing** a parameter:

```
$form = \Drupal::formBuilder()->getForm('\Drupal\example\Form\ExampleForm');
return $form;

```

Use this if **you are passing** a parameter:

```
$parameter = "your_parameter";
$form = \Drupal::formBuilder()->getForm('\Drupal\example\Form\ExampleForm', $parameter);
return $form;
//pass to formbuild function
public function buildForm(array $form, FormStateInterface $form_state, $parameter = NULL){//form code}

```

---

Drupal 7 Equivalent of the above:
```
$parameter = 'your_parameter';
$form = drupal_get_form('form_id', $parameter);
print drupal_render($form);
//pass to form function
function form_id ($form, &$form_state, $parameter){//form code}

```

Cheers. Let me know if it helps.
> 8 votes

# Answer
The documentation does allow an instance of the class as well. So

```
$formObj = new \Drupal\demo\Form\MyForm();
$form = \Drupal::formBuilder()->getForm($formObj);

```

is also correct.
> 1 votes

# Answer
Ok if all else fails here is a sneaky trick by setting a new form state object.

```
use Drupal\Core\Form\FormState;
...

$form_state = new FormState();
$form_state->set('name', $name);
$form_state->set('user', $user);
$render_array = \Drupal::formBuilder()->buildForm('\Drupal\mod\Form\MyForm', $form_state);
...
// Example render.
$response = new AjaxResponse();
// Show a dialog box.
$dialogText['#attached']['library'][] = 'core/drupal.dialog.ajax';
$response->addCommand(new OpenModalDialogCommand("Dialog Title", $render_array, ['width' => '300']));
return $response;

```

... then in your form method buildForm you can then...

```
 // Get form state.
 $name = $form_state->get('name');
 if (!empty($name)) {
    $form['name'] = [
      '#type' => 'item',
      '#markup' => $name,
    ];
  }

```
> 1 votes

# Answer
Assuming the below is your form class

```
namespace Drupal\demo\Form;
use \Drupal\Core\Form\FormBase;
class MyForm extends FormBase {
}

```

You have to create a new instance from your form class first, and pass it to formBuilder's getForm.

```
$form_obj = new \Drupal\demo\Form\MyForm();
$form = \Drupal::formBuilder()->getForm($form_obj);

```
> -1 votes

---
Tags: forms, 8
---


# Question
Title: Custom search function with result from external url
I need to create a page in Drupal 8 where there is a text field and a search button. When the user has entered a word to search and hit the search button a list with a search result should be displayed.

The search should go against this endpoint: https://example.com/api/json/1.0/searchProduct.json?query=\[SEARCHWORD\] Where \[SEARCHWORD\] is replaced with for example **Stockholm** and results are shown.

If more than 5 results are shown a pager should show up.

Have search the internet for tips or solutions, but couldn't find anything.. Is there anyone who has a clue that can point me in the right direction?

# Answer
> 1 votes
Hello since you are new to Drupal Answers I'll help you get started, but in future this type of question is way to specific and a self directed learning approach is better.

Well here we go this will get you pointed in the direction you need.

First: you need to find out how to make a custom module (quite easy) suggested google search "How to make Drupal 8 Module" -- then take you pick

-- option 1) (do it in a form with AJAX)

1.A) you need to find out how to make a form suggested google search "How to make Drupal 8 form" \- (read and understand) https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api

1.b) in that form create a text field. called "search"

1.c) Search Google for "drupal 8 ajax form example" -- (read and understand) https://www.drupal.org/docs/8/api/javascript-api/ajax-forms

1.d) in the form ajax call back:

```
 // example
 $url = 'http://systembevakningsagenten.se/api/json/1.0/searchProduct.json?query=';
 $term = $form_state->getValue('search');
 $query_url = $url. $term;
 $client =  \Drupal::httpClient();
 $request = $client->get($query_url);
 $data = json_decode($request->getBody(), TRUE);
 $results = [];
 if (!empty($data) && !empty($data['items'])) {
   foreach ($data['items'] as $item ) {
     $results[] = $item['name'];
   }
 }

```

at this point $results is what you want to display .. if you did step "1.c" it will be easy for you.

-- or -- Option 2 Do it in JS

2.a) Learn how and create a controller aka https://www.drupal.org/docs/8/creating-custom-modules/adding-a-basic-controller

2.b) Learn about drupal 8 add js to controller aka read and understand https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

* Key points: Defining a library (your\_module.libraries.yml)

Attaching a library to page (controller) $build\['#attached'\]\['library'\]\[\] = 'your\_module/library\_name';

2.c) Read https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

2.d) once you have a controller with some custom js file attached then, you can use mark up from controller to create the form, and use js to make the calls and update the markup.

-- or -- Option 3) do this in a block

2.a) find out how to make a block aka Google "Drupal 8 how to make a block"

2.c) use above options to deliver the functionality you require.

And with that this will get you started ! if not point you in the correct direction of how to.

---
Tags: javascript, 8
---


# Question
Title: Create an install profile with a config export
I want to create a Drupal 8 profile installer with a config export, to export regulary my config to push data modifications in git.

I tried this tutorial: https://www.valuebound.com/resources/blog/how-to-create-installation-profile-in-Drupal8 but it dont worked. And i exported the configuration with `drupal config:export –remove-uuid --remove-config-hash`

# Answer
> 1 votes
1. learn about `drush cex` (`drush config-export`) and Sync

https://www.drupal.org/docs/8/configuration-management/changing-the-storage-location-of-the-sync-directory

2. when you make config changes run `drush cex` then commit the changes.
3. on live when updated from git you need to run `drush cim` (which imports the config)
4. stuff to watch out for you want to make sure your site UUIDs match: aka

drush cget system.site uuid (gets UUID) drush cset system.site uuid (sets UUID)
5. if still stuck read How can I import the configuration on a different site?

# Answer
> 0 votes
Welcome to the community. I'll do my best to try and help here - You may want to look into Features - https://www.drupal.org/project/features. At this time, it's actually a really easy way to bundle functionality into an install profile in the form of modules. All the UUIDs are stripped out, and you can package up your functionality into discrete modules. Once "out in the wild", you'll have to consider that sites may modify the configuration, so any updates you provide will have the caveat that users manually reconcile the changes if they've started using configuration management on their site. If they haven't they can use `features_revert` and "update" the config to match whatever changes you shipped in the "Features module".

It's certainly not perfect, but given current options, it's workable for a distribution, or in many cases an install profile. As the Features project page puts it, "Most Drupal 8 sites should not need Features", but they go on to say "If you are building a Distribution you can still use Features to export specific configuration into your profile or modules."

Hopefully, we'll have some great improvements to this system with "CMI 2.0" - https://www.drupal.org/project/cmi2

---
Tags: installation-profiles
---


title: Excluding inline images in views

text:
# Question
Title: Excluding inline images in views
I have a node type with an image field and insert button to get the image into the text field.

Then there is a view that is getting the content of the text field and shortening it to 150 characters. But if there is an inline image at the beginning of the text the view is only showing three points that are linked to the image.

How can I exclude the inline images from views?

# Answer
You could use the `Rewrite results` option on that field and choose **Strip HTML tags**.

This will "remove" the image from display.

If you have some other HTML inside the Body that you want to keep you can enter them into the `Preserve certain tags` field, for example `<em> <span> <p>`.
> 2 votes

---
Tags: views, 8, nodes
---


title: Adding a script to certain pages

text:
# Question
Title: Adding a script to certain pages
I am trying to add a script code on all but few pages. I tried the following code on the template.php bfile, but it doesn't work.

```
 function THEME_preprocess_page(&$variables) {
   if (isset($variables['node']->type)) {
     $variables['theme_hook_suggestions'][] = 'page__' .
     $variables['node']->type;
   }

   if ($variables['nid'] == '77') {
     drupal_add_js(drupal_get_path('theme', 'THEME') .'/scripts/path.js');
   }
 }

```

# Answer
> 0 votes
You should try below solution as well. I have added JS & CSS for the specific node.

```
function YOURTHEME_preprocess_page(&$variables){
  if (array_key_exists('node', $variables)) {
    $node = $variables['node'];
    if ($node->nid == 8) {
      drupal_add_css(path_to_theme() . '/css/cdata.css', array('group' => CSS_THEME, 'media' => 'screen', 'every_page' => TRUE, 'browsers' => array('IE' => 'gte IE 9', '!IE' => FALSE), 'preprocess' => FALSE));
      drupal_add_js(path_to_theme() .'/js/custom_records.js', 'file');
    }
  }
}

```

---
Tags: 7, theming
---