# Question
Title: Invalidate Internal Page Cache at certain times in a day for anonymous users
Let say I have a webshop open from 9am to 11am (data coming from config). When the shop is closed, I would like to display a message (shop closed) and when the shop is open, my commerce product should be available. (only for 'lunch' bundle)

I have tried to update the following code: https://cornel.co/article/drupal8/page-cache-cookies-or-anything-available-http-request

Here is my try (edited with a comment from 4k4:

```
protected function getCacheId(Request $request)
{
    if (! isset($this->cid)) {
        $cid_parts = [
            $request->getSchemeAndHttpHost() . $request->getRequestUri(),
            $request->getRequestFormat(NULL)
        ];
        // Only cache by State of Store for some path
        if (strpos($request->getPathInfo(), '/lunches/') != false) {
            $store_state = get_store_state();
            $cid_parts[] = $store_state['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
        }
        $this->cid = implode(':', $cid_parts);
    }
    return $this->cid;
}

```

As stated by 4k4, I must create a new context which will bubble up and will invalidate the Internal Cache page.

Here is the code of

```
class StateStoreCacheContext implements CacheContextInterface

```

stored in `mymodule/src/CacheContext/StateStoreCacheContext.php`

```
public function getContext()
{
    $storeState=get_store_state();
    return $storeState['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
}

```

And here is mys service declaration:

```
services:
   cache_context.state_store_context:
    class: Drupal\mymodule\CacheContext\StateStoreCacheContext
    arguments: []
    tags:
      - { name: cache.context }

```

And here is the way I add my context to my page (in `mythem_preprocess_node(&$vars)`)

```
$vars['#cache']['contexts'][] = 'state_store_context';

```

Unfortunately, my page cache is not invalidate for anonymous users (but it is ok for logged-in users)

# Answer
You have to add a cache context as well. See both answers in this topic:

How do I create a cache context in Drupal 8 that varies on user/node field data?

You add a variation to the CID of the Internal Page Cache and a custom cache context to the node, so that it can bubble up to all elements which are dynamically cached. The difference is, CIDs can't bubble up, contexts can, and so vary all render elements no matter how deep they are nested.
> 1 votes

---
Tags: 8, caching
---


title: Add separate div after a form

text:
# Question
Title: Add separate div after a form
All I want to do is add a new `<div>`, ideally just *after* a `<form>` element. I have a self-written module that generates a payment form, using some routing, like this:

```
mymodule.applications.payment_form:
  path: '/payment/{submission}'
  defaults:
    _form: '\Drupal\mymodule\Form\PaymentForm'
    _title_callback: '\Drupal\mymodule\Form\PaymentForm::getTitle'
  requirements:
    _role: 'authenticated'
    _custom_access: 'Drupal\mymodule\Form\PaymentForm::access'
  options:
    parameters:
      submission:
        type: entity:webform_submission

```

The PaymentForm class has a standard buildForm() method, and it's easy to add render arrays to the $form build form elements and other decoration etc. But those are all *within* the `<form>` tag.

The payment form is displayed in the main page content block.

I've been trying is **HOOK\_preprocess\_HTML** in my `mymodule.module` file and looking at *$vars*.

$vars\['page'\] contains the various regions: sidebar\_first, content, secondary\_menu etc.

$vars\['page'\]\['content'\] consists of:

```
'mysite_page_title' => array(13)
'mysite_local_tasks' => array(3)
'mysite_help' => array(3)
'mysite_local_actions' => array(3)
'mysite_content' => array(12)
'#sorted' => boolTRUE
'#theme_wrappers' => array(1)
'#region' => string(7) "content"

```

`mysite_content` is a block - and I can't see how I can modify it from here...

I've also tried **HOOK\_block\_view\_BASE\_BLOCK\_ID\_alter**, which in this case is system\_main\_block (for the page content).

*function mymodule\_block\_view\_system\_main\_block\_alter* gives me a $build array with a *#block* element, but I don't see how I can find the `<form>` elements in there either and place something afterwards…

Anything else I can do?

# Answer
> 2 votes
There might be hundreds of ways to add this markup in Drupal. The two simplest that came to my mind are:

1) Add a suffix to the form tag in form build or form alter:

```
$form['#suffix'] = '<div>Suffix to form</div>';

```

2) or add the markup in a form.html.twig below the form tag:

```
{#
/**
 * @file
 * Default theme implementation for a 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}
<form{{ attributes }}>
  {{ children }}
</form>

<div>
  A div container after the form
</div>

```

For the second solution you might also need to add a theme name suggestion.

---
Tags: forms, blocks, hooks
---


# Question
Title: How to make Shipping services available in Rules tokens (data selectors)?
I am using D7 and Drupal commerce, with a flat rate shipping service. In my country the VAT for both products and shipping costs must be included in the total VAT amount. But the only line items available in Rules are product line items. So in order for the VAT post to include the VAT for the shipping cost, I need the token:

```
commerce_line_item

```

... to also include the shipping service selected in the order. I have spent days trying to figure this out, with no luck. I have read this answer, but those suggestions does not work either. If I remove the filter that only shows product line items in the order summary view, the shipping shows in the table together with the products, which I do not want. And also the tokens still only reflected the product lines.

This is how I need it to look:

```
Product line item 1
Product line item 2
Product line item 3
   Net amount excl. VAT
   Shipping service
   VAT (including vat on products and on the shipping service)
   Total amount

```

Any help?

# Answer
If the data about a product ***are not*** available when processing a "line item", you can ***make*** them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce\_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

```

Here is a blueprint of what you need to do:

1. Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
2. Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "`Some details about this product`"), by also using any of the available tokens that you're interested in.
3. Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
4. Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".
> 3 votes

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


# Question
Title: hook or similiar to automatically send any webform submissions to an email address, without manually adding a handler to each existing webform?
We have a Drupal 8 site running Webform 8.x-5.2. We have a special role, "Webform Editor", who is not a developer, but they are trained to create the webforms that we need for our organization.

We've been dealing with some organizational issues about who is getting what webform submission emailed to them. To help us troubleshoot the issue, we the developers want to implement a feature where each webform submission gets automatically copied (cc'ed or sent separately) to an email address that we devs have access to.

I looked at the webform module's hooks, and I didn't see any that jumped out at me as a post-submission hook. Webform version 7.x had one, but version 8.x doesn't appear to.

I made a custom submission handler, but realized I would have to add it manually to all existing webforms (we have more than I want to click through).

I began to write a `form_alter` hook to add custom submit handler, but when I debugged the `$form` and `$form_state`, I didn't see any information (i.e. sid) about the submission record. I suppose that the submit hooks fire before the submission record is created.

In the webform cookbook, there's a recipe for "How can you automatically create a default email handler for a webform when it is created", but again, I want to automatically add this to existing webforms.

If I could do this with something like a hook, once and for all, that is what I'm looking for. If the answer is "No, you can't do what you want automatically; you'll have to make a handler and manually add it to all existing webforms", am I interested in hearing that answer, too. I don't want to chase down any more rabbit holes of approaches that won't work.

# Answer
> 0 votes
I am going to go ahead and say **No**, there isn't any hook or otherwise automated way to do this.

I looked at `hook_entity_insert()`, as leymaxx suggested. From looking at the Webform Submission entity at `/src/Entity/WebformSubmission.php`, it appeared to me that the Webform Submission entity is not what triggers the emails and handlers of the webform, but rather the Webform entity does.

Looking further at the Webform entity at `/src/Entity/WebformSubmission.php`, I found functions for invoking handlers, but these only appeared to loop through existing handlers already attached to the Webform entity. So, there is no way to call an arbitrary handler on a webform.

What I'm going to do is create a custom handler, attach it manually to existing webforms, and use this recipe that I referenced in my question to have it automatically attached to new webforms as they are created.

**Edit** We are using config\_export on our site, which has yamls for all of our current webforms. Because of this, I was able to copy and paste the additional email handler into the yaml, and do a config import, to update existing webforms. This saved some time over manually editing them in the web interface.

---
Tags: webforms
---


# Question
Title: Using Drush without local copy of Drupal, only calling site aliases - No site aliases found
We have a project which does not contain a Drupal codebase. It's Cypress.io test with Drush 9 added using Composer. I would like to execute Drush with site alias to work with the remote site while running tests.

I'm able to call Drush from Cypress test just fine. The Cypress part actually does not matter at all as the behaviour is the same when I run Drush command directly.

The setup:

* `composer init` fresh project
* `composer require drush/drush`

```
✔ rk:/tmp/drushtest> vendor/bin/drush version
 Drush version : 9.7.1
✔ rk:/tmp/drushtest> vendor/bin/drush sa --debug
 [preflight] Config paths: /tmp/drushtest/vendor/drush/drush/drush.yml
 [preflight] Alias paths:
 [preflight] Commandfile search paths: /tmp/drushtest/vendor/drush/drush/src
 [bootstrap] Starting bootstrap to none [0.09 sec, 7.33 MB]
 [bootstrap] Drush bootstrap phase 0 [0.09 sec, 7.34 MB]
 [bootstrap] Try to validate bootstrap phase 0 [0.09 sec, 7.34 MB]
 [success] No site aliases found. [0.09 sec, 7.36 MB]

```
* Already there is nothing in `Alias paths`.
* Added some drush aliases to `drush/sites/remoteproject.site.yml` (valid yml file that is working in the Drupal project)
* While debugging this I tried to add a `drush.yml` config file to point drush to the alias.

```
✔ rk:/tmp/drushtest> tree
.
├── composer.json
├── composer.lock
├── drush
│   └── sites
│       └── remoteproject.site.yml
├── drush.yml
└── vendor
    ├── ...

✔ rk:/tmp/drushtest> cat drush.yml
drush:
  paths:
    alias-path:
      - drush/sites/remoteproject.site.yml

✔ rk:/tmp/drushtest> vendor/bin/drush sa --debug --config=drush.yml
 [preflight] Config paths: /tmp/drushtest/drush.yml,/tmp/drushtest/vendor/drush/drush/drush.yml
 [preflight] Alias paths: drush/sites/remoteproject.site.yml
 [preflight] Commandfile search paths: /tmp/drushtest/vendor/drush/drush/src
 [bootstrap] Starting bootstrap to none [0.08 sec, 7.34 MB]
 [bootstrap] Drush bootstrap phase 0 [0.08 sec, 7.34 MB]
 [bootstrap] Try to validate bootstrap phase 0 [0.08 sec, 7.34 MB]
 [success] No site aliases found. [0.08 sec, 7.37 MB]

```

So I convinced Drush to see the site alias file, but the alias itself is not loading.

When I try to use the alias:

```
✔ rk:/tmp/drushtest> vendor/bin/drush @remoteproject.remotesite.dev status -debug --config=drush.yml
 [preflight] The alias @remoteproject.remotesite.dev could not be found.

```

Is this conceptually wrong? (Having only Drush and calling remote site using site alias.) Am I just missing some option? Or is this ready to be "promoted" to Github bug report / feature request?

Thanks!

# Answer
If your Drush 9 alias file is `remoteproject.site.yml`, and it has keys like `live:`, then your alias should be `@remoteproject.live`.

If you have multiple remote sites, do not put them in the same `.yml` file in Drush 9. Make one file per site, e.g. `remotesite1.site.yml`, `remotesite2.site.yml` and so on.

Use `./vendor/bin/drush sa` to see the list of aliases found by Drush.
> 1 votes

---
Tags: drush
---


# Question
Title: How can I create a new Paragraph item programmatically in an Ajax form handler?
I need to add Paragraph fields programmatically to an entity in an AJAX handler.

This is my AJAX callback and how it's added:

```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_gallery_form') {
    $form['field_gallery_items']['multiple_button_dddd'] =   [
      '#type' => 'button',
      '#value' => t('Done, now tell us about you.'),
      '#limit_validation_errors' => array(),
      '#ajax' => array(
        'callback' => 'myAjaxCallback',
        'wrapper' => 'form_wrapper',
        'event' => 'change', //Use change instead of click so Drupal doesn't run any validation functions.
      ),
    ];
    $form['debug'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => ['debug-out'],
      ],
    ];

  }

function myAjaxCallback(array &$form, \Drupal\Core\Form\FormState $form_state)  {
  $paragraph3 = \Drupal\paragraphs\Entity\Paragraph::create([
    'type' => 'media',
    'field_caption' => 'Apart from the included Paragraph types, you can create your own simply by going to Structure -> Paragraphs types.',
  ]);
  $paragraph3->save();

  // Now I need to add $paragraph3 to $form['field_gallery_items']['widget']

  return $form;
}

```

I need to add the new Paragraph I created to the widget for the so that when the `$form` is returned I have added a paragraph.

How Can I do that?

# Answer
> 1 votes
What I ended up doing was: 1) add an hidden field to my form and populate that field with JS

```
function polaris_drupal_cloudinary_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_gallery_form') {
    // Add field to pass the number of images to be added from GalleryWidget.
    $form['field_gallery_items']['multiple_images_count'] =   [
      '#type' => 'hidden',
      '#value' =>'1',
      '#attributes' => [
        'id' => ['multiple_images_count'],
      ],
    ];

  }

}

```

2) extend the basic paragraph widget so that more than one paragraph can be added

```
<?php
namespace Drupal\polaris_drupal_cloudinary\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\paragraphs\Plugin\Field\FieldWidget\InlineParagraphsWidget;
/**
 * Gallery implementation of the 'entity_reference paragraphs' widget.
 *
 * We need to be able to add more than one Paragraph when the Add Media button is pressed.
 *
 * @FieldWidget(
 *   id = "entity_reference_paragraphs_gallery",
 *   label = @Translation("Paragraphs Gallery Items"),
 *   description = @Translation("A paragraphs inline form widget."),
 *   field_types = {
 *     "entity_reference_revisions"
 *   }
 * )
 */
class GalleryWidget extends InlineParagraphsWidget {
  /**
   * {@inheritdoc}
   */
  public static function addMoreSubmit(array $form, FormStateInterface $form_state) {
    $button = $form_state->getTriggeringElement();
    $howMany = $form_state->getUserInput()['multiple_images_count'] > 0 ? $form_state->getUserInput()['multiple_images_count'] : 1;
    // Go one level up in the form, to the widgets container.
    $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -2));
    $field_name = $element['#field_name'];
    $parents = $element['#field_parents'];
    // Increment the items count.
    $widget_state = static::getWidgetState($parents, $field_name, $form_state);
    if ($widget_state['real_item_count'] < $element['#cardinality'] || $element['#cardinality'] == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
      $widget_state['items_count'] += $howMany;
    }
    for ($i = 0; $i < $widget_state['items_count']; $i++) {
      $form_state->set([$field_name, $i, 'widget', 'fid'], 1);
    }
    if (isset($button['#bundle_machine_name'])) {
      $widget_state['selected_bundle'] = $button['#bundle_machine_name'];
    }
    else {
      $widget_state['selected_bundle'] = $element['add_more']['add_more_select']['#value'];
    }
    static::setWidgetState($parents, $field_name, $form_state, $widget_state);
    $form_state->setRebuild();
  }
}

```

---
Tags: 8, forms, ajax, paragraphs
---


# Question
Title: Module or method for handling my scheduling needs?
I'm using Drupal 8 to build a website that I will use to manage a D&D Campaign. I'm looking for a way to set up session planning.

I would like something where I can create time slots where I am available and then the users can do one of two things:

* Create a proposed session (select a time span within a time slot, add information on what they would like to do - could just be a textbox)
* Join a proposed session (potentially with a cap on # of users per session)

Ideally, I would then be able to approve/deny proposed sessions and have approved sessions block out their time slots.

Is there anything that could work for this? The closest thing I've found would be https://www.drupal.org/project/appointment\_calendar but that doesn't look like it would support the ability for multiple proposed sessions or the approve/deny aspect of it.

Or is there a way to make this work with a custom content type or something?

# Answer
You may want to try Bookable Entities Everywhere. It looks rather adapted to what you are looking for, is available to D8 and has a few tutorials to get you started.
> 0 votes

---
Tags: 8
---


title: How to track user logins

text:
# Question
Title: How to track user logins
I need to track user logins so I know how often "UserA" is logging into my site. Can anyone recommend a method to do this? Module or code?

# Answer
Just to close off this question I will share how I managed to track the user login times.

I simply wrote a module that added a table to the db and on login I would add the login/user event + date-time to the table.

Then I was able to access how many times and at what time users were logging in. This was something I wasn't able to get from the User Stats module.
> 2 votes

# Answer
I think you are looking for User Stats module.

> Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics are:
>
> * days registered;
> * join date;
> * days since last login;
> * days since last post;
> * post count;
> * login count;
> * user online/offline;
> * IP address;
> 7 votes

# Answer
use User Track module

> A simple module that tracks each time a user logs in and stores a historical record in your database. This data is then exposed to views so you can report on it if required.
>
> Logs minimal data: user ID, and time logged in Ability to exclude users from tracking by role Hooks to allow fine-grained control over which logins get tracked Hooks to allow you to add information to the data stored Views integration

it's available on both Drupal 7, 8
> 1 votes

---
Tags: 7, users
---


title: Drupal::entityQuery

text:
# Question
Title: Drupal::entityQuery
This is the official Drupal::entityQuery function definition I found

```
public static function entityQuery($entity_type, $conjunction = 'AND') {
  return static::getContainer()
    ->get('entity.query')
    ->get($entity_type, $conjunction);
}

```

I also see that conditions can be added after the original query has been assigned to a variable

```
// original query
$query = \Drupal::entityQuery('node')
              ->condition('status', 1)
              ->sort('field_some_field', 'some_value');

// expand query with another condition
if (!empty($taxonomy_type)) {
  $query->condition('field_taxonomy_type', $taxonomy_type, 'IN');
}

```
* Is this the correct way to query for nodes that contain a particular taxonomy type field?
* How do I filter for nodes that contain a specific taxonomy term?

# Answer
> 2 votes
* Is this the correct way to query for nodes that contain a particular taxonomy type field?

> \Drupal::entityQuery() is the correct approach, yes.

* How do I filter for nodes that contain a specific taxonomy term?

> Would you like to filter by the taxonomy term name? If so you need to get the taxonomy term ID and use that in your condition:

```
// Get an array of terms that have the name "foo".
$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadByProperties(['name' => 'foo']);

// Get the first term from the array.
$term = reset($terms);

// Get an array of nodes that reference the taxonomy term "foo"s ID.
$nodes = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('field_my_taxonomy_term', $term->id(), '=')
  ->execute();

```

All Drupal entity references are done via the entities ID, so you will always be using that as your condition.

Also, `entityTypeManager()` & `entityQuery()` are basically the same thing, just structured slightly differently, so you can use whichever one you find most convenient.

---
Tags: nodes, taxonomy-terms
---


# Question
Title: How can I get and format the node created date in field.html.twig?
The date is being rendered from field.html.twig template from {{ item.content }} from "items" array. After Using a twig filter date {{ items.content|date("long") }} it only outputs current date not the date node was created. How could I achieve node submitted date instead of the current date.

# Answer
> 6 votes
Having a field template you always can get the parent entity via `element['#object']`. And from there you can get everything else, also the creation timestamp. You then can format it using Twig's `date()` filter or with `format_date()` in a predefined Drupal date format.

In any variation of `field.html.twig` (`field--field-myfield.html.twig` etc.) do:

```
<div class="foo">
  {{ element['#object'].getCreatedTime | date('F j, Y') }}
</div>

<div class="bar">
  {{ element['#object'].getCreatedTime | format_date('html_datetime') }}
</div>

```

---

Source: Sample taken from Accessing the original entity in field templates is hard.

# Answer
> 3 votes
I believe you are wanting "node.createdtime"

```
<p class="post-date">{{ node.createdtime | date('F j, Y') }} at {{ node.createdtime | date('h:i a') }}</p>

```

This is for "node" template files. No loops or custom fields necessary as this comes from Drupal core.

```
{{ dump(node | keys) }}

```

# Answer
> 0 votes
In twig, date filter only works for timestamps. In above case it is assuming as the present date and printing the date in long format.

You can get the created timestamp by writing a preprocess.

```
$timestamp = $variables['node']->created->value

```

# Answer
> 0 votes
> If you are in views and want to print **node created datetime** value in twig you need to:

**1. If your views HAS outputted Field (Authored On): then `{{ fields.created.content }}`**

**2. If NOT: then `{{ row._entity.created.value }}`**

---
Tags: 8, theming
---


# Question
Title: How do we set required for new & optional for existing fields - when adding basic field to content type?
## How do we set required for new & optional for existing fields - when adding basic field to content type?

When using Drupal 8 following this how to article shows the steps to take to add a basic field to content types. https://www.drupal.org/docs/user\_guide/en/structure-fields.html

What I want to learn how to accomplish is to make the new field "Required" for all newly created content types however for existing content I want the field to be optional.

In the admin I see the `required` checkbox however this will make all of them required. Below is an image of what I am viewing:

Any & all feedback is greatly appreciated.

# Answer
> 1 votes
You can use hook\_form\_alter or hook\_form\_FORM\_ID\_alter to set require for that field.

```

function my_module_form_alter(&$form, $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  if ($entity->isNew()) {
    $form['my_field']['#required'] = TRUE;
  }
}

```

And, not set the field 'my\_field' as required field. Not tested, but it is a way to go.

---
Tags: entities
---


# Question
Title: How to add custom class on the menu block using twig?
I'm new in Drupal 8 and i'm trying to display my primary menu block using `twig` as below

```
 {% if page.primary_menu %}
   {{ page.primary_menu }}
 {% endif %}

```

which gives me like this

```
<ul class="sm menu-base-theme" id="main-menu">
   <li>
      <a href="/drupal8/" data-drupal-link-system-path="<front>" class="is-active">About</a>
   </li>
   <li>
      <a href="/drupal8/" data-drupal-link-system-path="<front>" class="is-active">Home</a>
   </li>
</ul>

```

I want to add my custom class attributes on `ul` and `a` elements to get the menu like this

```
<ul class="nav navbar-nav navbar-right" id="main-menu">
   <li>
      <a href="#about" data-drupal-link-system-path="<front>" class="page-scroll">About</a>
   </li>
   <li>
      <a href="#home" data-drupal-link-system-path="<front>" class="page-scroll">Home</a>
   </li>
</ul>

```

How can i add my custom class on the menu? If you have any idea about this problem then please help me. Thank you.

# Answer
> 4 votes
You can do this by creating template file called "menu--main.html" in your theme's template folder.

Then in place below code in that file:

```
{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
```

```
  <ul{{ attributes.addClass('menu', 'nav', 'navbar-nav','navbar-right') }}>

```

```
    {% else %}
```

```
  <ul{{ attributes.addClass('dropdown-menu') }}>

```

```
    {% endif %}
    {% for item in items %}
      {% if menu_level == 0 and item.is_expanded %}
```

```
    <li{{ item.attributes.addClass('expanded', 'dropdown') }}>
    <a href="{{ item.url }}" class="page-scroll">{{ item.title }}</a>

```

```
      {% else %}

        {{ link(item.title, item.url) }}
      {% endif %}
      {% if item.below %}
        {{ menus.menu_links(item.below, attributes.removeClass('nav', 'navbar-nav'), menu_level + 1) }}
      {% endif %}
```

```
  </li>
{% endfor %}
</ul>

```

```
  {% endif %}
{% endmacro %}
```

This will add the class "ul"

# Answer
> 3 votes
You can use Menu Link Attribute module which allows you to add class, id, etc.. to your menu item.

> This module allows you to add attributes to your menu links.

Hence, you can customize your menu item, using those added attributes.

# Answer
> 0 votes
May you can use hooks:

```
/**
* Implements hook_preprocess_HOOK() for menu.html.twig.
*/
function mytheme_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    if (!isset($variables['attributes']['class'])) {
      $variables['attributes']['class'] = [];
    }
    $variables['attributes']['class'] = array_merge($variables['attributes']['class'], ['my-main-menu']);  }
}

```

Source: https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file

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


# Question
Title: How do I add an additional database for migration?
I have a Drupal 8 site running in Lando. I need to have the 8 site connect to a Drupal 7 database so I can run a migration.

My understanding is I can import an additional database through Lando, but from the documentation I cannot figure out exactly how to do this.

I've tried adding this to my **.lando.yml**:

```
services:
  legacydatabase:
    type: mysql
    creds:
      user: root
      password:
      database: legacy

```

and then multiple attempts at the **lando db-import** command to no avail.

I need to know what exactly goes in .lando.yml and then what exactly goes in the lando db-import arguments to get this working.

# Answer
> 4 votes
You are on the right track. You can use

```
services:
  legacydatabase:
    type: mysql

```

And do a `lando rebuild` to spin up a second DB server. If you did not specify the credentials you can check them with `lando info`.

To use db-import (or export) you have to specify which host to use. By default it uses 'database' and not `legacydatabase` or whatever you called your second DB server. As per the documentation: Options: --host, -h The database service to use \[default: "database"\]

So the command to use in your case would be:

`lando db-import --host legacydatabase [your_mysql_file]`

# Answer
> 2 votes
Try this:

```
services:
  database2:
    type: mariadb

```

The creds will be set as:

```
"creds": {
  "user": "mariadb",
  "password": "password",
  "database": "database"
},

```

---
Tags: 8, migrations
---


# Question
Title: What is the use of page_cache_fastpath ? When and how should we implement it?
When I am debugging drupal, I came across the concept `page_cache_fastpath`. I want to know the use of it.

# Answer
I believe this was part of a technique for loading certain cached content from the database (thus requiring a db connection) without all the overhead of creating sessions, loading modules, etc.

Much of Drupal's functionality is unavailable while loading from fastcache which creates a tradeoff... load from cache more quickly but without Drupal being able to do things like run hooks or check permissions, or retain Drupal's core functionality while loading from cache more slowly.

Ref: https://www.drupal.org/project/drupal/issues/80887

You may also want to look at the boost module if you are looking for faster caching techniques
> 0 votes

---
Tags: 7, caching
---


# Question
Title: User register endpoint showing notifications
I'm trying to setup an endpoint for a 3rd party app to allow users to be created on my site through a REST endpoint, which is mostly working so far, although, I've just navigated to my site through the front end, and I've realised it's showing me all the notifications for all the test users I'm creating.

I'm not logged in as an administrator, just a normal user account, and the setting for Show errors and notifications is off, so why is it showing me all these notifications, there's no way I can leave that in

# Answer
> 0 votes
Base on you're working with RESTful API and does not need these messages anymore you can disable them ( all of them or parts of them based on what you don't want) by Disable message module :

```
Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Features

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the end users.

```

or another solution is on the theme prevent it got rendered by this solution : https://www.drupal.org/forum/support/installing-drupal/2011-01-23/how-to-turn-off-error-messages

---
Tags: 7
---


# Question
Title: User password reset link leads to access denied page
**Command:** drush uli

**Output:** http://default/user/reset/uid/..../...hash.../login

The output URL normally logs you in automatically, but it gets takes to access denied error instead.

# Answer
> -1 votes
To Fix It

1. Go to /admin/config/people/accounts
2. Disable "Require email verification when a visitor creates an account"

If you are not able to login to your admin account because your one-time login link does not work. And you have access to use Drush.

1. drush cset user.settings verify\_mail 0

If you don't have access to use Drush

1. Maybe other people can answer this one.

---
Tags: users, drush
---


title: File name transliteration

text:
# Question
Title: File name transliteration
I need to clean up file names on upload. Both for image fields, other file fields and IMCE file manager. The transliteration module is not yet ported to Drupal 8 and the community does not seem to agree on how to implement the core transliteration in Drupal 8.

Do I have to make a custom module for this, or is there a simpler way?

Right now, Drupal 8 seems to allow both spaces and special characters in filenames. I know about the module File (Field) Paths, but it will have to be set up for every file field on every content type. I don't think it will work with IMCE.

# Answer
It seems that the module already mentioned is now covered by Drupals security advisory policy:

**Transliterate filenames for uploads** \- https://www.drupal.org/project/transliterate\_filenames

> Stable releases for this project are covered by the security advisory policy.
>
> **8.x-1.3 Stable release** covered by the Drupal Security Team released 1 July 2019
> 3 votes

# Answer
I applied a Drupal 8 core patch from this page. It seems to work fine. It adds a new option to `/admin/config/media/file-system`:

This option enables transliteration for all future uploads to all file fields. It also works for inline images when `Enable image uploads` is enabled (for the text-format). I don't know if the patch affects IMCE, since IMCE was not installed on my test installation.
> 2 votes

# Answer
There is a module for that https://www.drupal.org/project/transliterate\_filenames

> Transliteration for all uploading files (includes fields and ckeditor inline upload)
>
> How to use: just enable module as usual. All new file names will be transliterate to Latin characters.
> 2 votes

# Answer
Just use this module. This module is based on the blog post by Alexander Belov, but simplified for a less specific use case. https://drupal.org/project/filename\_transliteration
> 0 votes

---
Tags: 8, transliteration
---


# Question
Title: How to set related products view contextual filter to get its value from current product category id
I have build a Related Products view that supposed to show latest products which in the same category of the current product being viewed.

so I set a contextual filter for the category\_id field, but couldn't find anyway to get the commerce product category id.

Drupal 8 / Commerce 2

# Answer
> 0 votes
I needed a block to display related products for the current viewed product by showing products from the same category.

To do that you can use the same steps used in the 'related article' tutorial.

but first you have to add the ability to extract term id from product page (like the way it is extracted from node page), so you have to modify

```
core\modules\taxonomy\src\Plugin\views\argument_default\Tid.php

```

like this

include this namespace:

```
use Drupal\commerce_product\Entity\ProductInterface;

```

look for:

```
    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  }

```

replace with:

```
    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  } elseif (($product = $this->routeMatch->getParameter('commerce_product')) && $product instanceof ProductInterface) {
    $taxonomy = [];
    foreach ($product->getFieldDefinitions() as $field) {
      if ($field->getType() == 'entity_reference' && $field->getSetting('target_type') == 'taxonomy_term') {
        $taxonomy_terms = $product->{$field->getName()}->referencedEntities();
        /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
        foreach ($taxonomy_terms as $taxonomy_term) {
          $taxonomy[$taxonomy_term->id()] = $taxonomy_term->bundle();
        }
      }
    }
    if (!empty($this->options['limit'])) {
      $tids = [];
      // filter by vocabulary
      foreach ($taxonomy as $tid => $vocab) {
        if (!empty($this->options['vids'][$vocab])) {
          $tids[] = $tid;
        }
      }
      return implode($this->options['anyall'], $tids);
    }
    // Return all tids.
    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  }

```

# Answer
> 0 votes
FWIW, I found a work around that doesn't involve modifying core, though its much less elegant and only really applicable if you only have a few terms. It also requires the twig\_tweak module. Basically I created a view block for each Related Products block filtered by one of the terms. Then in the twig template for the product view I created a bunch of conditionals for each term that checks for the term and then based on the result outputs the appropriate view: Like:

```
{% if 'term1' in product.field_my_term.0['#plain_text']  %}
  {{ drupal_view('related_products', 'block_1') }}
{% elseif 'term2' in product.field_my_term.0['#plain_text'] %}
  {{ drupal_view('related_products', 'block_2') }}
{% elseif 'term3' in product.field_my_term.0['#plain_text'] %}
  {{ drupal_view('related_products', 'block_3') }}
{% endif %}

```

---
Tags: views, commerce
---


# Question
Title: Fatal error: Declaration of ... must be compatible with
```
/**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    return [];
  }

```

in BlockBase.php

vs

```
/**
     * @inheritdoc
     */
    public function blockForm(array $form, FormStateInterface $form_state ) {
       $form = parent::blockForm($form, $form_state);

       $form['city'] = [
        '#type' => 'textfield',
        '#title' => $this->t('City'),
        '#default_value' => $this->configuration['city'],
       ];

       return $form;
    }

```

in CustomWeatherBlock.php

Adding array in first argument as typehint of $form gives above error. I just need to understand why is it giving an error.Is it because BlockBase is an abstract class and CustomWeatherBlock class extends BlockBase hence it needs to copy exactly the methods name and its arguments (including typehint) ?

Error

> ( ! ) Fatal error: Declaration of Drupal\custom\_changes\Plugin\Block\CustomWeatherBlock::blockForm(array $form, Drupal\custom\_changes\Plugin\Block\FormStateInterface $form\_state) must be compatible with Drupal\Core\Block\BlockBase::blockForm($form, Drupal\Core\Form\FormStateInterface $form\_state) in /Applications/MAMP/htdocs/d8jsonapi/web/modules/custom/custom\_changes/src/Plugin/Block/CustomWeatherBlock.php on line 16

# Answer
> 3 votes
`BlockBase` implements BlockPluginInterface, which defines `blockForm()` as follows:

```
public function blockForm($form, FormStateInterface $form_state);

```

Interfaces are like contracts. Any class that implements an interface (or one of it's descendants) must define all the functions in the interface, and they must be defined exactly as in the interface. This is so that developers can replace classes, but ensure the code will still work, since the function definition will always expect the same values, as defined by the interface.

When you add a typehint to force `$form` to be an array, you break the contract of the interface. The interface says that any value should be allowed for the `$form` argument, but you are saying it must be an array. If you used your code, and a function passed a non-array value, it would cause an error. The interface is there to prevent such errors from happening. This is why you cannot change the function definition.

---
Tags: 8, blocks
---


# Question
Title: Site keeps redirecting to core/install.php
I keep having this problem of drupal redirecting to `core/install.php` as shown below:

I already set the `max_allowed_packet` to 64MB on AWS RDS. I am not sure what else I am missing. Please help

The error in the logs is:

> Fatal error: Cannot redeclare \_drupal\_shutdown\_function\_handle\_exception() (previously declared in /var/www/html/web/core/includes/bootstrap.inc:1066) in /var/www/html/vendor/drupal/core/includes/bootstrap.inc on line 1066

and the following is my composer.json

```
{
  "name": "xxx/yyy",
  "description": "zzz",
  "type": "project",
  "license": "GPL-2.0-or-later",
  "authors": [
    {
      "name": "QQQ EEE",
      "role": "Developer"
    }
  ],
  "repositories": [
    {
      "type": "composer",
      "url": "https://packages.drupal.org/8"
    }
  ],
  "require": {
    "php": ">=5.6",
    "aws/aws-sdk-php": "^3.108",
    "composer/installers": "^1.2",
    "cweagans/composer-patches": "^1.6.5",
    "drupal-composer/drupal-scaffold": "^2.5",
    "drupal/console": "^1.0.2",
    "drupal/core": "^8.7.0",
    "drupal/ldap": "^3.0@beta",
    "drupal/redis": "^1.1",
    "drupal/s3fs": "^3.0",
    "drush/drush": "^9.0.0",
    "predis/predis": "^1.1",
    "vlucas/phpdotenv": "^2.4",
    "webflo/drupal-finder": "^1.0.0",
    "webmozart/path-util": "^2.3",
    "zaporylie/composer-drupal-optimizations": "^1.0"
  },
  "require-dev": {
    "webflo/drupal-core-require-dev": "^8.7.0"
  },
  "conflict": {
    "drupal/drupal": "*"
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "config": {
    "sort-packages": true
  },
  "autoload": {
    "classmap": [
      "scripts/composer/ScriptHandler.php"
    ],
    "files": ["load.environment.php"]
  },
  "scripts": {
    "pre-install-cmd": [
      "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "pre-update-cmd": [
      "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "post-install-cmd": [
      "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-update-cmd": [
      "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ]
  },
  "extra": {
    "composer-exit-on-patch-failure": true,
    "patchLevel": {
      "drupal/core": "-p2"
    },
    "installer-paths": {
      "web/core": ["type:drupal-core"],
      "web/libraries/{$name}": ["type:drupal-library"],
      "web/modules/contrib/{$name}": ["type:drupal-module"],
      "web/profiles/contrib/{$name}": ["type:drupal-profile"],
      "web/themes/contrib/{$name}": ["type:drupal-theme"],
      "drush/Commands/{$name}": ["type:drupal-drush"]
    },
    "drupal-scaffold": {
      "initial": {
        ".editorconfig": "../.editorconfig",
        ".gitattributes": "../.gitattributes"
      }
    }
  }
}

```

# Answer
You've got a problem with your installation. You have two copies of core, as can be seen from the two paths in the error message:

/var/www/html/web/core/includes/bootstrap.inc

/var/www/html/vendor/drupal/core/includes/bootstrap.inc

You should not have a copy of core in your vendor directory. That needs to be removed, though it may also break your site. Make sure to clear the registry `drush cr` or equivalent after removing that directory.
> 4 votes

---
Tags: 8
---


# Question
Title: Default moderated content view has an error message
The following error appears in the default state at Home\>Administration\>Structure\>Views\>Moderated content\>Edit.

> No valid values found on filter: Content revision: Moderation state.

What is wrong?

# Answer
I compared the views on the newly installed site. In the "Is not one of" operator, no options were selected. After setting up the workflow, I realized that I needed to check it. Thank you.
> 1 votes

---
Tags: views
---


# Question
Title: Inject a theme setting form into a block
Is there a way to inject the theme settings form into a block so it could fix to the left-hand side of the page when admin logins?

The url that would be injected into the block would be

```
admin/appearance/settings/<theme_name>

```

# Answer
> 1 votes
You can create a custom block: https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-blocks/create-a-custom-block

In the build() method, you can return the form:

```
public function build() {
  return \Drupal::formBuilder()->getForm('Drupal\system\Form\ThemeSettingsForm');
}

```

---
Tags: theming, blocks
---


title: System emails translation

text:
# Question
Title: System emails translation
I wanted to translate emails sent to users after signing up using different language than English. I know there is a way to translate the system emails from the account settings translate tab, so I added the translations as you can see in this picture.

>

This didn't work. Maybe this is not enough. I tested it (registering a new account using Arabic) and it is not working: The system emails are still sent in English.

Does Drupal send emails according to user's preferred language? If yes, how can Drupal send registration email in a language that is not English?

# Answer
Here is the steps to get user email in your language (describing all the steps in case you missed any)

Default installation of Drupal 8

## Enable translation module (core modules)

* Configuration Translation
* Content Translation
* Interface Translation
* Language

## add your language visiting

`/admin/config/regional/language` in my example added Greek with Language code `el`

## translate emails visiting

`admin/config/people/accounts/translate` and pressing edit on your language which in my example would be take me to this page `admin/config/people/accounts/translate/el/edit`

## add language switcher block (optional)

so you can switch to appropriate language

## visit registration form for your language

in my case `/el/user/register` and fill out the form

The email should come in the registration language

It came in Greek in my test.
> 4 votes

# Answer
On the user account, there is an option to choose Site Language. This account's preferred language for emails and site presentation. This is also assumed to be the primary language of this account's profile information. Based on the chosen language email for that user will send.
> 0 votes

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


# Question
Title: What is the logic of create method in ContainerInterface class & its argument when being used and how its related to argument of the construct method?
```
<?php

namespace Drupal\custom_changes\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GuzzleHttp\Client;
/**
 * Block to determine the weather
 * @Block(
 *   id = "weather_block",
 *   admin_label = "Weather Block",
 *   category = @Translation("Hello World"),
 * )
 */
class CustomWeatherBlock extends BlockBase implements ContainerFactoryPluginInterface
{

    /**
     * The HTTP client to fetch the feed data with.
     *
     * @var \GuzzleHttp\Client
     */
      protected $httpClient;

    /**
     * {@inheritdoc}
     */
    public function __construct(array $configuration, $plugin_id, $plugin_definition, Client $http_client) {
       $this->httpClient = $http_client;
    }

    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition){
       return new static(
         $configuration,
         $plugin_id,
         $plugin_definition,
         $container->get('http_client')
       );
    }

```

What does `return new static()` mean inside `CustomWeatherBlock` class and why do I need to pass all the arguments
\- $configuration
\- $plugin\_id
\- $plugin\_definition
as in the construct and how is construct and create related to each other? because when I tried to pass just $container-\>get('http\_client') inside

```
return new static(
  $container->get('http_client')
);

```

whereas when I pass

```
return new static(
  $configuration,
  $plugin_id,
  $plugin_definition,
  $container->get('http_client')
);

```

It does not give any error. I need to understand why is it so ?

# Answer
> 1 votes
`create()` is a static method called on this class, before it is instantiated (static methods don't require instantiation of the class). The `create()` method returns the arguments that are passed to `__construct()`.

> Whereas when I pass:
>
> ```
> return new static(
>   $configuration,
>   $plugin_id,
>   $plugin_definition,
>   $container->get('http_client')
> );
>
> ```
>
> It does not give any error. I need to understand why is it so?

Plugins that implement the `ContainerAwareInterface` pass the additional arguments of `$configuration`, `$plugin_id` and `$plugin_definition` to the create() function. These must be returned, as the `__construct()` argument will require these values in plugins.

---
Tags: 8, dependency-injection
---


# Question
Title: How to get the form field label of a multi-value field
In hook\_form\_user\_form\_alter I need to get the title of each field. When I dump a normal (single-value) field #title is an array value, like this:

```
array (size=13)
  '#title' => string 'Name' (length=13)
  '#title_display' => string 'before' (length=6)

```

but for fields that can contain more than one value, #title is an object that looks like this:

```
array (size=13)
  '#title' =>
    object(Drupal\Core\StringTranslation\TranslatableMarkup)[1544]
      protected 'translatedMarkup' => null
      protected 'options' =>
        array (size=0)
          empty
      protected 'stringTranslation' =>
        object(Drupal\Core\StringTranslation\TranslationManager)[285]
          protected 'translators' =>
            array (size=1)
              ...
          protected 'sortedTranslators' =>
            array (size=1)
              ...
          protected 'defaultLangcode' => string 'en' (length=2)
          public '_serviceId' => string 'string_translation' (length=18)
      protected 'string' => string '@title (value @number)' (length=22)
      protected 'arguments' =>
        array (size=2)
          '@title' => string 'Name' (length=19)
          '@number' => int 1
  '#title_display' => string 'invisible' (length=9)
  '#description' => string '' (length=0)
  '#field_parents' =>
    array (size=0)
      empty
  '#required' => boolean false
  '#delta' => int 0
  '#weight' => int 0
  '#type' => string 'textfield' (length=9)
  '#default_value' => string 'John Doe' (length=8)
  '#size' => int 60
  '#placeholder' => string '' (length=0)
  '#maxlength' => int 255
  '#attributes' =>
    array (size=1)
      'class' =>
        array (size=2)
          0 => string 'js-text-full' (length=12)
          1 => string 'text-full' (length=9)

```

If I just refer to #title, for the multi-value field I end up with:

```
Name (value 1)

```

What is the proper way of obtaining the title, and what causes the difference?

# Answer
> What is the proper way of obtaining the title, and what causes the difference?

The cause is this code in the field widget:

```
  // For multiple fields, title and description are handled by the wrapping
  // table.
  if ($is_multiple) {
    $element = [
      '#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
      '#title_display' => 'invisible',
      '#description' => '',
    ];

```

This t($string, array $args = \[\], array $options = \[\]) function returns a TranslatableMarkup object.

You can cast the translatable markup as string to obtain the title, but normally you don't have to. See both answers here How to get the string value from the function CountryManager::getStandardList()?
> 1 votes

---
Tags: forms
---


# Question
Title: Should we document AJAX-callback parameters?
Considering the `PHPCS` warning:

> phpcs: Hook implementations should not duplicate @param documentation

Is there any way to tell *PHPCS* that the function is an AJAX-callback (so that such warnings are generated)?

Or, Should we document all AJAX-callback parameters, with `@param` PHPDoc?

---

### Background:

There was a discussion in our company about the below AJAX-callback function:

```
/**
 * Prevents popup's redirection from dashboard to another link.
 *
 * Users were redirected to another page as soon as the Event-creation
 * popup form was submitted, just added an AJAX handler to submit button
 * which prevents the redirect using ajax,
 * and when there is any error on the form, the message is sent to the popup.
 */
function _MYMODULE_popup_submit(array &$form, FormStateInterface $formState) {
  // ...
}

```

Where one developer insisted on adding `@param` PHPDoc comments to each AJAX-callback like:

```
/**
 * Prevents popup's redirection from dashboard to another link.
 *
 * Users were redirected to another page as soon as the Event-creation
 * popup form was submitted, just added an AJAX handler to submit button
 * which prevents the redirection using ajax,
 * and when there is any error on the form, the message is sent to the popup.
 *
 * @param array &$form
 *   All data of the form.
 * @param \Drupal\Core\Form\FormStateInterface $formState
 *   State of the form.
 *
 * @return \Drupal\Core\Ajax\AjaxResponse
 *   Returns the data back as AjaxResponse object.
 */
function _amt_dayview_popup_submit(array &$form, FormStateInterface $formState) {
  // ...
}

```

And the other considered it as understandable and that it should not be documented:

> ... remember that *PHPCS* will warn you every time we use `@param` on any hook, like "`phpcs: Hook implementations should not duplicate @param documentation`", and just because *PHPCS* can not differ AJAX-callback from normal functions it does not mean that we should do this ...

---

**Edit:** The feature request is created for this on Drupal.org.

# Answer
> 1 votes
> Is there any way to tell PHPCS that the function is an AJAX-callback (so that such warnings are generated)?

Yes, it's as simple as implementing hooks except that instead of "`Implements hook_`", it starts with "`Implements callback_`".

The only problem is that currently (August 2019) it is not supported by Drupal's *PHPCS* standard and you don't get any warnings yet.

> Or, Should we document all AJAX-callback parameters, with @param PHPDoc?

That too is an option, for your newly hired dev interns, but especially when there was no official definition in any existing `*.api.php` file and when you do not want to write your own `*.api.php` file.

### Source:

In Drupal's Official-documentation of August 2019, we can find below *Callback implementation*:

```
/**
 * Implements callback_batch_finished().
 */
function _node_mass_update_batch_finished($success, $results, $operations) {
  // …
}

```

> **Note:** Unlike hooks any callback starts with an underscore (i.e. it is "`_MYMODULE_descreptive_name`").

---

### Callback definition example:

In our case, because Drupal's own `*.api.php` files did not cover AJAX-callbacks, we added our own `*.api.php` file to prevent copy/paste until Drupal's own `*.api.php` files cover that section as well, something like below:

```
<?php

/**
 * @file
 * Callbacks and hooks related to MYPROJECT system.
 */

/**
 * @addtogroup callbacks
 * @{
 */

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormStateInterface;

/**
 * Callback for AJAX events.
 *
 * AJAX callback functions can be used to update existing or
 * add new form fields, update values in form fields and more,
 * while users can still interact with the form.
 *
 * @param array &$form
 *   All data of the form.
 * @param \Drupal\Core\Form\FormStateInterface $formState
 *   State of the form.
 *
 * @return \Drupal\Core\Ajax\AjaxResponse
 *   Returns the data back as AjaxResponse object.
 */
function callback_form_ajax(array &$form, FormStateInterface $formState) {
  // Here we do something meaningful with the results.
  $response = new AjaxResponse();
  $response->addCommand(new HtmlCommand('#message-box', 'my message.'));
  return $response;
}

/**
 * @} End of "addtogroup callbacks".
 */

/**
 * @addtogroup hooks
 * @{
 */

/* Place any hook definitions here. */

/**
 * @} End of "addtogroup hooks"
 */

```

### Callback implementation example:

```
/**
 * Implements callback_form_ajax().
 *
 * Prevents popup's redirection from dashboard to another link.
 *
 * Users were redirected to another page as soon as the Event-creation
 * popup form was submitted, just added an AJAX handler to submit button.
 * which prevents the redirect using ajax,
 * and when there is any error on the form, the message is sent to the popup.
 */
function _amt_dayview_popup_submit(array &$form, FormStateInterface $formState) {
  // ...
}

```

---
Tags: 8, hooks, ajax
---


# Question
Title: Translation server suggests translation with old date
in admin/config/regional/translate/settings page, i had Check for updates set to never and translation server to Drupal translation server and local files.

i recently updated my site drupal version to 8.6.17.

after check for translation update manually i get a update available for drupal core translation with 2018 date for one of languages and i can't find .po file with this creation date.

my questions are:

* how drupal check for available translations?
* is it possible that it suggests translation for a older drupal version?
* and most important is it safe to delete .po files from translation folder on my site manually and run check again?

# Answer
> 0 votes
i didn't find answer for none of my questions but at least find a solution:

after testing clear cache without luck i did these steps:

user interface translation-\>setting-\>change translation source to 'local file only'-\>check update translation manually

and old translation suggestion was disappeared.

now with changing translation source to Drupal 'translation server and local files' i get related translation suggestion for my Drupal version.

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


# Question
Title: Show a content type's subfield instead of the default title in Drupal 7 when using an Entity Reference field
I am editing a large Drupal 7 website. In a part of this site, decisions are shown. Each decision can contain related decisions. There is a custom content type decision, in which there is a field that can link to other decisions (this is done by using the module Entity Reference).

The problem is, when the web page is generated, I want to see the related decision's short title (this is a subfield of the content type decision). By default the decision's 'normal title' is shown. The output should be something like this:

**Type of rule** Decision Gvt
**Status** Permanent
**Date** 12/11/2012

Text goes here.

**Link** decision link

**Related decisions** Not the title (system name: title), but the short title (system name: field\_verkorte\_titel) should be shown here.

Let me explain this by showing a screenshot of the content type decision (=beslissing overheid)

The red circle is what is shown now when the related decisions are shown. The title field (system name: title) is shown here.

The green circle is the field that should be shown, the short title (system name: field\_verkorte\_titel).

The yellow circle is the entity reference field, done with Entity Connect). Here a decision can link to an other decision.

I've looked up so much information, but I'm fairly new to Drupal, and it seems I'm not getting nowhere at this moment. Is there anyone who can push me in the right direction?

King regards

# Answer
> 0 votes
This will take a few steps.

1. Define an extra view mode, say 'short title'. Refer to How do I add additional view modes for a node?.
2. Format the short title view mode for the related decision so as to just show the short title field.
3. Suppress the regular title on that view mode by making sure the Display Suite Extras module is enabled then using the hide title option (see Display Suite Extras)
4. Change the display settings for the reference field to be 'rendered entity' with the view mode of 'short title'.

This is a summary rather than a detailed set of instructions but should be enough to get you underway. It's also possible to solve this problem in the theme but this way you should not have to write any code.

Addendum: you might need a little CSS to make the title appear inline.

---
Tags: 7, views
---


# Question
Title: Can I get the relationships of a node using node_load()?
I want to load relationships from the `node_load()`. So for example getting the article content type and loading the author information with the same query. How would I go about doing this?

The end goal is to make a computed field for Drupal Search API so that I can convert the field's name. The relationship fields are currently in the form `table_name:field_name` but I am indexing into Algolia and therefore need the field name to just be `field_name`.

# Answer
As an option you can index the entire rendered HTML of your content. Let's assume your index is called "default\_node\_index" and content type is "article".

1. Visit `/admin/config/search/search_api/index/default_node_index/workflow`
2. Enable "Complete entity view"
3. Visit /admin/config/search/search\_api/index/default\_node\_index/fields
4. Enable "Entity HTML output".
5. Manage display of your content type /admin/structure/types/manage/article/display
6. Enable "Search Index" in "Custom display settings" fieldset.
7. Visit /admin/structure/types/manage/article/display/search\_index
8. Add all the fields you want to render. You can extend this display using the regulat hooks, templates and preprocesses if needed.
> 0 votes

---
Tags: 7, nodes, search
---


title: Create a modal popup

text:
# Question
Title: Create a modal popup
I want to show a modal popup in drupal 7. On searching the web I came to know that it can be done using the ctools module itself. Here is the code I tried:

```
function codeexpertz_menu() {
  $items['codeexpertz/%ctools_js/page'] = array(
    'title' => 'Demo CTools Page',
    'access callback' => TRUE,
    'page callback' => 'codeexpertz_ctools_page_example',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function codeexpertz_ctools_page_example($js) {
  $output = "Sample CTools popup functionality for Demo purpose.";
  if ($js) {
    // Required includes for ctools to work:
    ctools_include('modal');
    ctools_include('ajax');
    return ctools_modal_render("Demo", $output);
  }
  return $output;
}

```

The link i referred is here

I added `<a href="codeexpertz/nojs/page" class="ctools-use-modal">Modal Window</a>` to my `page.tpl.php` file directly for now to test it. However when I click on the link I get redirected on the destination page rather than showing the content in a modal.

I tried this is a fresh installation also, but all in vain.

# Answer
You should use the ctools\_modal\_text\_button function to render your "popup-opener" links.

```
ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();
$link = ctools_modal_text_button('Open popup', 'codeexpertz/nojs/page', 'alt here', 'no-class');

```

You can have a look what the Modal Entities modue does in the `modal_entities_generate_link()` function for additional style settings.
> 1 votes

---
Tags: 7, chaos-tool-suite, modal-dialogs
---


# Question
Title: How do I programmatically remove a block?
I have a custom module that is intended to be deployed as a pure web view, with no styling whatsoever beyond what I created in the .twig file.

I installed the Stark theme and in my local instance I went to *Admin \> Structure \> Block layout* to manually remove all the active blocks.

However, this module will be deployed and I will have to have it programmatically remove all blocks when integrated into the mobile client.

Is there a way to turn off any automatic/default activation of blocks?

# Answer
You can use hook\_preprocess\_html(). For example, to remove the system navigation block from the "sidebar\_first" region, define the following hook in your MODULE.module:

```
function MODULE_preprocess_html(&$variables) {
  if($variables['page']['REGION']['BLOCK'])
    $variables['page']['REGION']['BLOCK']['#access'] = FALSE;
}

```

with REGION = sidebar\_first and BLOCK = system\_navigation.
> 1 votes

---
Tags: blocks, 8
---


title: Remove or hide the "View" tab on a node

text:
# Question
Title: Remove or hide the "View" tab on a node
I know how to rename "edit" or "track" tab on user page and node page. Here's the code, it might help someone.

```
<?php

function MYMODULE_menu_alter(&$items) {
//    drupal_set_message('Menu Items: <pre>'.print_r($items, TRUE).'</pre>');
    $items['user/%user/view']['title'] = "Profile";
    $items['user/%user/edit']['title'] = "Profile edit";
    $items['node/%node/edit']['title'] = "Node edit";

}

```

...but I don't know how to remove or hide the "View" tab on created node. my url page of the node is content/(node title).

What snippet should I use to remove the "View" tab on node page?

# Answer
You should be able to do this using css, or try using the code below or the tab tamer module

```
function MYMODULE_menu_alter(&$items) {
  $items['node/%node/view']['access callback'] = 'MYMODULE_disable_node_view';
  $items['node/%node/view']['access arguments'] = array(1);
}

function MYMODULE_disable_node_view($node){
        return false;
}

```
> 2 votes

# Answer
If you only want to hide the tab but maintain the access you could alter the menu callback type this way:

```
/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  // Example 1: hide tabs on user/* for anonymous:
  $items['user/login']['type']    = MENU_CALLBACK;
  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/password']['type'] = MENU_CALLBACK;
  // Example 2:
  $items['user/%user/view']['type'] = MENU_CALLBACK;
  $items['user/%user/edit']['type'] = MENU_CALLBACK;
  $items['node/%node/edit']['type'] = MENU_CALLBACK;
}

```
> 2 votes

# Answer
Since your requirement is more of a presentation issue you could either use the hidden option in the Tab Tamer Module or a simple `css hide` hack.

If your requirement is related to user access then you could use the code hack for access callback or disabled option in Tab Tamer Module.
> 0 votes

# Answer
For Drupal 8: you can use hook\_menu\_local\_tasks\_alter

```
/**
 * Hide view tab from node edit.
 */
function MYMODULE_menu_local_tasks_alter(&$data, $route_name, \Drupal\Core\Cache\RefinableCacheableDependencyInterface &$cacheability) {
  if($route_name == 'entity.node.edit_form'){
    unset($data['tabs'][0]['entity.node.canonical']);
  }
}

```
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How to disable htmlspecialchars in custom module form table?
I'm making a table form

```
$form['table'] = [
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $this->getOutput(),
  '#empty' => t('No vehicles found'),
];

```

In `getOutput()` I have `'vehicleName' => "<a href=\"/vehicle?id=" . $vehicle->vehicleId . "\">" . $vehicle->vehicleName . "</a>",` for one of the fields. And it doesn't print out as normal html. It goes through `htmlspecialchars()` and I don't have clickable link at the end. How can I disable this?

# Answer
You can use `FormattableMarkup`

Here's a simple example to get you started

```
use Drupal\Component\Render\FormattableMarkup; // place this at top of file

$options = [
  1 => ['foo' => 'Foo'],
  2 => ['foo' => 'Bar'],
  3 => ['foo' => new FormattableMarkup('<a href="http://example.com">I am a link</a>', [])],
];

$header = [
  'foo' => t('Foo bar')
];

$form['table'] = [
  '#type' => 'tableselect',
  '#title' => t('Foo bar table'),
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No foos found.'),
];

```

So in your case `$this->getOutput()` may return something like (this is untested):

```
['vehicleName' =>  new FormattableMarkup(
  '<a href="/vehicle?id=@id">@name</a>',
  ['@id' => $vehicle->vehicleId, '@name' => $vehicle->vehicleName]
)]

```
> 1 votes

---
Tags: 8, forms
---


title: Error when running custom migration

text:
# Question
Title: Error when running custom migration
I am new to writing migrations. I am attempting to figure it out with what I thought was simple case of migrating a title into a content type from a single XML file. The file has been uploaded to /sites/default/files/feeds/NCT00001239.xml. This is on Drupal 8.7.4.

When I run the migration I get the error posted below. Here is the migration YAML file:

```
id: clinical_trial_migrate
label: Clinical-Trial-Migrate
source:
  # XML data parser
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: xml
  urls: public://NCT00001239.xml
  item_selector: /clinical_study
  fields:
    -
      name: title
      label: title
      selector: official_title
process:
#  nid and vid commented out will allow them to autoincrement. Safe
as long
#    as nothing else is referencing them.
#  nid: nid
#  vid: vid
  Title: title
  type:
    plugin: default_value
    default_value: clinical_trial_record
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  uid:
    plugin: default_value
    default_value: 1
destination:
  plugin: entity:node

```

Here is the error:

> Invalid argument supplied for foreach() DataParserPluginBase.php:121 \[warning\] TypeError: Argument 2 passed to Drupal\migrate\Row::\__construct() \[error\] must be of the type array, null given, called in /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Plugin/migrate/source/SourcePluginBase.php on line 357 in Drupal\migrate\Row-\>\__construct() (line 101 of /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Row.php)
>
> #0 /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Plugin/migrate/source/SourcePluginBase.php(357): Drupal\migrate\Row-\>\__construct(Array, NULL)
>
> #1 /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Plugin/migrate/source/SourcePluginBase.php(330): Drupal\migrate\Plugin\migrate\source\SourcePluginBase-\>next()
>
> #2 \[internal function\]: Drupal\migrate\Plugin\migrate\source\SourcePluginBase-\>rewind()
>
> #3 /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/MigrateExecutable.php(188): FilterIterator-\>rewind()
>
> #4 /Users/JG/.composer/vendor/drush/drush/includes/drush.inc(720): Drupal\migrate\MigrateExecutable-\>import()
>
> #5 /Users/JG/.composer/vendor/drush/drush/includes/drush.inc(711): drush\_call\_user\_func\_array(Array, Array)
>
> #6 /Applications/MAMP/htdocs/CP8/modules/migrate\_tools/migrate\_tools.drush.inc(317): drush\_op(Array)
>
> #7 \[internal function\]: \_drush\_migrate\_tools\_execute\_migration(Object(Drupal\migrate\Plugin\Migration), 'clinical\_trial\_...', Array)
>
> #8 /Applications/MAMP/htdocs/CP8/modules/migrate\_tools/migrate\_tools.drush.inc(272): array\_walk(Array, '\_drush\_migrate\_...', Array)
>
> #9 /Users/JG/.composer/vendor/drush/drush/includes/command.inc(422): drush\_migrate\_tools\_migrate\_import('clinical\_trial\_...')
>
> #10 /Users/JG/.composer/vendor/drush/drush/includes/command.inc(231): \_drush\_invoke\_hooks(Array, Array)
>
> #11 /Users/JG/.composer/vendor/drush/drush/includes/command.inc(199): drush\_command('clinical\_trial\_...')
>
> #12 /Users/JG/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush\_dispatch(Array)
>
> #13 /Users/JG/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot-\>bootstrap\_and\_dispatch()
>
> #14 /Users/JG/.composer/vendor/drush/drush/drush.php(12): drush\_main()
>
> #15 {main}. TypeError: Argument 2 passed to Drupal\migrate\Row::\__construct() must be of the type array, null given, called in /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Plugin/migrate/source/SourcePluginBase.php on line 357 in /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Row.php on line 101
>
> #0 /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Plugin/migrate/source/SourcePluginBase.php(357): Drupal\migrate\Row-\>\__construct(Array, NULL)
>
> #1 /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Plugin/migrate/source/SourcePluginBase.php(330): Drupal\migrate\Plugin\migrate\source\SourcePluginBase-\>next()
>
> #2 \[internal function\]: Drupal\migrate\Plugin\migrate\source\SourcePluginBase-\>rewind()
>
> #3 /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/MigrateExecutable.php(188): FilterIterator-\>rewind()
>
> #4 /Users/JG/.composer/vendor/drush/drush/includes/drush.inc(720): Drupal\migrate\MigrateExecutable-\>import()
>
> #5 /Users/JG/.composer/vendor/drush/drush/includes/drush.inc(711): drush\_call\_user\_func\_array(Array, Array)
>
> #6 /Applications/MAMP/htdocs/CP8/modules/migrate\_tools/migrate\_tools.drush.inc(317): drush\_op(Array)
>
> #7 \[internal function\]: \_drush\_migrate\_tools\_execute\_migration(Object(Drupal\migrate\Plugin\Migration), 'clinical\_trial\_...', Array)
>
> #8 /Applications/MAMP/htdocs/CP8/modules/migrate\_tools/migrate\_tools.drush.inc(272): array\_walk(Array, '\_drush\_migrate\_...', Array)
>
> #9 /Users/JG/.composer/vendor/drush/drush/includes/command.inc(422): drush\_migrate\_tools\_migrate\_import('clinical\_trial\_...')
>
> #10 /Users/JG/.composer/vendor/drush/drush/includes/command.inc(231): \_drush\_invoke\_hooks(Array, Array)
>
> #11 /Users/JG/.composer/vendor/drush/drush/includes/command.inc(199): drush\_command('clinical\_trial\_...')
>
> #12 /Users/JG/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush\_dispatch(Array)
>
> #13 /Users/JG/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot-\>bootstrap\_and\_dispatch()
>
> #14 /Users/JG/.composer/vendor/drush/drush/drush.php(12): drush\_main()
>
> #15 {main} TypeError: Argument 2 passed to Drupal\migrate\Row::\__construct() must be of the type array, null given, called in /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Plugin/migrate/source/SourcePluginBase.php on line 357 in Drupal\migrate\Row-\>\__construct() (line 101 of /Applications/MAMP/htdocs/CP8/core/modules/migrate/src/Row.php). Drush command terminated abnormally due to an unrecoverable error.

Any ideas about what I am doing wrong?

Here is the xml source:

```
<?xml version="1.0" encoding="UTF-8"?>
<clinical_study rank="15424">
  <!-- This xml conforms to an XML Schema at:
    https://clinicaltrials.gov/ct2/html/images/info/public.xsd -->
  <required_header>
    <download_date>ClinicalTrials.gov processed this data on July 05, 2019</download_date>
    <link_text>Link to the current ClinicalTrials.gov record.</link_text>
    <url>https://clinicaltrials.gov/show/NCT00001239</url>
  </required_header>
  <id_info>
    <org_study_id>890119</org_study_id>
    <secondary_id>89-C-0119</secondary_id>
    <nct_id>NCT00001239</nct_id>
  </id_info>
  <brief_title>Combination Chemotherapy (FLAC) Combined With Granulocyte-Macrophage Colony Stimulating Factor in Locally Advanced and Metastatic Breast Cancer</brief_title>
  <official_title>Combination Chemotherapy (FLAC) Combined With Granulocyte-Macrophage Colony Stimulating Factor in Locally Advanced and Metastatic Breast Cancer</official_title>
  <sponsors>
    <lead_sponsor>
      <agency>National Cancer Institute (NCI)</agency>
      <agency_class>NIH</agency_class>
    </lead_sponsor>
  </sponsors>
  <source>National Institutes of Health Clinical Center (CC)</source>
  <brief_summary>
    <textblock>
      To evaluate a dose intensive chemotherapy regimen for the treatment of locally advanced and
      metastatic breast cancer using granulocyte-macrophage colony-stimulating factor (GM-CSF) to
      ameliorate chemotherapy-induced toxicity. Combination chemotherapy consists of Flurouricil,
      Leucovorin, Adriamycin, and Cytoxan (FLAC) which will be given every 21 days for 10 cycles.
      This protocol will replace the phase I study of this regimen (MB-232/88-C-0207) which found
      the MTD of this regimen to be at the first dose level. This is a phase II study to determine
      response rates of this regimen in advanced breast cancer.
    </textblock>
  </brief_summary>
  <detailed_description>
    <textblock>
      To evaluate a dose intensive chemotherapy regimen for the treatment of locally advanced and
      metastatic breast cancer using granulocyte-macrophage colony-stimulating factor (GM-CSF) to
      ameliorate chemotherapy-induced toxicity. Combination chemotherapy consists of Flurouricil,
      Leucovorin, Adriamycin, and Cytoxan (FLAC) which will be given every 21 days for 10 cycles.
      This protocol will replace the phase I study of this regimen (MB-232/88-C-0207) which found
      the MTD of this regimen to be at the first dose level. This is a phase II study to determine
      response rates of this regimen in advanced breast cancer.
    </textblock>
  </detailed_description>
  <overall_status>Completed</overall_status>
  <start_date>July 1989</start_date>
  <completion_date>January 2001</completion_date>
  <phase>Phase 2</phase>
  <study_type>Interventional</study_type>
  <has_expanded_access>No</has_expanded_access>
  <study_design_info>
    <primary_purpose>Treatment</primary_purpose>
  </study_design_info>
  <enrollment>100</enrollment>
  <condition>Breast Cancer</condition>
  <condition>Breast Neoplasms</condition>
  <intervention>
    <intervention_type>Drug</intervention_type>
    <intervention_name>FLAC with GM-CSF</intervention_name>
  </intervention>
  <eligibility>
    <criteria>
      <textblock>
        All stage III or clinical T3N0 or TxN2 patients must have a histologically documented
        diagnosis of breast carcinoma and evaluate disease in the breast or axilla.

        Patients with stage III must enter this protocol within 12 weeks of the initial diagnosis.

        Patients with Stage IV (metastatic) breast cancer must have histologically proven diagnosis
        and must have evaluate disease. Patients with bone-only disease may be considered eligible
        after discussion with Dr. Kenneth Cowan.

        For Stage III disease, there must be no history of prior cytotoxic therapy.

        Stage IV patients will be eligible if they have had prior adjuvant chemotherapy and/or
        hormonal therapy provided the regimen did not included adriamycin. Patients will also be
        eligible if they have been treated with one prior Phase I or II single chemotherapy agent
        on a Medicine branch protocol. Patients who have had prior radiation therapy may be
        eligible providing there was not extensive radiation to the cardiac area.

        There must be no history of previous malignancy except for cured non-melanoma skin cancer
        (basal cell carcinoma) and cervical cancer in situ.

        Performance status (Karnofsky scale) must be greater than 70.

        WBC count greater than 4000/mm3 and platelet count 100,000/mm3, unless there is evidence of
        bone marrow involvement with tumor.

        Liver function tests (SGOT, Alk. Phosph., and T. Bilil) should be less than 1.5 times the
        upper limits of normal, and serum creatinine should be less than 1.7 or creatinine
        clearance should be greater than 45 ml/min unless these abnormalities are due to tumor
        involvement.

        The patient must give informed consent.

        No pregnant patients may be entered on this study; all patients should be informed about
        the need for contraception.

        No history of other malignant neoplasms except for curatively treated basal cell skin
        cancer or surgically cured carcinoma of the cervix in situ.

        Patients must not be in poor medical or psychiatric risks because of nonmalignant systemic
        disease which would preclude them being subjected to any treatments in this protocol.

        Patients with a history of cardiac disease must have a normal ejection fraction by MUGA
        Scan and have no angina.

        Must not have evidence of CNS metastasis.
      </textblock>
    </criteria>
    <gender>All</gender>
    <minimum_age>N/A</minimum_age>
    <maximum_age>N/A</maximum_age>
    <healthy_volunteers>No</healthy_volunteers>
  </eligibility>
  <location>
    <facility>
      <name>National Cancer Institute (NCI)</name>
      <address>
        <city>Bethesda</city>
        <state>Maryland</state>
        <zip>20892</zip>
        <country>United States</country>
      </address>
    </facility>
  </location>
  <location_countries>
    <country>United States</country>
  </location_countries>
  <reference>
    <citation>Swain SM, Sorace RA, Bagley CS, Danforth DN Jr, Bader J, Wesley MN, Steinberg SM, Lippman ME. Neoadjuvant chemotherapy in the combined modality approach of locally advanced nonmetastatic breast cancer. Cancer Res. 1987 Jul 15;47(14):3889-94.</citation>
    <PMID>3036348</PMID>
  </reference>
  <reference>
    <citation>Antman K, Gale RP. Advanced breast cancer: high-dose chemotherapy and bone marrow autotransplants. Ann Intern Med. 1988 Apr;108(4):570-4. Review.</citation>
    <PMID>3279894</PMID>
  </reference>
  <reference>
    <citation>Clark SC, Kamen R. The human hematopoietic colony-stimulating factors. Science. 1987 Jun 5;236(4806):1229-37. Review.</citation>
    <PMID>3296190</PMID>
  </reference>
  <verification_date>April 2000</verification_date>
  <study_first_submitted>November 3, 1999</study_first_submitted>
  <study_first_submitted_qc>December 9, 2002</study_first_submitted_qc>
  <study_first_posted type="Estimate">December 10, 2002</study_first_posted>
  <last_update_submitted>March 3, 2008</last_update_submitted>
  <last_update_submitted_qc>March 3, 2008</last_update_submitted_qc>
  <last_update_posted type="Estimate">March 4, 2008</last_update_posted>
  <keyword>5-Fluorouracil</keyword>
  <keyword>Adriamycin</keyword>
  <keyword>Breast Carcinoma</keyword>
  <keyword>Leucovorin</keyword>
  <keyword>Phase II</keyword>
  <condition_browse>
    <!-- CAUTION:  The following MeSH terms are assigned with an imperfect algorithm            -->
    <mesh_term>Breast Neoplasms</mesh_term>
  </condition_browse>
  <intervention_browse>
    <!-- CAUTION:  The following MeSH terms are assigned with an imperfect algorithm            -->
    <mesh_term>Sargramostim</mesh_term>
  </intervention_browse>
  <!-- Results have not yet been posted for this study                                          -->
</clinical_study>

```

# Answer
Any source have to ids property. So you need define ids in your file like below:

```
  fields:
    -
      name: title
      label: title
      selector: official_title
    -
      name: id
      label: id
      selector: id_info/org_study_id
  ids:
    id:
      type: integer

```

**Note: after change file yml, you have to re-import and clear cache.**
> 2 votes

---
Tags: migrations
---


# Question
Title: Contact email flood limit is per whole system(application) or user/ip based?
I have a question with contact emails flood limit which is present in contact.settings.yml, the limit is going to for whole system(application-wide) or is it going to limit the number of emails per individual user or IP?

# Answer
> 0 votes
As you can see its number of emails a user can send in an hour

https://www.drupal.org/docs/8/core/modules/contact/overview#controlling-repeat-submission-blocking-flood-control

```
You can specify the text to display on your site-wide contact page and you can optionally limit how many times a user can submit a contact form in an hour.

```

btw, its defaults that you can override per any contact form . for example : `contact.settings.yml`

```
default_form: feedback
flood:
  limit: 5
  interval: 3600
user_default_enabled: true

```

---
Tags: emails, configuration
---


# Question
Title: Pass parameter to node twig template via url
The url to display node 100 is `<site>/node/100`. I want to pass a parameter to this node via the url. For example: `<site>/node/100/3`.

Question:

* What must I do to get Drupal 8 to see `/node/100/3` as `/node/100` with the parameter `3` instead of just the url `/node/100/3` (which fails)?

Efforts:

* I've read many posts, but didn't find any that seem to directly address this issue.
* I realize this can probably be accomplished via `/node/100?param=3`. I want to avoid using a query parameter if possible, just for cleanness.
* I realize this can probably be accomplished by displaying the node within a view and then using a contextual filter. I want to avoid using a view if possible, again just for cleanness.

# Answer
> 1 votes
try this in twig:

```
{% set url =  url('<current>')['#markup'] %}
{% set urllast =   url|split('/')|last %}
{{ urllast }}  // 3

```

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


title: Add Button to Node View

text:
# Question
Title: Add Button to Node View
I want to add custom button on node page.

I tried with `hook_node_view` but it didn't show up.

like this:

```
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

$build['mybutton'] = [
  '#type'       => 'button',
  '#name'       => 'mybutton_name',
  '#value'      => t('Click Here'),
  '#attributes' => [ 'class' => 'button button--primary'],
  '#weight'     => -11,
];

```

}

What am I doing wrong?

EDIT:

Here is the template

```
{#
/**
 * @file
 * Display Suite 2 column stacked template.
 *
 * Available variables:
 * - outer_wrapper: outer wrapper element
 * - header_wrapper: wrapper element around header region
 * - left_wrapper: wrapper element around left region
 * - right_wrapper: wrapper element around right region
 * - footer_wrapper: wrapper element around footer region
 * - attributes: layout attributes
 * - header_attributes: attributes for header region
 * - left_attributes: attributes for left region
 * - right_attributes: attributes for right region
 * - footer_attributes: attributes for footer region
 * - header: content of header region
 * - left: content of left region
 * - right: content of right region
 * - footer: content of footer region
 */
#}

<{{ outer_wrapper }}{{ attributes.addClass('ds-2col-stacked', 'clearfix') }}>

  {{ title_suffix.contextual_links }}

  <{{ header_wrapper }}{{ header_attributes.addClass('group-header') }}>
    {{ header }}
  </{{ header_wrapper }}>

  <{{ left_wrapper }}{{ left_attributes.addClass('group-left') }}>
    {{ left }}
  </{{ left_wrapper }}>

  <{{ right_wrapper }}{{ right_attributes.addClass('group-right') }}>
    {{ right }}
  </{{ right_wrapper }}>

  <{{ footer_wrapper }}{{ footer_attributes.addClass('group-footer') }}>
    {{ footer }}
  </{{ footer_wrapper }}>

</{{ outer_wrapper }}>

```

# Answer
> 0 votes
Just tried it out myself and for me it didn't work using your malformatted `#attributes` array. After I fixed it the following did work. `class` must provide another array.

```
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $build['mybutton'] = [
    '#type'       => 'button',
    '#name'       => 'mybutton_name',
    '#value'      => t('Click Here'),
    '#attributes' => ['class' => ['button', 'button--primary']],
    '#weight'     => -11,
  ];
}

```

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


title: Exposed Form in Block Missing?

text:
# Question
Title: Exposed Form in Block Missing?
I'm trying to create a view based on a Solr search index that includes a search form in a block. The view seems to be working based on the preview I see when editing the view. I have set "Exposed form in block: Yes" and "Exposed form style: Basic". The block is assigned to a region, and the block itself is rendered appropriately when the page is displayed. The problem I'm having is that the form is not displayed in the block. I see the block title, but no form and no button. What might I be missing here?

# Answer
> 0 votes
I found the solution to my problem. In addition to setting "Exposed form in block: Yes", I had to check the "Expose this filter to visitors, to allow them to change it" option for my "Search: Fulltext search" filter. The search form was properly displayed once that option was set.

# Answer
> 1 votes
Exposed filters on blocks will only work if you've enabled ajax on the view. Try enabling that and your filters should appear

---
Tags: views
---


# Question
Title: Commerce line item views with fields from content node
I have some fields on content node (not on product variation) like images, brand, and others that i want to show up in cart/order views on edit view in advance\>relationship, you can add product refference and that enables the option to add fields from product variations, but i cant find a way to add fields that are on the content node

In less words: i want to add fileds like image that are on the content type to cart/order views.

**Found a good work around:**

adding relationship you can obtain fields from product in views.

# Answer
This isn't easy, because the line item has no direct reference to the node. It does store the node URL in a textfield, but that does not a Views reference make. If you have a store where there's only one product display referencing each product, then you can get away with using a reverse product reference - i.e. starting with the line item, you reference the product, and from the product, you add a reverse reference to the "node referencing the product." Then you should be able to add fields from the product display node.

If you have multiple product displays referencing any given product, this solution might not work (unless of course each node contained the same fields you intend to pull into the View).
> 2 votes

# Answer
Using Commerce Kickstart 2, I was able to accomplish this, sort of, by creating a taxonomy term "product\_sku" and adding an image field to the term.

Then I created all of my base sku(s) there with the corresponding image.

I added my "product\_sku" term to my variant type fields as a term reference and added to the display my image as an extracted field.

Now when I create a new variant, I just select the sku from the drop-down list instead of uploading an image.

This could easily get muddy if you have 1000s of products even without variants. I only have 200 or so but each one has 28 +/- variants(color) and some of those have additional options.

I've used the same approach for the color swatches so when it comes to creating the variations, 120 for one of my products(?AUTO-VARIANT CREATOR?), I don't have to upload anything. This also works in the content type. I use it for manufacturer and model reference terms in the catalog and to display attached logo and model images.
> 0 votes

# Answer
I did this with this method edit cart views(or you can did it in your views but my requirement was in cart views) add relation to product reference( I want get product id) then add php field in views, create a function in my custom module and call it in added php field (also cache it for better perfomrance :D )

```
function mymodule_get_nid_of_pid($pid){
  if ($cache = cache_get('nid-product-' . $pid)) {
    $data = $cache->data;
  }
  else {
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'products')
  ->fieldCondition('field_product_select', 'product_id', $pid)
  ->propertyCondition('status', 1)
  ->range(0,1)
  ->execute();
  if(array_keys($result['node'])){
  $data = current(array_keys($result['node']));
  cache_set('nid-product-' . $pid, $data, 'cache', REQUEST_TIME + (3600 * 24 ));
  }
  return $data;
}

```
> 0 votes

# Answer
To achieve this in views, you have to add a relationship named "Commerce Line item: Referenced products" and it will fetch field from your product node.
> 0 votes

---
Tags: 7, nodes, commerce
---


# Question
Title: How to manage patches in composer when they're merged into the module?
I'm building a Lightning BLT project and recently the deploy:build failed because the features module merged a patch composer.json was set to apply.

Is there a way to indicate to composer that the patch is already applied and to skip it?

**Edit**

Is there a way for composer to know *programmatically*, perhaps from the module code itself, that the patch has been applied?

# Answer
> 1 votes
Composer-Patches: https://github.com/cweagans/composer-patches

> Simple patches plugin for Composer. Applies a patch from a local or remote file to any package required with composer.

Example composer.json:

```
{
  "require": {
    "cweagans/composer-patches": "~1.0",
    "drupal/drupal": "~8.2"
  },
  "config": {
    "preferred-install": "source"
  },
  "extra": {
    "patches": {
      "drupal/drupal": {
        "Add startup configuration for PHP server": "https://www.drupal.org/files/issues/add_a_startup-1543858-30.patch"
      }
    }
  }
}

```

Error handling:

> If a patch cannot be applied (hunk failed, different line endings, etc.) a message will be shown and the patch will be skipped.
>
> To enforce throwing an error and stopping package installation/update immediately, you have two available options:
>
> 1) Add "composer-exit-on-patch-failure": true option to the extra section of your composer.json file.
>
> 2) Export COMPOSER\_EXIT\_ON\_PATCH\_FAILURE=1 By default, failed patches are skipped.

# Answer
> 4 votes
Run your deploy build locally and if a patch fails during composer up and you see that it has already been integrated into the module, then delete the patch from composer.json.

---
Tags: 8, composer, version-control
---


# Question
Title: Restrict access to ECK full page, but allow embedded
Following the Lullabot article on how to embed anything in a wysiwyg with Entity Embed and friends we're using this to embed a custom entity type created with ECK (Entity Construction Kit).

The permissions for ECK require anonymous users have the "View My Entity" permission in order for it to appear in the embedded scenario. However ECK also provides a full page URL at `/my_entity/{id}`, but we want to restrict access and not index the full page, because the content will always be embedded inside other Articles.

I've already implemented the Metatag module for this entity to add the robots noindex meta tag. However the ideal case would be to restrict the ECK full page URL `/my_entity/{id}` to administrators only. How can this be done, when these entity types are dynamic and don't have a canonical route.

# Answer
It turns out that though the entities created by ECK are dynamic, they do have route definitions, so we can use this to restrict access, in a hook\_preprocess\_page placed in a custom module. Also worth noting that the administrative list display at `/admin/content/my_eck_entity` is visible to anonymous users when you set the `view my_eck_entity entities` permission to anonymous users, so we must also look out for this route as well.

```
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Prepares variables for page.html.twig.
 */
function mymodule_preprocess_page(&$variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();

  // Restrict access to ECK canonical full page display and the entity
  // administration list screen to content authors. Restricting full page
  // display helps to avoid mistakenly indexing the content in search engines
  // because these entities are only ever going to be seen by anonymous users
  // when embedded into other pages via WYSIWYG embed or rendered entities
  // from entity reference fields on other node types.
  $user = \Drupal::currentUser();
  $restricted_eck_entities = [
    'my_eck_entity', // Replace this with real entity type machine name!
  ];
  foreach ($restricted_eck_entities as $eck_entity) {
    if (
      (
        $route_name === "entity.$eck_entity.canonical"
        || $route_name === "eck.entity.$eck_entity.list"
      )
      && !(
        $user->hasPermission("create $eck_entity entities")
        || $user->hasPermission("edit $eck_entity entities")
      )
    ) {
      throw new AccessDeniedHttpException();
    }
  }
}

```
> 0 votes

---
Tags: 8, entities
---


title: Update enabled migration module

text:
# Question
Title: Update enabled migration module
I enabled a migration module. Now I would like to make some changes inside the yml file. How can I update my migration? I use migration plus.

# Answer
You could do a partial configuration import and then a cache rebuild

```
drush cim --partial --source=modules/custom/MY_MIGRATION_MODULE/config/install -y
drush cr

```
> 0 votes

---
Tags: migrations
---