# Question
Title: How do I create linked nodes without user intervention?
Suppose I have a cooking website where users can create `Recipe` nodes for `Food` nodes. For example, you might have a *Cake* node of type `Food`, and users should see an `Add Recipe` button on that page which takes them `node/add/recipe` except that the newly created `Recipe` node will have a reference to the parent *Cake* page.

I've added a `Content` type *Entity Reference* to to the `Recipe` node, which works fine. For programmatically generating the link I'm a bit lost though. I initially looked at using the Rules but it's still in alpha, and from the description it looks like I'd probably want to use the Rules Link module as well, but it doesn't have a version for 8.x at all.

Then I started looking at hook\_ENTITY\_TYPE\_create, which is my current best guess for how to achieve the desired behaviour, but that still leaves me with some questions about what the best approach is;

1. How / Where do I capture the node reference when all I'm given is the EntityInterface type?
2. What is a mechanism for passing information about the reference/parent node to `hook_ENTITY_TYPE_create` so that I can even know which reference to store?
3. How do I create links or buttons on the parent `Food` node that cause such information to be passed on to the hook?
4. Lastly, is this even the best approach, or am I missing a way that doesn't involve writing code?

I don't think I need any hand-holding or code, but I'd be very grateful for some pointers in the right direction for each of the above points from a veteran.

# Answer
A solution that doesn't go deep into the code is to use the Prepopulate module.

It enables you to prepopulate form fields through the link to the form page:

> ```
> http://www.example.com/node/add/recipe?edit[field_entity_reference][widget][0][target_id]=123
>
> ```

You'll probably want to construct the links automatically, it can be done with Views. You create a Block Display that contructs the link using the Food information it's been placed on, through a contextual filter. When the Block is placed on Food pages the link leads to new recipe form that has the food where you just left from already filled in.

You can find more info about how to construct the link with the help of Views in this answer: Add Prepopulate links to Node pages part of the answer.
> 2 votes

---
Tags: 8
---


# Question
Title: What does the "Views: Filter by an entity reference view" reference method do?
I was just creating a reference type and noticed that there is a reference method called `Views: Filter by an entity reference view`. What does this do, and how does it differ from the `Default` method?

I tried selecting it but received the following message:

> No eligible views were found. Create a view with an *Entity Reference* display, or add such a display to an existing view.

I tried creating a view but couldn't see any *Entity Reference* display options. I also couldn't find any documentation about what this reference method (or the default one, for that matter) do.

# Answer
In your Entity Reference Field settings the Default method will allow *all* of the entities of the type you specified to be eligible to be referenced.

If you're setting up your ER field to reference Taxonomy terms of a certain vocabulary then all of the terms from that Vocabulary will be able to be chosen inside that field.

If you want *more control* over which items should be eligible you can use Views to create a Display of type `Entity reference`.

Views module allows you to build various lists of entities. You can add filters and narrow down the list to the items you need in a specific case.

If you want a list of 10 specific Taxonomy Terms from a Vocabulary that contains 100 terms you can use Views to build it.

Usually you build Views Displays of types "Page" and "Block". But there is also the option to build "Entity reference" Display.

The "Entity reference" Display type has some special settings that other displays don't have, and they control what the list of entities should look like in the context of using that list in an ER field on a CT.

So once you create one Entity Reference Display type in Views, set it to filter the same type of items as an ER field in your Content Type, you will be able to return to your ER field settings and choose that Views Display as the field reference method.

This means that the entities offered to be chosen through the ER field when creating a new node will be only the entities from the Views you had created. If you had narrowed down the list of entities in the ER Views Display to only 3 items, then only those 3 items will be available in the ER field when creating a new node.

The Views Display must be Saved before it can appear in the ER field settings. When creating the View you choose the type of entities that will be listed, for example Taxonomy terms, and after the View has been created you can add a new Display to the Views, choose "Entity reference" from the list of the offered Views Displays (different Views Displays are shown as tabs on the Views Edit page).
> 12 votes

---
Tags: 9
---


# Question
Title: How to delete nodes without taking a lot of time?
My site has about 200 000 nodes. When I want to delete let say 200 nodes it takes about 2hr. I have also installed commerce module, views and a lot of the usual modules. What can I do to speed things up?

# Answer
Usually I use 2 approach from the command line. If you call a page from the browser to accomplish the task this will use more time and resources.

**1. You can create your own module named `drush_delete`**

Inside the `drush_delete.drush.inc` file put this code:

```
<?php
/**
 * @file
 * The Drush Delete drush commands.
 */

/**
* Implements hook_drush_command().
*/
function drush_delete_drush_command() {
  $items['node-delete'] = array(
    'description' => dt("Delete nodes."),
    'aliases' => array('nd'),
    'arguments' => array(
      'nids' => dt('The nids of the nodes to delete'),
    ),
    'examples' => array(
      'drush node-delete 1' => dt('Delete the node with nid = 1.'),
      'drush node-delete 1 2 3' => dt('Delete the nodes with nid = 1, 2 and 3.'),

    ),
  );
  return $items;
}

/**
 * Callback for the node-delete command
 */
function drush_drush_delete_node_delete() {
  $nids = func_get_args();
  $nids = array_filter($nids, 'is_numeric');
  $nids = array_map('intval', $nids);
  $nids = array_unique($nids);
  $nids = array_values($nids);
  $cant = count($nids);

  if ($cant > 0) {
    node_delete_multiple($nids);

    drush_print(dt("Deleted nodes:"));
    drush_print(implode(' ', $nids));
  }
  else {
    drush_set_error('DRUSH_ERROR_CODE', dt("You must enter at least one nid"));
  }
}

```

Install the module, run `drush cc drush` to clear the drush cache and use the command like this:

To delete a node use:

```
drush node-delete 1
drush nd 1

```

To delete multiple nodes use:

```
drush node-delete 1 2 3
drush nd 1 2 3

```

***EDIT:*** I just remeber that I have a collection of drush commands in github at https://github.com/adrian-cid/drush\_commands.

**2. You can use the Drush Entity module**

Deleting node with nid 1 and 2

```
drush entity-delete node 1 2

```

Deleting all the nodes:

```
drush entity-delete node

```

Deleting all the articles nodes:

```
drush entity-delete node --bundles=article

```
> 4 votes

# Answer
I think you should be able to speed things up by using `node_delete_multiple()`. You can create a simple script in your drupal installation path which then would be executed either using the command line or through a http 'POST' request:

```
/** bootstrap drupal **/
define('DRUPAL_ROOT', getcwd());
require_once 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Array of nid for each node to delete
$nids = array();

// Check if script running from cli or not
$isCli = defined('STDIN');
if ($isCli && $argc === 2) {
  $nids = explode(',', $argv[1]);
}
// Check if script is invoked using a 'POST' request
if (!$isCli && $_SERVER['REQUEST_METHOD'] === 'POST') {
  if (isset($_POST['nids'])) {
    $nids = explode(',', $_POST['nids']);
  }
}

if (count($nids)) {
  // make sure the script does not timeout
  set_time_limit(0);

  try {
    node_delete_multiple($nids);
  } catch (Exception $e) {
    echo $e->getMessage();
  }
}

```

Of course you need to supply the nids for all nodes that you wish to delete.

The fastest way would also be to run this script from the command line:

```
php delete-nodes.php 1,2,3,4

```

You could also make a 'POST' request, for instance using curl:

```
curl https://example.com/delete-nodes.php -d 'nids=1,2,3,4'

```
> 1 votes

# Answer
D7:

I would also use `node_delete_multiple()`. This is also the way that Devel generate handles it, https://git.drupalcode.org/project/devel/-/blob/57e32c63089216da92efe811212bd4f6026ba307/devel\_generate/devel\_generate.inc#L605-625

```
/**
 * Handle the devel_generate_content_form request to kill all of the content.
 * This is used by both the batch and non-batch branches of the code.
 *
 * @param $num
 *   array of options obtained from devel_generate_content_form.
 */
function devel_generate_content_kill($values) {
  $results = db_select('node', 'n')
              ->fields('n', array('nid'))
              ->condition('type', $values['node_types'], 'IN')
              ->execute();
  foreach ($results as $result) {
    $nids[] = $result->nid;
  }

  if (!empty($nids)) {
    node_delete_multiple($nids);
    drupal_set_message(t('Deleted %count nodes.', array('%count' => count($nids))));
  }
}

```

D8:

The Devel module also has a devel\_generate submodule. It has a `contentKill()` function,

First part is just querying the nodes.

```
  /**
   * Deletes all nodes of given node types.
   *
   * @param array $values
   *   The input values from the settings form.
   */
  protected function contentKill(array $values) {
    $nids = $this->nodeStorage->getQuery()
      ->condition('type', $values['node_types'], 'IN')
      ->execute();

    if (!empty($nids)) {
      $nodes = $this->nodeStorage->loadMultiple($nids);
      $this->nodeStorage->delete($nodes);
      $this->setMessage($this->t('Deleted %count nodes.', ['%count' => count($nids)]));
    }
  }

```

Source, https://git.drupalcode.org/project/devel/-/blob/b38337acfc47a3b208c46c98b8d9d219779f98fb/devel\_generate/src/Plugin/DevelGenerate/ContentDevelGenerate.php#L571-587

If for some reason it doesn't fit in memory, just use `array_chunk()`

Quick notes,

Instead of the script on another answer, I would just add a function on a custom module and call it with `drush ev function_name();`
> 0 votes

---
Tags: 7, performance
---


# Question
Title: How can I output log messages to stdout/stderr?
I can create log messages really easily in `Drupal 9.x` like this;

```
\Drupal::logger('mymodule')->error("something went wrong");

```

I see these messages appear in `/admin/reports/dblog`, but it would be convenient if I had the option to print them to stdout, or perhaps a file that I could `tail`. Is this possible?

Note that this question looks similar but I think it's for an older version of drupal using `watchdog`, so I don't think it applies: how to show admin/reports/dblog in terminal ( cli )

# Answer
> 6 votes
I’ve been using the log\_stdout module for stdout logging. It works well with Docker containers.

> This module provides a hook for Drupal Watchdog that directs log messages to `php://stdout` or `php://stderr` for better log handling with Docker.

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


# Question
Title: How do I generate-content of a particular type with drush 9.x+
```
root@0a581055a6ad:/opt/drupal# drush genc 10 --types=article

  The "--types" option does not exist.

devel-generate:content [--kill] [--bundles [BUNDLES]] [--authors [AUTHORS]] [--feedback [FEEDBACK]] [--languages [LANGUAGES]] [--translations [TRANSLATIONS]] [--add-type-label] [--skip-fields [SKIP-FIELDS]] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--notify [NOTIFY]] [--xh-link XH-LINK] [--druplicon] [--] <command> [<num> [<max_comments>]]

root@0a581055a6ad:/opt/drupal# drush --version
Drush Commandline Tool 10.3.4

```

According to the documentation this was an option with `drush 8.x`, but I don't see any equivalent in `drush 9.x` and up. What is the intended way to invoke `genc` for a particular node type with this new version of drush?

# Answer
> 3 votes
Yeah, it's `--bundles` now. That's also what the error output is telling you already when echoing all possible options.

```
drush genc 10 --bundles article,page

```

---
Tags: drush
---


title: Show node links in modal buttonpane

text:
# Question
Title: Show node links in modal buttonpane
I want to show some node fields in buttonpane when I open node in modal.

As far as I know, it will automatically show there inputs with type submit and links with class button, but I added class button on email field link, anchor rendered is like:

```
<a href="mailto:test@example.com" class="button">Send email</a>

```

but it's not showing in buttonpane.

Any idea why and how to fix it?

# Answer
Ah, I just figured out from *core/misc/dialog/dialog.ajax.js* that I need wrapper with class form-actions.

```
<div class="form-actions">
  <a href="mailto:test@example.com" class="button">Send email</a>
</div>

```
> 2 votes

---
Tags: 8, nodes, ajax, modal-dialogs
---


# Question
Title: Argument 2 passed to Drupal\Console\Command\Test\RunCommand::__construct() must be an instance of Drupal\simpletest\TestDiscovery
I'm trying to install drupal console with Drupal 9.0.5, so I ran this command:

```
composer require drupal/console:~1.0

```

However when I try run the `drupal` command with any arguments I get this error:

```
root@6dc17ce2d4bf:/opt/drupal# drupal --version
TypeError: Argument 2 passed to Drupal\Console\Command\Test\RunCommand::__construct() must be an instance of Drupal\simpletest\TestDiscovery, null given in /opt/drupal/vendor/drupal/console/src/Command/Test/RunCommand.php on line 58 #0 [internal function]: Drupal\Console\Command\Test\RunCommand->__construct('/opt/drupal/web', NULL, Object(Drupal\Core\Extension\ModuleHandler), Object(Drupal\Core\Datetime\DateFormatter))
#1 /opt/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php(1144): ReflectionClass->newInstanceArgs(Array)
#2 /opt/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php(618): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\Definition), Array, true, 'console.test_ru...')
#3 /opt/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php(558): Symfony\Component\DependencyInjection\ContainerBuilder->doGet('console.test_ru...', 1)
#4 /opt/drupal/vendor/drupal/console-core/src/Application.php(468): Symfony\Component\DependencyInjection\ContainerBuilder->get('console.test_ru...')
#5 /opt/drupal/vendor/drupal/console-core/src/Application.php(214): Drupal\Console\Core\Application->registerCommands()
#6 /opt/drupal/vendor/drupal/console-core/src/Application.php(119): Drupal\Console\Core\Application->loadCommands()
#7 /opt/drupal/vendor/drupal/console/src/Application.php(64): Drupal\Console\Core\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#8 /opt/drupal/vendor/symfony/console/Application.php(147): Drupal\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#9 /opt/drupal/vendor/drupal/console/bin/drupal.php(89): Symfony\Component\Console\Application->run()
#10 /opt/drupal/vendor/drupal/console/bin/drupal(4): require('/opt/drupal/ven...')
#11 {main}
TypeError: Argument 2 passed to Drupal\Console\Command\Test\RunCommand::__construct() must be an instance of Drupal\simpletest\TestDiscovery, null given in Drupal\Console\Command\Test\RunCommand->__construct() (line 58 of /opt/drupal/vendor/drupal/console/src/Command/Test/RunCommand.php).

```

I don't really understand this error. Any ideas what might cause this?

# Answer
This is really just kiamlaluno's answer, but they never posted it so I'll just copy it here verbatim:

> Drupal Console has not been updated to run on new Drupal versions. It's even less compatible with Drupal 9, as many classes or methods have been removed.
> 1 votes

---
Tags: console
---


# Question
Title: How to move views pager to different region as a block?
I created a page view and results are showing up in main page content block. Now i need to move the pager attached with view to different region.

I am not sure how to achieve this. Please suggest any preprocess or backend feature which can do this?

# Answer
The easiest is probably the comment from @No SSsweat

Another easy option is to place the view in each region and hide the pager/content using CSS depending on region.

The javascript option may be possible depending if you have anything already in place, as you can move the DOM pager element programmatically.

The neater solution is to use some php code, the drupal way, probably someone has already done this for you, so look for a drupal contributed module related to view and pager or paging, and layout, those would probably be my keywords for a search.
> 1 votes

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


title: Adding fields to user registration form

text:
# Question
Title: Adding fields to user registration form
I want to collect user personal information like first name, last name, and home address in in user registration, and I also want user to make the profile pubic or private.

I am using Drupal 7.

# Answer
> 12 votes
Go to Config \> People \> Account Settings \> Manage Fields

Then, you can add fields to user profiles just as you would add fields to any content type. When you add fields here, there is a checkbox to "Display on user registration form" if you want the field to be part of the user's registration process.

Hope this helps someone.

# Answer
> 4 votes
You can add fields by going to `/admin/config/people/accounts/fields` then set the privacy settings of those fields with an access control module like Field Permissions

http://drupal.org/project/field\_permissions

# Answer
> 0 votes
In order to add fields to "Create Account" registration form, you can do this in following way:

Go to "--/admin/config/people/accounts/fields" then while "Add new field". While adding new field, under label you could see "Display on user registration form". Check this box and the corresponding field will be shown on registration form.

# Answer
> 0 votes
From Drupal 8 you can easily drag and drop that field within the /user/register form. Up , down, visible, invisible. Super cool!

Link: `"/admin/config/people/accounts/form-display/register"`

---
Tags: users
---


# Question
Title: Why can't I see <div> tags added to $form in hook_form_FORM_ID_alter?
I want to modify the `$form` variable in an implementation of `hook_form_FORM_ID_alter` but can't seem to be able to set the `#prefix` and `#suffix` variables on field widget.

```
/**
 * @file
 * Implementations Module Hooks
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the node/create form for implementation types
 */
function implementations_form_node_implementation_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $prefix = '<div style="display:none;">';
  $suffix = '</div>';

  $form['field_parent_idea']['widget']['#prefix'] = $prefix;
  $form['field_parent_idea']['widget']['#suffix'] = $suffix;

  dpm($form['field_parent_idea']['widget']);
  dpm($form['field_parent_idea']['widget']['#prefix']);
  dpm($form['field_parent_idea']['widget']['#suffix']);
}

```

When I navigate to `node/add/implementation` I would expect to see the value of `$form['field_parent_idea']['widget']` with the `#prefix` and `#suffix` variables set, but instead they're blank. Here's the relevant snippet showing the suffix/prefix values:

```
[#max_delta] => 0
[#prefix] =>
[#suffix] =>
[add_more] => Array

```

Why are they blank?

This is the full output of what I see.

```

Array
(
    [0] => Array
        (
            [target_id] => Array
                (
                    [#title] => stdClass Object
                        (
                            [__CLASS__] => Drupal\Core\StringTranslation\TranslatableMarkup
                            [translatedMarkup:protected] =>
                            [options:protected] => Array
                                (
                                )

                            [stringTranslation:protected] => stdClass Object
                                (
                                    [__CLASS__] => Drupal\Core\StringTranslation\TranslationManager
                                    [translators:protected] => Array
                                        (
                                            [30] => Array(1)
                                        )

                                    [sortedTranslators:protected] => Array
                                        (
                                            [0] => Drupal\Core\StringTranslation\Translator\CustomStrings
                                        )

                                    [defaultLangcode:protected] => en
                                    [_serviceId] => string_translation
                                )

                            [string:protected] => @title (value @number)
                            [arguments:protected] => Array
                                (
                                    [@title] => Parent Idea
                                    [@number] => 1
                                )

                        )

                    [#title_display] => invisible
                    [#description] =>
                    [#field_parents] => Array
                        (
                        )

                    [#required] => 1
                    [#delta] => 0
                    [#weight] => 0
                    [#type] => entity_autocomplete
                    [#target_type] => node
                    [#selection_handler] => default:node
                    [#selection_settings] => Array
                        (
                            [target_bundles] => Array
                                (
                                    [idea] => idea
                                )

                            [sort] => Array
                                (
                                    [field] => _none
                                )

                            [auto_create] =>
                            [auto_create_bundle] =>
                            [match_operator] => CONTAINS
                            [match_limit] => 10
                        )

                    [#validate_reference] =>
                    [#maxlength] => 1024
                    [#default_value] =>
                    [#size] => 60
                    [#placeholder] =>
                )

            [_weight] => Array
                (
                    [#type] => weight
                    [#title] => stdClass Object
                        (
                            [__CLASS__] => Drupal\Core\StringTranslation\TranslatableMarkup
                            [translatedMarkup:protected] =>
                            [options:protected] => Array
                                (
                                )

                            [stringTranslation:protected] => stdClass Object
                                (
                                    [__CLASS__] => Drupal\Core\StringTranslation\TranslationManager
                                    [translators:protected] => Array
                                        (
                                            [30] => Array(1)
                                        )

                                    [sortedTranslators:protected] => Array
                                        (
                                            [0] => Drupal\Core\StringTranslation\Translator\CustomStrings
                                        )

                                    [defaultLangcode:protected] => en
                                    [_serviceId] => string_translation
                                )

                            [string:protected] => Weight for row @number
                            [arguments:protected] => Array
                                (
                                    [@number] => 1
                                )

                        )

                    [#title_display] => invisible
                    [#delta] => 0
                    [#default_value] => 0
                    [#weight] => 100
                )

        )

    [#theme] => field_multiple_value_form
    [#field_name] => field_parent_idea
    [#cardinality] => -1
    [#cardinality_multiple] => 1
    [#required] => 1
    [#title] => Parent Idea
    [#description] =>
    [#max_delta] => 0
    [#prefix] =>

    [#suffix] =>

    [add_more] => Array
        (
            [#type] => submit
            [#name] => field_parent_idea_add_more
            [#value] => stdClass Object
                (
                    [__CLASS__] => Drupal\Core\StringTranslation\TranslatableMarkup
                    [translatedMarkup:protected] =>
                    [options:protected] => Array
                        (
                        )

                    [stringTranslation:protected] =>
                    [string:protected] => Add another item
                    [arguments:protected] => Array
                        (
                        )

                )

            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => field-add-more-submit
                        )

                )

            [#limit_validation_errors] => Array
                (
                    [0] => Array
                        (
                            [0] => field_parent_idea
                        )

                )

            [#submit] => Array
                (
                    [0] => Array
                        (
                            [0] => Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
                            [1] => addMoreSubmit
                        )

                )

            [#ajax] => Array
                (
                    [callback] => Array
                        (
                            [0] => Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
                            [1] => addMoreAjax
                        )

                    [wrapper] => field-parent-idea-add-more-wrapper
                    [effect] => fade
                )

        )

    [#after_build] => Array
        (
            [0] => Array
                (
                    [0] => Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
                    [1] => afterBuild
                )

        )

    [#field_parents] => Array
        (
        )

    [#parents] => Array
        (
            [0] => field_parent_idea
        )

    [#tree] => 1
)

```

At first I thought that the issue was because I was setting on a nested array variable, but that's exactly what the example code in the documentation does.

```

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
    $upload_enabled_types = \Drupal::config('mymodule.settings')
      ->get('upload_enabled_types');
    $form['workflow']['upload_' . $form['type']['#value']] = array(
      '#type' => 'radios',
      '#title' => t('Attachments'),
      '#default_value' => in_array($form['type']['#value'], $upload_enabled_types) ? 1 : 0,
      '#options' => array(
        t('Disabled'),
        t('Enabled'),
      ),
    );

    // Add a custom submit handler to save the array of types back to the config file.
    $form['actions']['submit']['#submit'][] = 'mymodule_upload_enabled_types_submit';
  }
}

```

# Answer
> 3 votes
For some reason `dpm()` fails to show `#prefix` & `#suffix` values, bug maybe? Use `kint()` instead. You'll need to enable the Kint module if you're using Devel 8.x-2.1. But if using Devel 4.0.1 you'll need to install kint via `composer require kint-php/kint`.

Dump aside, Drupal automatically strips the `style=` for security reasons.

Instead, it should be

```
$prefix = '<div class="visually-hidden">';

```

<sub> **Note:** Assuming you're using the default Seven theme as admin theme. Otherwise, you would have to add this class to your admin's theme CSS and hide it. </sub>

---

The more Drupally correct way is to use hidden

```
$form['field_parent_idea']['widget']['#type'] = 'hidden';

```

---

Another way is to set #access to false, but you won't be able to change the value via JavaScript as the field doesn't get printed to the page.

```
$form['field_parent_idea']['widget']['#access'] = FALSE;

```

# Answer
> 3 votes
There are two basic problems here. First, your debug output doesn't display what you expect, and second the form is not visibly altered as you expect.

1. dpm() displays the output in the messages area of the page. What you are trying to display is an array containing an HTML tag as one of its values - that value will be interpreted as an HTML tag when shown in the messages area. `<div>` produces no visible output, which is why you think those array elements are "blank". But if you look at the page source you will see the `<div>`. Try using a regular non-HTML string as #prefix and #suffix and you will see this string in the output from the dpm(). First problem solved.
2. You're altering `$form['field_parent_idea']['widget']` but you don't show us what that form element is. Not all form elements respect #prefix and #suffix, so without knowing the element we don't know what to expect. Indeed, your verbose output looks like you're using a custom #theme function, so it's even less clear what we expect to see. It's highly likely that your theme function is ignoring what you put into #prefix and #suffix.

When doing something like this for the first time, it's best if you start off with some simple things and get those working first. Have you successfully used hook\_form\_FORM\_ID\_alter() elsewhere? Try just changing the form title, for example, and see if you can get that to work. Try adding a #prefix to the "Title" textfield and get that to work. Taking these little steps and getting them to work will help you get past all the little things like function naming and form ID naming etc. THEN you can move on to some complex form element with its own #theme function. You probably have to theme that complex form element by overriding the template, not by adding a #prefix and #suffix. Or, if this really is a field widget, then by writing your own custom widget.

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


# Question
Title: How do I restrict GraphQL access with Basic Auth?
According to this Gitbook (near the bottom), its possible to require GraphQL query authentication with Drupal Core's Basic Auth module. This allows GraphQL to authenticate against a user stored in the Drupal DB.

https://drupal-graphql.gitbook.io/graphql/authentication/authentication

I created an event subscriber that adds the Basic Auth option to the route like this:

```
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('graphql.query.default:default')) {
      $route->setOptions(['_auth' => ['basic_auth']]);
    }
  }
}

```

However, when I make a curl request without an Authorization header it still goes through:

```
curl -X POST -H "Content-Type: application/json"   --data '{"query":"{fileById(id: \"33\") {changed}}","variables":null,"operationName":null}' http://MYLOCALHOST/graphql

```

Response:

```
{"data":{"fileById":{"changed":1572374455}}}

```

I did enable my custom module with the RouteSubscriber information above and also the Basic Auth module. When I visit the `/graphql` Drupal path in a browser, access is denied but when I make the CURL request it goes through. I was hoping to restrict CURL access as well.

Here is the Drupal 8 documentation on Basic Auth:

https://www.drupal.org/docs/8/core/modules/basic\_auth/overview

I am using v3 of the Drupal 8 GraphQL module.

# Answer
> 2 votes
I got it!

I needed to add

```
$route->setRequirements(['_user_is_logged_in' => 'TRUE']);

```

...And then do the curl request with the username and password.

---
Tags: 8, authentication-authorization
---


title: Next and Previous Button for Pages

text:
# Question
Title: Next and Previous Button for Pages
I have created a 'Content Type' names it Stories. And have created 30 new pages for each stories using the same Content Type. Now how can i add **Previous and Next Button** under each stories?

Any Article or Video tutorial will be appreciated

Thank You, Mazhar P.S I am using D8

# Answer
> 1 votes
I would say that one relatively easy way without relying on any additional modules is to use the book module that comes with drupal core.

If you put the nodes in a book then you can use the book navigation's previous and next button.

You can override book-navigation.html.twig to remove elements of the book navigation that you don't need.

# Answer
> 0 votes
I know this is old thread, but for benefit of users looking for an answer in 2020 for Drupal 8 (8.8+) and 9, try out https://www.drupal.org/project/related\_nodes\_block.

It does not require any taxonomy terms, and it supports Prev/Next, First/Last, Most/Least Viewed and Random, of same content-type or others, you choose.

Disclaimer: I am the author of the module.

---
Tags: views
---


title: Alter Submit button of specific form

text:
# Question
Title: Alter Submit button of specific form
I am new to Drupal and want to alter a submit button of a node-edit form. So I wrote a basic module to do so. And it also alters the form button of my form with the id=node\_hotel\_edit\_form. But also it alters all submit buttons to the same text an classes, even in the backend.

My alter\_hotel\_form.info.yml

```
name: 'Alter Hotel Form'
type: module
description: 'Alters Hotel EDIT form'
core_version_requirement: ^8 || ^9
package: 'Custom'

```

My alter\_hotel\_form.module

```
<?php

function alter_hotel_form_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id = 'node_hotel_edit_form') {
    $form['actions']['submit']['#attributes']['class'][] = 'hotel-edit-submit btn btn-medium blue darken-2';
    $form['actions']['submit']['#value'] = t('Save Hotel');

  }

}

```

Can anybody point me a direction or tell me what I am doing wrong? Thank you very much in advance!

# Answer
> 3 votes
`if ($form_id = 'node_hotel_edit_form')` is wrong. This will **assign** `node_hotel_edit_form` to `$form_id` and always evaluate to TRUE.

It should be `if ($form_id === 'node_hotel_edit_form')` or `==` also works.

---
Tags: forms, hooks, 9
---


# Question
Title: How to add a view tab to node edit form?
I have two node bundles: events and registrations. Registrations have an entity reference field pointing to a given event.

I have a view, that list registrations with some event and registrant information and a contextual filter for given event. I would like to add this view as a tab to Event node edit form so, that it would list current registrations to given event.

I managed to display the view on the edit form easily by adding the view to form render array with event `nid` as an argument for the contextual filter, but not sure, what are the possible ways to add view to a node edit form as a tab.

# Answer
> 1 votes
I'm assuming you mean "Drupal tab" when you say you want to display Views as a tab on the Event edit form. "Drupal tabs" are the "View | Edit | Translate | Etc" links that are usually visually styled as tabs.

Although, a Drupal tab is an independent page, it will not be like a Block *within* the Edit form, it will be just a link on the "View | Edit" menu, you'll have "View | Edit | Registrations". This means you won't see registrations listed when you go to Edit (unless you add a Block to that page through regular procedure), you will see your Registration results when you visit the "Registrations" link/page.

## Display a Views Page as one of Drupal tabs

You will need to have the "Page" Display in your Registrations Views. Page Displays have special `Page settings` that include the `Path` and `Menu` options. Additionally, you'll need to adjust the Contextual filter too, to only appear on Event type nodes.

You can combine these two settings to make that Views Page appear among the Drupal tabs of a set of links.

The **Path** needs to follow the logic of the set of links. In your case you have drupal tabs `/node/[nid]`, `/node/[nid]/edit` etc. You'll want to set your `Path` to `node/%node/registrations`.

On the **Menu** you should choose the `Menu tab` option, fill in what you want the tab text to say (into "Menu link title"), choose a `Parent`, it can some menu you're not displaying anywhere if you don't need this page to appear as a menu item elsewhere. The `Weight` will affect the order on the Drupal tabs, enter a larger number (e.g. 50) to make sure it comes up at the end, and not before "View" or "Edit".

You already have the Contextual filter configured and working, so you might not need to do anything else. Check that the Contextual filter **ID** from the "Content" Category with these settings:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS in the URL or a default is provided`
**Specify validation criteria**
Validator: **Content**
Content type **Event**
Set the option for the case when the argument doesn't validate to something that makes sense to you.

When you save this View and reload some Event node page you should be able to see the Registrations as a Drupal tab. Rebuild Drupal cache if it doesn't appear.

---
Tags: views, nodes
---


title: Organic-Groups multisite architecture

text:
# Question
Title: Organic-Groups multisite architecture
I have a task to build a series of websites all related to the same core business.

Initially, I was going to build each one as a separate website. Later however, I was told the sites have to be able to share content which changed my plans.

Going by the logic that the easiest way to build multiple Drupal websites which share content is to build one site and make it work and appear as many.

So, I decided to build the site in Organic Groups but I have the following functionality challenges.

1. How can I direct unique URLs to individual Groups on my site. I:E configuring **www.mysite.co.uk** to visit Group#1 and **www.mysite.com** to visit Group#2 etc
2. Is there a way to create content on the Drupal site which can optionally be shared/posted to one or more of my Groups? **The idea is to create content on the primary 'website' and the same content displays in the Groups/'sub-sites'**.

I would appreciate any suggestions.

Thanks.

# Answer
> 0 votes
Honestly, I think that the module Domain Access would meet your needs more than Organic Groups would. A friend of mine recently created a site matching exactly your criteria.

> Module Package includes:
>
> Domain Alias 6.x.2 and higher only by bforchhammer. Allows you to specify subdomain aliases and domain name patterns for domain entries so that multiple hostnames are matched on a single domain entry.
>
> Domain Configuration -- Allows you to change select system variables for each subdomain, such as offline status, footer message and default home page.
>
> Domain Content -- Provides a content administration page for each subdomain, so that affiliate editors can administer content for their section of the site.
>
> Domain Navigation -- Supplies a navigation block with three themes. Creates menu items for each subdomain, suitable for using as primary or secondary links.
>
> Domain Path -- Enables custom path aliases per domain.
>
> Domain Prefix -- Provides a user interface for enabling select database table prefixing for use with subdomains. The Drupal 5 version is not fully functional on pgSQL, but Drupal 6 version is.
>
> Domain Settings -- Exposes domain-sensitive variable settings to most configuration forms. Requires Domain Conf.
>
> Domain Source -- Allows editors to set a primary source domain when links are written to content from other domains.
>
> Domain Strict -- Forces users to be members of domains in order to view content. This is a sample extension module that uses the API.
>
> Domain Theme -- Allows separate themes, theme settings and colors for each subdomain.
>
> Domain User -- Allows for the automatic creation of subdomains for registered users.
>
> Domain Views by mrichar1 and nonsie -- Provides Views integration for Views 5.x.1 and 6.x.2 or higher.

# Answer
> 0 votes
You could also try Spaces + PURL + Organic Groups, similar to OpenScholar Distribution. But the development for spaces module is almost stalled. If you are like me and want to go with that route then be prepared to write a lot of custom code.

# Answer
> 0 votes
For Drupal 7: Domain access would make more sense and you could share content between sites as well as views, themes, styles, modules.

In 8 Group (not organic groups) uses a domain access feature as well (a separate module).

You mentioned multisite in the title which is another option (share code, separate dbs).

---
Tags: 7, organic-groups, nodes, uri
---


# Question
Title: Migrated content type fields not showing
I'm trying to migrate custom content types with attached fields from Drupal 7 to Drupal 8. Using drush migrate commands I can successfully migrate all content types, but I have problem with fields.

First I run *upgrade\_d7\_field* migration, than *upgrade\_d7\_field\_instance* and last migration is *upgrade\_d7\_node\_MY\_CONTENT\_TYPE\_NAME\_content*.

If I go to *Structure -\> Content types* and then open my custom content type (by pressing *Manage fields*) I can see all fields attached to it - everything is ok. If I choose *Content* from main menu and try to create new content for my content type I only see Title field, no more fields are displayed. Same are with migrated content - if I 'm trying to edit it, I see only title.

What I'm missing ? I have migrated data in Drupal 8 fields table - node\_field\_*MY\_FIELD\_NAME*. I am logged in as admin user, so I should have all permissions to view this fields.

# Answer
> 0 votes
It sounds like the fields might be disabled on the entity form.

Goto Structure -\> YOUR CONTENT TYPE -\> Manage form display

Then move the fields you are expecting to see in the form from **Disabled** (bottom) to **Content**. You can also control the display order from there.

# Answer
> 0 votes
I had the same problem on a Drupal 8.9 site today. I went to Administration \> Configuration \> Content Authoring \> Text formats and editors and clicked on Configure next to 'Full HTML.' That page showed an error that a null filter type would be deleted after I saved the current filter, so I clicked "Save" without making any other changes. The error was gone, and now my content is being displayed as expected.

---
Tags: migrations
---


# Question
Title: How can I skip the current password validation on the user form?
My site requires that I turn off the current password validation on the Account Edit Form when changing / specifying a new password.

In D7 I accomplished this via a `hook_form_alter` implementation. With Drupal 8's new form api I am unsure of how I can make this alteration. `hook_form_alter` still exists, but the values in the `form[#validation]` seems to be used differently.

I see in the existing form code that a 'password reset' does exactly what I would like to do, but it's unclear how I can make this modification outside the actual `AccountForm` Class, or the `ProtectedUserFieldConstraintValidator` implementation of `ConstraintValidator`.

Thanks

# Answer
> 0 votes
`$account->_skipProtectedUserFieldConstraint` is a flag that is designed to prevent this validation.

The trick is setting it at the right place. Not exactly sure what works, since the code in AccountForm::buildEntity() always sets it to either TRUE or FALSE. Maybe we need to change that to only set it to TRUE if it's TRUE and not force it to FALSE. Then you could use an entity builder callback (see the last line in menu\_ui\_form\_node\_type\_form\_alter() for an example).

What you can try is setting $form\_state-\>set('user\_pass\_reset', TRUE) altough that could possibly have side effects.

# Answer
> 3 votes
A working code example for this is the No Current Password module.

Here's the relevant code:

> ```
> /**
>  * Implements hook_form_FORM_ID_alter().
>  * Remove the current password field from the user_profile_form form (user/%/edit).
>  */
> function nocurrent_pass_form_user_form_alter(&$form, &$form_state) {
>
>   // Get the module's configuration
>   $config = \Drupal::config('nocurrent_pass.settings');
>   $nocurrent_pass_disabled = $config->get('nocurrent_pass_disabled');
>
>   // If the Current password is disabled
>   if ($nocurrent_pass_disabled) {
>
>     $account = \Drupal::service('current_route_match')->getParameter('user');
>
>     // If this is not the Superadmin's edit page
>     if ( !empty($account) && ($account->id() != 1) ) {
>
>       // Turn off Current password field's validation
>       $form_state->set('user_pass_reset', 1);
>
>       // Hide the Current password fields
>       $form['account']['current_pass']['#access'] = FALSE;
>     }
>   }
> }
>
> ```

---
Tags: 8, forms
---


# Question
Title: How to render a field of a taxonomy term inside a view template?
I'm trying to display an image as a banner above the items of a view (which creates a block). The image is a field associated to a taxonomy term and the view is used to display all items which have this term. Is it possible to inject the image into the render array using a hook in order to access and render it on a specific location inside the view's template (for example `block--views-block--example.html.twig`)? I can't find a good solution anywhere on the web. I'm thinking of something like this (pseudo code):

```
function suitable_hook(&$vars) {
  $image = getFieldOfTaxonomyTerm('taxonomy_term', 'image_field_name');
  $vars['associated_image'] = $image;
}

```

If there are better approaches to this problem in general, please let me know as well. Thanks a lot in advance for your suggestions!

# Answer
> 5 votes
This can be done entirely from within the Drupal UI.

If you already have access to the taxonomy term in the view, you can add the term entity directly.

This is what the core taxonomy term pages view does.

To see for yourself, go to `/admin/structure/views/view/taxonomy_term` on a standard Drupal 8/9 installation.

In the header, you will find **Global rendered entity: Taxonomy term**. If you click this to open up the settings, you will see that Drupal is loading the term based on the argument `{{ raw_arguments.tid }}`, which is provided by the Contextual Filter **Content: Has term ID**. (Check the settings there as well.)

For your own block, I would use this same technique. You say you want to render the image, not necessarily the whole taxonomy term. To do that, I would create a new View Mode for the term that only has the image and whatever else you want to display.

You can create a View Mode for a taxonomy term by going to the "Manage Display" page for the relevant taxonomy vocabulary.

Then, in Views, in the header where you are rendering the term entity, you can set the view mode to your new custom view mode.

---
Tags: theming, hooks
---


# Question
Title: When I clear cache, my menu ordering seems to go out of order
When I clear cache, especially on high traffic times, my menu seems to go out of ordering. Usually I don't see any log messages except for one time:

> Message Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[HY000\]: General error: 1205 Lock wait timeout exceeded; try restarting transaction: INSERT INTO {cache\_render}

That time my ram and CPU also spiked. What I mean about go out of ordering is this:

The `ul.menu-level-1` is suppose to be inside the `div.container`, but for some reason, when I clear cache, sometimes it's rendered outside the `div.container`.

I am using the menu items extra module module. It does not have an issue related to this. My network team is pretty adamant that the resources I have are sufficient and i hover about 30%-40% utilization normally for my ram and cpu. The web and database nodes are separate.

I am self-hosted and have cloudflare in front of my website. I do not have caching in cloudflare turned on. Does anyone have any suggestions on what this could be. It normally only happens on my production site - of course - but it's happened on my test sites in the past as well. That's why I don't think its cloudflare.

# Answer
> 0 votes
I believe this had something to do with mysql's setting max\_allowed\_packet. Mine was only set to 1MB, when drupal recommended 16mb.

---
Tags: 8, navigation, caching
---


# Question
Title: How to get $_POST which has blank parameters
I understand that as per new rules, post request in drupal should be replaced with

```
$stack->getCurrentRequest()->request;

```

But I need to know what is the replacement for $\_POST which does not have any parameters. Should we use

```
$stack->getCurrentRequest()->request->get();

```

or

```
$stack->getCurrentRequest()->request->all();

```

?

# Answer
`$_POST` is according to the PHP documentation an associative array.

`$stack->getCurrentRequest()->request` is a Symfony parameter bag representing this array.

ParameterBag::all() would then be a method to get the entire array.
> 1 votes

---
Tags: symfony-services
---


# Question
Title: How can I export only one paragraph type, the fields, the form settings and the display settings?
Some days ago I've exported and imported a full configuration with `drush cex` and `drush cim`.

What are the steps to **export 1 paragraph type including the fields, form settings, display settings** etc ...

I'm using a multisite, so it would be great to copy them from one site to the other sites within the multisite.

**Can I:**

1. `drush cex` site 1
2. **copy exported .yml files** to other site in folder (sites/site1.multisite.com/files/config\_HASH/sync)
3. **Delete all .yml files except those needed** for the import of my paragraph type?

I guess there are **better methods** to establish this?

# Answer
That's exactly what the Features module is for. Syncing partial config across multi-site instances.

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it contains additional information in its info file so that configuration can be checked, updated, or reverted programmatically.

That means you would create a feature on your main multi-site instance which contains the paragraph type. Have it placed inside the modules/features/ folder. Related config will be added automatically. You then enable the feature (which basically is just another module) in another multi-site instance. The config will be imported into the database. On both multi-site instances you then export config as usual. Because every multi-site instance still is managed from its own config. Which then also contains the synced paragraphs config.

As soon as you add another field to the paragraph type on either multi-site instance Features will recognise the changes. You then can recreate your paragraph feature and import the changes on another multi-site instance (into the database). Finally, on both sites again export config as usual (which then also contains the paragraph types you've synced via Features). Features enables you to keep track of changes to a feature via built-in diffing, which after you recreated the feature (partial config gets exported) can be synced into the database on other multi-site instances again.

Of course Features also comes with a set of Drush commands to make your live easier.
> 4 votes

# Answer
Best way to do this is make custom modules and add the specific yml files to config/install. This way you can just enable the module on other websites.

A good way of working could be a custom module named custom\_paragraphs with a .info file and a modules folder. Within this module all your submodules per paragraph type.

* custom\_paragraphs
    + custom\_paragraphs.info.yml
    + modules
        - custom\_paragraphs\_two\_column
            * custom\_paragraphs\_two\_column.info (add dependencies here!)
            * config
                + install
                    - (all the yaml files here)
        - custom\_paragraphs\_slider
            * ...

Update a module by using:

```
drush config-import --partial --source=modules/custom/custom_paragraphs/modules/custom_paragraphs_two_column/config/install

```
> 2 votes

---
Tags: drush, configuration, paragraphs
---


title: Fetching only first row from database

text:
# Question
Title: Fetching only first row from database
I work with:

```
$mandator = $this->database->select('Mandators', 'm')
     ->fields('m')
     ->condition('idMandators', $mandatorId)
     ->execute()
     ->fetchAll();

```

to retrieve my data from database. The result is an array with 1 array item. How can I retrieve always only 1 object, without the array? Like e.g. `->fetchOne`?

# Answer
```
$query = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'my_content_type')
            ->condition('field_ref_au', $nid, '=')
            ->range(0,1)
            ->sort('created', 'DESC')
        ;

```
> 2 votes

# Answer
This works

```
$database = \Drupal::database();
$row = $database->query("SELECT column_name FROM {table_name} WHERE column_required = :value", [':value' => $value]);

```
> 0 votes

# Answer
As per my understanding I would say try to count the number of rows like this:

```
$number_of_rows = db_select('node')->countQuery()->execute()->fetchField();

```

then iterate to get the first count.

Or:

```
// Get a single record out of the database.
$node = db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchObject();

```
> -2 votes

# Answer
You can simply write (example get node) :)

```
$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n)->fetchObject();

```

If you want to get a single value you can use fetchField()

Example (get node title):

```
$node_title = db_query('SELECT title FROM {node} WHERE nid = :nid',
array(':nid' => $nid))->fetchField();

```
> -4 votes

---
Tags: 8, database
---


title: redirect /node?page=1 to main page

text:
# Question
Title: redirect /node?page=1 to main page
* I have already indexed drupal-8 website's pages with pattern like - node?page=1; node?page=2 and so on
* I would like to redirect them to site's front page

Tried:

* I have tried with the redirect module but its not working

# Answer
One way is to redirect page using events subscriber.

**src/custom\_module.services.yml**

```
services:

    custom_module.custom_redirect:
        class: Drupal\custom_module\EventSubscriber\CustomRedirect
        tags:
          - {name: event_subscriber}

```

***src/EventSubscriber/CustomRedirect.php***

```
<?php

namespace Drupal\custom_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class to redirect.
 */
class CustomRedirect implements EventSubscriberInterface {

  /**
   * Check redirection.
   */
  public function Redirection(GetResponseEvent $event) {
    $attr = $event->getRequest()->attributes;
    $route_name = $event->getRequest()->get('_route');
   //Check route name and attr
    if ($route_name == 'check route name') {
        $front = \Drupal\Core\Url::fromRoute('<front>')->toString();
        $event->setResponse(new RedirectResponse($front));
      }

  }

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

}

```
> 2 votes

# Answer
**mytheme.theme**

```
function mytheme_preprocess_page(&$variables) { // <-- your theme may already have one
  // redirect if URL has a "page" param.
  if (!empty(\Drupal::request()->query->get('page'))) {
    $front = \Drupal\Core\Url::fromRoute('<front>')->toString();
    $response = new \Symfony\Component\HttpFoundation\RedirectResponse($front);
    $response->send();
  }
}

```
> 0 votes

---
Tags: 8, redirection
---


# Question
Title: How can I set a webform's field value by query parameter?
I have created the query string for the particular fields.

My URL : www.examples.com/path?title=something

How could I pass the "title" query string value to webform field's default values.

# Answer
> 11 votes
This can be done in the webform backend settings: Edit your webform and go to *Settings \>\> Form*; then go down to *Form Behaviours* and select *Allow all elements to be populated using query string parameters*.

If you go back to the webform element, select the particular field, and enter *\[current-page:query:full\_name\]* as default value (where *full\_name* is the field name), if the query string contains *full\_name=John+Smith*, the *full\_name* field will be populated with *Josh Smith*.

# Answer
> 1 votes
To do this you need to go in your form and edit the field. In the edition modal window, go into the third tab "Advanced", where you can define the default value and add \[current-page:query:your\_parameter\] in the field, which in your case is \[current-page:query:title\]. You can find all the tokens available by clicking the "Browse available tokens" at the bottom of the modal window. (don't forget to save)

# Answer
> 0 votes
As of today, the default value needs to be explicitly set for some types of fields, for instance, a text field. I have found that a selection field with entity references for values does not need to have the default value set, but that a simple text field does.

So, edit the field you wish to populate from the query string, note the Key value beneath the Title field, scroll down to the Form Display section and check Prepopulate. In the Advanced tab, set the default value to \[current-page:query:\].

Be sure to save and maybe clear caches.

Now, loading the form with a query string like:

?service=10&pi\_first\_name=Chuck

Will cause the service selector (radio buttons) to be set to the entry whose node id is 10, and the PI First Name field to be filled with "Chuck."

Not sure why some fields require a default value to be set, and others do not, that would be a question for jrockowitz.

---
Tags: 8
---


# Question
Title: Checkboxes in access panel won't stay unticked
There's a page on my website that can't be made public because the checkboxes in the access panel - when I try to edit the page - won't stay unticked. I untick the checkboxes and hit save, but when I go back to edit the page again, the checkbox has become ticked again.

Here's a screenshot to highlight where the issue is. Is there a setting I need to turn off or something?

Thanks to No Sssweat and Beebee for the tips. There are error messages in the log, which are pasted below. Looks like an error from the 'Simple Access' module, which is apparently up-to-date.

Error Message:

> Notice: Undefined index: members in Drupal\simple\_access\Element\SimpleAccessGroups::processSimpleAccessGroups() (line 74 of /home/lz7m8hr2s8ob/public\_html/modules/simple\_access/src/Element/SimpleAccessGroups.php) #0 /home/lz7m8hr2s8ob/public\_html/core/includes/bootstrap.inc(584): *drupal\_error\_handler\_real(8, 'Undefined index...', '/home/lz7m8hr2s...', 74, Array) #1 /home/lz7m8hr2s8ob/public\_html/modules/simple\_access/src/Element/SimpleAccessGroups.php(74): *drupal\_error\_handler(8, 'Undefined index...', '/home/lz7m8hr2s...', 74, Array) #2 \[internal function\]: Drupal\simple\_access\Element\SimpleAccessGroups::processSimpleAccessGroups(Array, Object(Drupal\Core\Form\FormState), Array) #3 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/Form/FormBuilder.php(997): call\_user\_func\_array(Array, Array) #4 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/Form/FormBuilder.php(1060): Drupal\Core\Form\FormBuilder-\>doBuildForm('node\_page\_edit*...', Array, Object(Drupal\Core\Form\FormState)) #5 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/Form/FormBuilder.php(1060): Drupal\Core\Form\FormBuilder-\>doBuildForm('node\_page\_edit*...', Array, Object(Drupal\Core\Form\FormState)) #6 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/Form/FormBuilder.php(561): Drupal\Core\Form\FormBuilder-\>doBuildForm('node\_page\_edit\_...', Array, Object(Drupal\Core\Form\FormState)) #7 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/Form/FormBuilder.php(318): Drupal\Core\Form\FormBuilder-\>processForm('node\_page\_edit\_...', Array, Object(Drupal\Core\Form\FormState)) #8 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/Controller/FormController.php(93): Drupal\Core\Form\FormBuilder-\>buildForm('node\_page\_edit\_...', Object(Drupal\Core\Form\FormState)) #9 \[internal function\]: Drupal\Core\Controller\FormController-\>getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch)) #10 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call\_user\_func\_array(Array, Array) #11 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/Render/Renderer.php(582): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #12 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer-\>executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #13 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) #14 /home/lz7m8hr2s8ob/public\_html/vendor/symfony/http-kernel/HttpKernel.php(151): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #15 /home/lz7m8hr2s8ob/public\_html/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #16 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #17 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #18 /home/lz7m8hr2s8ob/public\_html/core/modules/page\_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #19 /home/lz7m8hr2s8ob/public\_html/core/modules/page\_cache/src/StackMiddleware/PageCache.php(78): Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object(Symfony\Component\HttpFoundation\Request), 1, true) #20 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #21 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #22 /home/lz7m8hr2s8ob/public\_html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #23 /home/lz7m8hr2s8ob/public\_html/core/lib/Drupal/Core/DrupalKernel.php(693): Stack\StackedHttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #24 /home/lz7m8hr2s8ob/public\_html/index.php(19): Drupal\Core\DrupalKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request)) #25 {main}.

# Answer
Nevermind this. The solution was to unpublish the page and make a new one. Someone at my organisation told me they did that, but I just tried it myself, and it seems fine.
> 0 votes

---
Tags: nodes
---


# Question
Title: Ajax submission not working for Webform within a node
I am working with a feature where a newsletter subscription form (Webform with ajax submission and confirmation type is inline) should appear in a node. The node would be showing as a popup and the contents of popup is being loaded using ajax. When the node is tested in it's own node page the submission is working fine but not in the popup.It is redirecting to another page. Inspecting the two cases, i found that the webform while being loaded in popup, lacks `event` handler that should refer to form submission.

In the controller where webform being loaded into the popup block, something like this is tried:

```
  $webform = $this->entityTypeManager->getStorage('webform')->load($formId);
  $view_builder = $this->entityTypeManager->getViewBuilder('webform');
  $build = $view_builder->view($webform);

```

Where `$formId` is the id of the webform and entityTypeManager is an instance of `Drupal\Core\Entity\EntityTypeManagerInterface`. Later this `$build` is being saved as the `webform` attribute of popup class and later being rendered. The fields of the webform appears to be loaded correctly but not the `event` of submission form. Any suggestion for solving the issue?

# Answer
> 3 votes
This is a gotcha of AJAX forms.

When you load an AJAX form via AJAX it loses its AJAX functionality.

In order to keep it working, for the form that is getting loaded via ajax, you need to add a `url` and `options` keys to `#ajax`

```
/*
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // I created a webform called "test"
  if ($form_id == 'webform_submission_test_add_form') {
    $webform_id = 'test';
    $form['actions']['submit']['#ajax']['url'] = \Drupal\Core\Url::fromRoute('entity.webform.canonical', ['webform' => $webform_id]);
    $form['actions']['submit']['#ajax']['options'] = [
      'query' => [
        Drupal\Core\Form\FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ];
  }

}

```

---

**Side note:** this loss of AJAX issue doesn't occur with the HTML way of opening dialog boxes

```
<a class="use-ajax"
   data-dialog-options="{"width":600}"
   data-dialog-type="modal"
   href="/form/test">
   Should load Test webform in a Modal
</a>

```

because it has the URL of the form and knows its an AJAX request from the class name.

---
Tags: javascript, ajax, webforms
---


# Question
Title: Does Quick Edit function work for embedded entities?
I have a view which creates a block of User data related to the author of the node. The view display is a view mode of the User entity.

I see my entity when the block is placed on the node page; but there is no quick edit functionality. Is this expected behavior?

# Answer
It does work, for Nodes, when set to `Show: Content | Full Content`.

However, it does not work for Users. Fairly expected as when you go to a user page, ex: */user/1* there is no quick edit feature there to begin with.
> 0 votes

---
Tags: 8, views
---


# Question
Title: View inside a node with content from a relationship
I have two content types: `Artist` and `Artwork`. An `Artwork` has a field called `field_artist` which relates to the relevant `Artist` node. I want to add a view to the `Artist` node page, so that all artworks of that artist are displayed.

I tried using EVA, but I can't figure out what relationship and contextual filters to choose. I looked for tutorials but I find this very confusing.

Is there a way to do this with EVA OR in some other easy way? The only crucial thing is that the entity reference field from `Artwork` to `Artist` must be used to filter the artworks in the view.

Thanks!

# Answer
> 2 votes
You can build it in Views without EVA.

Here's a great article about different cases of how to build Relational lists in Views (I'm not affiliated): Relationships and Contextual Filters in Views 3 for Drupal

In your particular case you need to look at the 'Pulling fields of “Child” nodes by node reference' section.

You build a list of Artwork, then add the Contextual filter for the Artist ER field, configure it to default to "Content ID from URL", add the Validation that limits it only to the Artist type so it appears only on Artist nodes, adjust the other settings to your particular needs.

# Answer
> 2 votes
The article mentioned in the accepted answer explains how to do it.

To include this in the view, there are some options.

1. Using **Block layout**, place the block in the desired region and filter the block to only display on the content type you desire (Artist).
2. If you have a custom Twig template, use module **Twig Tweaks** to leverage it's `drupal_view('view_id', 'block_id')` method.
3. Use module **EVA** to add the view to the node page. The order of display can be managed in "Manage field display" (in this case on the Artist node)

In short:

1. Create a view for the child node (Artwork) or use an existing one and create a new block (option 1 or 2 above) or new EVA (option 3 above).
2. Open **Advanced \> Relationships \> Add**
3. Choose **Content referenced from field\_parent - Appears in: child** (field\_artist, appears in Artwork)
4. Choose **Require this relationship**
5. Apply
6. Open **Advanced \> Contextual filters \> Add**
7. Choose **ID - Content**
8. Choose relationship **field\_parent: Content** (field\_artist: Content)
9. Choose **Provide a default value** and select **Content ID from URL**
10. Apply
11. Save the display and add it to your node using one of the methods described above.

Good luck!

---
Tags: views
---


# Question
Title: Can I disable a cookie from a contrib module, in this case fontawesome I believe
I have a D8 site v8.9.6 and have some questions on cookies.

I would prefer not to have any cookies on my site unless they are really required for a properly functioning website. With all things going on like GDPR and APP I prefer to have this as clean as possible.

In order to find out which cookies are in use I checked Chrome DevTools and it shows me just 1: \_ga with source of fontawesome.com (I installed the FontAwesome module).
First question, can I disable this cookie somehow?

Second question is related to Dropdown Language, a module that gives me a dropdown select list for the user to select its language of choice. I can't find anything in the documentation about how this tracks the user's choice and I don't see anything in DevTools (cookies, session), so this is not working with cookies?

# Answer
> 2 votes
The Font Awesome Icons module provides an option to use the Font Awesome library locally rather than from a CDN. It's the CDN that is creating the tracking cookie, so if you follow the instructions to download Font Awesome to your own server, you should not have that cookie to worry about.

The Dropdown Language module simply extends Drupal's built-in language switching, which defaults to storing the language in the current session, so will not require any additional cookies.

---
Tags: 8, cookies
---


# Question
Title: How can I change the name of migration database in database array?
For a Drupal migration from d7 to d8, I have to define my source database to be called 'migrate' in the settings.php as below. My question is: how can I define the source as something other than 'migrate', where is that set up?

```
`$databases['default']['default'] = array(
  'database' => "db",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);

$databases['migrate']['default'] = array(
  'database' => "drupal7",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);`

```

# Answer
`migrate` is the default key used by the `SqlBase` class which is the base for the D7 source plugins. Its documentation explains in detail how it determines what key to use and how it can be changed. Of relevance:

> As described above, the default source database is $databases\['migrate'\]. If the source plugin needs another source connection, the database connection parameters should be added to the $databases array as, for instance, $databases\['foo'\]. The source plugin can then use this connection by setting 'key' to 'foo' in its configuration.

So update the `source.key` value in your migration configuration to `foo` then re-import that configuration to change the default key used for that migration source.
> 3 votes

---
Tags: migrations
---


# Question
Title: Alter existing 'Log In' route so URL includes request_uri as query string
I am trying to alter the existing 'Log In' URL so that it points to a certain location and also includes the REQUEST\_URI as a query string that is not encoded. How do I do this?

Based on this article, Altering existing routes and adding new routes based on dynamic ones and this SE answer I can change the 'Log In' URL so it points to a different location (/login). What I can't seem to figure out is how to add a query string that isn't encoded.

This code:

```
$route->setPath('/login?destination=' . \Drupal::request()->server->get('REQUEST_URI'));

```

Gives me:

```
/login%3Fdestination%3Dpage2

```

What I want is:

```
/login?destination=page2

```

I have looked into RequestContext::setQueryString and Route::addOptions but can't seem to get anything to work.

Full code:

```
<?php
namespace Drupal\myModule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {

    /**
    * {@inheritdoc}
    */

    protected function alterRoutes(RouteCollection $collection) {
        // Change path '/user/login' to '/login'.
        if ($route = $collection->get('user.login')) {
            //$route->setPath('/login');
            $route->setPath('/login?destination=' . \Drupal::request()->server->get('REQUEST_URI'));

        }

        // Always deny access to '/user/logout'.
        // Note that the second parameter of setRequirement() is a string.
        if ($route = $collection->get('user.logout')) {
            $route->setRequirement('_access', 'FALSE');
        }
    }
}

```

# Answer
I think you'll need to have a look to PathProcessors, you might do something like that:

**mymodule/mymodule.services.yml**

```
mymodule.path_processor:
  class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
  tags:
    - { name: path_processor_inbound, priority: 250 }

```

**mymodule/src/PathProcessor/MymodulePathProcessor**

```
<?php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MymodulePathProcessor.
 *
 * @package Drupal\mymodule\PathProcessor
 */
class MymodulePathProcessor implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if ($path == '/user/login') {
      $request_uri = $request->server->get('REQUEST_URI');
      return "/login?destination={$request_uri}";
    }
  }
}

```

Don't forget to clear the cache before to try it.

You might need the `processOutbound` function too in which case you'll need one more line in your service

**mymodule/mymodule.services.yml**

```
mymodule.path_processor:
  class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
  tags:
    - { name: path_processor_inbound, priority: 250 }
    - { name: path_processor_outbound, priority: 250 }

```
> 0 votes

---
Tags: 8, routes
---


# Question
Title: Problem installing Devel module onto site
I went to drupal.org, copied the link for the Devel module, went to my site, New Module (under extensions) paste the link into the "Install from a URL" and when I hit Install it gives me the following error message: "Failed to fetch file due to error "cURL error 77: SSL: can't load CA certificate file /Applications/DevDesktop/common/cert/cacert.pem (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)" Unable to retrieve Drupal project from https://ftp.drupal.org/files/projects/devel-8.x-1.0-rc1.tar.gz."

How can I fix this?

# Answer
> 1 votes
Download this file and save it on the desktop.

Then copy (or move) it into the `C:\Program Files (x86)\DevDesktop\common\cert\` directory.

# Answer
> 0 votes
Restarting the server work for me

you might want to consider just restarting apache server only

otherwise you might have to follow the solution here https://www.drupal.org/node/2481341

```
- Download latest cacert.pem from http://curl.haxx.se/docs/caextract.html.
- On global PHP level add curl.cainfo = [enter your path]\cacert.pem to your php.ini.
- Restart Apache service.

```

# Answer
> 0 votes
I had the same issue with Acquia's Dev Desktop, copying the libcrypto-1\_1-x64.dll and libssl-1\_1-x64.dll from the PHP7.3 folder to the Apache/bin folder resolved the issue for me.

"Beginning with version 1.1.0 OpenSSL did change their libary names! libeay32.dll is now libcrypto-.dll (e.g. libcrypto-1\_1-x64.dll for OpenSSL 1.1.x on 64bit windows) ssleay32.dll is now libssl-.dll (e.g. libssl-1\_1-x64.dll for OpenSSL 1.1.x on 64bit windows)"

epos\_jk See https://www.php.net/manual/en/curl.installation.php#121921.

---
Tags: 8, installation
---


# Question
Title: How can I stop the full HTML editor from deleting my <p> paragraph?
https://drupal.slack.com/archives/C1BB308HH/p1602318464360700 Link to slack question in #support

JSFiddle of the offending html: https://jsfiddle.net/tyeth/xr4ohast/

Demo Video showing the paragraph beneath second image being removed: https://www.youtube.com/watch?v=Hw9NACmMsps \[Was private, now just unlisted, sorry\]

Hi supportive people, you must get this one a lot. I'm aware of the filter options and have customised the Full-Html mode to not use the 3 offending filters, and cleared cache, but I'm still losing content.

I'm using the drupal 8(and 9) add a custom body block using layout designer, I then use the WYSIWYG editor in *full-html* mode with the filters (strip bad html/convert newline br+p/convert images -- see screenshot) disabled. However it is DELETING html from the end of the editor. I wonder if it's technically an empty paragraph as that has been mentioned in other issues (it isn't but has a link inside so doesn't have it's own text content).

Also, which module is actually doing the rich editing these days?

# Answer
> 3 votes
Could be related to the auto paragraph funcitonality of CKEditor, which is used by default and can be disabled with this **!deprecated** setting:

```
"autoParagraph = false"

```

This can be easily disabled using the ckeditor\_config module, see https://www.drupal.org/project/drupal/issues/3131055 for more information.

The whole paragraph wrapping in CKEditor is kind of buggy, you could also try these patches: https://www.drupal.org/project/drupal/issues/2876094 (but there the problem is an added p after an img)

---

I had some troubles when using linkit: https://www.drupal.org/project/linkit/issues/3162596 and made this core issue https://www.drupal.org/project/drupal/issues/3162605 (this is not related to your problem as your using the align and caption filters - but you see where the magic happens - on Drupal side).

# Answer
> 2 votes
I checked your HTML code thoroughly. The culprit is `data-align="center"` used in the `img` tags. To fix the problem, we have two options:

Option 1. *(Recommended)* If you remove it(`data-align="center"`) from your code, your problem will be resolved, ie; the `p` tag won't be removed automatically when *Source* button is clicked.

Option 2. You can uncheck the **Align Images** in the above configuration. This is *not recommended* because this will apply the changes globally which we don't desire.

Here is the fixed HTML code.

*Explanation*: As seen in the Editor's configurations, there is an option called **Align Images**. This option also adds the same `data-align` attribute to centrally align the images. This could be causing the conflict and strangely removing the `p` tags.

---
Tags: theming, blocks, wysiwyg
---


# Question
Title: How to resave all user accounts on a schedule?
I want to re-save all user accounts on my site weekly because I wrote some code in `hook_user_presave()` that I want to update every week.

Specifically, my `hook_user_presave()` code updates the values of some fields like **Total number of comments posted** and **Total number of articles posted**, and it sends an email if the user hasn't logged in for more than a month. (This info is only available to the site admin, which is me, so it doesn't need to be perfectly in sync.)

Right now, I have a View with VBO that I can use to re-save all the user accounts manually. I want to automate this process by saving all the users automatically at 3 am on Sunday.

How do I schedule all user accounts to be saved? Is this a task for Queue API or does core/contrib provide something more appropriate for this use case?

# Answer
> 1 votes
### Ultimate Cron

Provides a UI where you can schedule all the cron jobs. Example:

---

### Job Scheduler

Provides an API to schedule jobs.

Simple example:

> ```
> // Declare scheduler.
>
>   function example_cron_job_scheduler_info() {
>     $schedulers = [];
>     $schedulers['example_unpublish'] = [
>       'worker callback' => 'example_unpublish_nodes',
>     ];
>     return $schedulers;
>   }
>
> // Add a job.
>
>   $job = [
>     'name' => 'example_unpublish',
>     'type' => 'story',
>     'id' => 12, // must be unique
>     'crontab' => * 3 * * 0, // Every Sunday at 3 AM
>     'periodic' => TRUE, // set to false if you want to just run once.
>   ];
>   $service = \Drupal::service('job_scheduler.manager');
>   $service->set($job);
>
> // Work off a job.
>
>   function example_update_users_total(\Drupal\job_scheduler\Entity\JobSchedule $job) {
>     // Do stuff.
>   }
>
> ```

There is more examples & info in the READ.ME, so read it.

---

**Important**

It's important to note that the above in reality is scheduled to run **the next time someone visits the site after 3am on Sunday**. So if no one visits the site until say 9am on Sunday, it will not run until 9am. This is because Drupal's Cron can only run when Drupal is initialized.

The only way to be sure that it runs at 3am, you have to set a cron job in your server (just know that your server time may not be the same as your timezone, so you'll have to check that), using the `crontab -e` command (for linux) will open the file where you can add jobs to the server. Have this server job run a file that contains code that performs a GET request on your site. OR alternatively a custom Drush command like Kevin commented.

---
Tags: users, batch-operations, queue
---


# Question
Title: Point dev URL to the default folder of a multisite
In a **multisite set up**, the default domain www.domain.com point to the 'sites/default' folder.

I want a **temporary subdomain point to the default site for development**.

In the **sites.php** files I have:

$sites\['dev.domain.com'\] = 'default'; // this line can be removed due to the default behavior (see comment below)

$sites\['sub1.domain.com'\] = 'sub1.domain.com';

$sites\['sub2.domain.com'\] = 'sub2.domain.com';

$sites\['sub3.domain.com'\] = 'sub3.domain.com';

**Pointing to the 'default' folder is not working for some reason?** What is wrong?

# Answer
> 0 votes
Above settings are correct. But there was an error in the DNS settings.

---
Tags: multi-sites
---


title: Failure in "file module Update #8700"

text:
# Question
Title: Failure in "file module Update #8700"
```
file module

Update #8700
•Failed: Drupal\Core\Field\FieldException: Field storage definition for 'type' could not be found. in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->getEntitySchema() (line 979 of /var/www/xxxxxxx.com/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).

```

This message is shown after running update.php

I believe this is also related to a brand new problem we're having since the upgrade to 8.9.7 -- we can no longer add images.

Need advice for how to perform this update. At this point I just want it done, so even if I have to manually hack something I'm fine with that. I can revisit how to fix things properly once the site is working again.

# Answer
This is probably connected to the module File Entity.

You find a patch in this issue:

https://www.drupal.org/project/file\_entity/issues/3060204
> 0 votes

---
Tags: 8, updating
---


# Question
Title: How to use a Twig variable as View name in drupal_view() Twig Tweaks function?
This works:

```
{{ drupal_view('nursing_resource_blog_teasers', 'block_1') }

```

But this doesn't:

```
{% set view_name = "nursing_resource_blog_teasers" %}
{{ drupal_view(view_name , 'block_1') }

```

It appears that drupal\_view() isn't allowing a variable as the View name. Is there a way to make this work?

# Answer
Solved it. I forgot about the tags in the field output.

This solved it for me:

```
{% set view_name = content.field_blog_teaser_block|render|striptags|trim %}

```
> 1 votes

---
Tags: theming
---


title: Canonical URLs per node

text:
# Question
Title: Canonical URLs per node
I'm trying to find out how to set a canonical url on certen pages/articles on a drupal 8 installation. Metatag module, have the option for setting the canonical URL but is a general setting not specific for every page/article.

Does anybody know how to solve this?

Thank you!

# Answer
> 2 votes
If you want to set a specific canonical URL for a given node, just edit your node and uncheck "Generate automatic URL alias" in the URL alias section and you'll be able to write your own URL.

You might need `Path` module to be enabled to do that.

If you want to have specific automatic patterns for your URL alias depending on the type of node, then you will need the module `Pathauto` (https://www.drupal.org/project/pathauto) ; just enable it and configure your patterns for each type of node

# Answer
> 0 votes
A friend suggest me the follow solution which works perfect!

https://www.drupal.org/docs/8/modules/metatag/standard-usage-scenario

To adjust metatags for a specific entity, the Metatag field must be added first. Follow these steps:

"Go to the "Manage fields" of the entity type. Select "Meta tags" from the "Add a new field" selector. Fill in a label for the field, e.g. "Meta tags", and set an appropriate machine name, e.g. "meta\_tags". Click the "Save and continue" button. If the site supports multiple languages, and translations have been enabled for this entity, select "Users may translate this field" to use Drupal's translation system."

---
Tags: 8
---


# Question
Title: creating a custom report page with a table
Drupal 8.9.6, I'm trying to create a custom module admin report page.

I have a custom sub theme of seven called wd\_admin.

I made a page controller that generates a table as markup, but want to use a twig file to render the html, and can't figure out the theming.

It is using **block.html.twig** to render the content, and the first suggested template is **block--wd-admin-content.html.twig**. So I created it, and plumbed it in with `hook_theme` and `hook_theme_suggestions_block_alter`, but it affected the content on all admin pages, wrong move.

Seems like for this to work it would have to be specific to the page. What do I need to do to render this page, maybe a page.html template?

# Answer
> 1 votes
Yeah I think you're conflating a few different concepts and making everything way more complex than it needs to be.

If you all you want to do is render a particular custom template with your controller then you'd want to:

```
// In fun.module
function fun_theme() {
  return [
    'a_fun_template' => [
      'variables' => [
        'heading' => '',
        'activities' => []
      ],
    ],
}

// Then in your controller
public function yourRenderMethod() {
  $heading = 'Some fun activities';
  $activities = [
     'Rocket League',
     'Violin'
  ];
  return [
    '#theme' => 'a_fun_template',
    '#heading' => $heading,
    '#activities' => $activities,
  ];
}

// Then in a-fun-template.html.twig
{#
  Do whatever with your variables, like print them
#}
<h1>{{ heading }}</h1>
<ul>
{% for activity in activities %}
  <li>{{ activity }}</li>
{% endfor %}
</ul>

```

EDIT: I *think* I figured out why you're looking at the block. All that that is is the "Main page content" block from the blocks page. This just renders the main content for the page, which in this case would be the contents of your controller's template. Now that said, what I wrote before was...

I really don't understand where the block is coming into play here, but I think you're misunderstanding that as well.

First, the default template suggestions are very general. `block--wd-admin-content.html.twig` is probably added by wd\_admin to every admin block by default. That's why a template by that name would be used by all blocks in the admin area. Generally the longer the suggested template name, the more specific it is. Template suggestions that you add to `hook_theme_suggestions_block_alter()` will apply to all blocks unless you wrap the suggestion in conditional logic that says otherwise. If all you're doing is using a hook\_theme template in a controller then you don't need this hook at all.

# Answer
> 0 votes
I found a pretty good solution here, no twig required: https://www.digitalnadeem.com/2019/12/13/how-to-create-a-custom-filter-form-and-update-custom-table-data-in-drupal/

I'm going to be presenting this with some options, so doing it in a form makes a lot of sense.

I'd still like to understand all that's involved with presenting twig templates better. I've been studying code in core, but a lot of what was done there is pretty complicated. It's well engineered and beautifully written, but I'm struggling to find all the parts involved in advanced theming.

---
Tags: 8, theming
---


# Question
Title: Listing child terms based on relationship with parent
The premise: I have a taxonomy listing “countries” on the first level and “country subdivisions” on the second level.

E.g.:

* Canada
    + Ontario
    + Quebec
    + etc..
* United States
    + Alabama
    + Alaska
    + etc..

A user is attributed to a country in the user Account Settings. E.g: John Doe is from Canada.

I would like to create an Entity Reference View that would list all Provinces related to the user attributed country.

E.g.:

List of provinces offered to John Doe while creating a node:

* Ontario
* Quebec
* etc..

# Answer
> 2 votes
First you have to create the Taxonomy hierarchy within Views, so later only the children terms will be in Views rows results (so they can be chosen from a ER field on the node creation form). You can't do that starting from User Views because only Parent Relationships are available, no way to drill down, only up is possible.

1. Create **Taxonomy term** Views of your particular Vocabulary. They will list both Parents and Children. It will already have the Taxonomy Name field, keep it.
2. To create the hierarchy add the Relationship Parent first (It's called "Taxonomy term", search for "parent" to find it quickly in the Relationships list. Require it because we only want to display terms that have a parent, we only want children terms to show on our list
3. Then add another Relationship, introducing the User, it will be named something like **User using field\_country**, make it use the Parent Relationship (so we get users who are tagged with top-level terms). Require the Relationship because we only need terms that do have users tagged with them.
4. Now add the Contextual filter **User ID**. It will automatically use the Country Relationship, and configure it:

`When the filter value is NOT available`
**Provide default value**
**User ID from logged in user**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**User ID**
**Single ID**
**Hide view** or what ever makes sense in your case

To easily test whether the correct sub-terms appear enter some user ID into the Views **Preview** field. It will provide the context directly to Views so you can see which sub-terms are shown and whether they match that user Country.
5. Add the Entity Reference Display to your Views and adjust its Settings, (**Search fields: Name**). Save the Views so you can use it in the next step.
6. Create/Edit Taxonomy Reference Field on your CT, select the Views as the `Reference Type` and then select the Views you've created in the first step.
7. Adjust the "Manage form display" for the new field so it appears as you like it on the node create page.

Now when you go to create a new node of that type the field will list all the sub-terms of the Country the author is tagged with.

You still have to test by logging in as some user to test that the context is passing through correctly (Switch user block can speed it up).

---
Tags: views
---


# Question
Title: Alter comment pager to jump to comment section right away?
I set up a content type and a specific comment type for this content. I set the comment pager to display 10 comments per page. When I now use the pager, I get redirected from the node URL itself www.domain.com/node/1, to www.domain.com/node/1?page=1.

Is there any possibility to add an ID to the URL for the comments pager only, for example www.domain.com/node/1?page=1#comments?

I want to do this, so the user doesn't need to scroll over the whole content of the node again, just to get to the second comments page. Instead, I want to jump to the comment section right away.

Is there any elegant way to do so? A module that does it, or similar? I already thought of altering the pager.html.twig in my theme. But then I would alter the node pager as well. Thank you very much in advance for pointing me any way to achieve this.

# Answer
> 2 votes
The only hook Drupal uses to alter a pager is `hook_preprocess_pager()` but that is invoked for every pager on any page, not just the pager used for comments.

The alternative is adding a new formatter for comments, which by default is the `CommentDefaultFormatter` class, and make it the default one with `hook_field_info_alter()`.

```
function mymodule_field_info_alter(&$info) {
  // Change the default widget for fields of type 'comment'.
  if (isset($info['comment'])) {
    $info['comment']['default_formatter'] = 'mymodule_comment_formatter';
  }
}

```

(*mymodule\_comment\_formatter* is the formatter ID used in its annotation.)

The relevant code that sets the pager is in `CommentDefaultFormatter::viewElements()`, which contains the following lines.

```
if ($comments) {
  $build = $this->viewBuilder->viewMultiple($comments, $this->getSetting('view_mode'));
  $build['pager']['#type'] = 'pager';

  // CommentController::commentPermalink() calculates the page number
  // where a specific comment appears and does a subrequest pointing to
  // that page, we need to pass that subrequest route to our pager to
  // keep the pager working.
  $build['pager']['#route_name'] = $this->routeMatch->getRouteObject();
  $build['pager']['#route_parameters'] = $this->routeMatch->getRawParameters()->all();
  if ($this->getSetting('pager_id')) {
    $build['pager']['#element'] = $this->getSetting('pager_id');
  }
  $output['comments'] += $build;
}

```

# Answer
> 0 votes
You could use `template_preprocess_pager()`, but I am not sure you will be able to target one specific pager. You should check in `$variables` if there's any ID you can use to target the comment pager.

---
Tags: comments, paging, 9
---