# Question
Title: Insecure content warning with D7 and SSL
I'm running Drupal 7 with Drupal Commerce module. I have SSL enabled on my server. I've confirmed that the SSL is properly enabled (If I replace Drupal's index.php with a simple index.html, Chrome allows me to browse to my domain via https).

I'm getting a bunch of error messages like this:

> `The page at https://example.com/ ran insecure content from http://www.example.com/sites/default/files/css/css_TsVRTbLFUpEZAfw-_bWPJu840QT523CPjUVJ5MRWfyk.css`

There are about 20-30 of these errors - mostly .js and .css files, some .png etc. Questions:

1. How can I configure d7 so that it accesses these files via relative paths
2. Are there any other workarounds here, to enable https on my drupal install?

Much thanks in advance.

# Answer
> 3 votes
Somewhat ugly, but you can do something like this for Drupal 6

```
function mytheme_preprocess_page (&$vars)
{
  $vars['scripts'] = str_replace("http://www.example.com/", "/", $vars['scripts']);
  $vars['styles'] = str_replace("http://www.example.com/", "/", $vars['styles']);
  $vars['content'] = str_replace("http://www.example.com/", "/", $vars['content']);
}

```

or for Drupal 7

```
function mytheme_process_html (&$variables) {
  $variables['scripts'] = str_replace("http://www.example.com/", "/", $variables['scripts']);
  $variables['styles'] = str_replace("http://www.example.com/", "/", $variables['styles']);
  $variables['page'] = str_replace("http://www.example.com/", "/", $variables['page']);
}

```

You can be a bit smarter and use PREG, but have never run into the need. Note that there may be a few additional regions / variables that you need to do replacement on.

I normally put in something similar to handle hardcoded URLs from the WYSIWYG when migrating from a dev URL to a live one.

# Answer
> 15 votes
Simply remove `$base_url` from your settings.php file; Drupal will detect `$base_url` automatically.

If you must set this value explicitly, you can add a little conditional logic to your settings file, such as:

```
if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
  $base_url = 'https://example.com';
}
else {
  $base_url = 'http://example.com';
}

```

# Answer
> 4 votes
I had the same issue. In my case the pre-processing worked fine. However, when the requests were coming in from our Load Balancer, the pre-processing was not working. Strange.

Even so, found an easier solution. Add - `$base_url = '';` to the settings.php

This way both http and https requests work fine. All css calls, etc. constructed by Drupal become relative and start with "/sites/..." instead of "http://servername/sites/..."

IMHO the default, if no base\_url is specified should be relative URLs and not absolute. May be a fix in the next version of Drupal?

# Answer
> 2 votes
In setting.php file of drupal 7/6 add the following:

```
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $_SERVER['HTTPS']='on';
}
else {
  $_SERVER['HTTPS']='';
}

```

# Answer
> 1 votes
If your website runs behind the reverse proxy (such as CloudFront), enable `reverse_proxy` setting.

### 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']];

```

---

Related: Setting reverse\_proxy and reverse\_proxy\_addresses behind AWS ELBs.

# Answer
> 0 votes
In your settings.php file, you can add the following line:

```
$base_url = 'https://www.yourdomain.com';

```

# Answer
> -1 votes
$base\_url=''; worked for me, but note that bootstrap will puke on it, and needs the following change:

/var/www/includes/bootstrap.inc

```
if (isset($base_url)) {

//change to (should be this way anyway?):

if (isset($base_url) && $base_url!='') {

```

---
Tags: 7, security
---


# Question
Title: How do I configure Apache and Varnish with both HTTP and HTTPS access and prevent mixed content error?
I have Drupal 7 installed on Ubuntu server with apache2 and varnish. I was asked to provide both http and https access to the site.

To utilize Varnish I setup apache reverse proxy to redirect all https traffic to varnish(http). Now I can access my site via http/https protocols fine.

However, when I load any https page with images in it, all images are served via http, thus making browsers issue a warning about mixed content. I would like to suppress that.

To suppress that, I changed `$base_url` to `https://` in `site/default/settings.conf` and that worked fine for all https pages.

However, I experienced the same mixed content error while loading normal http pages (images were served via https this time.) Then, I created an if statement trying to differentiate between http and https and assigning different `$base_url` values accordingly.

I have tried using `$_SERVER['']` array variables as well as `$is_https`, and nothing seems to be working.

I also used `$GLOBALS['']` variable to make sure variables are defined. I would clear the Drupal cache as well as browsers before each testing. However, when I access https version of a site, all is rendered ok and everuthing is fine. But when I access http, all images are served with https. I would clear cache again, and try accessing http first, and everything would be fine. But when I access https after that, images would be served with http. So, the logic within `settings.conf` is fine, but possibly caching makes browsers/Drupal to serve images with the protocol they were first accessed (be it http OR https).

My question: is there a way to assign `$base_url` dynamically based on the protocol used?

Some of the settings I have tried:

```
-----------------------------------
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
        $_SERVER['HTTPS']='on';
        $base_url = 'https://';
        }
else {
         $_SERVER['HTTPS']='';
         $base_url = 'http://';
}
-------------------------------------
#if (isset($GLOBALS['$is_https'])) {
#       $_SERVER['HTTPS']='on';
#       $base_url = 'https://example';
#       }
#else {
#        $_SERVER['HTTPS']='';
#        $base_url = 'http://example';
#}
---------------------------------------
$base_url = '//example'
---------------------------------------
$base_url = '';
---------------------------------------

```

# Answer
> 1 votes
### 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:

# Answer
> 0 votes
I've had this problem, and haven't really found a solution. I wish there was a way to tell Drupal to serve all site content using relative links, rather than absolute http/https URLs.

You could try setting up separate directories in the drupal/sites directory for http and https, and give each its own version of the settings.php file with a different $base\_url. Then create symlinks to the files and themes directories, so both versions have the same content.

Hope this helps you out.

---
Tags: 7
---


# Question
Title: Subdomain for each node from content type
Is there any way to automatically create subdomain for each node from some content type?

I have a lot of pages that should be created and each should be on separated subdomain, I'm trying to find the way to do that through current website on Drupal 8.

# Answer
You could use an outbound path processor and modify `$options['base_url']`, see LanguageNegotiationUrl::processOutbound. This method is from a language negotiation plugin, but you can place directly in a service tagged `path_processor_outbound`, see Global preprocess for all links
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: .htacces file setings for Drupal and other site folder in same host
Primary Domain Examle.com is on CMS Drupal 8.

I must to share host with other site on different CMS location `/public_html/othersite.com`.

What must I change in `.htacces` to have access to othersite.com, and not break anything?

# Answer
Create a new folder for the new site with your webhosts FTP solution, for example named "drupal-8-site".

Place all the new files in this folder and add the following line to the .htaccess file:

> RewriteBase /drupal-8-site

Try to clear the cache and see if the new Drupal 8 CMS works as expected.

With this solution you don't risk breaking the other site, as you aren't really changing anything in the othersite.com folder.
> 1 votes

---
Tags: 8, .htaccess
---


# Question
Title: Webform submission redirect to view with node ID
I have a view with table of data about a member of a sport club. I've placed a link to webform in the header that adds more rows into that view, which works fine but I'd like to redirect the form to go back to that view with person's ID as the argument/token. To make it more straightforward: my view is `/grade-details/%id`, webform pickups the ID and inserts new data into right person table.

How can I make the redirection to go back to the view with same person details?

# Answer
If it's anything like Drupal 8, tokens are supported if you pick the "URL (redirects to a custom path or URL)" confirmation type.

I'd try entering /grade-details/\[token:here\]

Some tokens that might work: \[current-page:url:absolute\] or \[current-page:url:relative\]
> 0 votes

---
Tags: 7, webforms
---


title: Webform submission tokens in emails

text:
# Question
Title: Webform submission tokens in emails
I am trying to print the webform submission label and value from tokens in confirmation email. The problem is that the label of the form element is not appearing, only the value. Tried with:

\[webform\_submission:values:email\] \[webform\_submission:values:email:withlabel\] \[webform\_submission:values:format:html\]

When I print all the elements with \[webform\_submission:values\] , I am able to see also the labels, but the formatting is not so good, so I want to print the values line by line.

# Answer
> 1 votes
My solution is simply manually typing out relevant labels for each line. I just use "Custom body"

For example:

Name: \[webform\_submission:values:navn:value\]

Email: \[webform\_submission:values:email:value\]

Date: \[current-date:html\_date\]

Unless you change your form often i find that to be the easiest way to format it exactly as you want it.

---
Tags: 8, tokens
---


# Question
Title: How can I modify the core field "link" widget?
I need to alter the "Embed Link" form provided by Drupal 8 in the node AddForm. Namely I need to add a select list form item to specify the "type" of the

For this I am trying to implement a hook\_form\_alter()

```
  if(isset($form['field_link_embed'])){
   $form['field_link_embed']['widget']['format'] = [
    '#type' => 'select',
    '#required' => TRUE,
    '#title' =>t("Link format"),
    '#options' => [
        'open' => t("option1"),
        'html' => t("option2"),
    ]
  ];

```

But I guess this is not the right chain how to access the form $form\['field\_link\_embed'\]\['widget'\]\['format'\], could you please help me?

# Answer
Here is quick and dirty `hook_form_alter` implementation that does this

Add this to your `THEMENAME.theme` or your `MODULENAME.module`

```
function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == "node_article_edit_form" || $form_id == "node_article_form") {
    $link_count = intval($form["field_link_embed"]["widget"]["#max_delta"]);
    for ($i = 0; $i <= $link_count; $i++) {
      if (isset($form["field_link"]["widget"][$i]["format"])) {
        continue;
      }
      $form["field_link"]["widget"][$i]["format"] = [
        '#type' => 'select',
        '#required' => TRUE,
        '#title' => t("Link format"),
        '#options' => [
          'open' => t("option1"),
          'html' => t("option2"),
        ],
      ];
    }
  }
}

```

**NOTE:** you have to modify `node_article_form` and `node_article_edit_form` and perhaps `field_link_embed` to match your setup.

Perhaps for more involved implementation you should create a dedicated `field_formatter` using `web/core/modules/link/src/Plugin/Field/FieldFormatter/LinkFormatter.php` as a starting point.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Page cache works on local dev but not on production
I've a Drupal 8.6.9 site running on Apache 2.4 and PHP 7.2. I've enabled the internal page cache, the dynamic page cache, and the BigPipe module in an effort to tease out some more performance.

I've set max-age to 1 day, under /admin/config/development/performance.

On my local development site (drupalvm, Ubuntu 16.04) I can see *X-Drupal-Cache: HIT* and a visible improvement in performance, but on the hosting server, also Ubuntu 16.04, I only ever see *X-Drupal-Cache: MISS*.

As far as I can tell, there's nothing amiss in settings.php on the live server, the Drupal config is identical, so there must be something amiss in the Apache settings, perhaps.

Has anyone come across this before where cache works on one environment, but not another?

# Answer
> 0 votes
Just leaving this here in case it helps someone else.

In my case, the Drupal cache HTTP headers were reporting MISS due an issue with memcache on the live server. The memcached daemon wasn't running, but the memcache Drupal module was enabled and being used as the default cache. Re-installing memcache on the live server resulted in the the X-Drupal-Cache header being set as expected.

Phew!

# Answer
> 2 votes
My guess is during your testing you're visiting the page for the first time which would result in a X-Drupal-Cache: MISS (As you'd expect)

And as you've got the max-age set to 1 day your browser has now cached that response so no matter how many page visits you do for the next day you'll always see the MISS for that page (Because your browsers not going back to your server to get a fresh response) So other future users/different browsers could potentially be getting a HIT response after you've now forced drupal to create its initial cache

I'm only guessing here as I haven't tried myself but would seem to make sense. You could test it out by opening the same page in a different browser after you've got the MISS on your first browser to see if that 2nd browser is now seeing HIT

---
Tags: 8, caching
---


# Question
Title: Enabling custom content entity module throws error
While enabling my custom module that creates a custom content entity through Drush, I get the following error:

> \[error\] Drush command terminated abnormally due to an unrecoverable error. Error: Declaration of Drupal\staff\_profile\Entity\StaffProfile::preCreate() must be compatible with Drupal\Core\Entity\EntityInterface::preCreate(Drupal\Core\Entity\EntityStorageInterface $storage, array &$values) in /Users/user/Sites/drupal8staff/web/modules/custom/staff\_profile/src/Entity/StaffProfile.php, line 54

Line 54 corresponds to the class StaffProfile in the following:

```
<?php
namespace Drupal\staff_profile\Entity;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Druapl\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\UserInterface;
use Drupal\staff_profile\StaffProfileInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityPublishedTrait;

/**
 * Defines staff_profile entity class
 *
 *  @ingroup staff_profile
 *  @ContentEntityType(
 *    id = "staff_profile_profile",
 *    label = @Translation("Staff Profile"),
 *    handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\content_entity_example\Entity\Controller\StaffProfileListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "form" = {
 *       "add" = "Drupal\content_entity_example\Form\StaffProfileForm",
  *       "edit" = "Drupal\content_entity_example\Form\StaffProfileForm",
  *       "delete" = "Drupal\content_entity_example\Form\StaffProfileDeleteForm",
  *     },
  *     "access" = "Drupal\content_entity_example\StaffProfileAccessControlHandler",
  *   },
  *    base_table = "staff_profile_entity",
  *    admin_permission = "administer staff profile entity",
  *    fieldable = TRUE,
  *    links = {
  *      "canonical" = "/people/{staff_profile_profile}",
  *      "add-page" = "/people/add",
  *      "edit-form" = "/people/{staff_profile_profile}/edit",
  *      "delete-form" = "/people/{staff_profile_profile}/delete",
  *      "collection" = "/people/list",
  *    },
  *    entity_keys = {
  *      "id" = "id",
  *      "uuid" = "uuid",
  *      "label" = "usernme",
  *      "published" = "status",
  *    },
  *    field_ui_base_route = "staff_profile.staff_profile_settings",
  *  )
  *
 */
 class StaffProfile extends ContentEntityBase implements StaffProfileInterface, EntityPublishedInterface {
   use EntityChangedTrait;

   /**
   * {@inheritdoc}
   * Set computed fields when creating a new Staff Profile
   */
   public static function preCreate(EntityStorageInterface $storage, array &$values) {
     parent::preCreate($storage, $values);
     $values += array(
       'user_id' => \Drupal::currentUser()->id(),
     );

// Methods omitted for brevity

   }

   /**
   * {@inheritdoc}
   *
   * Creates Fields and properties
   * Defines gui behavior
   */
   public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
     $fields['id'] = BaseFieldDefinition::create('integer')
       ->setLabel(t('ID'))
       ->setReadOnly(TRUE);

     $fields['uuid'] = BaseFieldDefinition::create('uuid')
       ->setLabel(t('UUID'))
       ->setReadOnly(TRUE);

 //Fields omitted for brevity

      $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
          ->setLabel(t('User Name'))
          ->setSettings(array(
            'target_type' => 'user',
            'handler' => 'default',
          ))
          ->setDisplayOptions('view', array(
            'label' => 'hidden',
            'type' => 'entity_reference_label',
            'weight' => -3,
          ))
          ->setDisplayOptions('form', array(
            'type' => 'entity_reference_autocomplete',
            'settings' => array(
              'match_operator' => 'CONTAINS',
              'size' => 60,
              'autocomplete_type' => 'tags',
              'placeholder' => '',                 ),
          ))
          ->setDisplayConfigurable('form', TRUE)
          ->setDisplayConfigurable('view', TRUE);
      }
  }

```

StaffProfileInterface.php contents:

```
<?php
namespace Drupal\staff_profile;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\user\EntityOwnerInterface;
use Drupal\Core\Entity\EntityChangedInterface;

/**
 * Provides an interface defining a StaffProfile entity.
 * @ingroup staff_profile
 *
 */

interface StaffProfileInterface extends ContentEntityInterface, EntityOwnerInterface, EntityChangedInterface {
}

```

The preCreate method is the exact same as what can be found on the example for content entities in the Drupal 8 entity API Docs. I was able to successfully install a copy of the example content entity, but not my entity. The example entity requires the examples module, is there something in that module that I am missing in mine or was this caused by an error in my implementation?

# Answer
Your problem is most likely this statement:

```
use Druapl\Core\Entity\EntityStorageInterface;

```

Drupal is spelled incorrectly. Thus it's not using the correct class in the type hint and thinking it's an incorrect implementation
> 0 votes

---
Tags: 8, entities, drush
---


# Question
Title: Converting seconds to date with Facet API
I've inherited a project that deals with Drupal Facet API. I've got everything working fine, except for the display of the date for events.

The filter by date and time \>\> start date displays the date in seconds, however I would like this to be the date and time, e.g. **Saturday 14th September 10:15 am**

Here is the code from the event\_system.module:

```
     if (isset($variables['view']) && $variables['view']->name == 'events') {
    $i = $variables['view']->row_index;
    $timestamp = strtotime($variables['view']->result[$i]->field_data_field_date_and_time_field_date_and_time_value);
    $variables['post_date'] = format_date($timestamp, 'medium');
  }

```

I've tried this:

```
$variables['post_date'] = format_date($timestamp, 'custom', 'g:i a, d F, Y',0);

```

and this:

```
$variables['post_date'] = format_date('l jS F Y', strtotime($timestamp));

```

I've tried adding different parameters to format\_date but with no success. If someone could point me in the right direction that would be great.

# Answer
So it sounds like the issue is you need to convert a UNIX timestamp to a human-readable datetime? PHP comes with the date() function which can handle this.

The first argument is the 'format' which you can find here: http://php.net/manual/en/function.date.php.

The second argument is the UNIX timestamp--just simply pass in the timestamp variable (the # of seconds) as the second argument.
> 0 votes

---
Tags: 7, search
---


# Question
Title: What is the deal with config collections?
When manipulating configuration yaml files in config/sync, I note that if you put files in subdirectories, and run `drush config:import`, the files in those subdirectories are denoted as belonging to a 'collection'. (Top-level files have no collection listed)

This seems like it might be a useful organisational unit. However, it seems like configurations that are part of a collection are not acted on.

For example, if I put a `node.type.test.yml` in `config/sync`, and run `drush config:import` then a corresponding node type is created as expected. However, if instead I put the file in `config/sync/test` and run `drush config:import`, then no type is created.

What is the purpose of these collections? Is there some way to indicate that you want collections to be activate/inactive within the configuration? Do they serve some completely different purpose?

# Answer
Collections are for configuration overrides. Mainly used for translations, but could be used for other purposes as well. You can list the available collections in your Drupal installation, starting with the default collection (empty string):

```
$collections = \Drupal::service('config.manager')->getConfigCollectionInfo()->getCollectionNames();

```

More info https://www.drupal.org/node/2268523
> 7 votes

---
Tags: 8, configuration
---


# Question
Title: Custom Display Modes on a custom entity type
I have created a custom entity type (without bundles) using the Drupal Console command. Everything works fine with the out the box stuff. I can configure fields, the order of the form and the order of the output display.

However, it seems impossible to add and new View Modes to my new entity type. I have tried adding a new mode to the "Content" view modes section but I don't have the collapsable details section to be able to enable new view modes.

Is there a setting I have missed in the entity code that will display this?

# Answer
> 10 votes
This can also be achieved through the UI.

1. Logged in as admin, press Structure \> Display modes \> View modes \> Add ( /admin/structure/display-modes/view/add )
2. Select your custom entity type to add a display mode
3. Enter a name for the display mode

# Answer
> 7 votes
As always, I found the answer just after posting the question.

For others looking for the same thing, you need to create an install .yml file in your custom module. I found this by looking at the Media module in core.

In your module create config/install/core.entity\_view\_mode.ENTITY\_TYPE\_ID.NAME\_OF\_VIEW\_MODE\_TO\_CREATE.yml that implements the following:

```
langcode: en # Or your default site language
status: false
dependencies:
  module:
    - my_module
id: entity_type_id.name_of_view_mode_to_create
label: 'My new View Mode'
targetEntityType: entity_type_id
cache: true

```

I hope this helps someone else too :D

---
Tags: 8
---


title: How can I remove old articles?

text:
# Question
Title: How can I remove old articles?
I have a Drupal 7 database that stores articles since 2013. The database is too big and I want to drop all the old articles to keep only the ones created on 2019, just for development purpose. I read Delete a node after X weeks it was created, which describes what to do on Drupal 8. Is there a similar method for Drupal 7?

# Answer
> 2 votes
The previous solutions offered by @berramou and @kiamlaluno♦ should serve you well. On the other hand, if you're looking for a step by step solution, it's the following:

Based on @kiamlaluno♦'s answer, here is the full solution for novices:

1. Go to your file directory and go to `/sites/all/modules`. Create a folder here called `delete_old_nodes`
2. Create a file in the folder you just created called: "delete\_old\_nodes.info" and paste this code in it:

```
name = Delete old nodes
description = Deletes nodes older than 30 days.
package = Custom
version = 1.0
core = 7.x

```
3. Create a file called "delete\_old\_nodes.module" and paste @kiamlaluno♦'s code into it:

```
<?php

function mymodule_cron() {
   $entity_query = new EntityFieldQuery();
   $entity_query->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'article')
     ->entityCondition('created', strtotime('1 January 2019'), '<')
     ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
     ->range(0, 25);
   $result = $entity_query->execute();
   if (isset($result['node'])) {
     node_delete_multiple(array_keys($result['node']));
   }
}

```
4. Flush cache, then navigate to modules page, `yoursite.com/admin/modules`, and enable your module, (by searching for "delete old nodes", click the checkbox by the modules name and click save).
5. When you want to **delete** all the nodes up to 1 January 2019, run cron by going to `yoursite.com/admin/reports/status/run-cron`.
6. Go back to the modules page, `yoursite.com/admin/modules`, and disable the module "delete old nodes".
7. Upvote @kiamlaluno♦'s answer.
8. Done!

# Answer
> 3 votes
The code I would use is similar to the following one.

```
$entity_query = new EntityFieldQuery();
$entity_query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->entityCondition('created', strtotime('1 January 2019'), '<')
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $entity_query->execute();
if (isset($result['node'])) {
  node_delete_multiple(array_keys($result['node']));
}

```

The differences between the code I am using and the code shown in the answers for Delete a node after X weeks it was created are the following:

* The object used to query the entity is instantiated differently and its class is different
* The code doesn't select just the published nodes (I take you are interested in deleting all the nodes created before 2019)
* The code is using `addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')` to get all the nodes, even the ones to which the currently logged-in user doesn't have access (Remember that cron tasks are executed as anonymous user, which possibly doesn't have access to many of the nodes)
* In Drupal 7, the functions to delete nodes are `node_delete()` and `node_delete_multiple()` which require, respectively, a node ID and an array of node IDs

If I were to do the task in a `hook_cron()` implementation, I would use the following code.

```
  function mymodule_cron() {
    $entity_query = new EntityFieldQuery();
    $entity_query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->entityCondition('created', strtotime('1 January 2019'), '<')
      ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
      ->range(0, 25);
    $result = $entity_query->execute();
    if (isset($result['node'])) {
      node_delete_multiple(array_keys($result['node']));
    }
  }

```

Older Drupal 7 versions would need to replace `addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')` with `addMetaData('account', user_load(1))`. For those versions the code would be then similar to the following one.

```
  function mymodule_cron() {
    $entity_query = new EntityFieldQuery();
    $entity_query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->entityCondition('created', strtotime('1 January 2019'), '<')
      ->addMetaData('account', user_load(1))
      ->range(0, 25);
    $result = $entity_query->execute();
    if (isset($result['node'])) {
      node_delete_multiple(array_keys($result['node']));
    }
  }

```

Using `hook_cron()` avoids issues in the case there are many nodes to delete. Trying to load, for example, 3000 nodes (even if the `EntityFieldQuery` class returns partially loaded nodes) could cause memory or timeout errors.

# Answer
> 2 votes
Yes you there is a similar method to do so you can use EntityFieldQuery

Here is a helper function to delete all `articles` older than two weeks. You can use it as `drush command` or in `cron_hook` as it described in the mentioned question.

```
function delete_older_articles(){
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->entityCondition('created', strtotime('-2 week'), '<=')
    ->propertyCondition('status', NODE_PUBLISHED);
  $result = $query->execute();
  foreach ($result['node'] as $nid => $node) {
    node_delete($nid);
  }
}

```

---
Tags: 7, nodes
---


# Question
Title: How to increase default Drupal minimum cache lifetime options to a custom value?
Currently the max page cache age is 1 day. I would like to icnrease to 1 year. How can I do that?

These settings are located at /admin/config/development/performance

* "Minimum cache lifetime"
* "Expiration of cached pages"

Boost had a patch http://drupal.org/node/326683, wonder if this somehow could be applied for the core cache.

# Answer
Just set the variable 'page\_cache\_maximum\_age' using variable\_set in custom module to the value 31536000

```
variable_set('page_cache_maximum_age', 31536000);

```

If you install the Devel Module there is a page for viewing and editing variables.

Above is a quick fix. If you want to do a perfect way then you need to form alter the "system\_performance" form and change the option of below field.

```
  $period = drupal_map_assoc(array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400), 'format_interval');
  $period[0] = '<' . t('none') . '>';
  $form['caching']['cache_lifetime'] = array(
    '#type' => 'select',
    '#title' => t('Minimum cache lifetime'),
    '#default_value' => variable_get('cache_lifetime', 0),
    '#options' => $period,
    '#description' => t('Cached pages will not be re-created until at least this much time has elapsed.')
  );
  $form['caching']['page_cache_maximum_age'] = array(
    '#type' => 'select',
    '#title' => t('Expiration of cached pages'),
    '#default_value' => variable_get('page_cache_maximum_age', 0),
    '#options' => $period,
    '#description' => t('The maximum time an external cache can use an old version of a page.')
  );

```
> 5 votes

# Answer
If you don't want to write a custom module, you can also set these values in your site's settings.php file:

```
$conf['cache_lifetime'] = 31536000;
$conf['page_cache_maximum_age'] = 31536000;

```

These values won't show up in the /admin/development/performance screen, so if you need to check the values in force, you can use drush:

```
> drush vget cache_lifetime
> drush vget page_cache_maximum_age

```

Or, go with @Anil-sagar's suggestion and implement an override to the system performance form.
> 0 votes

---
Tags: caching, 7
---


# Question
Title: Does the Transliteration module alter the existing URLs?
I want to install the Transliteration module for a site on Drupal.

If I install this module, would it also change existing URLs (if I enabled it in the Pathauto module settings), or would it change just the new urls? I don't to alter the existing URLs.

# Answer
> 0 votes
The Transliteration module doesn't update anything on its own. It's the Pathauto that controls that. Just enabling the Transliteration won't do anything.

Pathauto module has a setting for what happens when an entity is updated (`/admin/config/search/path/settings`). This means that when you edit existing content Pathauto may change the alias depending on your settings.

You can set it to `Do nothing. Leave the old alias intact.` This way you'll be able to edit old content without the alias being automatically changed.

If you need to use some other `Update action` setting you'll have to remember each time when editing an "old" node to untick the option `Generate automatic URL alias` and use the "old" alias manually.

---
Tags: 7, transliteration
---


title: Views Bootstrap (Carousel) Not Working

text:
# Question
Title: Views Bootstrap (Carousel) Not Working
I've installed the Views Bootstrap module primarily so that I can easily create the same carousels that the Bootstrap/non Drupal parts of our site use. I would prefer to use Views Bootstrap or else I will have to use a different carousel module and try to style it so it looks the same.

I have for images in my result set. All I am getting right now is a page with one number for each image like this:

1.
2.
3.
4.

Below this I get the images, left aligned, one per row.

In the view settings I am using Bootstrap Carousel for Format and Bootstrap Carousel for Show. I get this same result whether I am using this view as a block or as a page. I don't know if it matters but I am using the Omega 3 theme.

Any help would be appreciated.

Thanks

# Answer
To use Views Bootstrap module you need to have theme that based on Twitter Bootstrap. If your theme is not based on it, you may take a look to similar modules, such as Nivo slider
> 2 votes

# Answer
That's how it appears in the view but, if you place your view in a panel or in a region you'll see the bootstrap carousel working like a charm :)
> 1 votes

# Answer
I had a similar issue where my Slideshow images were listed in an order, instead of functioning as a slideshow. Initially I though it was the problem of Jquery.

But it was not basically I read through the documentation found that for my version of Drupal and Bootstrap which is Drupal 8 and Bootstrap 3 I am suppose to install 8.x-3.x version of Views\_Bootstrap

Walla! All of sudden my slide show started to work again.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: Where in The Database does File Usage Data Come From
How does data in file/\[id\]/**usage** get compiled?

From what tables does it determine a use?

Is there a way to track down how/where it gets this data and troubleshoot? Does it take include revision data?

# Answer
This route is provided by the File Entity module. See the `hook_menu()` implementation where it's registering a callback for that page: `file_entity_usage_page`.

> ```
> $items['file/%file/usage'] = array(
>   'title' => 'Usage',
>   'page callback' => 'file_entity_usage_page',
>   'page arguments' => array(1),
>   'access callback' => 'file_entity_access',
>   'access arguments' => array('update', 1),
>   'type' => MENU_LOCAL_TASK,
>   'context' => MENU_CONTEXT_PAGE,
>   'file' => 'file_entity.pages.inc',
> );
>
> ```

Inside `file_entity_usage_page()` in the `file_entity.pages.inc` file following function from core's `includes/file.inc` gets called which retrieves the information directly from the `file_usage` table.

> ```
> function file_usage_list(stdClass $file) {
>   $result = db_select('file_usage', 'f')
>     ->fields('f', array('module', 'type', 'id', 'count'))
>     ->condition('fid', $file->fid)
>     ->condition('count', 0, '>')
>     ->execute();
>   $references = array();
>   foreach ($result as $usage) {
>     $references[$usage->module][$usage->type][$usage->id] = $usage->count;
>   }
>   return $references;
> }
>
> ```

Core's `includes/file.inc` file provides the API for handling file uploads and server file management. It also provides a function `file_usage_add()` which gets called every time a managed file gets uploaded and which adds newly added file IDs to the `file_usage` table.

> ```
> function file_usage_add(stdClass $file, $module, $type, $id, $count = 1) {
>   db_merge('file_usage')
>     ->key(array(
>       'fid' => $file->fid,
>       'module' => $module,
>       'type' => $type,
>       'id' => $id,
>     ))
>     ->fields(array('count' => $count))
>     ->expression('count', 'count + :count', array(':count' => $count))
>     ->execute();
> }
>
> ```

The `file_usage` table gets installed from core upon Drupal installation from `modules/system/system.install`'s `function system_schema()`.

> ```
> $schema['file_usage'] = array(
>   'description' => 'Track where a file is used.',
>   'fields' => array(
>     'fid' => array(
>       'description' => 'File ID.',
>       'type' => 'int',
>       'unsigned' => TRUE,
>       'not null' => TRUE,
>     ),
>     'module' => array(
>       'description' => 'The name of the module that is using the file.',
>       'type' => 'varchar',
>       'length' => 255,
>       'not null' => TRUE,
>       'default' => '',
>     ),
>     'type' => array(
>       'description' => 'The name of the object type in which the file is used.',
>       'type' => 'varchar',
>       'length' => 64,
>       'not null' => TRUE,
>       'default' => '',
>     ),
>     'id' => array(
>       'description' => 'The primary key of the object using the file.',
>       'type' => 'int',
>       'unsigned' => TRUE,
>       'not null' => TRUE,
>       'default' => 0,
>     ),
>     'count' => array(
>       'description' => 'The number of times this file is used by this object.',
>       'type' => 'int',
>       'unsigned' => TRUE,
>       'not null' => TRUE,
>       'default' => 0,
>     ),
>   ),
>   'primary key' => array('fid', 'type', 'id', 'module'),
>   'indexes' => array(
>     'type_id' => array('type', 'id'),
>     'fid_count' => array('fid', 'count'),
>     'fid_module' => array('fid', 'module'),
>   ),
> );
>
> ```

---

Yes, on `file/%file/usage` not only the nodes get listed where a certain file is being referenced, also node revisions are listed.

On `file/%file/edit` then you have the option to replace this file on all listed places, and as another option to "Keep (the) original filename", which then replaces the file everywhere it's being used and keeps its former URL intact.
> 1 votes

# Answer
I couldn't find any `/usage` path in core. You must be using a custom or contrib file manager module.

> From what tables does it determine a use?

According to file\_usage\_list the file usage info is stored in the **file\_usage** table, so I bet the custom or contrib module must be reading from there.
> 1 votes

---
Tags: 7, files, media
---


title: How do I show a block in a region?

text:
# Question
Title: How do I show a block in a region?
All blocks in the *footer* region use a CSS grid system. I want to add a `<div>` with CSS attributes to each (custom) block in the footer. The code I have will show the blocks in the footer, but will give an error. Changing `{{ key }}` to `{{ key.content }}` is not helping. I am using Drupal 8.6.8.

The code that I am using in the page.html.twig template is the following.

```
{% for key in page.footer %}
    <div class="col col-4">
        {{ key }}
    </div>
{% endfor %}

```

Using that code, I get this error message.

> User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php).

# Answer
> 0 votes
Remove array keys starting with '#':

```
{% for key, block in page.footer if key|first != '#' %}
    <div class="col col-4">
        {{ block }}
    </div>
{% endfor %}

```

---
Tags: theming, blocks
---


title: Drupal 8, error on order view page

text:
# Question
Title: Drupal 8, error on order view page
I'm working on a Drupal 8 / Drupal Commerce website, and I run into "Website encountered unexpected error" when trying to access /admin/commerce/orders/\* pages (order view page).

In log messages I get :

```
Error : Unsupported operand types dans Drupal\views\Element\View::preRenderViewElement() (/---/core/modules/views/src/Element/View.php ligne 49)
#0 [internal function]: Drupal\views\Element\View::preRenderViewElement(Array)
#1 /---/core/lib/Drupal/Core/Render/Renderer.php(378): call_user_func(Array, Array)
#2 /---/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#...
#10 /---/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('commerce_order', Array)

```

So it seems that a view displayed on these pages causes this error. Does anyone ran into this error ?

Thanks

**EDIT**

After some debugging, I found that in

```
/core/modules/views/src/Element/View.php L49
$element += $view->element;

```

...$view is null, which causes the error. Above that line, $view is defined by this line (L43) :

```
$view = Views::getView($element['#name']);

```

...and $element\['#name'\] = commerce\_order\_item\_table.

The View::getView() method is :

```
public static function getView($id) {
  $view = \Drupal::service('entity.manager')->getStorage('view')->load($id); // this call returns null
  if ($view) {
    return static::executableFactory()->get($view);
  }
}

```

So it seems that I miss a view (commerce\_order\_item\_total) ?... I'll report further info here.

**EDIT 2**

My missing view seems to be defined in

```
/modules/contrib/commerce/modules/order/config/install/views.view.commerce_order_item_table.yml

```

...but is not found apparently.

**EDIT3**

On /admin/config/development/configuration/single/export (exporting a single element), selectting "view" as configuration type, I cannot find "commerce\_order\_item\_table". Doing a manual full export (drush cex --destination=sync) I don't find a views.view.commerce\_order\_item\_table in sync folder.

# Answer
I didn't find out why my order views disappeared, but I was able to import them back using configuration synchronization :

https://www.drupal.org/node/2917828#comment-12321847
> 0 votes

# Answer
I had the same error, but with a different view for commerce\_orders, views.view.commerce\_activity.yml, when viewing an order as an admin.

Export the view then importing the view with content synchronization did the trick.
> 0 votes

---
Tags: views, 8, commerce
---


# Question
Title: How to get all node entities tagged with a specific term?
For a given taxonomy term in D8, is there any API function/method that returns all node entities that reference it?

# Answer
> 19 votes
You can use `loadByProperties()` to get all node entities that reference `$term_id`:

```
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_tags' => $term_id,
]);

```

# Answer
> 11 votes
Easiest way I think is to query database `taxonomy_index` table keeps record of what node is tagged with what term

```
function _get_nodes_by_term($term_id) {
  $query = \Drupal::database()->select('taxonomy_index', 'ti');
  $query->fields('ti', ['nid']);
  $query->condition('ti.tid', $term_id);
  $nodes = $query->execute()->fetchAssoc();
  return $nodes;
}

dpm(_get_nodes_by_term(<term_id>));

```

Drupal Core does it by views.
Out the box term page display is created by views so if you visit `admin/structure/views/view/taxonomy_term`, this view is responsible to show all tagged content by given term, which is essentially running database query.

# Answer
> 5 votes
If you have multiple term ids you can pass an array of the ids instead of just a single value.

```
$term_ids =  array (1,2,3);
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_tags' => $term_ids,
]);

```

# Answer
> 3 votes
If your nodes not having revision then this code will work, by default it will return the first revision

```
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->getQuery()
 ->condition('field_tags', $termId)
 ->execute();

```

**If your nodes have multiple revisions, To get the nodes by the latest tagged revision. you need to use the following code**

```
$nodes = \Drupal::entityTypeManager()->getStorage('node')->getQuery()
->latestRevision()
->condition('field_tags', $termId, '=')
->execute();

```

***if you have multiple values then you can use array***

```
 $termIds = [3,56,456];
 $nodes = \Drupal::entityTypeManager()->getStorage('node')->getQuery()
 ->latestRevision()
 ->condition('field_tags', $termIds)
 ->execute();

```

---
Tags: 8, taxonomy-terms
---


title: How to hide a menu from <front> page?

text:
# Question
Title: How to hide a menu from <front> page?
The main menu comes with 5 items.

How can I hide one items from the \< front \> page, i.e. 4 items are shown on front page, 5 items are shown on other pages?

# Answer
The easiest way is through CSS.

```
body.front .your-menu .list-item-identifier {
  display: none;
}

```
> 3 votes

# Answer
If you don't have your own theme or a sub-theme you can simply use the css injector module which allows you to quickly implement CSS code with great granularity. This quick tutorial will show you how easy in a blink of an eye. Hope that helps.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Add external CSS file with custom backend setting
I'm trying to add a external CSS file. The client wants to be able to change the url from the backend. Creating a backend settings form is not an issue, but I can't seem to get the file loaded in the frontend.

My code:

```
function MYTHEME_library_info_build() {
  $libraries = [];
  $libraries['mylibrary'] = [
    'version' => '1.0',
    'css' => [
      'base' => [
        'https://www.mywebsite.com/css/styles.css' => [],
      ],
    ],
  ];

  return $libraries;
}

```

The fixed url will be replaced with a variable containing the value entered in the backend.

# Answer
`hook_library_info_build()` would be the right hook to add dynamic library definitions (definitions that depend on any run-time information) but it needs to be implemented by a module, as its documentation page says.

> Modules may implement this hook to add dynamic library definitions. Static libraries, which do not depend on any runtime information, should be declared in a modulename.libraries.yml file instead.

`hook_library_info_alter()` can be implemented by either a module or a theme.

> Allows modules and themes to change libraries' definitions; mostly used to update a library to a newer version, while ensuring backward compatibility. In general, such manipulations should only be done to extend the library's functionality in a backward-compatible way, to avoid breaking other modules and themes that may be using the library.

If there are default values you can use (for example, using a local CSS file that is then replaced from `hook_library_info_alter()` basing on run-time information), you can put those default values in the .libraries.yml file, and use `hook_library_info_alter()` to alter them.
> 1 votes

# Answer
This is what I ended up using:

```
/**
 * Implements hook_library_info_alter().
 */
function MYTHEME_library_info_alter(&$libraries, $extension) {
  if($extension == 'MYTHEME') {
    $css = theme_get_setting('theme_custom_css');
    $js = theme_get_setting('theme_custom_js');

    if(!empty($css) && substr(strrchr($css,'.'),1) == 'css') {
      $libraries['main']['css']['theme'][$css]['type'] = 'external';
      $libraries['main']['css']['theme'][$css]['weight'] = '110';
    }
    if(!empty($js) && substr(strrchr($js,'.'),1) == 'js') {
      $libraries['main']['js'][$js]['type'] = 'external';
    }
  }
}

```
> 0 votes

---
Tags: 8
---


title: Validating a node body

text:
# Question
Title: Validating a node body
hello i am trying to validate the content of the node body for certain text having some trouble with it. it outputs an message "array".

```
function test_form_alter(&$form, FormStateInterface $form_state) {
  // Custom validate function.
  $form['#validate'][] = 'submitForm';
}

function submitForm(array &$form, FormStateInterface $form_state) {
  $author = $form_state->getValue('author');
  $body = $form_state->getValue('body');
  $title = $form_state->getValue('title');
  drupal_set_message('Thanks for submitting the form! you typed in the following as author:' . $author . ' . body:' . $body . '. title:' . $title);
}

```

# Answer
You get the outputs message as an array, because you supplied `$body` and `$title` as arrays, and `$form_state->getValue('author');` doesn't give you author of node test with the following code:

```
function test_form_alter(&$form, FormStateInterface $form_state) {
  // Custom validate function.
  $form['#validate'][] = 'validateForm';
}

function validateForm(array &$form, FormStateInterface $form_state) {
  //- Get the author id.
  $author_uid = $form_state->getValue('uid')[0]['target_id'];
  // Load the author account.
  $author = User::load($author_uid);
  //- Get the body value, if you want just the summary change value by summary.
  $body = $form_state->getValue('body')[0]['value'];
  //- Get the title value .
  $title = $form_state->getValue('title')[0]['value'];
  //- Use addMessage instead of drupal_set_message its deprecated.
  \Drupal::messenger()->addMessage('Thanks for submitting the form! you typed in the following as author:' . $author->getAccountName() . ' . body:' . $body . '. title:' . $title);
}

```

Don't forget to add the following use:

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;

```
> 0 votes

---
Tags: 8, hooks
---


# Question
Title: Importing database: Duplicate entry 'X' for key 'PRIMARY'
I used this script to backup Drupal database from PHP - http://davidwalsh.name/backup-mysql-database-php , but removed all "DROP TABLE" stuff to be able to import it to empty database. However, when I'm doing

> mysql -u user -p database \< db-backup.sql

I'm getting error "ERROR 1062 (23000) at line 18512: Duplicate entry 'xxx' for key 'PRIMARY'". This is about cache\_path table, and specific path. I don't know how often it can happen but I'm wondering, what could cause it, and how handle it, in the best way.

The line that causes error looks like this:

> INSERT INTO cache\_path VALUES("some/path","a:39:{i:0;s:8:\\"node/432\\";i:1;s:8:\\"node/505\\";i:2;s:8:\\"node/475\\";i:3;s:8:\\"node/278\\";i:4;s:8:\\"node/424\\";i:5;s:8:\\"node/351\\";i:6;s:8:\\"node/332\\";i:7;s:8:\\"node/452\\";i:8;s:8:\\"node/382\\";i:9;s:8:\\"node/329\\";i:10;s:8:\\"node/181\\";i:11;s:8:\\"node/257\\";i:12;s:8:\\"node/274\\";i:13;s:8:\\"node/446\\";i:14;s:8:\\"node/182\\";i:15;s:8:\\"node/294\\";i:16;s:8:\\"node/183\\";i:17;s:8:\\"node/437\\";i:18;s:8:\\"node/184\\";i:19;s:8:\\"node/421\\";i:20;s:8:\\"node/192\\";i:21;s:8:\\"node/259\\";i:22;s:8:\\"node/414\\";i:23;s:8:\\"node/396\\";i:24;s:8:\\"node/375\\";i:25;s:15:\\"taxonomy/term/1\\";i:26;s:20:\\"taxonomy/term/1/feed\\";i:27;s:7:\\"node/29\\";i:28;s:6:\\"node/5\\";i:29;s:7:\\"node/30\\";i:30;s:7:\\"node/25\\";i:31;s:7:\\"node/26\\";i:32;s:7:\\"node/27\\";i:33;s:7:\\"node/28\\";i:34;s:8:\\"node/304\\";i:35;s:6:\\"node/4\\";i:36;s:6:\\"node/1\\";i:37;s:6:\\"node/2\\";i:38;s:6:\\"node/3\\";}","1377033251","1376946851","1");

# Answer
> 3 votes
> but removed all "DROP TABLE" stuff to be able to import it to empty database

That's where you went wrong. Leave the database dump file exactly as it is, and then import it.

mysqldump adds `DROP TABLE IF EXISTS` by default, so unless you've specifically told it not to do that, the changes you're making are redundant, even incorrect.

It's a good idea to truncate the `cache_*` tables *before* running the data export. That way you don't get lots of ephemeral data in your backup, and exports/imports are quicker. I don't know if it will solve your current problem (if you have no duplicate errors elsewhere in the SQL script then it probably will), but either way it's a good habit to get into.

# Answer
> 1 votes
When you have no control of the export and the database dump is a few GB in size which makes it very difficult to edit it with a text editor the best option perhaps is to force the sql queries to run even after/with errors with the `-f` option.

```
$ mysql -f -u username -ppassword database < db.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1062 (23000) at line 8002: Duplicate entry 'ever?' for key 'PRIMARY'
ERROR 1062 (23000) at line 8008: Duplicate entry '??' for key 'PRIMARY'

```

And then perhaps inspect the problematic lines using `sed 'LINENUMBERq;d' file` to see if those lines are critical insertions

```
$ sed '8002q;d' db.sql  > temp.sql
$ sed '8008q;d' db.sql  >> temp.sql
$ nano temp.sql

```

---
Tags: 7, database
---


# Question
Title: How do I fix the "The each() function is deprecated" error?
I am using Drupal 7.6.0 on a server with PHP version 7.2.11.

I get this error message.

> Deprecated function: The each() function is deprecated. This message will be suppressed on further calls in menu\_set\_active\_trail() (line 2405 of C:\xampp\htdocs\portailcommerce\includes\menu.inc).

How can I fix it?

# Answer
> 4 votes
Just update Drupal 7 to latest version which, as I am writing this answer, is version 7.64. Drupal 7 doesn't use `each()` in PHP since November 7, 2018, as the CHANGELOG.txt file says. (See the last line of the part I quoted.)

> Drupal 7.61, 2018-11-07
>
> * File upload validation functions and `hook_file_validate()` implementations are now always passed the correct file URI.
> * The default form cache expiration of 6 hours is now configurable (API addition: https://www.drupal.org/node/2857751).
> * Allowed callers of `drupal_http_request()` to optionally specify an explicit Host header.
> * Allowed the + character to appear in usernames.
> * PHP 7.2: Fixed Archive\_Tar incompatibility.
> * PHP 7.2: Removed deprecated function `each()`.

As long as you use at least Drupal 7.61, you will fix the error you shown, which (in your case) is caused from `menu_set_active_trail()`. (The code shown in the documentation page doesn't show any line using `each()` because the code has been updated to the latest Drupal 7 version.)

If you are using third-party modules, you could still see that error, but caused by other functions/methods. In that case, you need to update all the modules you are using on that site.
If this doesn't fix other *The each() function is deprecated* errors, you need to check the issue queue for every third-party module you are using, and verify there are patches for fixing that error.

---
Tags: 7
---


# Question
Title: Generate installed modules into a composer.json for existing site: I need to manage via Composer, not via UI
I have a Drupal 8 site up and running with modules that were manually installed. I want to generate an appropriate composer.json file to manage these using Composer.

The closest I could find to achieve this is an old Drupal 7 module, Composer Generate, mentioned in how to install package via composer? but that only works with Drupal 7 and it isn't any longer developed.

How to move Composer created folder of drupal-8.x.x up one level to html? suggests that third-party modules can/should be handled with Composer, but I would like to not have to manually rewrite the composer.json file to achieve this.

Is there a Drupal 8 / Composer / Drush way to accomplish this, or is manually updating the composer.json the only option?

# Answer
Composer Generate is a Drush extension. It can be used either with Drupal 7 or Drupal 8. Considering that the latest release available on drupal.org is dated Febrary 25, 2016, it's probable it is not compatible with the Drush version you would be use on your site.

The project page for *Composer Generate* suggests using the Composerize module, which is available for Drupal 8.

> This module can generate a composer.json from your installed Drupal code base, which can be used to regenerate that code base by running `composer install`.

Be careful of the warning reported in the project page.

> This module is still in development. It supports very basic Drupal 8 setups, but there are many necessary features it still lacks (e.g., support for patches, JavaScript libraries, distributions, etc). We're working on all that stuff, but **this module is definitely not ready for prime time**.

The module is supported by Acquia, and the development version has been updated on March 20, 2018.

Alternatively, as the project page suggests, you could use Composerize Drupal, a Composer plugin for converting a non-Composer-managed Drupal site to a Composer-managed Drupal site.
> 3 votes

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


# Question
Title: How do I programmatically duplicate a view display?
I have a view (*my\_view*) with the following displays:

1. master
2. page\_1

I am looking for a way to programmatically duplicate *page\_1*.

```
    $view = Views::getView('my_view');
    $storage = $view->storage;
    $display = &$storage->getDisplay('page_1');
    // Create a new display.
    // Remove some exposed filters from the new display.
    // save the view.

```

How can I achieve this?

# Answer
The View entity comes with a handy function for duplicating an existing display, -\>duplicateDisplayAsType().

-\>duplicateDisplayAsType() requires 2 arguments--ID of the display to duplicate & new display's type. First one is self-explanatory--if you want to duplicate something, you need to know what you want to duplicate (visit a View and look at the URL for the unique ID). For the second arg, a View Display needs to be of a certain type--page, block, feed, etc.

Finally, we have something like below:

```
$commentView = \Drupal::entityTypeManager()->getStorage('view')->load('comment');

// ->duplicateDisplayAsType() returns the new display's ID so it's not 100% necessary
//   to assign the return val to a variable.
$new_page = $commentView->duplicateDisplayAsType('page_published', 'page');
$new_block = $commentView->duplicateDisplayAsType('page_published', 'block');

$commentView->save();

```

Above, I am using the default 'Comments' view and duplicating the 'page\_published' Display as both a new page and new block. Try copy pasting the above code into a Controller and triggering the controller method once and visit the View to see your new Displays.

Finally, as with most entity operations, you'll want to -\>save() it afterwards.

Note: Using (presumably) \Drupal\views\Views::getView() will return a ViewExecutable--aka a configured View which is used for generating the actual output. You cannot edit the View's config via ViewExecutable. Above, I am using the entityTypeManager() to query for a View so I can retrieve the actual Entity so we can modify its configuration. The above code can act as boilerplate--try switching out values to achieve your desired goal.

EDIT: To answer your question more definitively, the above example code could be translated to match your code snippet:

```
$view = \Drupal::entityTypeManager()->getStorage('view')->load('my_view');
$new_page = $view->duplicateDisplayAsType('page_1', 'page');

$view->save();

```

Edit 2: Sorry, I didn't answer your second part--how do we modify the display after duplicating. This may not be the most efficient way so someone please tell me if there is a better way to do it. Luckily you want to only remove a filter. Because filters are not yet OOP, they're just giant arrays with specific keys you need to set. This part does get a bit more complicated.

There is one thing you need to keep in mind though--the default display will apply its display\_options across all displays unless you override them in the 'defaults' array on the specific display configuration. You can override defaults for each display\_option so you can still inherit defaults for some properties while overriding others.

For comments, specifically, the filters are all placed on the 'default'. Out of the box, the Comments view only comes with the `page_published` display. Let's say we want to duplicate the `page_published` display, copy over the filters from the original display, remove its default filters, and then array\_pop() one of the filters off our new display. So starting from scratch again:

```
$view = \Drupal::entityTypeManager()->getStorage('view')->load('comment');
$new_display_id = $view->duplicateDisplayAsType('page_published', 'page');
// Must use the getter--the display property is protected
// We assign by reference because there is no setter--we cannot set the display
//   options again after modifying but we can modify the referenced var to change
//   the original values
$new_display = &$view->getDisplay($new_display_id);
$default_display = &$view->getDisplay('default');
// Copy the filters from the 'default' to the new display
$new_display['display_options']['filters'] = $default_display['display_options']['filters'];
$new_display['display_options']['filter_groups'] = $default_display['display_options']['filter_groups'];

// Tell Views not to use the defaults for these two specific properties
$new_display['display_options']['defaults'] = [
  'filters' => FALSE,
  'filter_groups' => FALSE,
];

// For demonstration purposes, we remove 1 filter from our copied over filters
array_pop($new_display['display_options']['filters']);

$view->save();

```

You should see a page exactly like the `page_published` except it should be missing 1 filter.
> 1 votes

---
Tags: views
---


# Question
Title: Use 'Search Api Attachments' file extractor in my own custom 'Search Api' processor plugin
I'm writing a custom processor for search api that will search body content of nodes for links to pdfs and extract the content from them to be indexed. It's meant to be able to do the same thing search api attachments can do, it just searches for links inside bodies instead of just grabbing what's in an entity reference or file field. I'm using the drupal 7 search api attachments bf plugin as an example, but with Drupal 8 it's handled a bit differently

I currently have this file in a custom module located in /src/search\_api/processor/BodyFieldAttachments.php

```
<?php

namespace Drupal\search_api_attachments_bf\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * @SearchApiProcessor(
 *     id = "bodyfield_attachments"
 *  label = @Translation("Body Field Attachments")
 *  description = @Translation("Allows file links inside body fields to be indexed")
 * )
 */
class BodyFieldAttachments extends ProcessorPluginBase{
    /**
     * {@inheritdoc}
     */
    public function getPropertyDefinitions(DatasourceInterface $datasource = NULL){
        $properties = [];

        return $properties;
    }

    /**
     *  {@inheritdoc}
     */
    public function addFieldValues(ItemInterface $item){
        $node = $this->getNode($item->getOriginalObject());
        $body = $node->body->value;
        $files = $this->getFilesFromBody($body);

    }

    protected function getFilesFromBody($text){
        $files = array();
        if (isset($text) && !empty($text)) {
            global $base_url;
            // Parse href attributes in <a> links.
            preg_match_all('/href=[\'"]([^\>\'"]*)[\'"]/', $text, $matches, PREG_SET_ORDER);
            foreach ($matches as $match) {
                // Determine if the file is local. Absolute URL could be local.
                // Beginning double slashes is implicit for the current page's protocol
                // but just apply http.
                if (substr($match[1], 0, 2) == '//') {
                    $url = 'http:' . $match[1];
                }
                elseif (substr($match[1], 0, 1) == '/') {
                    $url = $base_url . $match[1];
                }
                else {
                    $url = $match[1];
                }

                $parse = parse_url($url);
                // Get absolute URL to the file location.
                $path_files = file_create_url('public://');
                if (isset($parse['host']) and $parse['host'] == $_SERVER['HTTP_HOST']) {
                    $uri = 'public://' . str_replace($path_files, '', $url);
                    // Convert back things (such as %20 back to a space).
                    $uri = urldecode($uri);

                    if (file_exists($uri)) {
                        $files_load = file_load_multiple(array(), array('uri' => $uri));
                        $file = reset($files_load);
                        if ($file) {
                            $files[] = (array) $file;
                        }
                    }
                }
            }
        }
        return $files;
    }
}

```

I have search api attachments installed and I do see that it has FilesExtractor class that handles file extraction but I'm not sure how to call upon it from my plugin and get it to use the config that's in place for Search Api attachments. Would I just create an instance of the FilesExtractor class and use one of its methods? Or is there some proper way to tap into it?

# Answer
> 0 votes
I was able to use the search api attachments file extractor by extending it.

The FilesExtractor class itself was a processor plugin. So I was able to access all the functionality by using

```
class BodyFieldAttachments extends
\Drupal\search_api_attachments\Plugin\search_api\processor\FilesExtractor

```

instead of

```
class BodyFieldAttachments extends ProcessorPluginBase

```

Then I could just override the specific functions that need to be overwritten while having access to all the functionality the search api attachment plugin had.

---
Tags: 8, search, plugins
---


# Question
Title: Pass hidden fields using drupalSettings to Twig template
We have a paragraph field (`field_pr_custom`) on the `Basic` page content type that has a custom twig template, `pr-custom.html.twig`. In the twig template, we need to pass in an array inside of a `<script>` tag. To accomplish this, we use the `mymodule_preprocess_paragraph__pr_custom` hook and set the array using the `#attached` variable. However, when we print the `drupalSettings` we are not finding the value passed in. There is no `Drupal behavior` used.

**How can we pass the value in an array from the `mymodule_preprocess_paragraph__pr_custom` into the `drupalSettings` variable inside the `pr-custom.html.twig` template?**

Here is what we tried:

**mymodule.module**

```
function mymodule_preprocess_paragraph__pr_custom(&$variables) {
  // pass node id.
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node instanceof \Drupal\node\NodeInterface) {
    $variables['elements']['#attached']['drupalSettings']['myArray']['myvar'] = $node->id();
  }
}

```

**pr-custom.html.twig**

```
<div>
  {{ content.field_text }}
  <script>
    // this doesn't print myArray and doesn't even have it.
    console.log(drupalSettings);
  </script>
</div>

```

# Answer
> 0 votes
Wish I could comment...

Are you sure your hook is running? the `instanceof` operator is not implemented correctly so you should be seeing an error when the hook tries to run.

Also, you may not need to add 'drupalSettings' to the 'elements' key. You should be able to put it on the top level of $variables.

---
Tags: 8, hooks, paragraphs
---


# Question
Title: JS batch progress bar: possible to force refresh more frequently than every 1500 ms?
After initiating a js-based batch with `batch_set()`, and the redirect to batch do URL, the JS refresh interval is every 1500 ms by default. So status message and progress bar are only updated every 1 1/2 seconds. For a specific application I need the refresh to happen more rapidly, let's say, every 500 ms. I couldn't find anything in `batch_set()` to set the refresh interval.

I believe that D8 core decides in file `core/misc/ajax.es6.js` that the default refresh interval ought to be 1500 ms, if nothing else specified:

```
if (this.progress.url) {
  progressBar.startMonitoring(
    this.progress.url,
    this.progress.interval || 1500,
  );

```

I could be wrong though and this code being only related to Ajax throbbers and such. The form Ajax API seems to have a way to pass `#interval` but I couldn't find anything for the batch API.

Be that as it may, my question is, how do I set my own custom refresh interval in a `batch_set()`, or if not there, is there another clean way to override the 1500 ms?

Thanks!

# Answer
> 2 votes
**Turns out none of us (neither I or nor the commenters) were completely "right", nor completely "wrong".** There **IS** an arbitrary limit hardcoded in D8's core, for JS batch progress bar refreshes, but it's not 1500 ms as I thought -- it's 1000 ms.

And it's harcoded in a different place than any of us thought.

As @MarioSteinitz stated, yes, the batch API inserts only a very short pause between two Ajax requests -- 10 ms. (The Ajax API is different with its 1500 ms default pause and I mixed up the two.)

**However, try as I might, I couldn't get the progress bar to refresh more often than once every approximately 1.1 or 1.2 seconds.** No matter how fast I finished my simulated batch work (by reducing my `usleep()` in the batch code), the relevant DOM objects, such as `progress__bar`, were never refreshing more frequently than just over once a second.

You can easily see their "throbbing" in Inspector's DOM view and count *onethousand-one, onethousand-two* as they pulse away... even when my batch function did absolutely nothing, the fastest I could get these DOMs to flash was just over once a second.

**So what gives?**

**Well the batch API is just weiiiiirrrrrd...** instead of giving the programmer the say in how much work ONE Ajax request is supposed to do, the function `_batch_process()` in core file `/core/includes/batch.inc` has a loop **harcoded** that calls the batch function again and again until at least 1000 ms have passed (or the batch is finished):

```
// If we are in progressive mode, break processing after 1 second.
if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {
  // Record elapsed wall clock time.
  $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
  break;
}

```

**Weird because a batch is ALREADY supposed to be a large process chopped into small bite-sized chunks.** So the entire batch already **IS** a loop, but there's, in fact, a **secondary inner loop**, whose break conditions are outside of the coder's control!

You think this kind of policing of the programmer's wishes is not weird, arbitrary and unnecessary? Well consider that that the batch API (after what feels like decades), still doesn't allow progressive batches (i.e. batches that are all processed in one swoop, for example from the shell) -- see https://www.drupal.org/project/drupal/issues/638712.

**But I digress.**

**So for sh\*ts and giggles I changed the \> 1000 to \> 100 in the above core code and what do you know, the progress DOMs refreshed like crazy!**

Of course I can empathize with the idea that no batch should hammer its host server with heavy requests every 10 ms, for obvious reasons. So the developers decided to loop and re-loop the batch function until at least 1000 ms have passed, before the next Ajax call is triggered.

**Well-intentioned? Yes! Arbitrary and inflexible? Absolutely.** As the programmer of a batch, I believe it should be **MY** choice how much exactly I want to do in one Ajax call. Any Drupal code has the potential to crash or deadlock the server, or overwhelm the browser. Why police this particular part?

**Drupal maintainers:** Why not default to 1000 ms if that is a trusty value for most applications or unaware coders, but for batches that require a more dense flow of output, let's say, once every 100 ms, give us the power to do that!

**So how to get rid of the pesky \> 1000 condition - without hacking the Drupal core of course!?**

```
if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {

```

**If this were D7, we'd just manipulate the global $timers array:** Just before our batch function exits, set its start value back to the stone age (01/01/1970), and the calling `_batch_process()` will always "think" at least one second has passed, and give control back to Ajax immediately.

Just that this isn't your grandma's Drupal; we are now all fancy object-oriented and stuff.

Looking at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Timer.php/8.2.x we notice that we can't just poke whatever we want into the `Timer::$timers` array any more. It is declared `protected`, i.e. no outsider, such as my batch function, is allowed to mess with its internal values.

**So we're back to square one... or are we?**

Well thankfully this is PHP and not a "real" programming language! *(ducks)*

Meaning, there's always a loophole to bypass any new-fangled OOP restrictions that those eggheads at Software Engineering University demanded. *To hell with them!*

After some googling, I wrote the following function. And by "wrote" I mean I all but stole it from people who know much more about PHP than I do: https://stackoverflow.com/questions/6448551/is-there-any-way-to-set-a-private-protected-static-property-using-reflection-cla

```
  /**
   * Revert Timer::$timers['batch_processing'] back to the stone age
   * to trick batch.inc / _batch_process() into thinking at least 1 second has passed
   */
  protected static function revertTime() {

    $obj         = new Timer();
    $refObject   = new ReflectionObject($obj);
    $refProperty = $refObject->getProperty('timers');
    $refProperty->setAccessible(true);
    $myTimers = $refProperty->getValue();
    $myTimers['batch_processing']['start'] = 0;
    $refProperty->setValue(null, $myTimers);

  }

```

I now call `revertTime()` at the very end of all my "batch on crack" functions, *juuuuust* before they exit. It sets the start time of `_process_batch()`'s `Timer::$timers['batch_processing']['start']` to 0.

**And 0 is always more than one second ago.**

The effect is that `_batch_process()` never loops; the Ajax call terminates after exactly one call to my batch function.

10 ms later, the batch API initiates another Ajax call to my batch function, resulting potentially in a rat-tat-tat machine-gunning refresh cycle for my progress bar.

**NOTE OF CAUTION:** When I first ran this, with all checks and balances disabled, it overwhelmed Chrome with its rapid-fire Ajax calls every 10 ms. Today was a hot day (I live in the southern hemisphere) and my Mac slowed down to a crawl under the load of the Ajax calls... the built-in overheat protection kicked in!

**When you use this hack, it is your responsibility to make your batch functions either do a LOT of slow stuff in one iteration, or waste sufficient time with `usleep()`. Otherwise the batch staccato may overwhelm your visitor's browser or your server.**

Thanks again to all the contributors here and elsewhere who finally led me to a semi-clean (non-core hack) solution! ❤

---
Tags: ajax
---


# Question
Title: Notify a user if a node has a comment or status updated
I'm trying to build a simple ticketing system with Drupal 8.6. I'm able to create a content type for these tickets and the comments will be the responses to the ticket. Also I have a status field for open, pending, and closed. I want to be able to email all the users on the ticket if the node is updated or commented on. And I have another user reference field for "assigned ticket to".

What modules would I need that work with 8.6 to get this kind of funtionality? I prefer no modules, but I'm not sure if core itself supports this type of thing.

# Answer
> 1 votes
I recently did something similar, for reacting when the node is updated i used hook\_node\_presave(). Here's an example on how to send an email when the node is updated and the status is changed from "open" to "pending".

```
function my_module_node_presave(NodeInterface $node){
  if($node->getType() == 'your_content_type_name' AND $node->isNew() == FALSE) {
   $status_original = $node->original->get('status_field')->value;
   $status_updated = $node->get('status_field')->value;

 if ($status_original !== $status_updated AND $status_original == 'open' AND $status_updated == 'pending') {
   send_mail();
  }
 }
}

```

For creating the send\_mail function or whatever you'd like to call it i used the following resource and modified the code where necessary: How to send a mail programmatically in Drupal 8. Also, i used the SMTP Authentication Support module to send the emails using a gmail account: SMTP Authentication Support. The configuration page of the module is on `admin/config/system/smtp`.

For checking if a comment has been posted you can use hook\_ENTITY\_TYPE\_insert() and replace "ENTITY\_TYPE" with "comment" and inside the hook you can call again the send\_mail function.

I did not quite understood how you are storing "all the users on the ticket", but it would be the case of getting the users email address with getEmail();

---
Tags: 8, emails, notifications
---


# Question
Title: How do I clear the cache for a custom block?
I have a custom block which is not updating when the data in the database is updated. It works when cache is cleared.

Is there any solution for this cache issue?

This is the code I am using.

```
global $base_url;

clearstatcache();
\Drupal::service('page_cache_kill_switch')->trigger();
$msg='<div id="notice"><ul id="holiday">';
$holiday_select = db_query("select id,student_holiday from student_holiday as b where  b.isactive = 't' and display_from <=now() and display_to>=now() order by id desc");

foreach ($holiday_select as $h_data) {
  $student_holiday[] = $h_data->student_holiday;
}

if (count($id) > 0) {
  $s = 0;
  while ($s<count($id)) {
    $holiday_view = $student_holiday[$s];
    $msg .= '<li><a href="'.$base_url.'/holiday"> ' . $holiday_view . '</a></li>';
    $s++;
  }
}
else {
  $msg .= '<li><a href="#">No holiday </a></li>';
}

$msg .= '</ul></div>';

echo $msg;

```

# Answer
**Add the below preprocesser function to your .theme file**

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function YOURTHEME_preprocess_block(&$vars) {
  if ($vars['derivative_plugin_id'] == 'your_block_ID') {
    // This stops the block being cached.
    $vars['#cache']['max-age'] = 0;
  }
}

```
> 0 votes

---
Tags: 8, blocks, caching
---


# Question
Title: How to get the real sql query of a view?
One of drupal view displays reviews based on a selected event. It should display 3 reviews but instead it displays only 2. It doesn't happen for all the events and only for certain events instead of 3 it displays 2 items. As the data is all correct and I have validated the same. I wanted to see the query that is being used. The query that is displayed in the view is not helping me either. If I copy paste the same and run the sql, it throws a lot of error. How can I debug and see what is the query that got executed for that particular view? The view has relationsships and also it uses contextual filters. Thanks

# Answer
The query displayed in the administration UI contains database prefixing brackets. You can remove those brackets to have valid SQL that can be executed by any SQL client.
> 5 votes

# Answer
The Devel module has a setting that will show all executed queries in the footer.
> 3 votes

# Answer
You have to use hook\_views\_pre\_execute and with Devel installed use `dpq` to view the SQL String:

```
function hook_views_pre_execute(&$view) {
  dpq($view->build_info['query']);
}

```
> 0 votes

---
Tags: views
---


# Question
Title: How do I remove the term ID from the view URL?
I have a content view with an exposed filter based on a vocabulary.

In the URL (for example, mysite/myview?tid=taxonomy+term+(3)), and incidentally in my page title (I use argument.tid to display a title based on the term typed in the exposed filter), there are the name of the term (perfect) but also the term ID.

I only need mysite/myview?tid=taxonomy+term or, better, mysite/taxonomy-term.

How can I achieve this?

# Answer
Perhaps you can do this using htaccess rules.

You can probably apply the patch from this issue and than according to the reports you will be able to create a path alias from within drupal that accept url parameters (as in your case)

But you can also try views\_url\_path\_arguments which seems to be usable in Drupal 8 judging from the amount of downloads.

Perhaps you can also give this sandbox module Query Parameters To Url a try

Note: I have not tested the above 2 modules
> 1 votes

# Answer
You can use Better Exposed Filters Module, it's useful module, in drupal 8 still alpha version but.

> Drupal 8:
> The Drupal 8 branch is in active development. If you have immediate need of a specific feature in BEF, please contact a maintainer to discuss sponsorship. BEF will work best if you are at least using Drupal 8.3 and you should be using newer.
>
> ✓ Recommended by the project’s maintainer.
> 0 votes

---
Tags: views, 8, uri
---


# Question
Title: How do I configure subdomain url as one.mysite.com/subdomain1
I am a Drupal Developer currently working on Drupal 7.15 multi domain site. In my site, I have already installed Domain module and configured the domains as:

* Main domain - mysite.com (say 1st level)
* Sub Domains - one.mysite.com, two.mysite.com, ... (say 2nd level)

Now I need the 3rd level Domains as:

```
one.mysite.com/subdomain1,
one.mysite.com/subdomain2,
one.mysite.com/subdomain3.

```

But my control panel only has the option of setting this as `one.subdomain1.mysite.com`

Can any one help on this. Either how to configure the subdomain as of my requirement or else how to re-write the url?

Thanks

# Answer
> 0 votes
The Subfolders Domain module sounds like it'll handle what you're after. Additionally, you may want to read through my blog entry about serving Domain Access-controlled sites from subfolders instead of subdomains.

# Answer
> 0 votes
You can check the server side configuration.The sub folders module is for the purpose of sub directory multi sites configuration. And this will not be useful for this scenario I think.

# Answer
> 0 votes
Frankly, there are many ways to achieve this. I am just listing a few that come to my mind.

* Check out the settings.php, it has some info on this. I think using that and .htaccess we can achieve this.
* You can also do this by configuring the Virtualhost in a way that achieves this type of setting for you.
* I also have used services like pound, using which we can direct each request based on our requirement.

---
Tags: subsites
---


title: Commerce discount rule

text:
# Question
Title: Commerce discount rule
Have this scenario, a user must get 10% discount on only these products (product 1 & 2 is defined in rules), if at least 5 items of each is in cart.

Cart:

* 5 pcs product 1 500
* 5 pcs product 2 50
* 1 pcs product 3 100

with the discount, the total will be 595, since the user will get 10% on 500+50 and not product 3

If the scenario is

* 5 pcs product 1 500
* 4 pcs product 2 50
* 1 pcs product 3 100

the user will not get any discount.

# Answer
> 1 votes
It will help if you add the rule that you have added. Also if you think it's a complex rule to be applied, you can apply the discount in the checkout page rather than before that without using the rules itself. In other places just display the 1pcs price with the discount applied.

# Answer
> -1 votes
I sort of have figured half of it out.

the below isnt any particular programming language, but to show what i mean.

```
foreach (items as item)
  if (item.sku == v1 & item.value >= 5) or (item.sku == v2 & item.value >= 5)
    item.price -= 10%
  endif
endforeach

```

My problem with rules is that both have to be present in the order.

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


# Question
Title: Disable registration on commerce checkout
According to https://docs.drupalcommerce.org/commerce2/user-guide/checkout/allow-register-at-checkout the 'Login or continue as guest' checkout pane should have an option 'Allow registration'. In my environment with the latest commerce 2.12 however I can't find this option. Why is this option not shown?

I don't want to allow registrations on my site and only allow guest checkout. How can I achieve this?

# Answer
> 1 votes
Per Bojan's comments, leave "Allow guest checkout" checked and disable the "Guest registration after checkout" pane. We may need to update the documentation a little, but doing these things and then configuring your general Drupal settings to deny user account registration will leave you with a site that no one can ever register against and anonymous users can still checkout on.

(The fact that you don't see the checkbox to "Allow registration" in the "Login or continue as guest" checkout pane configuration is irrelevant, because it's disabled by default. You don't need access to it in order to disable the ability for guests to register prior to checkout.)

If you don't need this intermediate step at all, you can simply disable the checkout pane and the page will be skipped for all customers.

---
Tags: commerce
---


# Question
Title: Help with Views Relationships and Entity References
This is my scenario:
I have three content types,
Content type A is linked to Content type B with an Entity reference field .
Content type C is linked to Content type B with an Entity reference field

What I would like to achieve is a view, to be shown on type A nodes, showing all type C nodes that have the same relation to type B.

Any hint?

# Answer
> 1 votes
This is usually called "sibling" nodes, and you can do it with the help of two Relationships and one Contextual filter.

List Content C in a View, then add the first Relationship for the Entity reference field on that type.

Add the second Relationship that goes in reverse from the field to the content (Content using field\_\[referencename\]). The second Relationship must use the first Relationship.

Then add the Contextual filter for node ID that uses the second Relationship. That will recognize which node A you're on and also filter out only content C that have in common through content B reference.

For more details see in this answer (look at Relationship and Contextual configuration steps): Entity Reference widget selctor in view referring same reference

---
Tags: 7, views
---


# Question
Title: Using "if statements" to add classes in Twig
I'm attempting to use an if statement to determine the value of a field and print a class based on that value. I'm not getting any errors, but the addClass is not working. No classes are being added. I'm assuming it's a simple syntax error. I'm a designer first, and I'm new to Twig templating. Thank you in advance!

```
{% for key, item in content.field_stat_value if key|first != '#' %}
    <div class="stat-column">
        <div
        {% if content.field_special_character[key] == '%' %}
          {{ attributes.addClass('percent') }}
        {% elseif content.field_special_character[key] == '$' %}
          {{ attributes.addClass('dollar') }}
        {% endif %}
        class="stat counter" data-count="{{ content.field_stat_value[key] }}">0</div>
        <div class="title">{{ content.field_stat_title[key] }}</div>
        <div>{{content.field_special_character[key]}}</div>
    </div>
  {% endfor %}

```

# Answer
1) Install and enable the Devel module.

2) Add your **/sites/development.services.yml**:

```
# Local development services.
#
# Place this file in the /sites/ directory.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    # Twig debugging:
    #
    # When debugging is enabled:
    # - The markup of each Twig template is surrounded by HTML comments that
    #   contain theming information, such as template file name suggestions.
    # - Note that this debugging markup will cause automated tests that directly
    #   check rendered HTML to fail. When running automated tests, 'debug'
    #   should be set to FALSE.
    # - The dump() function can be used in Twig templates to output information
    #   about template variables.
    # - Twig templates are automatically recompiled whenever the source code
    #   changes (see auto_reload below).
    #
    # For more information about debugging Twig templates, see
    # https://www.drupal.org/node/1906392.
    #
    # Not recommended in production environments
    # @default false
    debug: true
    # Twig auto-reload:
    #
    # Automatically recompile Twig templates whenever the source code changes.
    # If you don't provide a value for auto_reload, it will be determined
    # based on the value of debug.
    #
    # Not recommended in production environments
    # @default null
    auto_reload: auto_reload
    # Twig cache:
    #
    # By default, Twig templates will be compiled and stored in the filesystem
    # to increase performance. Disabling the Twig cache will recompile the
    # templates from source each time they are used. In most cases the
    # auto_reload setting above should be enabled rather than disabling the
    # Twig cache.
    #
    # Not recommended in production environments
    # @default true
    cache: false

```

3) Add your **/sites/default/settings.local.php**:

```
<?php
/**
 * @file
 * Local development override configuration feature.
 *
 * Place this file in the /sites/default/ directory next to settings.php.
 * This will include the development.services.yml file for twig debug use.
 *
 */
assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();

$config['system.logging']['error_level'] = 'verbose';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

4) Update your **/sites/default/settings.php**:

(uncomment this section)

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

```

This will allow you to add `{{ dump(content.field_name | keys) }}` to your template file so you can see just what keys you need to access the correct values.

Try:

```
{% for key, item in content.field_stat_value %}
  <pre>
    {{ dump(content.field_special_character | keys) }}
  </pre>
{% endfor %}

```

Then just add what you need to follow:

```
{% for key, item in content.field_stat_value %}
  <pre>
    {{ dump(content.field_special_character.mynextkey.0.whatever | keys) }}
  </pre>
{% endfor %}

```

I add this answer as being able to print out values will help a designer best. Plus, if your class is not printing, I just think `content.field_special_character[key]` is not evalutaing to `%`.

Having debug setup will also allow you to ensure you have the correct naming conventions for your twig template.
> 1 votes

# Answer
Try the following code:

```
{% for key, item in content.field_stat_value if key|first != '#' %}
<div class="stat-column">
  {% if content.field_special_character[key] == '%' %}
    {% set attributes = attributes.addClass('percent') %}
  {% elseif content.field_special_character[key] == '$' %}
    {% set attributes = attributes.addClass('dollar') %}
  {% endif %}
    <div {{ attributes.addClass('stat counter').setAttribute('data-count', content.field_stat_value[key]) }}>
      0
    </div>
    <div class="title">{{ content.field_stat_title[key] }}</div>
    <div>{{content.field_special_character[key]}}</div>
</div>
{% endfor %}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Check if user_picture value is changed or compare with old value
I am trying to find if a field value is changed or updated by the user. But there are blockers.

```
function custom_form_process_user_picture(&$form, FormStateInterface &$form_state) {
  $file_name = "";
  $username = "";
  $fid_0 = NULL;
  $user_picture = $form['user_picture'];
  $uid = $form_state->getValue('uid');
  if ($form_state->hasFileElement() && $form_state->hasValue('user_picture')) {
    $username = $form_state->getValue('field_name')[0]['value'];
    $fid_0 = isset($form_state->getValue('user_picture')[0]['fids'][0]) ? $form_state->getValue('user_picture')[0]['fids'][0] : $fid_0;
    /*
      $changed = $form_state->get('user_picture')->getValue() == $form_state->getValue('user_picture');
      //This is not working as $form_state->get() returns null.
    */
    /*
      $changed = $form_state->get('user_picture')->getValue() == $form['user_picture']['#default_value'];
      //This is not working as $form['user_picture']['#default_value'] is null.
    */
      if($changed) {
        // Proceed to rename the file.
      }
    }

```

What piece of the code I am doing wrong? Searched drupal and stackoverflow for the changed/updated/dirty field value. Also tried with `$form_state->getFormObject()->getEntity()` and got no clue if there is old value stored or not. `FormStateInterface` seems to have no method to find out altered/modified values.

# Answer
> 2 votes
Perhaps you should use `hook_entity_presave` that keeps the old (original) value

```
function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  if($entity->getEntityTypeId() == "file"){

    $filename = $entity->getFilename();

    $file_old = $entity->original;

    if($file_old != null){
      $filename_old = $file_old->getFilename();

      if($filename_old !== $filename){
        $entity->setFilename('newfile.jpg');
      }
    }
  }
}

```

The function above changes the filename if its not the same as old filename.

Depending on your use case you might want to apply the above logic when `user` is presaved

```
function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity)
  if($entity->getEntityTypeId() == "user"){

    // get specific field by field machine name
    $file = $entity->get('field_file');

    // or get the user_picture field
    $picture = $entity->get('user_picture');

    $user_old = $entity->original;
    // drill down in the old user object to see values changes
    // and do appropriate changes
  }
}

```

---
Tags: 8, forms
---


# Question
Title: Trouble installing drupal-project with Composer
I have followed the directions to install drupal-project with drupal-composer. I keep getting this error and it doesn't make sense to me.

> \[InvalidArgumentException\]
> Could not find package drupal-composer/drupal-project with version 8.x-dev in a version installable using your PHP version 5.5.38.

I am using MAMP and the php version is 7.1.22. I even tried the template download for drupal-composer/drupal-project and I still get the same error. Composer is installed, verified with the checking the version in terminal.

I have searched and cannot find anything to assist me in solving. Yes, I am new to composer and trying to get a local environment setup with composer versus just downloading etc. Any help or direction would be appreciated.

# Answer
> 1 votes
Despite not technically being a Drupal question, this gets asked a lot. The answer, for anyone coming across this using various local dev stacks - you need to inform your command line of where PHP ($PATH variable) is that you want to use. Otherwise it will default to what is installed on your machine, likely very out of date.

---
Tags: 8, composer
---


# Question
Title: Permission for private file to anonymous
I have an ad content type, with a file field that is in a private directory when saving the node.

Ads and their files are only accesible for authenticated users.

I wish I could allow anonymous users to see ads and their files that are promoted.

I use content\_access module

I want programmaticly, change acces control foreach ads who is promoted and I don't how to achieve that.

# Answer
It sounds like you might want to check out the Private Files Download Permission module which may provide exactly the functionality you're looking for.
> 0 votes

---
Tags: 8, users, files
---


title: Non-standard port with aliases

text:
# Question
Title: Non-standard port with aliases
I'm running Drush 9.5.2.

I set up a site alias. Drush recognizes it, but it will not connect via SSH. I get the following error:

```
ssh: connect to host mysite.com port 22: Operation timed out

```

The server doesn't use port 22. It uses port 2234.

My SSH config is set to use port 2234. I can SSH in if Drush isn't involved. There's nothing in the docs that addresses this. What am I missing?

# Answer
Create an alias that looks something like one of the examples below:

**Drush 9 Example:** ~/.drush/sites/my-site.yml

```
live:
  uri: example.com
  host: isp.net
  user: www-admin
  paths:
    drush-script: /path/to/drush
  ssh:
    options: '-p 2222 -o "AddressFamily inet"'
    tty: false

```

**Drush 8 Example** ~/.drush/aliases.drushrc.php

```
$aliases["my-site.live"] = array (
  'uri' => 'example.com',
  'remote-host' => 'isp.net',
  'remote-user' => 'www-admin',
  'ssh-options' => '-p 2234 -o "AddressFamily inet"',
  'path-aliases' =>
    array (
      '%drush-script' => '/path/to/drush',
    ),
);

```

Adjust 'ssh-options' as necessary for your configuration.

You may omit 'path-aliases' entirely if Drush is in your $PATH on the remote machine. Defining the Drush path is safer, though; the rules Bash follows for sourcing resource files for login shells vs. non-login shells et. al. is somewhat confusing.
> 11 votes

---
Tags: drush
---