# Question
Title: Node body to entity reference revision (paragraph) field not working/processing
I want to migrate the Drupal 7 body of my blog to a Drupal 8 paragraph (field\_stories\_content which is Entity reference revisions).
The body is to be assign to the field\_stories\_text\_formatted field.

1- I have my first migration (mm\_d7\_node\_blog\_body\_to\_paragraph) with a source of d7\_node, and a destination of entity\_reference\_revisions:paragraph to create the paragraphs using the plugin mmNodeBlogBodyToParagraph.php.
2- I do the actual node migration where I lookup the result of the first migration and use it in the process for my new paragraph field (field\_stories\_text\_formatted) in the node migration (mm\_d7\_node\_blog).

```
node__field_stories_content (TABLE, Entity reference revisions field)
bundle
entity_id
revision_id
field_stories_content_target_id
field_stories_content_target_revision_id

paragraph__field_stories_text_formatted  (TABLE, paragraph)
bundle
entity_id
revision_id
field_stories_text_formatted_value

entity_id is field_stories_content_target_id
revision_id is field_stories_content_target_revision_id

```

But It is not processing and I don't know why. What am I missing?

This is what I have so far.

### migrate\_plus.migration.mm\_d7\_mm\_blog.yml

```
langcode: en
status: true
dependencies: {  }
id: mm_d7_node_blog
label: 'Blog -> Article (Nodes)'
source:
  plugin: d7_node
  node_type: blog
destination:
  plugin: 'entity:node'
migration_dependencies: {  }
process:
  type:
    plugin: default_value
    default_value: article

field_stories_content/target_id:
  plugin: migration_lookup
  migration: mm_d7_node_blog_body_to_paragraph
  no_stub: true
  source: nid

field_stories_content/target_revision_id:
  plugin: migration_lookup
  migration: mm_d7_node_blog_body_to_paragraph
  no_stub: true
  source: nid

```

### migrate\_plus.migration.mm\_d7\_node\_blog\_body\_to\_paragraph.yml

```
  langcode: en
  status: true
  dependencies: {  }
  id: mm_d7_node_blog_body_to_paragraph
  source:
    plugin: d7_node
    node_type: blog
  destination:
    plugin: 'entity_reference_revisions:paragraph'
    default_bundle: field_stories_text_formatted
  migration_dependencies:
    required:
      - mm_node_blog_body_to_paragraph
  process:
    field_stories_text_formatted:
      plugin: mm_node_blog_body_to_paragraph
      no_stub: true
      'field_stories_text_formatted/value': body
      'field_stories_text_formatted/format':
         plugin: default_value
         default_value: full_html
       source: nid

```

### mmNodeBlogBodyToParagraph.php

```
<?php

namespace Drupal\mm_migrate\Plugin\migrate\process;

use Drupal\migrate\MigrateException;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
* Provides a 'MmNodeBlogBodyToParagraph' migrate process plugin.
*
* @MigrateProcessPlugin(
*  id = "mm_node_blog_body_to_paragraph",
* )
*/
class MmNodeBlogBodyToParagraph extends ProcessPluginBase  {
  /**
 * {@inheritdoc}
 */
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $body = $row->getSourceProperty("field_body")[0]["value"];
    $nid = $row->getSourceProperty("nid");
    $paragraph_text_values = array(
   'field_stories_text_formatted' => array(
     'bundle' => 'stories_text',
     'value' => $body,
     'format' => 'full_html',
   ),
  );
      $paragraph_text_paragraph = Paragraph::create($paragraph_text_values);
      var_dump("--------------------------------PARAGRAPH paragraph_text *********** ------------------------------------");
      var_dump($paragraph_text_values);
      $paragraph_text_paragraph->save();

      $target_id_dest = $paragraph_text_paragraph->Id();
      $target_revision_id_dest = $paragraph_text_paragraph->getRevisionId();
      //node__field_stories_content (TABLE) -> field_stories_content_target_id, field_stories_content_target_revision_id
      //paragraph__field_stories_text_formatted  (TABLE) -> bundle, entity_id, revision_id, field_stories_text_formatted_value
      //entity_id => field_stories_content_target_id & revision_id => field_stories_content_target_revision_id

     $paragraphs[] = array('target_id' => $target_id_dest, 'target_revision_id' => $target_revision_id_dest);

      $node = entity_load('node', $nid);
      $node->field_stories_content = array( $paragraph_text_paragraph);
      //$node->save();
      return paragraphs;
   }
}

```

----------- **Update** based on @Hudri feedback ----------

**migrate\_plus.migration.mm\_d7\_mm\_blog.yml**

```
langcode: en
status: true
dependencies: {  }
id: mm_d7_node_blog
label: 'Blog -> Article (Nodes)'
source:
  plugin: d7_node
  node_type: blog
destination:
  plugin: 'entity:node'
migration_dependencies:
  required:
    - mm_d7_node_blog_body_to_paragraph
  optional: {  }
process:
  type:
    plugin: default_value
    default_value: article

  title: title

  field_stories_content:
-
  plugin: migration_lookup
  migration: mm_d7_node_blog_body_to_paragraph
  no_stub: true
-
  plugin: iterator
  process:
    target_id: '0'
    target_revision_id: '1'

```

**migrate\_plus.migration.mm\_d7\_node\_blog\_body\_to\_paragraph.yml**

```
langcode: en
status: true
dependencies: {  }
id: mm_d7_node_blog_body_to_paragraph
label: 'Blog body -> Paragraph'
source:
plugin: d7_node
node_type: blog
destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: field_stories_text_formatted
migration_dependencies:
  required: { }
  optional: { }
process:
  field_stories_text_formatted/value:
    plugin: entity_generate
    source: field_stories_text_formatted
    default_values:
    'field_stories_text_formatted/value': 'field_body/0/value'
    'field_stories_text_formatted/format':
       plugin: default_value
       default_value: 'full_html'
     no_stub: true
     bundle: 'stories_text'

```

After making changes it is still not processing. Am I missing something

# Answer
> 1 votes
This is what work for me (hope it helps):
**migrate\_plus.migration.mm\_d7\_node\_blog.yml**

```
langcode: en
status: true
dependencies: {  }
id: mm_d7_node_blog
label: 'Blog -> Article (node)'
source:
  plugin: d7_node
  node_type: blog
destination:
  plugin: 'entity:node'
process:
  #create temporary field to call plugin that create the paragraph
  _field_stories_text_formatted:
    plugin: mm_node_blog_body_to_paragraph_plugin
    source: 'field_body/0/format'
title: title
field_stories_content/target_id:
no_stub: true
plugin: extract
source: '@_field_stories_text_formatted'
index:
  - 0
  - entity_id
field_stories_content/target_revision_id:
no_stub: true
plugin: extract
source: '@_field_stories_text_formatted'
index:
  - 0
  - revision_id
migration_dependencies:
  required:
    - mm_node_blog_body_to_paragraph_plugin

```

**mmNodeBlogBodyToParagraph.php**

```
<?php

namespace Drupal\mm_migrate\Plugin\migrate\process;

use Drupal\migrate\MigrateException;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
  * Provides a 'MmNodeBlogBodyToParagraph' migrate process plugin.
  *
  * @MigrateProcessPlugin(
  *  id = "mm_node_blog_body_to_paragraph_plugin",
  * )
  * *
  * To do create a paragraph type field_stories_text_formatted:
  *
  * @code
  * field_stories_text_formatted:
  *   plugin: mm_node_blog_body_to_paragraph_plugin
  *   source: 'field_body/0/format'
  * @endcode
  *
  */

class MmNodeBlogBodyToParagraph extends ProcessPluginBase  {
  /**
 * {@inheritdoc}
 */
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
   $body = $row->getSourceProperty("field_body")[0]["value"];

   $ppt_values = array(
       'type' => 'stories_text',
        'bundle' => 'stories_text',
        'field_stories_text_formatted' => array(
          'value' => $body,
          'format' => 'full_html',
        ),
      );

  $ppt_paragraph = Paragraph::create($ppt_values);
      $ppt_paragraph->save();

      $target_id_dest = $ppt_paragraph->id();
      $target_revision_id_dest = $ppt_paragraph->getRevisionId();
      $paragraphs[] = [ 'entity_id' => $target_id_dest, 'revision_id' => $target_revision_id_dest, ];

        return $paragraphs;
    }
}

```

---
Tags: 8, nodes, migrations, paragraphs
---


# Question
Title: Failed to load popup dialog with in views
I am using Drupal 8.6.1 with the 8.x-1.0-alpha2 Footable module and the core dialog.

What I did so far:

* Install the Footable module.
* Download the most recent 3.x.x version of the FooTable jQuery plugin from https://github.com/fooplugins/FooTable/tags and move the contents of the **compiled** directory into the **libraries/footable** directory.
* I have created a simple "footable" views showing all articles with below fields:

+ Title (Title)
    + Body (Body)
    + Image (Image)
    + Tags (Tags)
* Configured the footable settings to hide the below element on any device:

+ Body (Body)
    + Image (Image)
    + Tags (Tags)
* So far, the footable view is working just as expected without no error at all.

**Here is an image:**

Now, I want when I click on the title field, a dialog popup will open displaying me the contents of the `/node/{{ node:nid }}` in that popup so:

* Under the advanced Section, Set the Use Ajax to: **Yes**
* Add the Content: ID to the footable view but excluded form the display.
* Edit the **title** field:

+ Uncheck the "Link to the Content" box.
    + Check the "Override the output of this field with custom text" box.
    + Add this line of code: `<a class="use-ajax" data-dialog-type="modal" href="/node/{{ nid }}">{{ title }}</a>`

Now, If I visit the Footbale view page, the footable is working prefectly but when I click on any **title**, the entire page will refresh and redirect me to `/node/{{ nid }}` path with no any dialog poping up.

Am I missing something here in my configuration ?!

**NOTE:**

If I change the view display from **Footable** to any other display like for example the built-in **Table**, the dialog will popup without any issues at all.

Thank you,

# Answer
After further Google search I found this Webform issue.

**Solution:**

You have to use the Footable **dev version** and not the **alpha2** version.
> 0 votes

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


# Question
Title: How do I save a new field value for node without saving the node?
I am developing a Drupal 8 website and I added a new field to a custom content type called Download. This field is updated each time a file is downloaded from this content type. I use hook\_file\_access to find a node from which a file was downloaded. I then get current download count value by getting a field from a node. The value is incremented by 1 and the new value is stored in the field. I then save the node to store the value. Below is the code used for node (field change) saving:

```
$field_download_count = $entity->get('field_download_count')->get(0);
if ($field_download_count == null) {
    $download_count = 1;
} else {
    $download_count = $field_download_count->getValue()['value'];
    $download_count += 1;
}
$entity->set('field_download_count', $download_count);
$entity->setNewRevision(false);
$entity->save();

```

The problem is that with this code, updated date of the content changes and this is a problem for me as I use updated date in many view and data is not valid as per this code, updated date is changed with each file download from the node.

**Is there a way to store the field value only on Drupal 8?**

In Drupal 7, one could use field\_attach\_update but this function was removed in Drupal 8.

I tried to update the field value using Drupal update SQL function, but this is not a proper way and also didn't play well with a cache system.

# Answer
> 2 votes
You could directly update the field table in the database ?

$database = \Drupal::database(); $result = $database-\>query("UPDATE node\__field\_download\_count SET field\_download\_count = field\_download\_count + 1 WHERE entity\_id = " . $entity\_id);

---
Tags: 8, entities
---


title: Node urls indexed by Google

text:
# Question
Title: Node urls indexed by Google
I am pretty new to Drupal, can someone tell me why ive got lots of node urls in my index on Google, is this because i havent given the post on my site a friendly url ?

Is there a way to fix this or do i have to edit every post with a node url ?

Is there a way to stop this happening in future

JC

# Answer
If you want to reduce the content indexed by search engines use your robots.txt file to instruct them to ignore certain paths or sets of paths.

Many Drupal projects use Path, Pathauto and one of redirect modules to automatically assign aliases to links. Usually, the path pattern is set to automatically replace `node/[nid]` with something like `content/[title]`. Globalredirect or Redirect modules permanently automatically redirect from the default Drupal query to the alias, so there is nothing else you have to do (no need to edit Robots.txt unless you want to exclude some of them).

Path aliases can be generated automatically for existing content so it will work for your case and also in the future.
> 1 votes

---
Tags: nodes
---


# Question
Title: What should I use in Drupal 8 instead of votingapi_set_vote()?
VotingAPI docs are out of date. `votingapi_set_vote()` has been removed in Drupal 8.

What should I use in its place to programmatically set votes (for instance in a migration)?

# Answer
> 1 votes
> Do you know how to set votes programmatically?

```
use Drupal\votingapi\Entity\Vote;

$vote = Vote::create(['type' => 'vote']); // this comes from /admin/structure/vote-types
$vote->setVotedEntityType('node'); // entity type
$vote->setVotedEntityId($nid); // node id
$vote->setValueType('points'); // this comes from /admin/structure/vote-types
$vote->setValue(1); // the number of points given per vote
$vote->setOwnerId($uid); // the user id of the person who casted the vote
$vote->setCreatedTime($timestamp) // timestamp of when vote was casted (optional)
// it will use the current time if you don't include it
$vote->save();

```

The above code will create 1 casted vote. Therefore, you will have to run this code for every single vote.

---
Tags: 8
---


# Question
Title: Drush is updated but not usable in Drupal 8 in Windows
Is this a bug? I've the version that does support Drupal 8, so what is actually the problem here?

## Update

I followed kiamlaluno and seem to have updated Drush but I still get the same error. I haven't touched the settings.php file. It's a totally brand new site so I would still get an error :\

# Answer
> 5 votes
As reported in Drupal Compatibility, only Drush 8 and higher versions are compatible with Drupal 8. To be more exact, Drush 8 is compatible with Drupal 8.3 or previous versions, while Drush 9 (the master branch) is compatible with Drupal 8.4 or higher versions.

```
Drush Version   Drush Branch    PHP     Compatible Drupal versions
Drush 9         master          5.6+    D8.4+
Drush 8         8.x             5.4.5+  D6, D7, D8.3-
Drush 7         7.x             5.3.0+  D6, D7        Unsupported
Drush 6         6.x             5.3.0+  D6, D7        Unsupported
Drush 5         5.x             5.2.0+  D6, D7        Unsupported

```

\[Copy of the table taken from Drush documentation on October 24, 2018\]

When this answer was written, Drupal 8.4 didn't exist, and Drush 8 (the master branch at the time) was compatible with every Drupal 8 release existing at that time.

Since you are using Drush 7, you are using a version that is not compatible with Drupal 8 (and it's not even supported anymore). To install Drush master as global Composer package, you need to run the following command.

```
composer global require drush/drush:dev-master --prefer-source

```

On OS X, if you have Homebrew installed, you just need to run the following command, which would install Drush 8.

```
brew install drush

```

After I do that, `drush --version` returns me the following.

> Drush Version : 8.0.0

On Windows, the Drush documentation suggests:

You probably need to first remove Drush 7.

# Answer
> 6 votes
You need drush 8 for drupal 8. You have drush 7 installed.

# Answer
> -1 votes
Please, use as simple as: `composer require "drush/drush:^9.0"` in folder within composer.json

---
Tags: drush, 8
---


# Question
Title: Print Webform reference in custom view display
On our D8 site we have a content type with a webform reference field `field_reference_webform`. We then created a view with a custom views display style plugin for above content type that uses the webform reference field `field_reference_webform`.

What we want to achieve is to print the webform field in our custom view display style directly via views-view-our-display-plugin.html.twig.

The contents of our Webform reference field, however, wouldn't print. We tried to print it with below code:

```
{% if rows|length %}
{% for row in rows %}
{{ row._entity.field_reference_webform }}
{% endfor %}
{% endif %}

```

Instead we get the following error:

```
Object of type Drupal\webform\Plugin\Field\FieldType\WebformEntityReferenceFieldItemList cannot be printed

```

We cannot figure out what we got wrong.

We are on Drupal 8.6.2 using Webform 8.x-5.0-rc22

# Answer
> 2 votes
At first glance it would seem you need to render this webform yourself in a preprocess function and then pass it to twig. You are trying to access the entity object using row.\_entity.field\_reference\_webform which is protected from outside access. However views should already be rendering this webform. I think maybe your template file is just setup wrong. All you have done is create a view, and put a template file for it in your theme correct?

For row level output, if your display is setup as unformatted list, your views twig file should be named:

```
views-view-unformatted--our-display-plugin.html.twig

```

and the basic code inside it should be:

```
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}

```

Just use {{ row.content }} which should have the rendered webform in it already.

If that doesn't work perhaps we need more information on what exactly youre trying to create a template file for. The view container, the row level, or the field level.

# Answer
> 1 votes
Thanks to Matt's answer we could solve the problem as follows:

In custom\_view\_format.theme.inc we implemented a preprocess function:

```
function template_preprocess_views_view_sunlime_custom_view_format(&$variables) {
// View options set by user.
$options = $variables['view']->style_plugin->options;

$rows = $variables['rows'];

if($rows && sizeof($rows) > 0){
  $idx = 0;
  foreach($rows as $row){

  // We need to preprocess the referenced webform object to output it as desired in the twig template
  $webform = $row->_entity->field_candidate_status_client[0];

  // Get the machine name from the referenced webform data
  $webform_machinename = $webform->target_id;

  // Init the webform object with the given machine name
  $my_form = \Drupal\webform\Entity\Webform::load($webform_machinename);

  // Generate the output from the generated webform object

  $output = \Drupal::entityTypeManager()
                   ->getViewBuilder('webform')
                   ->view($my_form);

  // Set this output into a custom variable so it can be accessed in the twig file
  $variables['sl_webform'][$idx]['field_candidate_status_client'] = $output;

  $idx++;
  }
 }
}

```

Then he printed the webform field in the twig template like below:

```
<div class="col col-lg-6">
  {# Access the rendered webform from our own variables array - see docroot/modules/custom/custom_view_format/sunlime_custom_view_format.theme.inc #}
  {{ attribute(sl_webform,idx).field_candidate_status_client }}
</div>

```

---
Tags: theming
---


# Question
Title: I am trying to update my site to 8.6.3 and I receive the following message
When I try to update Drupal to **8.6.3** i receive the message

> CONFIGURATION DIRECTORY: SYNC The directory drupal-8/sites/default/config\_acq does not exist.

I don't know what to do. Please help me

# Answer
Add the following to your `settings.php` file:

```
$config_directories = array(
CONFIG_SYNC_DIRECTORY => 'sites/default/files',
);

```

For more information take a look to this issue
> 0 votes

# Answer
Two ways to resolve your concerns

1. Either create the folder at specified location
2. Or change the setting into settings.php file. Below is the code

$config\_directories\['sync'\] = 'Path of sync directory';
> 0 votes

---
Tags: 8, updating
---


# Question
Title: How to hide node/add and */edit page titles
Need to change Drupal 8 node/add page titles - there have been some answers here (most for Drupal 7), but none of them have worked.

So there is always Create in front of the title in add page - need to drop the part Create - how ?

Need to drop also word Edit in from the already created node in edit mode - how ?

If someone can point me in right direction and give me \_preprocess\_node\_add\_list or some node preprocess sample.

Regards

Virgo

# Answer
Try with `hook_preprocess_page_title`

```
function myModule_preprocess_page_title(&$variables) {
  //- Get the Current route name
  $route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    //- Add node Page
    case 'node.add' :
      $variables['title'] = t('New add page title');
      break;
    //- Edit node Page
    case 'entity.node.edit_form' :
      $variables['title'] = t('test');
      break;
  }
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to display custom token in custom block
In a Drupal 8 website I created a custom token that is working in basic page.

Then I created a custom block with a WYSIWYG field :

```
class Myblock extends BlockBase {

  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public function getMachineName() {
    return 'my_custom_blcok';
  }

  public function label() {
    return $this->t('Block label');
  }

  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $form['my_field'] = [
      '#type' => 'text_format',
      '#format' => 'content_manager',
      '#title' => $this->t('Field name'),
      '#default_value' => isset($config['my_field']['value']) ? $config['my_field']['value'] : '',
    ];

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->setConfigurationValue('my_field', $form_state->getValue('my_field'));
  }

  public function build() {
    $config = $this->getConfiguration();
    $content = $config['my_field']['value'];

    return [
        '#theme' => 'simulator_block',
        '#content' => $content,
      ];
  }
}

```

If I type `My content [module:my_token]` in the WYSIWYG.

The following content is display :

```
<p>My content [module:my_token]</p>

```

How can I replace the token ?

# Answer
> 2 votes
Place the formatted text in a render element `processed_text`:

```
 $content = [
    '#type' => 'processed_text',
    '#text' => $config['my_field']['value'],
    '#format' => 'content_manager',
  ];

  return [
    '#theme' => 'simulator_block',
    '#content' => $content,
  ];

```

Configure the text format to include the token filter.

---
Tags: 8, tokens
---


# Question
Title: How to pipe output of "drush sql-dump" without warnings
When I do: `drush sql-dump > somewhere/database.sql` if there will be any warnings printed by Drush, they will be included at the beginning of the created database.sql file. Can we avoid it somehow?

I know there is the `--result-file=` option that ignores all warnings when creating the file, but is there any way to ignore warnings when piping the output? I would like to parse the output before actually saving it into a file if its possible.

`drush 8`

# Answer
> 0 votes
Seems `-q` should do the job.

> ```
> $options['quiet'] = array(
>   'short-form' => 'q',
>   'description' => 'Suppress non-error messages.',
> );
>
> ```

Source: `function drush_get_global_options`

---
Tags: drush
---


# Question
Title: Create a webform which creates a user account
I'm looking to create a user registration form on a Drupal 8 site that has multiple clearly defined sections (possibly on separate pages).

I've explored doing this with the standard Drupal registration form building tools in account settings but it doesn't seem possible to create a form with such a layout using just account settings (correct me if I'm wrong).

The webform module allows me to create a form which is styled exactly how I want but I'm not sure how to create a user account with data entered into a webform. Is there another module I can use for this or can I do it from within the webform module?

# Answer
> 2 votes
So as I mentioned in my comment, the proper way to achieve this is to use the `Handlers` functionality in Webform, for that we need a custom module for our `Handler` to show up in `admin/structure/webform/manage/[WebformName]/handlers`

One thing that you need to make sure is correct, is the structure of the module folder, so that webform would read it as a `handler`, we assume the module name here is: `webform_handler_user_creation` so the structure would be something like this: `webform_handler_user_creation>src>Plugin>WebformHandler>UserCreationHandler.php` with a `webform_handler_user_creation.info.yml` file in the root of the module directory.

With all that said, here's an example of the module on my github page

So what we need to do first is to make sure we do our thing after saving the webform submission, then load the submission values and use them based on their machine names to fill in our user creation thingy, here's the code:

```
<?php
namespace Drupal\webform_handler_user_creation\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;
/**
 * Webform submission action handler.
 *
 * @WebformHandler(
 *   id = "usercreate",
 *   label = @Translation("User Create"),
 *   category = @Translation("Action"),
 *   description = @Translation("Creates a user after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */

class UserCreationHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
        $user = \Drupal\user\Entity\User::create();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $user_name = $webform_submission->getElementData('user_name');
        // Mandatory user creation settings
        $user->enforceIsNew();
        $user->setPassword('testPassword');
        $user->setEmail('test@example.com');
        $user->setUsername($user_name); // This username must be unique and accept only a-Z,0-9, - _ @ .
        $user->set("langcode", $language);
        // Optional settings
        $user->set("init", 'email');
        $user->set("preferred_langcode", $language);
        $user->set("preferred_admin_langcode", $language);
        $user->activate();
        // Add a custom role in case you need one
        $user->addRole('CustomRoleName');
        //Save user
        $user->save();

  }
}

```

also note the namespace at the beginning of the file, this is where it gets loaded into the administration area of a webform like the following image:

Note that in this example we use `$user_name` as the only field that gets populated dynamically from the webform submission, you have to replace the rest according to your webform fields machine names

# Answer
> 3 votes
Welcome to Drupal Answers!

If styling is the only concern here, I would strongly recommend not using webform over Drupal's default registration process. You could simply add more fields to the user from account settings and have them displayed while registration. Benefits:

1. The data remains attached to the user entity even after registration, which means the users' will have the facility to edit the values provided while registration.
2. You could use them with ease to create the profile pages if intended.
3. You could use these fields as filters on the users listing page.
4. Many other cases depending on the site.

As for theming the form, I did a quick search and found some useful links:

1. Drupal 8: How to theme any form.
2. Send a form to twig template.
3. How do I theme a custom form?
4. Theming form elements in Drupal 8.

# Answer
> 3 votes
```
There is a module for that.

```

Forms Steps provides an UI to create forms workflows using forms modes. It creates quick and configurable multisteps forms.

# Answer
> 0 votes
As stated, if possible, you'll have a much easier time using the standard Drupal registration process, rather than trying to create a webform and sync fields with the registration form.

Depending on your site needs / restrictions, you could always "fake" a multi-step form with a custom template. If all of the form fields print out on the same page, you can use the template to split those fields into "sections" and then use JS to let the user step through the full process while staying on the same page.

A great example is provided here - https://www.w3schools.com/howto/howto\_js\_form\_steps.asp \- which also includes form validation on the form step buttons, so that users can't skip a required field on Step 1 before moving on to Step 2.

# Answer
> 0 votes
I was able achieve this on multiple Drupal 8 site and could create users on both Drupal & civicrm. I used some custom code to create user in Drupal by taking the submitted values.

Here is a thread but it is old and may have different approach with Drupal 8.6.x

https://www.drupal.org/forum/support/module-development-and-code-questions/2015-03-04/how-to-programmatically-create-a-user

This is about creating users in code after the webform has been submitted. For template, check this: https://www.drupal.org/docs/8/theming/twig

---
Tags: users, webforms
---


title: Translations string email not work

text:
# Question
Title: Translations string email not work
in D8 (multilanguage site, with two languages) i wanna send email for registration, etc by user preference of language of user (People -\> Edit people -\> Language Settings)

I've enabled all modules for translations and translations are saved correctly (see the attachment).

I followed this guide: https://www.valuebound.com/resources/blog/how-to-send-mail-programmatically-drupal-8 but not work for me.

The language code passed for the email is correct but the email is always send in default language (in my case, english).

# Answer
> 0 votes
Be sure that the string you sent by mail is already translated in the target language. Otherwise it will not work. You can check it here http://youwebsite.com/admin/config/regional/translate

# Answer
> 0 votes
For solve this problem, in hook\_mail insert this:

```
    $token = \Drupal::service('token');
    $language_manager = \Drupal::languageManager();
    $language = $language_manager->getLanguage($user->getPreferredLangcode());
    $original_language = $language_manager->getConfigOverrideLanguage();
    $language_manager->setConfigOverrideLanguage($language);
    $mail_config = \Drupal::config('user.mail');

    $subject = $token->replace($mail_config->get($key . '.subject'), [
        'user' => $user
    ]);

    $body = $token->replace($mail_config->get($key . '.body'), [
        'user' => $user
    ]);

    $language_manager->setConfigOverrideLanguage($original_language);

```

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


title: Pantheon Live / Test / Dev Login Issue

text:
# Question
Title: Pantheon Live / Test / Dev Login Issue
I have recently inherited a Drupal 7 site on Pantheon.io. None of the admin logins that work flawlessly in the Live environment work in either Test or Dev. I have pushed/pulled code and DB between the three to make sure they are all identical, but the logins still fail in Test and Dev. Any thoughts or suggestions would be greatly appreciated.

# Answer
> 1 votes
After more hours than I care to admit, I came to realize that the issue was very simple... The Pantheon Dashboard's links to "site admin" go to the `http://` site and NOT the `https://` site, therefore, none of the addresses were resolving correctly. The live site automatically redirects `http://` traffic to `https://` so it works just fine.

---
Tags: 7, authentication-authorization
---


# Question
Title: Pseudo-field for custom entity without hook
I developed custom entities in the code, using entity references : A \<- R -\> C. Entity "R" contains references to "A" and "B".

I'd like to add a pseudo-field in entity "A", configurable in view display, that could render referencing entities (mean "R" entities referencing "A" with a given field "F").

Since I made my own classes for the entities, I'd really like to continue that way and prevent using hooks. I know I could achieve this with views, but it seems more logical, reusable, and quicker, to put it in entity code.

1. Is there a way to add the display field to my entity without using hook\_entity\_extra\_field\_info() ? For example could I create my own FieldEntityManager ?
2. Is EntityViewBuilder the right place to render the field with my own data ?
3. In a more generic way, would it be possible to develop a custom field type "referencing\_entities" that I could reuse in every referenced entities I have ? Would it be only a field formatter since I don't need to store anything ? Is it possible to access to the entity from the field to query referencing entities ?

# Answer
As time goes by there's Extra Field now.

> Provides a plugin type for extra fields in entity view.
>
> This module allows developers to add custom fields by simply providing a plugin. Site builders can use these fields in entity view modes as normally. Extra fields do not store data and do not have a field widget. Extra fields typically combine existing entity data and format it for display.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Call preprocess_node (or get variables) from Twig template?
I have the following content types (for a simple LMS) defined:

* `Lessons`, for which there are rather complex rules for handling view access.
* `Courses`, which contain entity references to one or more `Lessons`.

Now, in the Twig template for rendering a `Course` node, I am trying to create a "table of contents" (a list of `Lessons`), using the following snippet:

```
<nav id='toc_lessons' class="list-group">
  {% for key, lesson in content.field_lessons %}
    {% if lesson['#node'].title.value|render|striptags|trim %}

        <a class="list-group-item list-group-item-action
           href="{{ url('<current>') }}/?lesson={{ lesson['#node'].nid.value }}">
          {{ lesson['#node'].title.value }}
          {{ (*****) ? '<span class="label">LOCKED</span>' }}
        </a>

    {% endif %}
  {% endfor %}
</nav>

```

This works well. However, the problem with this code is the line that I marked with (\*****): I would like to do a simple access check, i.e. I would like to **check, if the user is allowed to view the `Lesson`**. If not, the label "LOCKED" should be added.

In my implementation of function `THEME_preprocess_node` I have already defined such a check that is called whenever a `Lesson` is rendered:

```
function THEME_preprocess_node(&$variables) {
  ...
  $node = $variables['elements']['#node'];
  $variables['viewaccess'] = $node->access('view');
  ...
}

```

But **can I call the preprocessing function** for a `Lesson` from within the `Course` template to receive the variable `viewaccess`?

Another idea would be to modify the above snippet as follows:

```
<nav id='toc_lessons' class="list-group">
  {% for key, lesson in content.field_lessons %}
    {% if lesson['#node'].title.value|render|striptags|trim %}

        {{ bamboo_render_entity('node', lesson['#node'].nid.value, 'toc_entry') }}

    {% endif %}
  {% endfor %}
</nav>

```

so, I am now rendering the `Lesson` using Bamboo Twig and the output `<a>...</a>` is fully handled by the `Lesson` template, which works fine. The problem now is that a Lesson that the user does not have view access for, is **not rendered at all**.

Now, I'm stuck. Can anybody offer any ideas?

Any help would be much appreciated.

# Answer
> 3 votes
You're pretty close. I think there are a couple of approaches to this. This is what I would do

preprocess the lessons entity reference field for the courses bundle, iterate through the values, check the access, set a variable with the access value for each item. Then in field--field-lessons.twig.html, render the field if the access value is true.

```
<?php
//the name of your lessons entity reference field on courses
function THEME_preprocess_field__field_lessons(&$variables) {

  if($variables['element']['#bundle'] == 'courses') {
    $account = \Drupal::currentUser();
    $ent_refs = $variables['element']['#items']->referencedEntities();

    foreach ($ent_refs as $key => $ent_ref) {
      $check = $ent_ref->access('view', $account);
      $variables['items'][$key]['my_access'] = FALSE;

      if ($check) {
        $variables['items'][$key]['my_access'] = TRUE;
      }
    }

  }
}

```

**then in field--field-lessons.twig.html**

```
...
{% for item in items %}
    {% if item.my_access == TRUE %}
      I'm Unlocked: {{ item.content }}
    {% else %}
      I'm locked :(
    {% endif %}
  {% endfor %}
...

```

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


title: Custom validation for paragraph field

text:
# Question
Title: Custom validation for paragraph field
I have a content type with one paragraph field which has a checkbox and a text field.

By default, the text field is optional. I want to make it required when the checkbox is checked. Conditional fields module does not work with paragraphs properly. I tried with #states, but this just adds a class. It doesn't make the field required in the back-end.

Maybe I should write a custom validation. How can add it for paragraph field with two fields inside?

# Answer
As you mentioned, you'll need to add a custom validate function. Since this checkbox can be checked or unchecked on the fly, you will also need to use some javascript to toggle the "required" class on and off the textbox. This will make sure it looks right to the user. Of course you'll need to make sure you have a required class style in css.

This is just freehand, and just one way it could be done. You would need to adapt this to your fields.

**create a custom module. In your .module file**

```
<?php
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //where CONTENTTYPE is the machine name of your content type
  if ($form_id == 'node_CONTENTTYPE_edit_form') {
    $form['#validate'][] = 'my_test_validate';
  }
}

function my_test_validate($form, FormStateInterface &$form_state) {
  $checkbox = $form_state->getValue('field_my_checkbox');
  $textfield = $form_state->getValue('field_my_textbox');

  //if the checkbox is checked
  if ($checkbox['value'] == 1) {
    if (trim($textfield[0]['value']) == "" || empty($textfield)) {
      $form_state->setErrorByName('mytextfield', t('Text field blah blah is required'));
    }
  }
}

```

**In a js file somewhere in your module or theme you could have something like:**

```
(function ($, Drupal) {

  Drupal.behaviors.myForms = {
    attach: function (context, settings) {
      //add a click listener to toggle whatever styles you want
      $('#edit-field-mycheckbox-value').click(function(){
        $('#edit-my-textfield-0-value').toggleClass('required');
        $("label[for='edit-my-textfield-0-value']").toggleClass('form-required');
      //etc
      });

    }
  };

})(jQuery, Drupal);

```
> 3 votes

---
Tags: paragraphs
---


# Question
Title: How can I create a custom module that can be reinstalled without throwing an error?
I'm creating a custom module based off of Bootstrap Paragraphs, with a bunch of configuration files for custom paragraph types.
The configuration includes a bunch of `field.storage.` files, which AFAICT result in tables being created in the underlying MySQL data store for the respective fields.

The module is under active development, and I often need to reinstall it to pick up new changes.
Whenever I uninstall it and install it again, I get the error

> Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "'field\_config' entity with ID 'paragraph.custom\_component.custom\_component\_field' already exists." at /var/www/html/core/lib/Drupal/Core/Entity/EntityStorageBase.php line 425, referer: http://localhost:2345/admin/modules.

My best interpretation of this error is that the MySQL store already contains this table, so it can't be created.
Sure enough, when I access MySQL, the tables are there, even after module uninstallation.
Elsewhere, I've seen people say that in Drupal 8 uninstalling a module should cause all traces of the module to be removed, but that doesn't seem to be the case for me.

How can I set up my component so that it will delete the fields from the store when I uninstall it? Is there a better approach I should consider?

### What I've tried

* Overriding `hook_uninstall()` in the module file and adding the following code

```
\Drupal::configFactory()
  ->getEditable('field.storage.custom_component.custom_component_field')
  ->delete();

```
* Renaming the config/install directory to config/optional
* Purging configuration using the "Purge Configuration" tab available from the Easy Install module

# Answer
> 1 votes
You can make your config dependent on the module by adding this to the relevant config file(s):

```
dependencies:
  enforced:
    module:
      - module_name

```

When your module is uninstalled, the config will go with it. You probably want to delete any content and field instances in `hook_uninstall` as well.

---
Tags: 8, installation
---


# Question
Title: Double slash in path for downloaded modules
When I download a module via Drush, the path contain two consecutive slashes like in /home/www/example/sited8//modules/contrib/key\_value.

In *admin/config/media/file-system*, no extra slash is shown.

Perhaps it could be set in another part of the website.

Could it be a bug?

# Answer
It's an artifact of how Drush builds the path. It looks at your Drupal project dir, and where it's placing the the project download, then appends it together without concern for a trailing slash in the Drupal project dir. It has nothing to do with your Drupal project file settings

Is it bug? Perhaps if you consider it a UX problem. As far as POSIX is concerned, the double slash is treated as one so it shouldn't matter in terms of referencing the directory. Whatever the case, `drush pm-download` is deprecated in later versions.
> 1 votes

---
Tags: drush
---


title: Site name is not changing in <title>

text:
# Question
Title: Site name is not changing in <title>
When I change the site name in admin/config/system/site-information it has no effect on the site name between the title tags. It always shows "Drupal" as the site name.

I'm using the Basic theme with the same implementation as in the core themes:

```
<title>{{ head_title|safe_join(' | ') }}</title>

```

I already checked the translations and the site name is also not hard coded in settings.php

# Answer
I had same problem, and I solved it after reading this article:

Source : https://www.drupal.org/node/2844755

you can do it step by step :

1. Change the default language to English.
2. Delete the other language.
3. Clear the cache.
4. Change the site name.
5. Add the other language and set it back to default.

It works after adding new language again
> 4 votes

# Answer
I was not able to change the front page title of my drupal 8 site I have done it by Jquery, and used the following code in the front page twig file.

document.title="new title";

It worked for me
> 0 votes

---
Tags: 8
---


title: Identify submit button in webform

text:
# Question
Title: Identify submit button in webform
I am trying to add additional submit buttons to the webform to navigate between different steps. I have added button like below:

```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if($form_id == 'mywebform_id') {

    $form['actions']['submit_button_step_1'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 1'),
      '#submit' => array('custom_navigation'),
    );

    $form['actions']['submit_button_step_2'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 2'),
      '#submit' => array('custom_navigation'),
    );
  }
}

function custom_navigation(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  $value = $form_state->getValues();
  //echo '<pre>';print_r($form['actions']);echo '</pre>';exit;
}

```

But, I'm using same custom submit handler both the custom buttons. How I identify which button has clicked by user? And based on user click I need to redirect user to corresponding wizard page.

# Answer
Below codes work for two submit buttons given at webform for identify which button is click.

```
function modulename_form_submit(&$form, FormStateInterface $form_state) {

  $myurl = FALSE;
  $triggerElement = $form_state->getTriggeringElement();

  if (isset($triggerElement['#id']) && $triggerElement['#id'] == 'COMPARE BUTTON ID') {
    $myurl = Url::fromUri('internal:/SETYOURFIRSTACTIONPATH');
  }

  if (isset($triggerElement['#id']) && $triggerElement['#id'] == 'COMPARE ANOTHER BUTTON ID') {
    $myurl = Url::fromUri('internal:SETYOURSECONDACTIONPATH');
  }

  if ($myurl) {
    $form_state->setRedirectUrl($myurl);
  }
}

```
> 3 votes

# Answer
```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'mywebform_id') {
    $form['actions']['submit_button_step_1'] = array(
      '#type' => 'submit',
      '#name' => 'step_1',
      '#value' => t('Go to Step 1'),
      '#submit' => array('custom_navigation'),
    );
    $form['actions']['submit_button_step_2'] = array(
      '#type' => 'submit',
      '#name' => 'step_2',
      '#value' => t('Go to Step 2'),
      '#submit' => array('custom_navigation'),
    );
  }
}

function custom_navigation(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  print $form_state->getTriggeringElement()['#name'];
}

```
> 1 votes

---
Tags: 8, forms, webforms
---


# Question
Title: Paragraphs: referenced entity error on save
I recently updated to Drupal 8.6.2 and Paragraphs 8.x-1.3.

I have a content type with a Paragraphs field. When I try to update an existing node I get the following error message:

`The referenced entity (user: 21) does not exist.`

* The existing paragraphs do not reference users directly.
* User 21 does not exist.
* User 21 is not the node author.
* I can only update the node if delete *all* of the paragraphs, of every type.
* There are no pending db updates or entity updates.

My feeling is that something didn't update correctly, but I'm not sure how to check / rerun the updates. (There were a number of updates to be run when I deployed the 8.6.2 update.)

*UPDATE:* I rolled back to the previous release and DB state, and I *still* get the error (which no one noticed), so it is not related to the update.

*UPDATE 2:* Ticket on drupal.org

# Answer
User 21 was deleted, but `21` was still stored as the value in the `uid` column of the paragraphs tables. Changing the uid to that of an existing user (23) solved the problem:

```
UPDATE paragraphs_item_field_data SET uid = 23 WHERE uid = 21;
UPDATE paragraphs_item_revision SET revision_uid = 23 WHERE revision_uid = 21;
UPDATE paragraphs_item_revision_field_data SET uid = 23 WHERE uid = 21;

```

Run SQL, empty cache, reload edit page.

Note: other tables also contain the uid 21, but without a (noticeable) adverse effect.

```
UPDATE file_managed SET uid = 23 where uid = 21;
UPDATE node_field_data SET uid = 23 where uid = 21;
UPDATE node_field_revision SET uid = 23 where uid = 21;
UPDATE node_revision SET revision_uid = 23 where revision_uid = 21;

```

And two from contrib:

```
UPDATE crop_revision SET revision_uid = 23 where revision_uid = 21;
UPDATE redirect SET uid = 23 where uid = 21;

```
> 1 votes

---
Tags: 8, paragraphs
---


title: how to rename file before/after upload

text:
# Question
Title: how to rename file before/after upload
I want to rename an up-loaded file. I have the following code. I have defined a submit handler to do so.

```
function example_form_submit(&$form, FormStateInterface $form_state) {
    if ($form_state->hasFileElement()) {

        $video_file_file_array = $form_state->getValue('field_video_file');
        if (is_array($video_file_file_array)) {
            if (isset($video_file_file_array[0])) {
                $video_file_file_id = $video_file_file_array[0]['fids'][0];
                if($video_file_file_id){
                    $file = \Drupal\file\Entity\File::load($video_file_file_id);
                    $file->set('filename', 'something');
                    $file->save();

                }
            }
        }
    }
}

```

This is not working. Is there any other way.

# Answer
Your implementation should work. I suspect that for some or other reason the execution just doesn't pass all the conditions you have there which looks a bit weird. Here is an example from my project:

```
$fid = $form_state->getValue(['field_video_file', 0]);
if (!$form_state->getErrors() && !empty($fid)) {
  try {
    $file = \Drupal\file\Entity\File::load($fid);
    $file->setFilename('smth');
    $file->save();
  }
  catch (\Exception $e) {
    watchdog_exception('myerror', $e);
  }
}

```
> 3 votes

# Answer
Renaming file entity in Drupal 8 can be achieved like this:

```
    $file = File::load($file_target_id);
    $new_filename = "filename.png";
    $stream_wrapper = \Drupal::service('file_system')->uriScheme($file->getFileUri());
    $new_filename_uri = "{$stream_wrapper}://{$new_filename}";
    file_move($file, $new_filename_uri);

```

As you can see in this example Drupal `file_move` function is used here which takes care of everything. You only need to know file `target_id` which is the file `fid`.
> 4 votes

# Answer
I had to allow users to upload a file then rename it and erase existing with same name. In a way to have always only on file on the folder which always have the same path.

I try `$file->setFilename` and `$file->setFileUri` but these only change the name and url for Drupal (in database) but not the real file (on the server) name. That's why I had to add a specific piece of code to rename it using drupal/php function.

Maybe I should not have to do it because of bad configuration but it works for me.

```
// In this variable you will have file entity
$file = \Drupal::entityTypeManager()->getStorage('file')
    ->load($form_state->getValue('csv_file')[0]);
if (!$file)
  return;

$exUri  = explode('/', $file->getFileUri());
array_pop($exUri);
$rename = file_unmanaged_move($file->getFileUri(), implode('/', $exUri) . '/' . self::FILE_NAME . '.csv', FILE_EXISTS_REPLACE);

if ($rename) { ... }

```

If you also want to change the file uri and name to let Drupal know it, just add these lines :

```
$file->setFilename(self::FILE_NAME);
$file->setFileUri(self::FILE_URI . self::FILE_NAME . '.csv');
$file->save();

```

In my case I had no needs for that.
> 1 votes

---
Tags: 8, files
---


# Question
Title: Programatically render a view in twig template
I want to render a particular view like Who's new,Recent content present in the core in my the twig template.Any suggestion on how to do it? I was thinking of using `views_embed_view()` because in Drupal 7 it used to work with php but I don't know how to do it Drupal 8. Thanks. For recent I tried following code:

`function template_preprocess_module(&$variables) {
 $variables['view_output']=views_embed_view("Recent content");
}`

and then in the twig template did this:

`{{ view_output}}`

# Answer
> 4 votes
Right, twig no longer allows you to execute php code anymore. This is a main feature of twig and its security model.

I'd suggest to use a preprocess function for now and there call the function or even better add a render array with `#type` view, with `#view_id` and `#display_id`, as it gives you caching as well.

On top, maybe add an issue against core. That sounds like a really helpful thing to have

Oh and `views_embed_view` should be changed to enable caching as well.

# Answer
> 3 votes
You might be interested by the contrib module Twig Tweak.

Among other things, it will let you render views like this :

```
{{ drupal_view_result('view_name', 'view_display_name') }}

```

Cheat sheet : https://www.drupal.org/docs/8/modules/twig-tweak/cheat-sheet-8x-2x

---
Tags: views, theming, 8
---


# Question
Title: Values don't get saved to the database when fields are wrapped in a container
When I wrap a field in a container, the field value doesn't get saved to the database. But if it lives in root, it works properly.

```
public function formElement(
  FieldItemListInterface $items,
  $delta,
  array $element,
  array &$form,
  FormStateInterface $form_state
) {

    $item =& $items[$delta];
    $element += array(
      #type' => 'fieldset',
    );

    /** a bunch of fields **/

    $element['concelhocontainer'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'concelhocontainer']
    ];

    /** works properly **/
    $element['concelho'] = [
      '#type' => 'select',
      '#title' => t('County'),
      '#default_value' => isset($item->concelho) ? $item->concelho : '',
      '#options' => $this->getConcelhoList()
    ];

  /** does not work
  $element['concelhocontainer']['concelho'] = [
    '#type' => 'select',
    '#title' => t('County'),
    '#default_value' => isset($item->concelho) ? $item->concelho : '',
    '#options' => $this->getConcelhoList()
  ];
  */
  return $element;
}

```

The problem is that the value of the second input is not saved to the database (I've confirmed it in the database).

# Answer
> 5 votes
It seems Drupal adds a `#tree = true` property to the field parent so you need to process the data output by the form youserlf or the form nested elements will be ignored. As @IvanJaros poited out, `WidgetBase::massageFormValues` let's you alter the data.

```
public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
{
  for ($i=0; $i < count($values); ++$i) {
    if (isset($values[$i]['concelhocontainer']['concelho'])) {
      $values[$i]['concelho'] = $values[$i]['concelhocontainer']['concelho'];
    }
  }
  return $values;
}

```

# Answer
> 2 votes
Life saver. `massageFormValues()` above did the trick. Only that I had to get my values from `$form_state->getUserInput()` and store them in a new `$values = []`

---
Tags: 8, entities, ajax
---


# Question
Title: How to disable redirection to the node after node form submission
I have a node form exposed in the front-end to allow visitors to add their organisation to the list of partners. Below the form, I have exposed view block with the list of existing partners.

When a visitor enters a new organisation to the list I want the form just to add a new node type "partner" and reload the page/block without redirecting to the node content (node/\[node ID\]).

At the beginning I ed taxonomy terms instead and it worked as it should, now I want to achieve the same with node entity.

I have tried various solutions but none of it works correctly and I didn't find much by googling it.

For example, this is not functioning:

```
function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  if ($form_id == 'node_partners_form') {
    $form_state->disableRedirect(); // This is not functioning
  }
}

```

This does not work either:

```
function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  if ($form_id == 'node_partners_form') {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'THEME_node_form_submit';
      }
    }
  }
}

function THEME_node_form_submit($form, &$form_state) {
  $form_state->setRedirect(Url::fromUri('internal:/node/1')->toString());
}

=> Error: Route /partners does not exist.

```

Value of attribute action in the exposed node form is correct and therefore I think the proper solution should be elsewhere then altering form properties - probably it has more with the Drupal behaviour after adding a new node.

```
<form action="/en/partners">...</form>

```

# Answer
Thank you for the comment 4k4. Unfortunately, I didn't have enough time to find a proper solution so I just changed the redirection URL to the same content where the form is exposed.

```
function THEME_node_form_submit($form, FormStateInterface $form_state)  {
    $node_id = 1;
    $form_state->setRedirect('entity.node.canonical', array('node' => $node_id));
}

```

I'll try to find a more appropriate solution if I'll have some extra time before deadline :)
> 0 votes

# Answer
I don't know you form code in particular, but another thought in finding a solution might be to modify the form action on-the-fly like this to get what you want:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
    global $base_url;
    $form['#action'] = $base_url . '/whatever_you_like';

```

This might be a little extraordinary, but it might help in some special use cases depinding on your code and I must admit I did not test it with:

```
function THEME_node_form_submit($form, FormStateInterface $form_state)

```

Good luck :-)
> 0 votes

---
Tags: 8, nodes, redirection
---


# Question
Title: How to add a class attribute to a block?
How can I add a class attribute to a Drupal 8 block?

There are many examples in Drupal core such as the help modules that sets the *role* attributes for the block. So following that I can succesfully add a class.

```
/**
 * Implements hook_preprocess_HOOK() for block templates.
 */
function mymodule_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'mymodule_my_block') {
    $variables['attributes']['class'][] = 'my-nice-block';
  }
}

```

Is it possible to add a class without the preprocess hook? Ideally within the block plugin file located in src/Plugin/Block/ ?

This would help keeping all the code related to one block contained in one location.

# Answer
Have you tried to just set #attributes on the render array returned by our block plugin?

```
$build['#attributes']['class'][] = 'my-nice-block';

```

Looking at `BlockViewBuilder::preRender()`, that should work.
> 15 votes

# Answer
You can check Block Class module.

> Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's `block.tpl.php` file, classes can be added to the parent element of a block. Hooray for more powerful block theming!
> 3 votes

# Answer
find a twig template name suggestion for your block ( using twig debug comments ) and override it

> themes/templates/block--my-custom-block.html.twig

```
{% extends "block.html.twig" %}
{#
/**
 * @file
 * Theme override for tabs.
 */
#}

{% block title %}
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes.addClass(title_classes, 'accordion') }}{{ title_attributes.setAttribute('id', 'campus') }}>
      {{ label }}
      <i class="fa fa-plus" aria-hidden="true"></i>
    </h2>
  {% endif %}
  {{ title_suffix }}
{% endblock %}

```
> 2 votes

# Answer
**1. Create hello.config file**

```
    my_module_name/config/install/my_module_name.config content this code:
    color :"blue"
    color_red: "red"

```

**2. Attach your library file my\_module\_name.libraries.yml**

```
  // This function below is located on my_module_name.module file

 function my_module_name_page_attachments(array &$page){
     $page['#attached']['library'][]= 'my_module_name/library_name';
}

```

**3. Set the class in my\_module\_name.module file**

function my\_module\_name\_preprocess\_block(array &$variables){

```
// Get the value of my color content in
     my_module_name/config/install/my_module_name.config

    $class = \Drupal::config('my_module_name.config')->get('color');

```

// Get the ID of the block

```
    $id= $variables['elements']['#id'];
    $block = Block::load($id);

```

// Get the region having the block

```
    $region = $block->getRegion();

    if($region == 'name_of_the_block_id'){

        // Set the class
        $variables['attributes']['class'][] = $class ;
    }
}

```

**4. my\_module\_name.libraries.yml**

here, my\_module\_name is the name of my library

**5. Create your css file css/my\_module\_name.css**

.red{ background: red !important; }

.green{ background: green !important ; }

.yellow{ background: yellow !important; }
> 2 votes

---
Tags: 8
---


# Question
Title: Local drush stops working after changing files and folder permissions
I changed the files and folder permissions with the following commands.

```
find . -type f -print0 | xargs -0 chmod 0644
find . -type d -print0 | xargs -0 chmod 0755

```

I can't run Drush commands anymore, unless I change file permissions back to 777. When I run `drush cr`, for example, I get this error.

> PHP Warning: pcntl\_exec(): Error has occurred: (errno 13) Permission denied in /usr/local/bin/drush-8/vendor/drush/drush/includes/startup.inc on line 415
> Error has occurred executing the Drush script found at /data/websites/virtualmax.ca/public\_html/vendor/drush/drush/drush (errno 13) Permission denied

Is there a certain permission required to run Drush commands?

# Answer
Apparently, you have two Drush instances installed, as you can see in your error log, it tries to run the global Drush which is located at `/usr/local/bin/drush-8/vendor/drush/drush` first

the reason that you cannot run Drush commands locally after file permission changes is that it's not executable, try this in your installation root:

`sudo chmod +x vendor/drush/drush/drush`
> 3 votes

---
Tags: 8, drush, composer
---


# Question
Title: Search API for searching in existing Solr Core
I'm using Drupal 8 with Search API and Search API Solr Search.

I'm tasked with making an existing Solr installation searchable within Drupal. This core indexes PDFs and serves other systems, thus I may not edit the schema there. It can be assumed that this schema has fields like "author", "title" and "abstract".

I tried the following:

* Add a server in Search API: This seems to work as I see the (correct) number of indexed documents in Solr.
* Add an index with "Solr Document" as data source. I can see fields from the Solr core here.

However, in the View tab, I always see "0/0 Indexed".

Am I missing something here or is perhaps the wrong approach?

# Answer
The Solr core's schema must have a field "index\_id" and the value must be the same as the machine name of the Drupal index (in order for that (Drupal) index to find it). Moreover, the (Drupal) server has to use "Any Schema" and the (Drupal) index must be read-only.

Note that under "View" it still says "0/0 Indexed", however the search works.

There is a datasource.md in the search\_api\_solr module's folder which was helpful. I found it helpful to use search\_api\_devel as it shows the queries to Solr.
> 0 votes

---
Tags: search
---


# Question
Title: Question about New releases and what to do with them
CAVEAT - I am NOT a technical person - the instructions on the Drupal site make no sense to me.

So someone built a site for me using Drupal, its hosted via Domain.com I can go in and edit pages but I keep getting emails about New Releases "There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately!"

But I'm not sure what to do with the updates - do I just save the downloads to my PC even though the site is being hosted? Any help would be greatly appreciated Michele

# Answer
> 2 votes
How to manually update your Drupal 8 installation is explained several places - see

PS! If you are familiar with the Command Line and have shell access on Domain.com, you might consider using Composer for updating.

# Answer
> -1 votes
For update your Drupal and its modules go to the below URL: http(or https)://YOURSITENAME/admin/reports/updates/update

---
Tags: 8
---


# Question
Title: How to pass seperate contextual filter values to a view and get results programatically?
I've a view having two (separate) contextual filters, say `node id` and `taxonomy id`. We can pass separate contextual filter values with a "`/`". example: 12,13,14/8,9 as URL arguments.

But how can we get the view results by passing the dynamic contextual filter values to the view?

# Answer
Here we go.

```
 $nodes_str = implode(',', $nids); // $nids is an dynamic array.
 $args[] = $nodes_str; // First contextual filter argument. 12,13,14.. etc
 $args[] = $tag; // Second contextual filter arguments 8,9.. etc
 $view = views_get_view('view_machine_name');
 $view->set_display('display_name');
 $view->set_arguments($args);
 $view->pre_execute();
 $result = $view->execute();
 $output = $view->result;

```

If need futher details of the view parameters. You can debug the values using the hook\_views\_pre\_view()

```
function YOUR_MODULE_views_pre_view(&$view, &$display_id, &$args) {

}

```

Hope this helps someone.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Combining a digital and a physical version of the same product (without making 2 different nodes/products) using Ubercart
I have been struggling for weeks now to find the best solution for the following problem.

Suppose I am a filmmaker and want to sell my films on DVD, Blu Ray, but also as a digital download. Without having to create 3 different products.

I suppose for the two physical objects (choice between DVD or blu ray), I could use a product option. But how to combine it with something only virtual (so no shipping fees, ..) ? Any thoughts what the best way to tackle this would be?

Thanks kind internet stranger!

# Answer
I would add the digital download as another product option after the DVD and BluRay. Then alter the option’s weight so it’s zero. Then I would create rules that allow for the access or sending a downloadable link once the checkout is complete. Also have a think about how you want to handle a cart that has both physical and digital products together.
> 0 votes

---
Tags: ubercart
---


title: Custom action context for order

text:
# Question
Title: Custom action context for order
I'm trying to write a custom RulesAction to perform an operation after an order status is updated. Basically, I want to perform this operation after checkout is complete (but this event doesn't exist anymore in D8).

```
namespace Drupal\my_module\Plugin\RulesAction;

use Drupal\uc_order\OrderInterface;
use Drupal\uc_order\OrderStatusInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Definition of the action performed.
 *
 * @RulesAction(
 *   id = "my_action_id",
 *   label = @Translation("My action label"),
 *   category = @Translation("My module"),
 *   context = {
 *     "entity" = @ContextDefinition("entity",
 *       label = @Translation("Entity"),
 *       description = @Translation("Specifies the entity, which should be saved permanently.")
 *     )
 *   }
 * )
 */
class MyActionClass extends RulesActionBase {

  /**
   * Def.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *    The order update triggered by rules.
   */
  protected function doExecute(OrderInterface $order) {
    // @TODO.

  }

}

```

My action do come in rules, I have set it up after the event: After updating order (rules\_entity\_update:uc\_order)

When triggering it I get the error : If I set the context to entity (I've looked and no context is defined by ubercart for order):

> The website encountered an unexpected error. Please try again later.Drupal\Core\Entity\EntityStorageException: Required context entity is missing for plugin my\_action\_id. in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save() (line 783 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

If no context is set :

> The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\my\_module\Plugin\RulesAction\MyActionClass::doExecute() must implement interface Drupal\uc\_order\OrderInterface, none given in Drupal\my\_module\Plugin\RulesAction\MyActionClass-\>doExecute()

So my questions are :

* Do I need a context for rules action to work ?
* If yes, how can I find it and get it working ?

Here are the documentations I find (but rules is unfornately not very well documented for now):

Rules documentation for dev | RulesAction examples | Context documentation

# Answer
So the context is mandatory and it is actually important because it sets the data you want to fetch when the rule is triggered.

I just needed to set the context to the good entity as follow.

```
"entity" = @ContextDefinition("entity:uc_order",

```

The working annotation is the following.

```
/**
 * Definition of the action performed.
 *
 * @RulesAction(
 *   id = "my_action_id",
 *   label = @Translation("My action label"),
 *   category = @Translation("My module"),
 *   context = {
 *     "entity" = @ContextDefinition("entity:uc_order",
 *       label = @Translation("Entity"),
 *       description = @Translation("Specifies the entity, which should be saved permanently.")
 *     )
 *   }
 * )
 */

```

Then you are able to fetch the current uc\_order in the administrative page.
> 1 votes

---
Tags: 8, rules, ubercart
---


# Question
Title: Show the ID of referenced entities using tokens, instead of the label with link
I have a content type, Company, which is referenced to a User with an entity reference. The token for that entity reference for the current user is `[current-user:field_user_company]`.

No matter how I configure the field I'm using the token in, when using this token, it always translates in a the label with a link `<a href="/node/17" hreflang="en">TEST COMPANY</a>.`

Is there any way I could make this token translate into just the Node ID (17 in this case)? I would need just the ID to pass the reference on to other entities in a workflow (using Rules or Business Rules).

# Answer
Adding the solution given by Clive in the comments to my question as an answer :

```
[current-user:field_user_company:target_id]

```

= the token translating into the node ID of a referenced content type.
> 1 votes

---
Tags: 8, nodes, tokens
---


# Question
Title: Retrieve reference to content type in preprocess
I have a content type (let's name it Wheel for an example) that have a field referencing an other content type (which could be Car, Motorbike, Bicycle ...). So a node named WheelMotorbikeBrand whould reference the content type Motorbike. I would like to retrieve the value of this field in a preprocess with something like $node-\>get('field\_wheel-type') but I'm not able to obtain a value. How can I retrieve the value of my field ?

# Answer
You get a field value:

```
$value = $node->field_text->value;

```

If the field has a property `value` like fields for texts, numbers or booleans usually have.

A reference field has no `value` property, but one for `target_id`. So you get the id of the referenced entity with:

```
$target_id = $node->field_reference->target_id;

```

Or the referenced entity already loaded:

```
$referenced_node = $node->field_reference->entity;

```

Which you then can use to obtain a field value from the referenced node:

```
$value = $referenced_node->field_text->value;

```

---

The method `->getValue()`:

```
$values = $node->field_text->getValue();

```

gets an array of all properties and field items and so works also if you don't know the properties of a field or how many items it has.

Caveat: You don't find the property `entity` from the example above in this array, because it is computed and not stored in the database.
> 3 votes

# Answer
try :

```
$value = $node->get('field_wheel-type')->getValue();

```
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: How do I programmatically get the content title field from a view?
How do I programmatically get the content title field from a view?

# Answer
> 1 votes
Try with this out:
The following example with hook hook\_preprocess\_views\_view

```
/**
 * Implements hook_preprocess_views_view().
 */
function myModule_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $result = $view->result;
  //- Titles Array
  $titles = [];
  for ($i = 0; $i < count($result); $i++) {
    $titles[]= $result[$i]->_entity->title->value;
  }
}

```

---
Tags: views, 8, hooks
---


# Question
Title: How to render content with <p> in twig to create paragraph
Sorry I'm newbie in drupal 8
I want to render my content from database which have `<p>` tags inside and my expectation every `<p>content</p>` will create new paragraph
My database content was like this:

```
<p>Content 1</p>

<p>Content 2</p>

<p>Content 3<a href="#"></a></p>

```

I was try using `{{ content.value |raw }}` but it was render all content without create new paragraph

I also try using `{{ content.value | raw | nl2br }}` and `{{ content.value | replace({"\n": "<br>"}) | raw }}` but this one create double `<br>` every paragraph so my paragraph become annoying

Is there any solution in twig to render `<p>` tags to create beautifull paragraph?

Thank you

# Answer
> 1 votes
1) It's bad security practice to use `|raw`. See How do I get the raw field value in a twig template? for proper/safe way to do it.

2) I am confident that `{{ content.field_name }}` or `{{ entity.field_name.value }}` is printing your `<p>` tags. If you right click and inspect element, you should see them in the HTML. Your issue must be CSS related perhaps the `p { ... }` CSS code have an `inline` or a `float` in them.

---
Tags: views, theming
---


# Question
Title: How does core triggers cleanup of expired sessions in database?
core/lib/Drupal/Core/Session/SessionHandler.php defines a method (gc()) to clear expired sessions from the database (sessions table)

when is that triggered ? is there a way to trigger it from the interface ?

i know i can just truncate sessions manually or with a cron or a custom drush command..., but i wonder how does core uses it and what triggers it by default

Thanks

# Answer
> 5 votes
> ### Configuring Garbage Collection
>
> When a session opens, PHP will call the `gc` handler randomly according to the probability set by `session.gc_probability` / `session.gc_divisor`. For example if these were set to 5/100 respectively, it would mean a probability of 5%. Similarly, 3/4 would mean a 3 in 4 chance of being called, i.e. 75%.
>
> If the garbage collection handler is invoked, PHP will pass the value stored in the **php.ini** directive `session.gc_maxlifetime`. The meaning in this context is that any stored session that was saved more than `gc_maxlifetime` ago should be deleted. This allows one to expire records based on idle time.
>
> However, some operating systems (e.g. Debian) do their own session handling and set the `session.gc_probability` variable to 0 to stop PHP doing garbage collection. That's why Symfony now overwrites this value to 1.
>
> If you wish to use the original value set in your **php.ini**, add the following configuration:
>
> ```
> # config/packages/framework.yaml
> framework:
>     session:
>         gc_probability: null
>
> ```
>
> Source: Symphony's official docs on Configuring Sessions and Save Handlers

In Drupal this is seen in /sites/default/**default.settings.php**

```
/**
 * Some distributions of Linux (most notably Debian) ship their PHP
 * installations with garbage collection (gc) disabled. Since Drupal depends on
 * PHP's garbage collection for clearing sessions, ensure that garbage
 * collection occurs by using the most common settings.
 */
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

```

Since the above "most common settings" is set to 1/100, Garbage Collection would run 1% of the time.

Now, as per the code comment, I presume this does not get put into settings.php when it gets auto-generated if your distribution has one already set one in one of its files as I don't see this in my settings.php

You can also set this in **services.yml** as seen in this answer.

---

## In Conclusion

Note that while Drupal is built on top of Symphony, it does not rely on Symphony for this. I just quoted their nice explanation from their documentation.

We learned that PHP automatically calls this `gc()` method every `session.gc_probability/session.gc_divisor` % of the time and if you look at PHP docs on SessionHandler.

> **SessionHandler** is a special class that can be used to expose the current internal PHP session save handler by inheritance. There are seven methods which wrap the seven internal session save handler callbacks (open, close, read, write, destroy, gc and create\_sid).
>
> Source: http://php.net/manual/en/class.sessionhandler.php

core/lib/Drupal/Core/Session/**SessionHandler.php**

```
/**
 * Default session handler.
 */

class SessionHandler extends AbstractProxy implements \SessionHandlerInterface { ...

 /**
   * {@inheritdoc}
   */
  public function gc($lifetime) {
    // Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
    // value. For example, if you want user sessions to stay in your database
    // for three weeks before deleting them, you need to set gc_maxlifetime
    // to '1814400'. At that value, only after a user doesn't log in after
    // three weeks (1814400 seconds) will his/her session be removed.
    $this->connection->delete('sessions')
      ->condition('timestamp', REQUEST_TIME - $lifetime, '<')
      ->execute();
    return TRUE;
  }

```

---
Tags: 8, sessions
---


# Question
Title: Is there a way to display primary tabs vertical in separate block?
In Drupal 7 I want to rearrange standart drupal tabs (eg. 'View' and 'Edit') as vertical and move it to sidebar. Is there a way to do this?

# Answer
> 2 votes
The `Tabs` rendered in **page.tpl.php** like this:

```
<?php if ($tabs): ?>
        <div class="tabs">
          <?php print render($tabs); ?>
        </div>
<?php endif; ?>

```

in the main content div: You can override the **page.tpl.php** in your custom theme and move this part of code to sidebar:

something like :

```
<div class="sidebar">
<?php if ($tabs): ?>
            <div class="tabs">
              <?php print render($tabs); ?>
            </div>
    <?php endif; ?>
</div>

```

---
Tags: 7, blocks
---


# Question
Title: How can I add a variables to my page.html.twig file?
I'm trying to add a variable that i can use in page.html.twig that will add a class to the header region if a field in the node exists.

In template\_preprocess\_page() i've tried doing the following and have not been able to add a variable:

```
function theme_preprocess_page(&$variables){
  $variables['header_attributes']['class'] = [];
  $variables['header_attributes']['class'] = array_merge($variables['header_attributes']['class'], ['myClassHere']);
}

```

I based this off the example for menu preprocess but no new class was added to the ta

# Answer
> 2 votes
There is no index called `header_attributes` inside `$variables` array no need to create it, there is `page` index just use it:
Try this out:

```
function [yourThemeName|yourModuleName]_preprocess_page(&$variables){
  $variables['page']['header_attributes']['class']= 'myClassHere';
}

```

**Note** don't forget to clear cache.
In your twig you will get your class by:

```
page['header_attributes']['class']

```

---
Tags: 8, theming, hooks
---


# Question
Title: How to use different sets of fields for unique pages like the home page?
Some pages, like the home page, have unique content/layouts that are very different from basic pages. I want the editor to be able to fill in a different set of fields for the home page. Currently, the only way I can achieve this is by making a "Home Page" content type and setting up its fields. However, that feels wrong to make a whole content type for just one page. It would be great if the editor can create a basic page, then choose a layout (maybe a dropdown with the options: Default Page, Home Page, About Page, etc). Each layout would have it's own set of fields.

In WordPress, this can easily be achieved by assigning fields (usually with the Advanced Custom Fields plugin) to different page templates. I would love to replicate this in Drupal.

# Answer
In Drupal you can achive this using Paragraphs

> Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.

You can create paragraph types, and these paragraph types you can add sets of fields.

---

Alternatively, if you just need this type of functionality for the home page only, then just create a block type `/admin/structure/block/block-content/types` and add fields to it and then create a block of your block type and assign this block to the home page only.
> 2 votes

---
Tags: 8
---


# Question
Title: |slice filter does not work with special characters
I try to use the **slice** filter in order to limit a link to a specific amount of characters. The field that I render is a link field and my code is the following:

```
{% set title_text = title|render|striptags %}
<span>
     {{ title_text|length > 65 ?
         title_text|slice(0,65)  :
         title_text|striptags}}
</span>

```

Unforturnately some characters like the apostrophe are not rendered appropriately.

So instead of rendering "I've learned", they render "I& #039;ve learned"

# Answer
> 1 votes
Actually the culprit is `|striptags`

> The problem with using twig's **|striptags** is double encoding of html entities, not markup, so & becomes & and then & – Berdir
>
> source: How do I get the raw field value in a twig template?

If your setup relies on you running striptags last, you will need to do this all of this magic in a preprocess function with php setting a variable here and then printing your formatted variable on twig.

---
Tags: theming
---


# Question
Title: Can't get drush script to stop at breakpoint with Xdebug/Phpstorm
I had this working on another Drupal VM, but for some reason I can't get it to work anymore. I am trying to debug a Drush migration script and I have some breakpoints put in but it never stops at the breakpoints. I followed the steps shown here.

Here is my Xdebug section of config.yml from Vagrant:

```
# XDebug configuration. XDebug is disabled by default for better performance.
php_xdebug_default_enable: 1
php_xdebug_coverage_enable: 1
php_xdebug_cli_enable: 1
php_xdebug_remote_enable: 1
php_xdebug_remote_connect_back: 1
php_xdebug_remote_host: xxx.xxx.xx.xx // My Vagrant IP is really here.
# Use PHPSTORM for PHPStorm, sublime.xdebug for Sublime Text.
php_xdebug_idekey: PHPSTORM
php_xdebug_max_nesting_level: 256

```

The web server debug validation shows everything is good. I also verified that if I debug on a page that I visit from a browser, it stops at breaks points so it is for sure working.

Also, the PHP CLI does have Xdebug:

```
PHP 7.0.14-2+deb.sury.org~xenial+1 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.14-2+deb.sury.org~xenial+1, Copyright (c) 1999-2016, by Zend Technologies
    with Xdebug v2.5.0, Copyright (c) 2002-2016, by Derick Rethans

```

One thing I noticed, is that if I set Phpstorm to break at first line in PHP Script, I noticed the following notice in debugger: Can't compute source position. The script 'drush.phar' isn't associated with any text file type.

Here is the Xdebug log:

```
Log opened at 2017-03-24 02:21:50
I: Connecting to configured address/port: 10.0.2.2:9000.
I: Connected to client. :-)
-> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/mysite/web/drush.phar" language="PHP" xdebug:language_version="7.0.14-2+deb.sury.org~xenial+1" protocol_version="1.0" appid="12759" idekey="18466"><engine version="2.5.0"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[http://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2016 by Derick Rethans]]></copyright></init>

<- feature_set -i 1 -n show_hidden -v 1
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1" feature="show_hidden" success="1"></response>

<- feature_set -i 2 -n max_depth -v 1
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="2" feature="max_depth" success="1"></response>

<- feature_set -i 3 -n max_children -v 100
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="3" feature="max_children" success="1"></response>

<- status -i 4
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="status" transaction_id="4" status="starting" reason="ok"></response>

<- step_into -i 5
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="step_into" transaction_id="5" status="break" reason="ok"><xdebug:message filename="file:///var/www/mysite/web/drush.phar" lineno="8"></xdebug:message></response>

<- breakpoint_set -i 6 -t line -f file:///var/www/mysite/web/modules/contrib/migrate_tools/migrate_tools.drush.inc -n 226
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="6" id="127590001"></response>

<- breakpoint_set -i 7 -t line -f file:///var/www/mysite/web/core/modules/field/src/Plugin/migrate/source/d6/FieldInstance.php -n 22
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="7" id="127590002"></response>

<- breakpoint_set -i 8 -t line -f file:///var/www/mysite/web/core/modules/field/src/Plugin/migrate/source/d6/FieldInstance.php -n 56
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="8" id="127590003"></response>

<- breakpoint_set -i 9 -t line -f file:///var/www/mysite/web/core/modules/field/src/Plugin/migrate/source/d6/FieldInstance.php -n 37
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="9" id="127590004"></response>

<- stack_get -i 10
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="stack_get" transaction_id="10"><stack where="{main}" level="0" type="file" filename="file:///var/www/mysite/web/drush.phar" lineno="8"></stack></response>

<- run -i 11
Log opened at 2017-03-24 02:21:51
I: Connecting to configured address/port: xxx.xxx.xx.xx:9000.
W: Creating socket for 'xxx.xxx.xx.xx:9000', poll success, but error: Operation now in progress (29).
E: Could not connect to client. :-(
Log closed at 2017-03-24 02:21:51

```

Any ideas on what I can try to get it to work?

**Update - Things I have tried**

* Destroy vagrant machine and start over
* Different combination of Xdebug settings in config.yml (Set to how it comes by default, removing remote\_host, adding localhost, etc..)
* Changing port to 9001 (both PHPStorm and Vagrant)

# Answer
> 5 votes
I just had this problem. It happened because I was using drush launcher (https://github.com/drush-ops/drush-launcher). This tool allows to type "drush" in your Drupal directory, instead of "./vendor/bin/drush", but it seems to confuse xdebug. Using "./vendor/bin/drush" fixed the problem.

# Answer
> -1 votes
Maybe this can help: Debugging PHP CLI scripts with PhpStorm

---
Tags: debugging, virtual-machine
---


# Question
Title: Change status field options in edit user screen
I want to change the *status* field (`radio`) options from `Blocked/Active` to `Unapproved/approve` in Drupal 8.5. How to achieve it?

I have tried with `Hook_form_alter` and tried to change the options with `$form` parameter but no success.

This is the code I have tried:

```
  $form['status']['#options'] = [1 => t('Published'),0 =>t('Not Published') ];

```

# Answer
> 1 votes
Resolved the issue...

Following is the code:

```
 $form['account']['status']['#title'] = 'User Status';
 $form['account']['status']['#options'] = [1 => t('Published'),0 =>t('Not Published') ];

```

I am missing the **account** parameter.

---
Tags: hooks
---


# Question
Title: In a writing a Views style plugin, how can I create a text input that accepts Twig?
I am writing a Views style plugin, and I have a text field (input) that I want to be able to accept Contextual Filter arguments (or potentially field values). I am envisioning it working the same as the input that shows up when you click "Override title" under the "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED" fieldset. So, for example, you could add `{{ arguments.nid }}` into the text field.

This (below) is my current form element/text field that I'd want to be able to accept the arguments. I looked into the Views codebase, but was wasn't able to figure out how Views implements accepting arguments in a text field.

```
$form['display']['title'] = [
    '#title' => t('Chart title'),
    '#type' => 'textfield',
    '#default_value' => $options['title'],
    '#parents' => array_merge($parents, ['title']),
  ];

```

Any help would be greatly appreciated!

# Answer
To replace argument tokens in a Views plugin you need:

```
$tokens = $this->view->build_info['substitutions'];
$value = $this->viewsTokenReplace($value, $tokens);

```

If you've based your plugin on `StylePluginBase` you can use StylePluginBase::tokenizeValue, which additionally replaces row tokens as well.
> 1 votes

---
Tags: views, 8
---


title: Set access restriction for baseroute

text:
# Question
Title: Set access restriction for baseroute
Let's say I have the following in `example.links.task.yml` from a contributed module:

```
    example.view:
    title: 'View'
    base_route: 'entity.example.canonical'
    route_name: 'entity.example.canonical'

    example.edit_form:
    title: 'Edit'
    base_route: 'entity.example.canonical'
    route_name: 'entity.example.edit_form'

    ... more routes with the same base_route

```

Now I'd like to add a custom access restriction for all these local tasks. I tried to set a restriction to the `base_route`, thinking that all other routes with this particular `base_route` would have the restriction too, but it only works for `entity.example.canonical`. I tried the following way:

```
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if (($route = $collection->get('entity.example.canonical'))) {
      $route->setRequirement('_role', 'administrator');
    }
  }

}

```

I could explicitly name all different routes, but I thought there might be a way to only use the `base_route` \- not knowing if this would work though. Any ideas?

# Answer
This might work

```
if (($route = $collection->get('entity.example.canonical'))) { // base_route
      $current_route = \Drupal::routeMatch()->getRouteObject(); // get current route
      $current_route->setRequirement('_role', 'administrator');
}

```
> 1 votes

---
Tags: routes
---


# Question
Title: Image upload: Failed to open output stream
I created a media entity browser and for the image upload widget i choose the DropzoneJS.The widget settings are in the image bellow, pretty standard.

And regardless of image type (png, jpg, jpeg) any image selected for upload returns with the follow error message "Failed to open output stream". I'm guessing the upload is ok but it can't be saved?

The `public` dir is writable (sites/default/files). This is tested successfully when for the widget type i choose normal file upload. The image is uploaded and saved successfully.

Dropzone lib is the most current one from their master branch on GIT (was previously on 4.0.1 but i thought that the version is outdated and that was causing the issue, i was wrong).

Core: 8.5

Any ideas?

# Answer
In /admin/config/media/file-system look at the value of "Temporary directory" (`/var/tmp` or `/tmp` or ...) and check if that path is writable by the webserver user.
> 1 votes

---
Tags: entities, media
---


# Question
Title: Manage Form Display - not saving configuration
i'm working on a pretty big User/register site. Today i created some more fields. Now i want to order them properly with the "manage form display" settings like i used to but it is not working. Everytime i press save the page is reloaded but no changes are made. Yesterday evening everything worked fine.

Is there a maximum of fields you can use? Or does anyone has an idea what could be the problem here?

I'm really clueless because 12 hours ago it worked just fine for me...

with best regards

# Answer
How many fields are we talking? Is it hundreds?

I don't believe there is a maximum within Drupal but your server might have a limit. Within the php.ini config file on your web server you should see "max\_input\_vars"

You could try increasing that and restarting your apache/nginx server to see if that resolves the issue
> 1 votes

---
Tags: forms
---


# Question
Title: How to associate multiple profiles per user with Profile2
I'm running a Drupal 7 site that has different profile types (created using the Profile2 module). Each user is associated with a profile, so at the time of registration, a potential user can choose a specific profile, and based on that, a different registration page is displayed.

I was wondering, is it possible to allow a normal user (not admin) to associate more than one profile for itself? So that he/she can see the fields of each specific profile to which is associated?

At present, the Profile2 module allow to have one User: one Profile relationship, and only the admin can add multiple profiles to a user. Is there a patch for Profile2 module to permit this kind of feature?
Thank you!

# Answer
I was able to achieve the solution with this module, and by setting the right permissions offered by this module.
> 0 votes

---
Tags: users, version-control
---


# Question
Title: Anonymous users skip comment approval but they shouldn't
In my drupal 8.6.1 news blog anonymous users can skip comment approval althouth permissions are set to not skip. I rebuilt the permissions but nothing changed.

Also in comments page I see that some anonymous users are linked to an anonymous user account with id = 0 !

My site is not hacked and I can't understand what is going on.

Check this image!

Is there a chance that my drupal 8.6.1 has this unexpected behavior because is running on server with php 5.6?

Thanks in advance

# Answer
> 1 votes
On my side, the problem was the use of the cleantalk module.

In this module, in the configuration page: `admin/config/content/cleantalk/settings`

You must uncheck **"Enable automoderation"** if you do not want to override the "Skip comment approval" permission

---
Tags: users, comments
---


# Question
Title: Language detection by domain breaks ajax requests over https
What do I have:

* Drupal 8.6.2
* Domain Access
* Language modules
* Cloudflare with https

Problem:

If in URL language detection option (**/admin/config/regional/language/detection/url**) I have "**Path prefix**" - everything works fine.

Party starts, when I change it to "**Domain**" - ***every ajax request on any subdomain is trying to get through http instead of https*** and I can see "**mixed content error**" in console, so these requests are being blocked and website is malfunctioning. I cant use views propeerly, upload files through Plupload, use autocomplete forms, change some settings etc.

If I change it back to prefix - ajax works great again.

For prefix I have **site.com** for default language and **site.com/en** \- for english. For domain setting: **site.com** \- default and **en.site.com** is english version.

In Domain Access settings I've tried to set all possible URL schemas (http, https and variable) - no change. In Cloudflare settings I have speacial rules, redirecting every request from http to https (*I set up CF's https for dozen of websites, I know how to do it*).

If I set back to **prefix** and go to **en.site.com** (*it still works as an alias for the main domain*) ajax works fine, so this is not something about server or background settings - it's just Drupal messing around.

I could run it with prefix, but for SEO purposes it is better to use subdomain, because website is going to be big and it is better to separate languages technically on different websites, search engines will rank these subdomains more correct.

Please help! This is my first experience with multilingual website and I don't have a clue what to do.

# Answer
> 0 votes
Ok, after hours of searching the web, googling, asking... here is the solution.

1) Go to **ISP panel** \> Web-server settings \> SSL Sertificates \> add self signed sertificate for your domain.

2) While in ISP, go to **WWW-domains** and double click on your domain \> check **Secure connection (SSL)**, SSL port - 443, select your sertificate from dropdown list and save.

3) Then go to Cloudflare domain settings, open **Crypto** page and change SSL from Flexible to **Full**.

Thats it! As simple as that. And there is no need in reverse proxy in settings.php

# Answer
> 1 votes
The problem is the CDN, which connects to Drupal via HTTP and to the client via HTTPS. Then all absolute URLs generated by Drupal have the wrong protocol. Not only this one for ajax, which is absolute because you've switched language detection to domain based. Prefix based it uses relative paths and then the protocol doesn't matter.

Normally CDN's add a header `X_FORWARDED_PROTO` to the request, which Drupal can use to determine the correct protocol. For this to work you have to configure the CDN as reverse proxy in settings.php.

---
Tags: 8, ajax, domain-access, subsites
---