# Question
Title: Upgrade breaks Rest Export View in Calendar
We have a website that uses Views with a serializer rest export to display events on a monthly calendar. When we upgraded from 8.6.16 to 8.7.3 the calendar display is blank. All the json information displays in the view preview, and using console.log I can see the information load on the page. I can load events in a normal view without any issues. I've spent several days trying to figure out what change may have caused this, my leading theory is that something with date formatting may have changed somewhere, but so far, no luck. Does anyone have any documentation about a date format change between Drupal 8.6 and 8.7?

EDIT: I just noticed the difference by exporting the views preview and running a diff on them. The live site displays dates correctly like this `"value":"2019-06-27T00:30:00` while the updated dev site displays dates like this `"value":"2019-06-26T17:30:00-07:00"` so could something have changed with time zone translations or date fields that is interfering with our code?

# Answer
My edit gave me a clue to look at the date formatting. In our specific calendar instance there is an event-calendar.js file that was manually converting the dates pre-Drupal 8.7 to UTC with a `.field_date_range[0].value+'+00:00',`. It appears that Drupal 8.7 does this automatically, so removing that extra bit of code solved the issue and dates are being populated into the calendar correctly now.

EDIT: For those interested, I was finally able to find the drupal documentation about this change in 8.7 here
> 1 votes

---
Tags: views, 8, datetime
---


# Question
Title: no search_api_solr results when search term ends with number
I have search\_api\_solr with views (I use as external Solr server https://hostedapachesolr.com. )

There is this strange issue:

1/ When I search for **951**, there are correct results

2/ When I search for **V951L**, correct results

***3/ BUT ... when I search for *V951*: there are NO results at all ...***

This weird behavior stays the same, even when I alter the "views" settings or the search\_api\_solr settings. It's like the system is confused that the search term begins with a letter and ends on numbers.

Does anybody knows how to fix this ?

Best regards

# Answer
I would try this.

Go into The solr server configuration - assuming it's named 'solr' /admin/config/search/search-api/server/solr/edit

In Advanced, see if "Targeted content domain" is set to scientific. And see the description next to it to see why I'm thinking this might be your issue.

Save. You'll probably need to re-export your config zips and definitely need to clear and re-index.
> 0 votes

---
Tags: views, search
---


# Question
Title: How to query external database for Count
How do I query the below SQL query to an external database table from Drupal 8 custom module,

```
Select Count(requestID) FROM requestDB.request where request.dateCreated >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) and ek_borrowerID = 111;

```

I have configured the settings.php already. Below is the query I tried to build, but it does not work

```
Database::setActiveConnection('requestDB');
$db = Database::getConnection();
$db->select('request')
    ->fields('request', array('Count(requestID)'))
    ->condition('dateCreated','DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)', '>=')
    ->condition('ek_borrowerID','111')
    ->execute();
Database::setActiveConnection();

```

# Answer
You're not selecting the default database for the new connection.

Try:

```
$select = Database::getConnection('default', 'requestDB')->select('request');
$select->addExpression('Count(requestID)', 'rec_count');
$select->condition('dateCreated','DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)', '>=');
$select->condition('ek_borrowerID','111');
$select->execute();

```

With this method you dont need to switch back to your original database as this just creates a temporary connection.

Also you need to use addExpression for your count as mentioned by Charles Bamford below
> 1 votes

# Answer
You need to use -\>addExpression() instead of -\>fields()
> 1 votes

---
Tags: 8, database
---


# Question
Title: Why do I get "Type does not correspond to an entity on this site" when POSTing to REST api behind an Apache Reverse proxy?
I have the REST api configured to allow POSTing new users to `/entity/user`. On my local machine, it works just fine. Once I push up to my remote host, it stops working.

The key difference is that on my local machine, my site is running in a docker container bound to port 6050, so all rest calls go to `localhost:6050`.

On my remote host, I have docker configured behind an Apache 2.4 reverse proxy. So the docker container is still bound to `127.0.0.1:6050`, but all requests should go to `https://sub.example.tld/`.

To summarize, posting a new user to `http://localhost:6050/entity/user?_format=hal_json`, with the appropriate `X-CSRF-Token` and `Content-Type` headers set, works. It returns **200**.

Posting to `https://sub.example.tld/entity/user?_format=hal_json`, with the appropriate `X-CSRF-Token` and `Content-Type` headers set, does not. It returns **422 Unprocessable Entity**.

```
{"message":"Type https:\/\/sub.example.tld\/rest\/type\/user\/user?_format=hal_json does not correspond to an entity on this site."}

```

In the recent log messages, I see:

```
Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException: Type http://sub.example.tld/rest/type/user/user?_format=hal_json does not correspond to an entity on this site. in Drupal\rest\RequestHandler->deserialize() (line 201 of /var/www/html/web/core/modules/rest/src/RequestHandler.php).

```

I do manually set the user's "\_links" array:

```
"_links": {
        "type": {
          "href": "https://sub.example.tld/rest/type/user/user?_format=hal_json"
        }
      },

```

I know that authentication isn't the issue. My code is successfully accessing views that require authentication.

Since I think it might be something to do with these settings, I do have the following set:

* `$settings['trusted_host_patterns'] = ["$sub\.example\.tld$"]`
* `$settings['reverse_proxy'] = TRUE;`
* `$settings['reverse_proxy_addresses'] = ["internal network ip","172.18.0.1","127.0.0.1"];`

I'm running Drupal 8.7.3.

My docker image is based on php:7.1-apache.

Any ideas what I'm doing wrong?

# Answer
> 3 votes
The solution is to remember set the base url of any \_links href values to use http if Drupal expects it, and https if Drupal, instead, expects that.

In my case, I was using https, but the https connection was terminated at the Apache reverse proxy, so Drupal wanted http.

Using a REST extension to test with let me manually change the links array to reflect that, and the user was created just fine.

Also, the "type" href should not have the `_format=hal_json` on it.

---
Tags: 8, users
---


title: CKEditor configuration is not working

text:
# Question
Title: CKEditor configuration is not working
In my site it was not required to add color to text or change its size, but now we want to add formatting to our posts.

So I tried to configure CKEditor's Toolbar to add text formatting options in Drupal administration page, and after I added that, I see no changes in my CKEditor, new options weren't added.

How could I add that options?

Thanks in advance for your help

# Answer
A few things you can try:

1. Make sure that when you are editing or creating new content that the "Text Format" selection box at the bottom of the WYSIWYG editor shows the same profile that you edited. On my site an advanced user can be allowed to choose from Filtered or Full HTML, and by default the Filtered HTML profile is loaded (thus they wouldn't immediately see changes to the "Full HTML" profile).
2. You can try clearing your cache if you haven't already.
3. I understood your question as not seeing the new options in the Toolbar, but if your issue is that you are not seeing something like bolded or larger font upon saving, it may be that you need to create an exception to a specific HTML tag in your "Advanced Content Filter" and/or the "Cleanup and Output" settings under your CKEditor profile options (/admin/config/content/ckeditor/ in Drupal 7).
> 0 votes

---
Tags: configuration
---


title: No way to install or add libraries?

text:
# Question
Title: No way to install or add libraries?
I've been trying to set up a site on Acquia for a good 3 days now, and am baffled - Acquia doesn't allow Composer, the Acquia Dev Desktop does not sync libraries. I've tried ludwig with no luck.

Is there any way to add csv/league libraries to Acquia? W/o this capability, I'm not sure how useful Acquia is, or am I missing something simple?

# Answer
> 1 votes
Acquia has to have the full site, core, modules, themes, libraries, et.al. checked into their git repo in the format like:

```
git root
  docroot
    core
    modules
    themes
    etc.
    (includes index.php and other root files)

```

As Clive said, there is a pay for it CI process. However, for the normal sites, you need to manage the site as a whole entity. They do have Deployment hooks, but that is generally for clearing cache and the like.

FYI - I use composer on all my sites. You run it locally and check in the composer files to the repo (e.g. the composer.lock, etc.). Things like js libraries are added by manually adding repo's to the composer.json file if they are not composer friendly. E.g., here's how the jquery chosen plugin gets added:

```
"harvesthq.chosen": {
  "type" : "package",
  "package" : {
    "name" : "harvesthq/chosen",
    "version" : "1.8.7",
    "type" : "drupal-library",
    "dist" : {
      "url" : "https://github.com/harvesthq/chosen/releases/download/v1.8.7/chosen_v1.8.7.zip",
      "type" : "zip"
    },
    "require" : {
      "composer/installers" : "^1.2.0"
    }
  }
},

```

It's also best to have the Drupal friendly paths defined in your composer file. E.g.:

```
"extra" : {
    "installer-paths" : {
        "docroot/core" : [
            "type:drupal-core"
        ],
        "docroot/libraries/{$name}" : [
            "type:drupal-library"
        ],
        "docroot/modules/contrib/{$name}" : [
            "type:drupal-module"
        ],
        "docroot/themes/contrib/{$name}" : [
            "type:drupal-theme"
        ]

```

These make sure things get placed properly by composer.

# Answer
> -1 votes
Acquia dev desktop comes with composer and drush installed already.

You can also install composer on your machine by following the instructions here: https://getcomposer.org/download/

There is a good tutorial here to get you set up with a Drupal 8 site package built with composer here: https://www.youtube.com/watch?v=IhWAegz8glk

The github project for that Drupal 8 composer package is here: https://github.com/drupal-composer/drupal-project

You can then open a command window in devdesktop/Sites/your-new-d8-site/Web *(the root of the site you are building in dev)* and then run for example `composer require "drupal/commerce"` This will pull in all the dependencies (and libraries) for Drupal Commerce 2 very easily without fussing with ludwig. it's very fast and easy.

Also here is a good video here on installing modules with composer: https://modulesunraveled.com/drupal-8-composer-and-configuration-management/installing-and-uninstalling-modules-composer

Hope this helps!

---
Tags: 8, acquia-cloud
---


# Question
Title: Custom checkout pane for order comments not saving
I've created a custom checkout pane for commerce 2.x, Drupal version 8.7.x. I've added a textfield called `field_order_notes` on the order entity. The pane works, and I can run `$this->order->set('field_order_notes', $values)` in my pane's submit handler, and I can debug the order object and see the value's set. But when i finish the order, `field_order_notes` is empty on the order. Not sure what I'm missing here.

```
 /**
 * Adds a section for order notes.
 *
 * @CommerceCheckoutPane(
 *   id = "order_notes",
 *   label = @Translation("Order notes"),
 *   default_step = "order_information",
 * )
 */
class OrderNotes extends CheckoutPaneBase implements CheckoutPaneInterface {
  /**
   * The inline form manager.
   *
   * @var \Drupal\commerce\InlineFormManager
   */
  protected $inlineFormManager;
  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, CheckoutFlowInterface $checkout_flow, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $checkout_flow, $entity_type_manager);
  }
  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form['order_notes'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Order notes'),
      '#default_value' => $this->order->get('field_order_notes')->getString(),
      '#required' => FALSE,
    ];
    return $pane_form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
    $values = $form_state->getValue($pane_form['#parents']);
    $this->order->set('field_order_notes', $values);
  }
}

```

# Answer
This was fixed by passing `['order_notes']` into `$values`.

```
 /**
   * {@inheritdoc}
   */
  public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
    $values = $form_state->getValue($pane_form['#parents']);
    $this->order->set('field_order_notes', $values['order_notes']);
  }

```
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: Set a boolean (single on/off checkbox) value while creating a node
I am creating a node (in Drupal 8) with the following code.

```
use \Drupal\node\Entity\Node;

$node = Node::create([
            'type' => 'calendar_data',
            'title' => 'testing finaly 1111111111111111111111111 ',
            'field_current_month' => date('Y-m-d'),
            'field_date_type_value' => '1',
        ]);
$node->save();

```

The value of field\_date\_type\_value is set to 0, not the expected value (1) I am using in the code.

# Answer
> 0 votes
Sorry for late response, but I had the same problem few days ago. What worked for me was first of all creating the node and then setting the boolean value:

```
$node = Node::create([
  'type' => 'calendar_data',
  'title' => 'testing finaly 1111111111111111111111111 ',
  'field_current_month' => date('Y-m-d'),
]);
$node->field_date_type_value->value = TRUE;

$node->save();

```

The 'inline' field setting didn't work neither for some other fields for me. But the explicit version is working very well.

# Answer
> 0 votes
Try

```
$node = Node::create([
        'type' => 'calendar_data',
        'title' => 'testing finaly 1111111111111111111111111 ',
        'field_current_month' => date('Y-m-d'),
        'field_date_type_value' => ['value' => '1'],
    ]);

$node->save();

```

---
Tags: nodes
---


# Question
Title: How can I display custom data from the database in a View?
I'm working to create a new website in Drupal 8 and cannot figure out how to reference custom table data within a View.

Specifically, I have a script that is taking data from an external DB and populating it into my Drupal DB into custom tables. How can I allow Views to see this data?

In Drupal 7 I have experience using the Forena module and the Data and Schema modules to accomplish same DB and external DB references, but what I'm finding is that support for these three modules in Drupal 8 appears to be lacking, making me think that there is a better way to do this in D8 that everyone knows about but me. :)

I'm not sure if I'm just not researching correctly, but I'm unable to find a clear answer about how to go about obtaining this functionality in Drupal 8. Drupal 8 is so different and I'm not sure if I should be looking for a contributed module or if this is something I would code directly.

Hopefully someone can point me in the correct direction?

# Answer
> 1 votes
Ok, yeah, I feel a bit silly now and was making this too difficult. There is a module for this for Drupal 8!

I was able to accomplish what I needed with Views Custom Table.

Thank you prkos for the comment.

---
Tags: views, 8, database
---


# Question
Title: Handling anonymous orders in custom commerce module
Drupal: 8.7.2 Commerce: 2.13

I have a custom module set up that adds the following functionality to Commerce:

1. It prevents the user from adding more than one item to their cart. If they try to add a second item, it removes the first item from their cart and adds the second item.
2. When clicking "Add to Cart", it redirects the user to a confirmation page.
3. On that page is a button that links to the order's checkout page.

I am handling all of these via queries that use the user ID and order ID to pull the correct order/cart information.

This all works great for logged in users. Most of our customers will be anonymous, though. It does work for anonymous users, but my concern is that if multiple anonymous users are placing orders at the same time, their carts will get mixed up, because all anonymous users have a UID of 0.

How can I better differentiate between anonymous user's carts? Is there a way to store their IP in the database, and then use that?

Here is my module's code:

commerce\_custom.module (handles removing first item from cart, redirecting to confirmation page):

```
<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_order\Entity\Order;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function commerce_custom_form_commerce_order_item_add_to_cart_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $form['actions']['submit']['#value']='Sponsor';
   $form['#validate'][] = 'commerce_custom_form_validate';
   $form['actions']['submit']['#submit'][] = 'commerce_custom_cart_alter_redirect';
}

function commerce_custom_form_validate(array &$form, FormStateInterface $form_state) {

    $user = \Drupal::currentUser()->id();
    $connection = \Drupal::database();
    $query = $connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft'", [':user' => $user]);
    $result = $query->fetchAll();
    //dpm($result);

    $cart_count = $result[0]->quantity;
    $order_id = $result[0]->order_id;

    if ($cart_count > 0 && $order_id) {
        $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($order_id);
        $items = $order->getItems();
        foreach($items as $item_key => $item) {
            $order->removeItem($item);
            $item->delete();
        }
    }
}

function commerce_custom_cart_alter_redirect(&$form, FormStateInterface $form_state) {
  $responce =  new RedirectResponse('/how-it-works');
  $responce->send();
}

```

ContinueCheckoutBlock.php (creates block with button linking to checkout page):

```
<?php

namespace Drupal\commerce_custom\Plugin\Block;
use Drupal\Core\Block\BlockBase;

class ContinueCheckoutBlock extends BlockBase {

   public function build() {

        $user = \Drupal::currentUser()->id();
        $connection = \Drupal::database();
        $query = $connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft'", [':user' => $user]);
        $result = $query->fetchAll();
        $order_id = $result[0]->order_id;

        return array(
            '#type' =>'markup',
            '#markup' => '<a href=checkout/' . $order_id . '/order_information class=button>Continue</a>',
        );
   }
}

```

# Answer
> 0 votes
Perhaps you could use PHP's `session_id()`?

> session\_id() is used to get or set the session id for the current session.

Basically copied from this answer.

---

You may also find useful information here: *Anonymous Personalization Without Leaving Drupal*, which appears to be a topic from DrupalCon Seattle 2019.

---
Tags: commerce
---


# Question
Title: Performance for file serving and storage
I intend to allow users to upload images to my website, but I'm concerned that Drupal's default handling of files might not be cut out for storing and serving potentially thousands of files without bogging down. Should all files be stored in the same directory? Should I use something like amazon instead of the same server the website is stored on?

What are the best practices for serving images, potentially thousands or tens of thousands, through a Drupal 7 site? Is it reasonable to expect Drupal to perform well if I just leave it the file handling as is?

# Answer
> 2 votes
If you are storing them the public file system, Drupal does not really interact with them other than to provide the URL. The .htaccess rules check if the request is for a real file. If it is a real file, the web server service it up.

So for individual files, it is more about can your webserver handle the load. You probably want to look at using a static file caching service in front of your site. CloudFlare does a good job and its basically free. Some alternates are to have a varnish server or a caching Nginx server in front of your server.

Drupal has been used for a lot of sites with a lot of users, files and the like. E.g. I know that Story Corps uses it internally to manage the thousands (millions) of interviews they have.

Just be aware that if you need to have a large volume site, you will need to plan for a large volume system setup. This is true of ANY web software you use.

---
Tags: 7, media
---


# Question
Title: how to remove duplicate in view search API?
I get some duplicate article for the site. How can i remove the duplicate? There is no distinct setting. Here is the setting of view

# Answer
> 1 votes
Depending on your setup there are different reasons why you can get duplicates. A common reason is, that you're using related entities (nodes, taxonomies). Let's say you got a content type car with a taxonomy term that shows the car's color. If you create a relationship between car and color in your view, you can see duplicates if a car has multiple colors.

There are three different options that allow you to reduce duplicates.

In the view's ADVANCED tab you can find USE AGGREGATION and QUERY SETTINGS. Try out which of them works for your use case.

Inside QUERY SETTINGS you can find the DISTINCT option.

If you enable USE AGGREGATION your fields and filters will receive a new option AGGREGATION SETTINGS where you can define the type of aggregation (ie. Group results, Minimum, Maximum, etc.)

When you add fields to your FILTER CRITERIA there is another setting to prevent duplicate entries when a filter is applies.

But beware, complex views tend to get slow when aggregation is enabled.

---
Tags: search
---


title: Customize the title field

text:
# Question
Title: Customize the title field
I want to display updated content's field with views block on the front page.

```
2019/06/20 newly posted content1-title
2019/06/19 updated content2-title

```

The words `updated` and `newly posted` before the title want to customize according to whether the content was first posted or updated. My code is as follows.  However, even at the time of initial content posting, durpal has different created and changed timestamps, which is not the expected result.
Is there are good ways? Thanks.

# Answer
Views module comes with the field **`Has new content`** that outputs `New` or `Updated` depending on the status of the node as being viewed by a visitor.

Anonymous visitors don't see anything because there is no history record about that users visits to a particular node.

Authenticated users will see the word `New` if they never visited that node. If they have visited that node in the past, but the node has been updated in the meantime, they will see `Updated`. Once they visit the node again, they won't see any output for that field.

So this doesn't work quite as you described in your question, but it still may be what you're after.

You can add that field to your Views, Exclude it from display, and then Rewrite the Title field to include it before the actual title text.

The way you've written your condition in the screenshot is criss-crossed, you're trying to output "updated" for nodes that are new (at least according to your logic of those times being equal).

Your rewrite would also *always* show output for *all* nodes, even the ones the visitor has seen. Visitors usually don't expect that to behave like that. That's why it makes more sense to use `Has new content` field, but it all depends on your project and your visitors' expectations.

The created and updated time always differ because the created time is the one when the Create node form was loaded in the browser, and the updated time is the actual time when the Save button was hit, when the node was actually saved. The difference in created and updated times is the time it takes to fill in the form ;)
> 0 votes

# Answer
You can 'hide the title' field from the display and afterwards create a php field. The php field can reference the title field if it is declared higher in the list than the php block and then you can use php for your condition.
> 0 votes

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


title: Field collection translation

text:
# Question
Title: Field collection translation
My site has a number of content types that have Field Collection fields. All of these field collection fields allow more than one value.

I've marked the content types as translatable, and the field collection fields as well. It does not work though; changes to translations are also visible in the original language.

Field collection is obviously an entity reference of sorts, and adding a new translation does not appear to link the field to a newly created entity, but the same one.

How do I fix this? Is this a configuration issue, or is this a bug?

# Answer
For the record, if other people have a hard time figuring how the translation in Field Collection works, here's what I found out:

**It does not work.**

There is an issue here: https://www.drupal.org/node/2618016 that provides a patch to add support, but does not retroactively add translation support to existing field collections. If your site already has field collections you are SOL - and in my case the whole site becomes non-functional.

I'm now looking into migration towards paragraphs, but not sure how to migrate my data. Will update when I have a good solution.
> 2 votes

# Answer
It works if you are using latest Drupal-fc module and define from the creation of the content type as translatable. If you already created fields and then make the CT translatable, it does not work, maybe because its schema does not expect it to be translatable when field was created.

I have successfully edited multilingual values for same node in FC fields, the only thing that still does not work well is that when you delete the translated node, the FC Fields become empty in origin node and viceversa.
> 1 votes

# Answer
> Both - ***node's field\_collection field and field\_collection's inner fields should be translatable***. Otherwise you will have same field values for different languages.
>
> If values already exists then you need to manually set language from **und** to **en** then duplicate the whole table and set the **new** language from **und** to your desired\` for example **'hy'** =\> 'Armenian', **'ar'** =\> 'Arabic'.
>
> **All your field\_collection\_item's fields (looks like this - field\_collection\_item\__field\_title)** and your **field\_collection\_item\_revision's fields (looks like this - field\_collection\_item\_revision\__field\_title)** values in that tables should also be duplicated with the same logic.
> 0 votes

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


# Question
Title: How to disable creation of node revisions on programmatic node update?
I added a field of type computed field to existing nodes. It's required to re-save the nodes to set/update computed field values. As I do not want to update the changed timestamp I decided to not use the views bulk update to resave content. The easiest way would be a drush script, that way I can re-save content whenever it is necessary.

My first problem was that I was not able to leave the changed time unchanged on update ($node-\>save()). But I found that it could be re-set on a second node save.

My problem is that on each node save a new revision gets created. The node type is revision-able and beside the core module content moderation is enabled. I would appreciate any help on how to prevent the creation of revisions.

This is my current drush script in custom\_helper.drush.inc:

```
<?php
/**
 * @file
 * Provides drush command to update all articles.
 */

use Drupal\node\Entity\Node;

/**
 * Implements hook_drush_command().
 */
function custom_helper_drush_command() {
  $items = array();
  $items['custom-resave-content'] = array(
    'description' => dt('Resaves all article entities.'),
    'options' => [
      'types' => dt('Coma separated list of content type to be resaved.'),
      'nids' => dt('Coma separated list if node ids.'),
      'field' => dt('Machine name of computed field to be updated.')
    ],
    'aliases' => array('custom-rc'),
  );
  return $items;
}

/**
 * Moves paragraphs into one paragraph reference field.
 */
function drush_custom_helper_custom_resave_content() {
  $nids = _convert_csv_to_array(drush_get_option('nids', []));
  $types = _convert_csv_to_array(drush_get_option('types', []));

  if (!$nids || $types) {
    // Get an array of node IDs.
    $query = \Drupal::entityQuery('node');
    if ($types) {
      $query->condition('type', $types, 'IN');
    }
    if ($nids) {
      $query->condition('nid', $nids, 'IN');
    }
    $nids = $query->execute();
  }

  // Load all the nodes.
  if ($nids) {
    $field_name = drush_get_option('field', '');

    $nodes = Node::loadMultiple($nids);
    foreach ($nodes as $node) {
      $entity_type = $node->getEntityType();
      $original_changed = $node->getChangedTime();
      if ($entity_type->isRevisionable()) {
        $node->setNewRevision(FALSE);
      }

      // Force update of computed field.
      if ($field_name) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $items */
        $items = $node->get($field_name);
        if (empty($items[0])) {
          $items->appendItem();
        }
        $items->preSave();
      }

      // Save the updated computed field value.
      $node->setChangedTime($original_changed);
      if ($entity_type->isRevisionable()) {
        $node->setNewRevision(FALSE);
      }
      $node->save();

      // Reset changed time to original value.
      $node->setChangedTime($original_changed);
      if ($entity_type->isRevisionable()) {
        $node->setNewRevision(FALSE);
      }
      $node->save();

      $changed_after = $node->getChangedTime();
      drush_print('node:' . $node->id() . ':' . $original_changed . ':' . $changed_after);
    }
  }

  drush_log(dt('Resave finished.'), 'ok');
}

```

# Answer
Right now, this isn't possible with content moderation installed without doing backflips such as replacing the moderation handler for the node entity type.

This is however being worked on! Here are some issues which are relevant to the problem you are having:

The proposal is essentially two pronged:

* Better describe to callers of `SynchronizableInterface::setSyncing()` when it's appropriate to mark an entity as "syncing".
* Encourage implementors of entity lifecycle hooks to reduce disruptive side effects while entities are syncing.

Quoting myself from the issue:

> IMO, the current 'syncing' status for content entities is shaping up into a flag to indicate that a save is happening under conditions which are outside of a typical user initiated content update and that as much as possible, side effects from that save should be limited. Examples might be:
>
> * Deploying a workspace.
> * Batch updating old revisions.
> * Running an update from a migration.
>
> After defining some of those scenarios it becomes easier to rationalise eliminating some of the side effects that have been discussed (CM revision handling + changed timestamp).

In your case, you are attempting to resolve integrity in your model by bulk updating existing entities/revisions, it's outside a standard editorial based content change, so in my opinion it fits very clearly within the semantics that are being proposed for content entities and this interface. So with a few of these patches applied your code sample might look like:

```
  $node->setSyncing(TRUE);
  $node->save();

```

And then the changed timestamp wouldn't be updated and content moderation wouldn't force the creation of a new revision.
> 9 votes

---
Tags: 8, nodes, drush
---


# Question
Title: Getting PHP extension "gd" and Database support disabled error
I am trying to install Drupal 8.7.3 on my windows machine through the Xampp (PHP 7.3.6). But I am getting following errors:

# Errors:

Please see the screenshot: https://snag.gy/06sMEa.jpg

# Tried to attempt:

I tried to do the following but couldn't resolve it:

1- I have copied php.ini under the root of my drupal folder and made sure that extensions are enabled. and I made sure the default php.ini has the same extensions enabled as well. Please see the screenshot: https://snag.gy/nN8BGA.jpg

2- I have also downloaded the php\_gd2.dll and php\_gd.dll and put them to the /ext folder as well. please see the screenshot: https://snag.gy/RHqrlI.jpg

My problem still the same. Can you please help me to sort this issue out.

This is my phpinfo() result about the extensions: https://snag.gy/ifsIjo.jpg

Also, see the extension path: https://snag.gy/Jlcw01.jpg

# Answer
Long ago I came to my belief that even when a web engine says it can run on Windows... avoid if possible. Follow the herd.

These are not Drupal issues. This is an environment issue. You would probably be better off using Laravel's homestead virtual machine to host your Drupal site locally (and it would be on a linux environment inside of your windows environment).

Or if you want to focus on development and non system administration tasks, find a hosting provider that will tackle things like this for you. I have hosting companies that I would just email them requests to install the missing modules and they would do it for me.
> 0 votes

---
Tags: installation
---


# Question
Title: Display Suite Token Fields in Custom Block Types
I want to add a Display Suite token field to my Custom Block Type.

1. I have a custom block type.
2. I created a token field with Display Suite
3. Entities: Block Content
4. Limit field `*|*` or `link_card|*` where link\_card is the machine name of my custom block type

I expect to be able to go to Manage display of my custom block type and see the token field I created, but it's not there. I have successfully made token fields and added them to Content Types.

What am I missing?

--

UPDATE: Whatever this was, it resolved itself. Shrug!

# Answer
Does it work when you don't limit?

And just to be double sure.... you have got to Structure \> Block Layout \> Types \> (actual type) \> Manage Display. And once there, in the bottom area where it says "Layout for basic in default", you selected a "Select a layout" of something other than "-None-". Because the fields won't show until you select a Display Suite layout.
> 2 votes

---
Tags: 8, blocks, display-suite
---


# Question
Title: Which files do I need to edit to alter webform #states with hook_form_alter?
I need to create #states conditions between either the fields in any one element in a webform or across other elements in the same form. I'd hoped I could do it via the WF yaml editor but it seems I couldn't \[1\]. As per @jrockowitz 's comment on the attached link #1, I

> might be able to use a form alter hook to add the needed #states

I am not a developer but it seems with drupal 8+ I do need to learn to start to be one and that's on my list for sure. I'd love to be able to contribute something to Drupal and especially webform but I find the learning process intimidating especially with the lack of "beginner-type" tutorials at least when it comes to creating custom modules with more than "hello world!".

For now, **I need to know the steps I need to follow @jrockowitz 's advice and use hook\_form\_alter to serve my goal**. My understanding is that could be done either on a theme level or custom module level (please correct me if wrong) and since I'm more comfortable with the theme way and I feel it's simpler for someone like me, I like to know (at least):

1. which files ( other than MYTHEME.theme) I need to edit or/and create to start with and
2. what info do I need to look for and study so I can do the job and begin my learning journey.
3. I learn best by example and so any extra clear a-b-c type tips to get me started is greatly valued if any.

**If the custom module way is more advisable or the only way:**

1. What is the minimal skeleton of a custom module that I need to have for the purpose.
2. What do I need to study to learn how to create such a module.

(I'm not sure if the last question should be a separate question so please forgive my newbie status here but I promise I've done my best)

Thanks so much everyone

**A sample of what I want to achieve:**

```
some_question:
  '#type': tableselect
  '#title': 'some question'
  '#options':
    q1: 'q1 (hide if q2 is checked)'
    q2: 'q2 (hide if q1 is checked)'
    q3: q3
    q4: q4
    q5: q5
    q6: q6
    q7: q7

```

Related links:

\[1\] Why isn't my custom Form API #states applied in my webform yaml editor working?

\[2\] https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook\_form\_alter/8.7.x

\[3\] https://www.jrockowitz.com/blog/add-ons

# Answer
> 0 votes
Ok, if you need to rely on custom dev, you can indeed use `hook_form_alter()`.

It would work if you set it in your mytheme.theme file but for unrelated theme issues I prefer to rely on custom modules. To create your module:

* Create a `mymodule.info.yml` file in the folder /modules/custom/mymodule of your Drupal website. See this page for providing your file with the minimal content to have your module detected by Drupal.
* With only this file you should be able to enable your module
* Create a `mymodule.module` file at the same level as your .info.yml file
* In your .module file (or mytheme.theme if you chose not to create a module), add the following:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Target your form
  if($form_id == "your_form_id") {
    // Use Devel Kint module to display the architecture of your form and make it easier for you to find the elements you wish to alter
    kint($form);
    // Now you can access the elements of your form and edit the desired ones

    // Hide checkbox "my_checkbox_name" if checkbox "my_other_checkbox" is checked
    $form['my_checkbox_name']['#states'] = array(
      'invisible' => array(
        ':input[name="my_other_checkbox"]' => array('checked' => TRUE),
      )
    );
    // Make field "some_input_text" required if input field "some_other_input" is filled with value 'hello'
    $form['some_input_text']['#states'] = array(
      'required' => array(
        ':input[name="some_other_input"]' => array('value' => 'hello'),
      )
    );
  }
}
```

I recommend you to have a look at this page for the list of available #states and some examples as well.

Happy coding!

---
Tags: 8, webforms
---


# Question
Title: Remove the cache for a particular Twig file
I'm showing the name of the currently logged-in user in header, using `\Drupal::currentUser()->getUsername()`, but it's showing an already cached page. I know I can disable the cache for a particular page using `\Drupal::service('page_cache_kill_switch')->trigger()`, but this won't work with the header.html.twig file.

How can I achieve it without affecting the performance?

# Answer
> 4 votes
You need a cache context and a cache tag of the user:

```
$variables['username'] = [
  '#markup' => \Drupal::currentUser()->getUsername(),
  '#cache' => [
    'contexts' => [
      'user',
    ],
    'tags' => [
      'user:' . \Drupal::currentUser()->id(),
    ],
  ],
];

```

You can add this directly in a preprocess hook, but then the rendered output will vary for each user. For large numbers of users you might want to put this in a lazy builder callback, which will then match the auto-placeholder conditions and can be lazy-loaded through BigPipe without affecting page load performance.

See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering

---
Tags: theming, caching
---


# Question
Title: Why did my site crash when I moved module and theme folders?
A little background, I am quite new to Drupal and IT in general, so this may be a silly/basic question (I am going to start learning HTML, CSS, PHP, etc. for Drupal). I first set up my Drupal site by following the steps on drupalize.me, and then I installed the Sublime Text Editor 3. I realized I had already installed some contributed modules and the Bootstrap theme from drupal.org, but I didn't have contrib and custom folders for modules and themes, both. So I created them and moved the contributed module folders to the contrib folder under 'modules'. I also moved the contributed Bootstrap theme folder to the newly created contrib folder under themes. Then I tried to load my website but it said 'The website has encountered an unexpected error'.

What went wrong here and how can I move my already installed modules and themes correctly to their respective contrib folders?

# Answer
Drupal keeps an extensive cache of all functions in (contrib) modules and the files in which those functions can be found. Since you moved the files, Drupal is probably attempting to call a function from a file that is no longer there. (It should have thrown a more detailed error in your webserver log.)

Steps to repair could be to move the files back to their original position (Drupal works fine without contrib and custom folders, but it might be easier for yourself). Or enter the database and attempt to empty all tables that end in `_cache`. That should make Drupal reïndex the functions.
> 0 votes

---
Tags: installation
---


title: Using pathauto for taxonomy pages

text:
# Question
Title: Using pathauto for taxonomy pages
I'm using pathauto on a D8 site successfully for pattern type Content using a pattern like this:

```
[node:content-type]/[node:title]

```

But I'm not having any luck at all when trying to use it for pattern type Taxonomy term using a pattern like this:

```
[term:vocabulary]/[term:name]

```

I just keep getting /taxonomy/term/123 instead of /taxonomyname/taxonomyterm

I have searched and searched and every article I find only covers the tokens for Content, not Taxonomy. I did find one youtube video that covered it in D7 and the pattern was identical to mine, yet his worked but mine doesn't. I've cleared caches and even tried bulk generate to no avail. But Taxonomy (list) pages don't create aliases though, so I'm wondering if that has something to do with it.

# Answer
OK, I figured this out, and the funny thing is, I had it right from the start. The pattern I used above is correct (what I wanted). The only problem I created for myself was, I created the taxonomy terms before I created the pattern for it, so all those terms needed to have aliases generated for them. Hint: bulk generate

When I generate new terms now, I see at the bottom of the form there is a checkbox (default is checked) to `Generate automatic URL alias`. And that does in fact create a new alias because I tested it.

If you find yourself in the same position, go to `/admin/config/search/path/update_bulk` and select the `Taxonomy term` checkbox, and then the `Generate a URL alias for un-aliased paths only` radio button. Alternatively, you can check the `Regenerate URL aliases for all paths` if you think you have some existing alias that may be wrong to changes you've made to taxonomy.
> 1 votes

# Answer
Have you actually tried to visit `/taxonomyname/taxonomyterm`?

The `/taxonomy/term/123` isn't actually a taxonomy page, it is a Views showing **content** tagged with the term from the URL. It's a separate thing.

What do you expect to see on that page? Just the term name and description? That should work with the Pathauto as you have set it up.

If you want to see the content, like that Views page, you can use the `Taxonomy term` Views, Duplicate it and disable the original just for future reference, and modify the Contextual filters and Path to your preference.

You will need to add the Relationship to the term so you could use the `Taxonomy: Name` Contextual filter to get the term name in the URL.

You can also set up aliases for the default Taxonomy term Views so they use names, but I think it would have to be done manually, and isn't at all elegant/smart solution. It make more sense to set up the Views as you intend it to be used.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: WebForm images not displayed after node creation with submission handler
I'm at a loss.

I'm using WebForm 8.x-5.2 on Drupal 8.7.3. I have a custom webform handler that takes the submission and creates an unpublished node for review. The webform includes an image field that saves one or more images submitted through the form in the Private Files area as suggested.

Everything in my submission handler works as expected except for the images. Upon viewing the page created by the handler, the images are not displayed. The images are there. If you simply edit the node in the UI and save it, the images show up. I've tried a bunch of things, without success...

* Saving files to the public files directory
* Adding code to the handler to save the node a second time
* Adding code to the handler to make a change to the Title field after saving and then saving again.

Inspecting the node with Devel before and after the manual edit/save shows no difference that I can see. Here's the relevant code snippets...

```
$values = $webform_submission->getData();
if (!$webform_submission->isDraft()) {
  $node = Node::create([
  ...
  'field_image' => $values['image'],
  ...
 ]);
 ...
$node->save();

```

My submission handler is setting taxonomy terms, multiple fields, URLs, and everything is working except for the images. What am I missing?

# Answer
I would agree with cchen - you need to use the URI of the image to print it - and I'm not sure 'field\_image' =\> $values\['image'\] would work in this case.
> 0 votes

---
Tags: webforms
---


# Question
Title: Contextual filter in path for block view display, alongside pathauto aliases in Drupal 8
On our Drupal 8 site, we are using the `article` content type for press releases. We have the `pathauto` module generating automatic aliases for these nodes, so the article node entitled "Cool Things are Happening" would get the url `/press-releases/cool-things-are-happening`.

Additionally, we have a view of press releases, at `/press-releases`. This is provided by a view of articles that has a `page` display.

Our marketing department wants some changes implemented to the page delivered from `/press-releases`. Since we have the paragraphs module installed on our side, I decided the best way to future-proof the page would be to disable the press releases page display, create a block display of that view, and add a basic page with the press releases block display in a paragraph, and set the alias of that node to `/press-releases`.

However, one of the requested changes is a year filter feature on the press releases page, so that the results of the view can be filtered by year.

I have that filter working on the view, as I've confirmed in the block display preview. I've added a custom block to the new `/press-releases` page that has links to `/press-releases/2019`, `press-releases/2018`, etc. The idea, obviously, is that the second part of the path would be the value for the contextual filter on the block display of the view.

However, I'm not sure if it's possible, and if it is, then how to specify a wildcard route in Drupal 8 that passes the second url parameter to the contextual filter. Currently, when I navigate to `/press-releases/2018`, I get a 404, which is not unexpected.

Since the view display is not a page, but a block, I don't see where I can indicate a path with a wildcard value, like `/press-releases/%`. (It's been a while since I've developed for Drupal 7, but I seem to recall that's how values were grabbed from paths.)

Editing the Contextual Filter on the block display of the view, I tried adding "Raw value from URL". I set the settings

When the filter value is NOT available \- Provide default value \- Type: Raw value from URL \- Path component: 2 \- Exception value: all

However, with these settings, `/press-releases` and `/press-releases/all` show the page with an empty view block display, and also paths with the year value (like `/press-releases/2018`) are also empty. However, node paths still work. I'm not sure if I'm using the wrong settings, or if this way is not going to work regardless.

This answer shows how to get a value from the URL using the `InboundPathProcessorInterface` in a custom module, but I'm not sure how to then pass that value to the view's block display in the paragraph. Also, if I'm using `/press-releases/%` as my pattern to match, I don't want to interfere and break existing node paths at e.g. `/press-releases/cool-things-are-happening`. I only want to match `YYYY`, where `Y` is a number. (I could do more advanced validation for the year, but I can pretty much guarantee we are never going to have just a year by itself as the actual title of a press release node.)

How can I pass the year value to the contextual filter? Have I gone down the wrong path for developing this feature?

We are on Drupal 8.7.3.

# Answer
> 1 votes
So I was able to get my functionality by changing the Contextual Filter to a query parameter:

So in my widget block, I changed the link values from `/press-releases/2015` to `/press-releases?year=2015`. Now the functionality works as wanted. Both urls `/press-releases/` and `/press-releases?year=all` show all the press releases, and the node urls still work.

---
Tags: views
---


# Question
Title: How to add two separate GA accounts in one Drupal site
I have one Drupal site and I am using google analytic module for add ing GA account? Now client want to add two separate accounts.

> UA-87XXX-XX
>
> UA-87YYY-YY

How can I add these two accounts?

# Answer
Go to /admin/config/system/googleanalytics \> ADVANCED SETTINGS \> CUSTOM JAVASCRIPT CODE \> Code snippet (after)

```
ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'foo'});
ga(function(foo) {
  foo.send('pageview');
});
ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'bar'});
ga(function(bar) {
  bar.send('pageview');
});

```

This worked for me.
> 1 votes

# Answer
In drupal 8 with google-analytics v8.x-2.x, go to /admin/config/system/google-analytics \> Advanced settings \> Code snippet (after), and type this:

```
ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('create', 'UA-XXXXXXXX-Y', 'auto',{'name': 'WebProperty2'});
ga('send', 'pageview');
ga('WebProperty2.send', 'pageview');

```

```
Code 1: UA-XXXXXXXX-X
Code 2: UA-XXXXXXXX-Y

```
> 0 votes

---
Tags: google-analytics
---


# Question
Title: How to correctly configure settings.php to use reverse proxy and ssl termination
In settings.php there is the section "Reverse Proxy Configuration". It suggests settings to add when you are using a reverse proxy and SSL termination.

Nginx is listening on port 443, adds the headers and then passes to Apache Httpd on localhost port 80. Here is the Nginx as described:

```
    server {
        listen 443 ssl http2;

        server_name example.com;
        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;

        location / {
            proxy_pass http://127.0.0.1:80;
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
            proxy_set_header X-Forwarded-Port 443;
            proxy_set_header Host $host;
        }
}

```

With these settings/headers in mind what selection would be correct from the 'Reverse Proxy Configuration;' in settings.php?

```
 * Reverse Proxy Configuration:
 *
 * Reverse proxy servers are often used to enhance the performance
 * of heavily visited sites and may also provide other site caching,
 * security, or encryption benefits. In an environment where Drupal
 * is behind a reverse proxy, the real IP address of the client should
 * be determined such that the correct client IP address is available
 * to Drupal's logging, statistics, and access management systems. In
 * the most simple scenario, the proxy server will add an
 * X-Forwarded-For header to the request that contains the client IP
 * address. However, HTTP headers are vulnerable to spoofing, where a
 * malicious client could bypass restrictions by setting the
 * X-Forwarded-For header directly. Therefore, Drupal's proxy
 * configuration requires the IP addresses of all remote proxies to be
 * specified in $settings['reverse_proxy_addresses'] to work correctly.
 *
 * Enable this setting to get Drupal to determine the client IP from
 * the X-Forwarded-For header (or $settings['reverse_proxy_header'] if set).
 * If you are unsure about this setting, do not have a reverse proxy,
 * or Drupal operates in a shared hosting environment, this setting
 * should remain commented out.
 *
 * In order for this setting to be used you must specify every possible
 * reverse proxy IP address in $settings['reverse_proxy_addresses'].
 * If a complete list of reverse proxies is not available in your
 * environment (for example, if you use a CDN) you may set the
 * $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
 * Be aware, however, that it is likely that this would allow IP
 * address spoofing unless more advanced precautions are taken.
 */
# $settings['reverse_proxy'] = TRUE;

/**
 * Specify every reverse proxy IP address in your environment.
 * This setting is required if $settings['reverse_proxy'] is TRUE.
 */
# $settings['reverse_proxy_addresses'] = array('a.b.c.d', ...);

/**
 * Set this value if your proxy server sends the client IP in a header
 * other than X-Forwarded-For.
 */
# $settings['reverse_proxy_header'] = 'X_CLUSTER_CLIENT_IP';

/**
 * Set this value if your proxy server sends the client protocol in a header
 * other than X-Forwarded-Proto.
 */
# $settings['reverse_proxy_proto_header'] = 'X_FORWARDED_PROTO';

/**
 * Set this value if your proxy server sends the client protocol in a header
 * other than X-Forwarded-Host.
 */
# $settings['reverse_proxy_host_header'] = 'X_FORWARDED_HOST';

/**
 * Set this value if your proxy server sends the client protocol in a header
 * other than X-Forwarded-Port.
 */
# $settings['reverse_proxy_port_header'] = 'X_FORWARDED_PORT';

/**
 * Set this value if your proxy server sends the client protocol in a header
 * other than Forwarded.
 */
# $settings['reverse_proxy_forwarded_header'] = 'FORWARDED';

```

Testing host settings that end up being passed to PHP (7) by adding the following to the bottom of the setting.php:

```
print '<pre>';
print_r($_SERVER);
print '</pre>';

```

The headers added by Nginx are being passed down but the Server URI is always set to `[SCRIPT_URI] => http://www.example.com/` rather than `[SCRIPT_URI] => https://www.example.com/`.

What would be the correct reverse proxy Drupal settings in settings.php to get things working properly?

# Answer
This should work for both Drupal 7 and 8. It's actually the global.inc for one of my Aegir set-ups, which gets injected into all hosted sites' `settings.php` files.

```
<?php # global settings.php

/**
 * Tell all Drupal sites that we're running behind an HTTPS proxy.
 */

// Drupal 7 configuration.
if (explode('.', VERSION)[0] == 7) {
  $conf['reverse_proxy'] = TRUE;
  $conf['reverse_proxy_addresses'] = ['1.2.3.4', ...];

  // Force the protocol provided by the proxy. This isn't always done
  // automatically in Drupal 7. Otherwise, you'll get mixed content warnings
  // and/or some assets will be blocked by the browser.
  if (php_sapi_name() != 'cli') {
    if (isset($_SERVER['SITE_SUBDIR']) && isset($_SERVER['RAW_HOST'])) {
      // Handle subdirectory mode.
      $base_url = $_SERVER['HTTP_X_FORWARDED_PROTO'] . '://' . $_SERVER['RAW_HOST'] . '/' . $_SERVER['SITE_SUBDIR'];
    }
    else {
      $base_url = $_SERVER['HTTP_X_FORWARDED_PROTO'] . '://' . $_SERVER['SERVER_NAME'];
    }
  }
}
// Drupal 8 configuration.
else {
  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = ['1.2.3.4', ...];
}

```
> 6 votes

# Answer
This is part of settings.php that I'm using on Google Cloud:

```
// Force secure connection if the request wasn't made from CLI.
if (PHP_SAPI !== 'cli') {
  // Fix HTTPS if we're behind load balancer.
  if (getenv('HTTPS') !== 'on' && getenv('HTTP_X_FORWARDED_PROTO') === 'https') {
    $_SERVER['HTTPS'] = 'on';
  }

  // Perform redirect to secure connection if needed.
  if ($_SERVER['HTTPS'] !== 'on') {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: https://'. getenv('HTTP_HOST') . getenv('REQUEST_URI'));
    exit;
  }
}

//...

// Enable LB headers, if applicable.
if (getenv('HTTP_VIA')) {
  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = ['0.0.0.0']; // LB IP
}

```

Have a look at https://www.drupal.org/node/2492389 and also see which headers you are receiving so that you can adjust Drupal's values accordingly.
> 1 votes

# Answer
I used @colan 's excellent solution as a base, and modified 2 lines so that there is no need to manually define the reverse\_proxy\_addresses.

I used this solution with great success for a site sitting behind an SSL-Terminating nginx reverse-proxy in kubernetes (nginx-ingress)

```
/**
 * Tell all Drupal sites that we're running behind an HTTPS proxy.
 */

// Drupal 7 configuration.
if (explode('.', VERSION)[0] == 7) {
  $conf['reverse_proxy'] = TRUE;
  $conf['reverse_proxy_addresses'] = array($_SERVER['REMOTE_ADDR']);

  // Force the protocol provided by the proxy. This isn't always done
  // automatically in Drupal 7. Otherwise, you'll get mixed content warnings
  // and/or some assets will be blocked by the browser.
  if (php_sapi_name() != 'cli') {
    $base_url = $_SERVER['HTTP_X_FORWARDED_PROTO'] . '://' . $_SERVER['SERVER_NAME'];
  }
}
// Drupal 8 configuration.
else {
  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = array($_SERVER['REMOTE_ADDR']);
}

```

**Dislaimer**: (Thanks to @DavidStinemetze)

**While this solution solves a unique problem of being able to serve a site from behind a CDN or service with unpredictable IPs, it is likely that this method would allow IP address spoofing unless more advanced precautions are taken. So make sure to take these precautions to prevent spoofing**

From default settings.php:

```
 * In order for this setting to be used you must specify every possible
 * reverse proxy IP address in $settings['reverse_proxy_addresses'].
 * If a complete list of reverse proxies is not available in your
 * environment (for example, if you use a CDN) you may set the
 * $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
 * Be aware, however, that it is likely that this would allow IP
 * address spoofing unless more advanced precautions are taken.

```
> 0 votes

# Answer
### Drupal 8

Apply the following settings in site's `settings.php` file:

```
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']]

```

It should work for CDN where IP addresses are dynamic.

This is explained in the following comment:

```
 * In order for this setting to be used you must specify every possible
 * reverse proxy IP address in $settings['reverse_proxy_addresses'].
 * If a complete list of reverse proxies is not available in your
 * environment (for example, if you use a CDN) you may set the
 * $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
 * Be aware, however, that it is likely that this would allow IP
 * address spoofing unless more advanced precautions are taken

```

### Drupal 7

```
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']];

```

---

See also:
> 0 votes

# Answer
If you have a dynamic reverse proxy IP, but you know it should be on the internal network (e.g kubernetes cluster) to validate the `remote_addr` is internal first you can use something like this in `settings.php` (D8):

```
/**
 * Helper function to check
 * if IP address is internal network
 * @param string $ip - IP address to test
 * @return boolean - false if private/internal IP
 */
function is_public_ip($ip) {
  return (bool)filter_var(
    $ip,
    FILTER_VALIDATE_IP,
    FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
  );
}

// Set reverse proxy config for correct client IP lookup (uses env var check)
if (getenv('DRUPAL_REVERSE_PROXY')) {
  $settings['reverse_proxy'] = TRUE;
  // Init address list, no overwrite
  $settings['reverse_proxy_addresses'] = $settings['reverse_proxy_addresses'] ?? [];
  // Get dynamic forwarded for or remote IP for proxy config
  // Check x-forwarded-for
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $forwarded_for_ips = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
    foreach ($forwarded_for_ips as $forwarded_for_ip) {
      // Not already added and is not public ip (is internal ip)
      if (!in_array($forwarded_for_ip, $settings['reverse_proxy_addresses']) && !is_public_ip($forwarded_for_ip)) {
        $settings['reverse_proxy_addresses'][] = $forwarded_for_ip;
      }
    }
  }
  // Check remote_addr to add as well just in case not added above
  if (!empty($_SERVER['REMOTE_ADDR']) && !in_array($_SERVER['REMOTE_ADDR'], $settings['reverse_proxy_addresses'])) {
    // Ensure is internal IP
    if (!is_public_ip($_SERVER['REMOTE_ADDR'])) {
      $settings['reverse_proxy_addresses'][] = $_SERVER['REMOTE_ADDR'];
    }
  }
  // No reverse_proxy for this case, as proxy address is required, use default
  if (empty($settings['reverse_proxy_addresses'])) {
    $settings['reverse_proxy'] = FALSE;
  }
}

```
> 0 votes

---
Tags: proxies, ssl, 8
---


# Question
Title: How do I use PHP in "Rewrite results" for a field in a view?
In a view, I configured a file to "Rewrite the output of this field." In the text area I need to use PHP. Can this be done?

# Answer
> 2 votes
No, it cannot be done. You can write HTML code in the rewrite box. Please take a look at this if you need to write php code in Views: Views Custom Field Although I would suggest you create a template to add any custom php code you require.

# Answer
> 1 votes
I would like to be more specific than Perisdr and to describe how to add template for this field. In view I went 'style settings', then checked 'use field template', added field.tpl.php to theme(in /modules/field/theme there is an example).

in this template you can rewrite everything.

# Answer
> 0 votes
You can use a PHP field. Place it after the field you want to rewrite. Hide the initial field and use PHP to output the result.

This does quickly become opaque as noted it is best to go under 'advance', review the template choices (at the bottom of the column) and then put the php in the template.

I have also been trying to avoid this and use display suite and if an appropriate formatter does not exist write a custom formatter instead. There are examples for links such as 'image\_link\_formatter'.

---
Tags: views
---


# Question
Title: How do you use hook_form_FORM_ID_alter() to alter the USER EDIT form?
I'm trying to mark fields on the `/user/_uid_/edit` screen as disabled. These are custom fields I've created in `/admin/config/people/accounts/fields` in D8.

I have this code for another node entity type...

```
function MODULENAME_form_node_survey_edit_form_alter(&$form, $form_state, $form_id) {
  $form['field_content_type']['widget']['#type'] = 'hidden';
}

```

This works as expected, and on the node/123/edit screen for a that content type, that field is hidden. (works as expected)

(it gets populated by a migration process, and needs to stay how its set, even if users change other fields...)

My problem is, that I'm trying to disable a field on the USER-EDIT screen, such as /user/123/edit.

I'm trying the EXACT same code structure.

```
function MODULENAME_form_user_edit_form_alter(&$form, $form_state, $form_id) {
    $form['field_organization_reference']['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
}

```

But it doesn't work.

I've tried throwing in class changes, and other things to alter the input fields, but they don't work.

```
$form['field_organization_reference']['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
$form['field_organization_name']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
$form['field_organization_reference']['#attributes']['class'][] = 'borkbork';
$form['field_organization_name']['#attributes']['class'][] = 'borkbork';
$form['field_organization_name']['widget']['#type'] = 'hidden';

```

All as attempts to try and change something on the user edit form.

But nothing is working.

Is `user-edit` the correct form id? Is there something else I'm missing

Thoughts? Help? Thank you!

# Answer
Try:

```
function MYMODULE_form_user_form_alter(&$form, $form_state, $form_id) {
  // Your code...
}

```

Inspecting element, I see the form id is `user-form`, which needs to be translated to the machine-readable name `user_form`

Otherwise, you can always do a standard `HOOK_form_alter()`:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_form') {
    // Your code...
  }
}

```

And always clear cache after adding/changing hook names.
> 2 votes

# Answer
Here's the answer I was helped with.

```
function MODULENAME_form_user_form_alter(&$form, $form_state, $form_id) {

      if (!\Drupal::currentUser()->hasPermission('administer users')) {

        $form['field_organization_name']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
        $form['field_organization_reference']['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';

      }

}

```

The important part being \**user\* in the function name. not `user-edit` or `user_edit`.

The next challange was figuring out that the ORG REF field (being a auto complete reference) has a different structure then the name, which is plain text.

I used `dpm($form['field_name'])` on both, inside the function, and as UID 1 you can see the output of that dpm() call.

The IF check makes sure that admins can still see the fields to edit the user directly if they need to.
> 0 votes

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


# Question
Title: Can I include other template into template?
I override template in my custom theme na (`templates/block--[module]--[delta].tpl.php`) and I would like to include other template (from the same directory) into this. Can I do it and how?

Directory structure

```
sites\all\themes\
   my_name_of_theme\
        templates\
             block--views--front-page-block-1.tpl.php
             example-file-template.tpl.php

```

`block--views--front-page-block-1.tpl.php` (concept what I want to do):

```
<?php
     /* init $path (or maybe it is not needed) */
     include($path . 'example-file-template.tpl.php');
?>

```

# Answer
You can get another drupal theme path with `drupal_get_path('theme', 'theme_name');` and finally

```
<?php
     include(drupal_get_path('theme', 'theme_name').'/example-file-template.tpl.php');
?>

```
> 12 votes

# Answer
You can use path to theme (Uses the current allowed theme):

```
<?php
include(path_to_theme().'/templates/TEMPLATE_NAME.tpl.php');
?>

```

Or Drupal get the path (You can set the theme you want to use):

```
<?php
    include(drupal_get_path('theme', 'THEME_NAME').'/templates/TEMPLATE_NAME.tpl.php');
?>

```
> 0 votes

---
Tags: theming
---


# Question
Title: Custom CSS and JS that would load only for a content type's view mode
I am trying to load a custom css and js on my content type's view mode. Can this be achieved in drupal 8?

# Answer
> 2 votes
Yes. You can create a new library as follows:

\[THEME\].libraries.yml

```
mycontenttype:
  css:
    theme:
      path/to/my.file.css: {}
  js:
    path/to/my.file.js: {}

```

Next, you attach that library to the node in hook\_node\_view\_alter():

```
function THEME_node_view_alter(array &$build, Drupal\node\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  // Check the content type (bundle) and view mode:
  if ($entity->bundle() == 'mycontenttype' && $build['#view_mode'] == 'myviewmode') {
    // Attach your library in the form of MODULEKEY/LIBRARYKEY
    $build['#attached']['library'][] = 'mymodule/mycontenttype';
  }
}

```

Now your CSS and JS will be rendered on the page if/when a node of the given content type is rendered on the page with the given view mode.

---
Tags: 8, theming
---


# Question
Title: Synchronizing a webform to populate MailChimp lits
I'm synchronizing a webform to populate MailChimp lits via the MailChimp module. As well as capturing the first and last name I also want to capture the City and Province.

However when I submit I only seem to capture the email address in MailChimp.

I configured my form for each field as the following.

#### Email Field (This works.)

* Title: Email
* Key: email
* Type: Email

#### First Name (This doesn't transfer to MailChimp.)

* Title: First Name
* Key: fname
* Type: Text field

#### Last Name (This doesn't transfer to MailChimp.)

* Title: Last Name
* Key: lname
* Type: Text field

In MailChimp I set up in the List fields and *|MERGE|* tags the following.

* First Name *|FNAME|*
* Last Name *|LNAME|*

Has anyone else had issues with merging fields from Drupal 8 into MailChimp via the MailChimp module?

# Answer
> 2 votes
I've recently built a subscriber module with a small piece of custom code. I prefer working with webform handlers instead of the Mailchimp module. In a custom module add a folder `src/Plugin/WebformHandler` and create a file `newsletterSubscription.php`. Add the following code:

```
<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "newslettersubscription",
 *   label = @Translation("Newsletter subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions in Mailchimp"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class newsletterSubscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const MAILCHIMP_API_KEY = 'x'; // see https://mailchimp.com/help/about-api-keys
  const LIST_ID = 'x'; // see https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // The data to send to the API
    $postData = array(
      "email_address" => "$email",
      "status" => "subscribed",
      "merge_fields" => array(
        "FNAME" => "$first_name",
        "LNAME" => "$last_name"
      )
    );

    // Setup cURL
    // To get the correct dataserver, see the url of your mailchimp back-end, mine is https://us20.admin.mailchimp.com/account/api/
    $ch = curl_init('https://us20.api.mailchimp.com/3.0/lists/'.self::LIST_ID.'/members/');
    curl_setopt_array($ch, array(
      CURLOPT_POST => TRUE,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.self::MAILCHIMP_API_KEY,
        'Content-Type: application/json'
      ),
      CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Send the request
    $response = curl_exec($ch);
    $readable_response = json_decode($response);
    if($readable_response->status == 403) {
      \Drupal::logger('Mailchimp_subscriber')->error($readable_response->title.': '.$readable_response->detail .'. Raw values:'.print_r($values));
      \Drupal::messenger()->addError('Something went wrong. Please contact your webmaster.');
    }
    if($readable_response->status == 'subscribed') {
      \Drupal::messenger()->addStatus('You are now successfully subscribed.');
    }
    if($readable_response->status == 400) {
      if($readable_response->title == 'Member Exists') {
        \Drupal::messenger()->addWarning('You are already subscribed to this mailing list.');
      }
    }

    return true;
  }
}

```

Read more on how to enable and use the handler here: How to create a mailchimp subscription with drupal 8 webform and custom handlers (Video)

# Answer
> 0 votes
1. Go to the settings of your webform
2. Add handler on the Emails/Handlers tab
3. Select your List and Email field you wish to use
4. In the merge vars section you can link your webform fields with fields from your Mailchimp webform. For example:

```
FNAME: [webform_submission:values:name]
LNAME: [webform_submission:values:surname]

```

# Answer
> 0 votes
For me to get this to work, I needed to quote the tokens:

```
FNAME: '[webform_submission:values:name]'
LNAME: '[webform_submission:values:surname]'

```

---
Tags: 8, webforms, emails
---


# Question
Title: What is the progress bar periodic update function return data?
In Drupal 7 from the function called with 'url/to/call/progressbar/update/function' (see below) you would return an array converted to JSON like this:

```
drupal_json_output($message);

```

I cannot find any examples for Drupal 8 and I suspect it's an object rather than an array that gets returned.

Does anyone know how/what to return from the progress bar update function?

The setup for the bar progress indicator would be something like this:

```
$form['some_item'] = array(
  '#type'  => 'submit',
  '#value' => t('My action'),
  '#ajax'  => array(
    'callback' => 'a_function',
    'wrapper'  => 'ajax-response-goes-here',
    'method'   => 'replace',
    'progress' => array (
      'type'     => 'bar',
      'message'  => 'Starting...',
      'url'      => 'url/to/call/progressbar/update/function',
      'interval' => '1000'
)

```

# Answer
> 2 votes
The core example is in `FileWidgetAjaxController::progress`. You need to return a JSON-encoded associative array with `message` and `percentage` keys. For example:

```
$progress['message'] = t('Uploading... (@current of @total)', ['@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])]);
$progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
...
return new JsonResponse($progress);

```

---
Tags: 8, ajax
---


# Question
Title: Redirect domain to www, but on subdomain do not use www
I have a multilanguage website. The main language is English and the second language is Spanish.

I need to have all the traffic using this domains:

* English domain: www.example.com
* Spanish domain: es.example.com

If I use the .htaccess rules from Drupal, I can redirect all the traffic to www, but it includes the Spanish traffic too. Or I can remove www to use es.example.com, but again, it would redirect the English traffic to use example.com (without www).

I have tried a lot of .htaccess combinations but I finish in a worst situation that is redirecting the Spanish traffic to the Encglish URL, so... I need to know what rules can I use to have these redirections:

* example.com to www.example.com
* www.es.example.com to es.example.com

# Answer
> 1 votes
These rules must be included in Drupal's .htaccess file, **before** the *RewriteBase /* line.

```
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ http%{ENV:protossl}://www.example.com%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} ^www\.es\.example\.com$ [NC]
RewriteRule ^ http%{ENV:protossl}://es.example.com%{REQUEST_URI} [L,R=301]

```

---
Tags: 8, redirection
---


# Question
Title: Show Content Type Fields from a entity reference
I have a content type which i have linked to another content type. For e.g.

* Companies (Content Type)
* Employees (Content Type)

When creating a new employee i have to say which company it works for so in the Field Type i chose "Entity Reference and chose Autocomplete as the widget".

Now i have created a view which shows a list of all the employees, in this view i can show the companies Name however i want to show the companies logo instead of the name.

How can i grab the fields from "Companies" and display them within the Employees VIEW?

Thanks in advance.

# Answer
To show the Parent info (Company) through Child nodes (Employee) you need to add the Relationship for the Entity Reference field that is connecting the child to the parent.

Once you add that Relaionship you will be able to add the fields from the Company CT. Those fields must use that Relationship to show the Company info, otherwise if you don't select the Relationship for a field it will show the original (Employee) info.

So after you add the Relationship for the Company ER field (that is on Employee CT), you will be able to add the Logo field to your Views, and that field will use the Relationship you've just added.
> 0 votes

---
Tags: views, entities
---


title: Link module output with content type

text:
# Question
Title: Link module output with content type
I am confused on how to output links from a content type into a list in HTML. Currently I have the following code.

```
<div class="lenders-block-content clearfix">
  <ul>
    <?php print render($content['field_link']) ?>
  </ul>
</div>

```

The output just adds the links back-to-back within an `<a>` tag.

Is there a way to render the links so its outputted within a `<li>` tag?

I am using multiple links. When adding a content type you can add up to ten links.

# Answer
As you mentioned in the comments you field is multivalue field so you should loop over it and render the item inside `<li>` tag something like the following:

```
<div class="lenders-block-content clearfix">
    <ul>
      <?php foreach ($content['field_link'] as $key => $link):?>
      <?php if (is_numeric($key)): ?>
        <li> <?php print render($link) ?></li>
      <?php endif;?>
      <?php endforeach;?>
    </ul>
  </div>

```
> 0 votes

---
Tags: 7, theming, nodes
---


# Question
Title: Skip a form step programmatically in simple_multistep module
I am trying to skip a step in multistep node form using Simple Multistep module. I have tried following snippet that works pretty good to skip one step.

```
$skipStep = $form_state->get('multistep_controller');
$skipStep->increaseStep();
$form_state->setRebuild();

```

**However, it has a problem click on back button it doesn't come back**.

I have search a lot but no luck, do anyone have idea?

# Answer
I have solved it by using **reduceStep()** method to come back.

```
$skipStep->reduceStep();
$form_state->set('multistep_controller', $skipStep);
$form_state->setRebuild();

```

Hope this would help someone.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: How can I allow remote access to specific folders in my site?
I have a drupal 8 site that has a folder (/learning/sales) in it that is custom html/php/etc. In there I make an ajax call from one .html file to a .php file in another folder (from /learning/sales to /learning/sales/ajax/getAreas.php) when I try to run it it fails (403 error), and when I try to go directly to my php file to check to see if it works I get this error, "Forbidden You don't have permission to access /learning/sales/ajax/getAreas.php on this server."

I think the solution to this is to edit my .htaccess file to allow access to those folders, however I don't really know how to do that.

Am I correct in my thoughts that it is the .htaccess file that needs to be fixed? and if so what do I need to do to get it to work? And if not then what could be the problem?

Thanks!

**P.S. Here is my .htaccess code for reference.**

```
#
# Apache/PHP/Drupal settings:
#

RewriteEngine On
# ensure www.
#RewriteCond %{HTTP_HOST} !^www\. [NC]
#RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Only serve the static site for a particular host.
# RewriteCond %{HTTP_HOST} ^local.learning\.com$
# Don't loop anything targeting the actual mask directory, to allow
# for linked scripts, stylesheets etc in the static HTML
# RewriteCond %{REQUEST_URI} !^/learning/
# Any requests that made it this far are served from the /static/ directory
# RewriteRule ^(.*)$ /learning/$1 [PT,L]

# Only serve the static site for a particular host.
RewriteCond %{HTTP_HOST} ^www.[sitename]\.com$
# Don't loop anything targeting the actual mask directory, to allow
# for linked scripts, stylesheets etc in the static HTML
RewriteCond %{REQUEST_URI} !^/learning/
RewriteCond %{REQUEST_URI} !^/learning/sales
#Any requests that made it this far are served from the /static/ directory
RewriteRule ^(.*)$ /learning/$1 [PT,L]

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  #RewriteRule "/\.|^\.(?!well-known/)" - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Various header fixes.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
  # Disable Proxy header, since it's an attack vector.
  RequestHeader unset Proxy
</IfModule>

```

# Answer
> 1 votes
the htaccess has these lines

```
# Pass all requests not referring directly to files in the filesystem to
# index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

Which means if it's an actual file, it won't be redirected to drupal. So there shouldn't be any Drupal reason you can't call a PHP file from your setup. Perhaps if you have an htaccess popup password (Basic Auth) in place, that could cause issues. Or if the permissions on your folder/file aren't correct, that could be an issue.

If your getAreas.php bootstraps (starts Drupal instance), then Drupal permissions come into play. And some Drupal files may not like being directly accessed.

---
Tags: 8
---


# Question
Title: Filter a view with contextual authored date
I have a Drupal 8 view where I want to sort nodes by authored year using contextual filters.

So www.mysite.com/2017

will list all nodes from 2017.

I set up the filter using 'Content: Created Year' which takes YYYY format.

But the filter is ignored.

www.mysite.com/2017 returns all years.

What did I miss?

# Answer
> 1 votes
Try adding the placeholder `%` to the path (in the main views UI in the middle column under "Page settings"),

e.g. something like `my-view/by-year/%` which will accept URLs like `my-view/by-year/2019`

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


title: Token for first media Image in the body

text:
# Question
Title: Token for first media Image in the body
I need to display an image url in a metatag item. The problem is on one of my node types, the editors only upload an image as a media entity inside the body.

What is the best way to handle this?

# Answer
> 3 votes
I feel like there is a better way but I just quickly created a custom token.

```
<?php

/**
 * @file
 * Node custom functionality.
 */

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_token_info().
 */
function my_custom_module_token_info() {
  $type = [
    'name' => t('My Custom'),
    'description' => t('My Custom Tokens.'),
    'needs-data' => 'node',
  ];

  $node['body_first_media_image_url'] = [
    'name' => t("Body First Media Image Url"),
    'description' => t("Body's first media image url."),
  ];

  return [
    'types' => ['node' => $type],
    'tokens' => ['node' => $node],
  ];
}

/**
 * Implements hook_tokens().
 */
function my_custom_module_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'node' && !empty($data['node'])) {
    /** @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        // The first media item embedded in body.
        case 'body_first_media_image_url':
          $dom = new DOMDocument();
          @$dom->loadHTML($node->body->value);
          $embedEntities = $dom->getElementsByTagName('drupal-entity');
          if ($embedEntities->length > 0) {
            $uuid = $embedEntities->item(0)->getAttribute('data-entity-uuid');
            $media = \Drupal::entityManager()->loadEntityByUuid('media', $uuid);
            $url = ImageStyle::load('extra_large')->buildUrl($media->image[0]->entity->uri->value);
            $replacements[$original] = $url;
          }
          break;
      }
    }

  }

  return $replacements;
}

```

---
Tags: tokens, meta-tags
---


# Question
Title: How to join the `field_data_field_*` tables with `node` table using SQL?
I apologize if I ask for something obvious, but I am asking because I could not find a simple answer anywhere.

I know how to work with these tables in the PHP Drupal code, which built-in functions to use, etc., but for some reasons, I have to write a literal SQL query to the Drupal database.

That's why I'm asking what condition I need to use in the SQL query to connect the `field_data_field_abc` table with the `node` table?

If the data in the `field_data_field_abc` table contains the `entity_type` column with the value "*node*", can I do something like this:

```
SELECT *
FROM node n
LEFT JOIN field_data_field_abc abc ON n.nid = abc.entity_id
WHERE abc.entity_type = 'node'

```

# Answer
Yes, you are right :)

In general, for each table from `field_data_field_*` family, if its `entity_type` is equal to the "*node*" value, then it can be associated with the `n.nid` from the `node` table and if the `entity_type` is equal to the "*user*" then the `entity_id` value is associated with the `uid` value from the `users` table.

I hope it will help somebody.
> 0 votes

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


# Question
Title: Programatically render block with contextual links (in php)
I'm trying to find a solution to embed a drupal custom block using PHP. I found this snippet that works :

```
<?php
$block = \Drupal\block\Entity\Block::load('your_block_id');
$render = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
print render($render);
?>

```

The problem is that this code directly render the block content, I don't have any contextual links for that block. My question is, how to render the whole block (including contextual links), exactly like if I added it in a region using the UI.

Thank you

# Answer
> 2 votes
You can use the Twig Tweak module to insert the 'local tasks' menu in your template file:

`{{ drupal_entity('block', 'THEME_local_tasks', check_access=true) }}`

# Answer
> 0 votes
This is an open issue. Block Content entities have no Contextual links when rendered outside of Block config entity: https://www.drupal.org/project/drupal/issues/2666578

---
Tags: blocks
---


title: How to send mail when node is published

text:
# Question
Title: How to send mail when node is published
I have a content type "Properties". By default, content type is set to "Not published"

When users add a node of the content type, node is not published.

Another role gets a notification and then publishes the node.

Once the node is published, an email should be sent out to multiple roles.

I used Rules module to do that but emails are not being send out once nodes are published. I also created other rules and emails are being send out just fine. I am not sure why this specific rule does not send emails.

# Answer
From your scenario it seems that your event is wrong. The content is already saved before. So you should use an event like after updating existing content, of type "Properties". If you then also replace your condition by 2 conditions to check that (a) the unsaved node is unpublished and (b) the saved node is published, you should be close to what you want.

Try it, and see what happens ...the bets are open ...
> 0 votes

---
Tags: rules
---


title: How to remove base field overrides?

text:
# Question
Title: How to remove base field overrides?
Half of our content types have had their publication status fields overridden. The override is causing the fields to read "Publishing status" and have the description "A boolean indicating whether the node is published." I believe this is the same problem described in this comment. The row names are in the format `core.base_field_override.node.[content-type].status` in the database.

However, I am unsure of how to *properly* remove these overrides. Certainly I could just delete that row of the config table, but I am unaware of what consequences that may have or whether that would be the appropriate way to handle this one-time problem.

Can anyone tell me the correct way to remove base field overrides? Thanks!

# Answer
> 2 votes
Don't modify the config table. Export the config, delete the yaml file and import the config again.

From the command line you can delete configuration items with drush:

```
drush config:delete core.base_field_override.node.[content-type].status

```

# Answer
> 1 votes
This is another solution. With Base Field Override UI module you can delete that configuration from the UI.

> The Base Field Override UI module enables an interface to be able to change the labels and descriptions of the fields that have been created by code using the BaseFieldDefinition class (Example, the title field of the node entity).

---
Tags: 8
---


# Question
Title: Target individual items of a multi-value field in my page template
I created one field for an image and In the field setting, I made allowed number of values to 2 (please find the attached screenshot

)

So my question is, how can I add both the images in a different div tag in my page template.

Or, how can I target first and second image in my page template.

# Answer
There are many ways to achieve this. Given you use a custom or sub-theme you'd follow Twig Template naming conventions and create your own `field--node--MYFIELDNAME.html.twig` template. And then simply adjust the markup according your needs.

See Classy's `field.html.twig` for reference and its for-loop you simply can customize:

```
{% for item in items %}
  <div{{ attributes.addClass(classes, 'field__item') }}>
    {{ item.content }}
  </div>
{% endfor %}

```

---

To target the second item in a multi-value field inside `page.html.twig` use the following snippet (it starts to count with `0`, so that `0` is the first and `1` is the second item).

```
{{ node.field_MYFIELD.1.value }}

```
> 0 votes

---
Tags: 8, theming
---