# Question
Title: Best way to set up attributes/variations
This is probably an embarrassingly basic question, but I haven't been able to find a definitive answer after a fair bit of searching.

If you're setting up a store with Drupal Commerce (2.x, in Drupal 8), and each of your products come in a variety of colours, but the range of colours is different for each product - should Colour be a single attribute, added to a single product variation type, and then assigned to a single product type (assuming no other significant variations in product structure)?

Or should each specific set of colours be a different attribute and/or a different product variation type, which I suppose would mean each individual product would need a unique product type?

To clarify, we're talking several dozen products, each of which might come in anywhere from 10-30 unique colours that are only used for that one product, so the total possible number of colours would be well into the hundreds, if that makes a difference.

I'd like to set this up in the most efficient and user-friendly way possible, since the staff who will be maintaining the site and adding items in the future may not be very technical... So the less configuration they have to do for new products, the better. But on the other hand, having hundreds or thousands of colours showing up in a single dropdown when they're trying to create product variations might be overwhelming.

# Answer
> 0 votes
I'll preface this by saying that every situation is different so it's hard to say what the "best" option is. This tutorial seems to go the route of having different product variation types, with a specific color attribute created per variation type. Having a separate variation type for every item feels a bit awkward, but it might make sense in your scenario.

Two other solutions that I can think of are:

**1. Multiple Attributes (only):**

You could do this without creating unique product types for every product, or even multiple product variation types. You could have 5, 10, 2000, however many different color attributes, all of which are made available to your single product variation type.

The main drawback that I foresee with having separate attributes for each color set is that, after the fact, any grouping/reporting that needs to be done on colors *may* need to accommodate all of these disparate attributes in a single place. One way to help mitigate this might be to create an "attribute categories" (or similar) taxonomy vocabulary to group related attributes together, and tag that on a taxonomy ref field on each attribute. If you anticipate this only ever being an issue for "colors" then you could probably also get away with adding a boolean field to do something similar.

That said, having the color sets as separate attributes might be preferred for reporting as well. Hard to say.

**2. One Attribute**

Another option is to have a single Color attribute containing every single color, but add a Product Entity Reference field onto it. In this case, every color would inherently be treated the same, but you could relate them directly to their associated Products. This avoids the issue of needing to relate the different attributes after the fact. This would give you the option to do a form\_alter on the product\_variation creation form to limit the options on the color attribute field to those which reference the Product that you're creating a variation of.

This option could end up with a pretty big list of options when editing the attribute, though, so it might be worth populating it with a bunch of dummy data to see how it fares. Devel\_generate (included with Devel module) might be helpful, here.

**EDIT:** I should note that I initially failed to say that option 2 was my preferred option, for the same reason that Ryan notes in his answer. That is to say, all colors are colors and should be present on the same attribute. If Select2 is viable for attributes fields then that's probably the simplest way to make the list more manageable when authoring new product variations.

Alternatively, as mentioned in 2, using a reference field on each color to its related products (or alternatively a reference field on the product to its given colors) would maintain the "correct" single attribute while also allowing you to limit the options to those appropriate for the current product. IMO this probably leads to a less overwhelming interface in the event that the list of available colors is sufficiently large, and could also be paired with something like Select2 to further improve the authoring UI/UX.

# Answer
> 1 votes
Absent any other details, this question actually has a single definitive answer. I hate to contradict an accepted answer, but the only way I would build the site to address your use case would be:

1. One "Color" attribute with...
2. Values for every possible color...
3. Variations on your product type only for the colors the product needs.

Each product contains one or more variations differentiated (usually) by having one or more attribute value differing from the others. In your case, it would be one variation per unique color. Nothing requires you to use every available attribute value in a product. For example, there's no reason you can't have one "Color" attribute with values for "Red", "Green", and "Blue" and have a product on your site whose only color variations are "Red" and "Blue."

(I see from Mrweiner's comment that the selected answer was trying to solve the UX problem via existing architectural components. I'd recommend setting the proper architecture first and solving the UX challenge separately, e.g. via a front-end library like Select2 or other that makes large select lists more manageable.)

---
Tags: commerce
---


# Question
Title: How do I flag the update store automatically?
I created a flag to flag the stores. I want when a user updates a store, the store is automatically flagged. The code below does not work and there is no error message.

I don't want to use the Rules module.

How do I flag the update store automatically?

```
use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;

/**
 * Flag store.
 */
function admin_task_notify_commerce_store_update(Store $commerce_store) {

    $flag_id = 'report_store';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $flag_service->flag($flag, $commerce_store);

}

```

# Answer
The code looks ok, and you confirm it works for nodes. Then I can only guess that the used flag\_ids are wrong, the flag is not enabled for the given entity, or the user does not have permission to place the flag .
> 1 votes

---
Tags: 8, commerce, flags
---


title: How do I update an old project?

text:
# Question
Title: How do I update an old project?
I have been tasked with updating my code shop's long-abandoned Drupal 7 codebase to the most recent Drupal core, in order to bring in the latest security fixes (it's currently using v7.67). But all the knowledge I had about how to use drush seems to now be completely worthless.

What is this "composer" thing that it keeps complaining about? We never used anything like that back when we were still developing this Drupal 7 project (we abandoned PHP and switched to Python/Django a few years ago). I tried installing Drush through `composer require drush/drush`, which worked (and dumped a load of new code into my repo for some reason...). But even though I'm running it in the root of my repo, it says this:

```
! [NOTE] Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands.

```

When I pass the root folder name via --root, it says the same thing. Thus, my old strategy of just running `drush up drupal`, which worked dozens of times in the past, no longer works.

Could someone who understands how Drush works these days explain to me how I can use it to update my codebase? Or maybe there's a way to install an old version of Drush that can actually understand my repo's layout? That'd be even better.

# Answer
I came across this issue myself when starting my first Drupal 8 project.

This is most likely due to the version of Drush you are using being not compatible with Drupal 7. You can check your Drush version by running `drush --version` in the command line.

If Drush 9 or above, you should downgrade to version 8, i.e. `composer require drush/drush:^8`.

Tip: if ever wondering which Drush (local or global) you are using, type `which drush` in the command line.
> 1 votes

---
Tags: 7, drush
---


title: Getting a field value from a view

text:
# Question
Title: Getting a field value from a view
I am new to Drupal8. In one of the preprocess functions in my customtheme.theme file, I need to get the value of a field from a view that I have already created. I searched the web and got:

```
 $view = $variables['view'];
    $view_result = $view->result;
    if (!empty($view_result)) {
      foreach ($view->result as $rid => $row) {
        foreach ($view->field as $fid => $field ) {
          $values[$rid][$fid] = $field->getValue($row);
        }
      }
    }
   $array[0] = $values[0]['nid'];

```

AND i got another one too :

```
$view = $variables['view'];
$values = [];
foreach ($view->result as $row_id => $row) {
  foreach ($view->field as $field_id => $field ) {
    $values[$row_id][$field_id] = $field->getValue($row);
  }
}

```

The first solution worked but I want an explanation of it please especially that I tried to print\_r ($view\_result) and that didn't work, so I managed to print its keys and got onyl one key which is 0. Then I got many weird keys when I did a foreach to print the keys of $view\_result\[0\]. I would be grateful if someone can explain to me the code and why did the getValue function take an argument ? I usually write it as getValue() only.

# Answer
> 1 votes
What you usually write as getValue() without arguments is a method of an entity FieldItemList.

`$view->field` returns field handler plugins configured in the FIELDS section of a View.

Views fields handler plugins are an abstraction layer for all kind of data not necessarily based on entity fields.

If based on entity fields then `getValue($row)` runs this code:

*/core/modules/views/src/Plugin/views/field/EntityField.php:*

```
 public function getValue(ResultRow $values, $field = NULL) {
    $entity = $this->getEntity($values);

    // Ensure the object is not NULL before attempting to translate it.
    if ($entity === NULL) {
      return NULL;
    }

    // Retrieve the translated object.
    $translated_entity = $this->getEntityFieldRenderer()->getEntityTranslation($entity, $values);

    // Some bundles might not have a specific field, in which case the entity
    // (potentially a fake one) doesn't have it either.
    /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
    $field_item_list = isset($translated_entity->{$this->definition['field_name']}) ? $translated_entity->{$this->definition['field_name']} : NULL;

    if (!isset($field_item_list)) {
      // There isn't anything we can do without a valid field.
      return NULL;
    }

    $field_item_definition = $field_item_list->getFieldDefinition();

    $values = [];
    foreach ($field_item_list as $field_item) {
      /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
      if ($field) {
        $values[] = $field_item->$field;
      }
      // Find the value using the main property of the field. If no main
      // property is provided fall back to 'value'.
      elseif ($main_property_name = $field_item->mainPropertyName()) {
        $values[] = $field_item->{$main_property_name};
      }
      else {
        $values[] = $field_item->value;
      }
    }
    if ($field_item_definition->getFieldStorageDefinition()->getCardinality() == 1) {
      return reset($values);
    }
    else {
      return $values;
    }
  }

```

You can see how Views API connects with Entity API, but when programming Views API code you should stay at this abstraction layer if possible.

---
Tags: views
---


# Question
Title: Setting node ID sequence to a particular higher value for future created records
We have an organic groups based portal in D7 where many blood banks add records. We recently initiated Drupal 8 migration and are close to completion. However, we would want to add selective blood banks first to the new D8 portal, have it tested before we ask all the other blood banks to use the new portal.

Is it possible to set a higher NID value when new records are created by new users? Migration data for remaining customers can happen seamlessly as their NID values will be lower.

Thanks.

# Answer
Yes, you can set the `nid` to a higher value in your D8 instance, then continue to migrate D7 nodes under that.

Something like the following to set the `auto_increment` value.

```
// Set the next auto increment field value on the table
$result = db_query('ALTER TABLE {' . $connection->escapeTable($table) . '} AUTO_INCREMENT = ' . (int)$auto_increment);

```

e.g for `node` and `node_revision`

```
// Set the next auto increment field value on the node tables
$result = db_query('ALTER TABLE {node} AUTO_INCREMENT = 8000000');
$result = db_query('ALTER TABLE {node_revision} AUTO_INCREMENT = 8000000');

```
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: Can't update nodes / node unpublishes itself
This problem has been bugging me for some time now and I haven't been able to find this issue online anywhere else.

My Drupal 7 website has a very simple photo gallery, using a custom node type called *gallery* with image upload fields.

One or two of these nodes (but not all) have started behaving very strangely. When I upload new images, the files appear to upload successfully and the thumbnails appear, but immediately I get a message directly above the field on the edit page saying "**Gallery (node title) has been updated.**" Normally this message would only appear after submitting changes using the save button.

When I click 'Save', I get the following message:

"**The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.**"

At this point, the node unpublishes itself, and the changes I make are not saved. The only way to publish the node again is by using the */admin/content* interface.

I have noticed that nodes that have many images are the problematic ones. One such node has 160 images.

This behavior only happens with the gallery node type. I have tried creating a new node type with the same fields and recreating the node from scratch, but the same thing happens. I have tried using the *image* widget and the *multiupload* widget.

# Answer
This seems to be a common problem when exceeding the `max_input_vars` on saving nodes. Which might seem your problem regarding the 160+ images on the node.

First, check your server logs for anything related to this error.

Then update `php.ini` (check for `max_input_vars`) to an amount that suits your needs.
> 0 votes

---
Tags: 7, nodes, media
---


# Question
Title: How do I track a publicly downloaded file?
I am creating a custom module to track the file download time and user id with a file link or path. I have tried multiple modules but the download the file time tracking option is not available.

How I can programmatically track the file download time?

This is the code I am using.

```
function mymodule_file_download($uri) {
$scheme = \Drupal::service('file_system')->uriScheme($uri);
  if (in_array($scheme, ['private', 'temporary', 'session'])) {
    $permission = "read $scheme files";
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
    if ($account->hasPermission($permission)) {
      return [
        'Content-Type: text/plain',
      ];
    }

    if (\Drupal::currentUser()->isAnonymous()) {
      throw new NotFoundHttpException();
   }

  }
  elseif (in_array($scheme, ['public'])){
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
   \Drupal::logger('downloads_tracker1')->notice($account);
  }

}

```

# Answer
> 0 votes
`hook_file_download` doesn't run for public file downloads.

> Control access to private file downloads and specify HTTP headers.

If you want to track public file downloads, you will need a different approach.

For example, track downloads with Google Analytics event tracking

---
Tags: 8, files
---


# Question
Title: I need to update a longblob value in the variable table using variable_set
This would be in an install file in a module. The purpose is to create setting for a module that is already installed (the module is node\_revision\_delete). I know how to use variable\_set to change a value in the variable table but not when it is longblob. Do I just use the variables from the module? Do you know of any examples I could look at?

# Answer
> 0 votes
With `variable_set()` you can set a persistent variable to any PHP value, including array. `variable_set()` will serialize the value passed as second argument, and `variable_get()` will unserialize that value. If you pass an array to `variable_set()` for a persistent variable, `variable_get()` will return an array for the same persistent variable (if another module doesn't change that persistent variable's value to an integer, for example).

Suppose that you want to change the value of *node\_revision\_delete\_minimum\_age\_to\_delete\_time*, which is set from that module in its installation hook using the following code.

```
  $node_revision_delete_minimum_age_to_delete_time = array(
    'max_number' => 12,
    'time' => 'months',
  );
  variable_set('node_revision_delete_minimum_age_to_delete_time', $node_revision_delete_minimum_age_to_delete_time);

```

If you want to change *max\_number* to 24, you would use code similar to the following one.

```
$node_revision_delete_minimum_age_to_delete_time = variable_get('node_revision_delete_minimum_age_to_delete_time', array());

if (is_array($node_revision_delete_minimum_age_to_delete_time)) {
  $node_revision_delete_minimum_age_to_delete_time['max_number'] = 24;
  variable_set('node_revision_delete_minimum_age_to_delete_time', $node_revision_delete_minimum_age_to_delete_time);
}

```

---
Tags: 7
---


# Question
Title: How can I install an installation profile?
I have an installation profile with custom modules and themes.

How should I use Composer so that Drupal and the installation profile's dependencies are downloaded and copied in the right directories?

# Answer
You need to use the Composer Manager, which search the composer.json file in any module add the dependency on the core composer.json

How to handle the dependency ? By writing a composer.json file that contains all the php libraries that are been load it.

Here is an example of a good composer.json

```
{
  "name": "drupal/mobile_detect",
  "description": "Mobile_Detect is a lightweight PHP class for detecting mobile devices.",
  "type": "drupal-module",
  "homepage": "http://drupal.org/project/mobile_detect",
  "authors": [
    {
      "name": "Matthew Donadio (mpdonadio)",
      "homepage": "https://www.drupal.org/u/mpdonadio",
      "role": "Maintainer"
    },
    {
      "name": "Darryl Norris (darol100)",
      "email": "admin@darrylnorris.com",
      "homepage": "https://www.drupal.org/u/darol100",
      "role": "Co-maintainer"
    }
  ],
  "support": {
    "issues": "http://drupal.org/project/mobile_detect",
    "irc": "irc://irc.freenode.org/drupal-contribute",
    "source": "http://cgit.drupalcode.org/mobile_detect"
  },
  "license": "GPL-2.0+",
  "minimum-stability": "dev",
  "require": {
    "mobiledetect/mobiledetectlib": "~2.8"
  }
}

```

This composer.json is for the mobile\_detect drupal module. Once you run the core composer.json this will download the mobile\_detect library into the vendor directory and support autoload. And you can do the same thing with your libraries.

For more information about D8 and composer I will recommend reading this article - https://bojanz.wordpress.com/2015/09/18/d8-composer-definitive-intro/
> 0 votes

# Answer
It seems composer-manager is deprecated in drupal 8 and composer does not automatically install the profile's dependencies.

Also trying to build the profile's `.make` files as per this page results in

> Make has been removed, in favor of Composer. Use the make-convert command in Drush 8 to quickly upgrade your build to Composer.

It seems there is no clear documentation on how to load dependencies of a profile/distribution.

After reading this issue with comments from some years ago it seems that to this date the only viable option for profiles that have not created their own composer project is to copy the required section from the `profile_name/composer.json` file and include them in the main `composer.json` and run

```
rm composer.lock
composer install

```

or alternatively just run `composer update --with-dependencies`
> 0 votes

---
Tags: 8, composer, installation-profiles
---


# Question
Title: How do I get the administrator to automatically flag?
I created a module for flagging entities automatically when created or updated.

There are some errors in my code because only nodes work.

If a user "user1" creates a node, the flag will be in his name. I want the flag to be done automatically on behalf of the site administrator.

How do I get the administrator to automatically flag?

```
use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;

/**
 * Flag node.
 */
function admin_task_notify_node_update(Node $node) {
    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $flag_service->flag($flag, $node);
}

```

# Answer
> 1 votes
`FlagServiceInterface::flag` takes an `$account` argument:

> The account of the user flagging the entity. If not given, the current user is used.

So for example:

```
$flag_id = 'moderate_node';
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);
$account = \Drupal\user\Entity\User::load(1);
$flag_service->flag($flag, $node, $account);

```

---
Tags: 8, nodes, flags
---


title: Updating core to 8.9.6 fails

text:
# Question
Title: Updating core to 8.9.6 fails
I'v installed Drupal 8 by composer. Everything worked fine, but when I tried to update core from 8.9.1 to 8.9.5 in ended up in 8.9.4.

Today I tried to update from 8.9.4. to 8.9.6 by changing composer.json to demand v 8.9.6 at least.

The result was following error message:

> Your requirements could not be resolved to an installable set of packages. Problem 1
>
> * Installation request for symfony/http-kernel (locked at v3.4.41) -\> satisfiable by symfony/http-kernel\[v3.4.41\]. \> - drupal/core-recommended 8.9.6 requires symfony/http-kernel v3.4.44 -\> satisfiable by symfony/http-kernel\[v3.4.44\]. \> - drupal/core-recommended 8.9.x-dev requires symfony/http-kernel v3.4.44 -\> satisfiable by symfony/http-kernel\[v3.4.44\]. \> - Conclusion: don't install symfony/http-kernel v3.4.44 \> - Installation request for drupal/core-recommended ^8.9.6 -\> satisfiable by drupal/core-recommended\[8.9.6, 8.9.x-dev\].

I'm stuck, since I don't know what locks symphony/http-kernel to v3.4.41.

I'm still pretty new with composer and would be glad if anybody could help me. Thanks a lot.

EDIT 1

```
{
"name": "drupal/legacy-project",
"description": "Project template for Drupal 8 projects with composer following drupal/drupal layout",
"type": "project",
"license": "GPL-2.0-or-later",
"homepage": "https://www.drupal.org/project/drupal",
"support": {
    "docs": "https://www.drupal.org/docs/user_guide/en/index.html",
    "chat": "https://www.drupal.org/node/314178"
},
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
],
"require": {
    "civicrm/civicrm-asset-plugin": "~1.0.0",
    "civicrm/civicrm-core": "~5.28",
    "civicrm/civicrm-drupal-8": "~5.28",
    "civicrm/civicrm-packages": "~5.28",
    "composer/installers": "^1.2",
    "drupal/admin_toolbar": "^2.2",
    "drupal/antibot": "^1.4",
    "drupal/at_tools": "^3.2",
    "drupal/barrio": "1.x-dev",
    "drupal/captcha": "^1.0",
    "drupal/clever_theme_switcher": "^3.0",
    "drupal/colorbox": "^1.4",
    "drupal/commerce": "^2.17",
    "drupal/commerce_shipping": "^2.0@RC",
    "drupal/core-composer-scaffold": "^8.9.6",
    "drupal/core-project-message": "^8.9.6",
    "drupal/core-recommended": "^8.9.6",
    "drupal/core-vendor-hardening": "^8.",
    "drupal/ctools": "^3.4",
    "drupal/editor_advanced_link": "^1.6",
    "drupal/editor_file": "^1.4",
    "drupal/entity_browser": "^2.4",
    "drupal/hotkeys_for_save": "^1.0",
    "drupal/imce": "^2.3",
    "drupal/layout_builder_kit": "^1.0@beta",
    "drupal/layout_builder_modal": "^1.0",
    "drupal/linkit": "^4.3",
    "drupal/media_library_theme_reset": "^1.0@beta",
    "drupal/menu_block": "^1.5",
    "drupal/menu_item_role_access": "^2.0",
    "drupal/mobile_device_detection": "^3.2",
    "drupal/module_filter": "^3.1",
    "drupal/nagios": "^1.9",
    "drupal/pathauto": "^1.6",
    "drupal/permissions_by_term": "^2.18",
    "drupal/pixture_reloaded": "^3.0",
    "drupal/printable": "^1.1",
    "drupal/quick_node_clone": "^1.12",
    "drupal/redirect": "^1.5",
    "drupal/superfish": "^1.3",
    "drupal/swiftmailer": "^2.0@beta",
    "drupal/token": "^1.6",
    "drupal/upgrade_status": "^2.0",
    "drupal/views_conditional": "^1.0",
    "drupal/views_slideshow": "^4.7",
    "drupal/webform": "^5.9",
    "drupal/webform_civicrm": "^5.0@beta",
    "drupal/xmlsitemap": "^1.0@RC",
    "wikimedia/composer-merge-plugin": "^1.4"
},
"conflict": {
    "drupal/drupal": "*"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "sort-packages": true
},
"extra": {
    "drupal-scaffold": {
        "locations": {
            "web-root": "./"
        }
    },
    "installer-paths": {
        "core": [
            "type:drupal-core"
        ],
        "libraries/{$name}": [
            "type:drupal-library"
        ],
        "modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "drush/Commands/contrib/{$name}": [
            "type:drupal-drush"
        ],
        "modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ]
    },
    "merge-plugin": {
        "include": [
            "modules/contrib/webform/composer.libraries.json"
        ]
    },
    "drupal-core-project-message": {
        "include-keys": [
            "homepage",
            "support"
        ],
        "post-create-project-cmd-message": [
            "<bg=blue;fg=white>                                                         </>",
            "<bg=blue;fg=white>  Congratulations, you’ve installed the Drupal codebase  </>",
            "<bg=blue;fg=white>  from the drupal/legacy-project template!               </>",
            "<bg=blue;fg=white>                                                         </>",
            "",
            "<bg=yellow;fg=black>Next steps</>:",
            "  * Install the site: https://www.drupal.org/docs/8/install",
            "  * Read the user guide: https://www.drupal.org/docs/user_guide/en/index.html",
            "  * Get support: https://www.drupal.org/support",
            "  * Get involved with the Drupal community:",
            "      https://www.drupal.org/getting-involved",
            "  * Remove the plugin that prints this message:",
            "      composer remove drupal/core-project-message"
        ]
    }
}

```

}

My update command was

```
composer u drupal/core* --with-dependencies

```

# Answer
> 0 votes
I tried an update with composer u. This updated my CiviCRM packages and their dependencies and thus removed the dependency conflict described above.

I had removed drupal/core-vendor-hardening as was suggested in @leymannx's answer (but kept the vendor/ directory). That broke the installation and produced a fatal error running composer u. After restoring it everything worked fine for me. Thanks for everyone who helped.

---
Tags: updating, composer
---


# Question
Title: Allow shipping that is calculated using a base rate plus a rate per item?
I figured this would be built in, but it seems it is not. See here:

I have two options:

1. Flat rate: I can make it 9.99 USD, but then if it's 100 items, it's still 9.99 USD.
2. I can make it 1 USD per item, but I als don't want that.

What I want is a base rate of 10 USD, and then 1 USD per item after that. Anyone know how to do that?

*UPDATE*

There is some information available for Commerce 1.0 here, but hardly any information on Commerce 2. This is basically all there is.

Can it be that Commerce 2 doesn't support this? I mean, nowhere can I see "shipping rules" or anything related to that that allows me to set up these rules?

(I miss UberCart)

# Answer
Programmatically create your own custom shipping method in a custom module.

Example, custom module called "mymodule":

/modules/custom/mymodule/src/Plugin/Commerce/ShippingMethod/**CustomRate.php**

```
<?php

namespace Drupal\mymodule\Plugin\Commerce\ShippingMethod;

use Drupal\commerce_shipping\Plugin\Commerce\ShippingMethod\ShippingMethodBase;
use Drupal\commerce_price\Price;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\commerce_shipping\PackageTypeManagerInterface;
use Drupal\commerce_shipping\ShippingRate;
use Drupal\commerce_shipping\ShippingService;
use Drupal\Core\Form\FormStateInterface;
use Drupal\state_machine\WorkflowManagerInterface;

/**
 * Provides the FlatRatePerItem shipping method.
 *
 * @CommerceShippingMethod(
 *   id = "custom_rate",
 *   label = @Translation("Custom Rate"),
 * )
 */
class CustomRate extends ShippingMethodBase {

  /**
   * Constructs a new FlatRate object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\commerce_shipping\PackageTypeManagerInterface $package_type_manager
   *   The package type manager.
   * @param \Drupal\state_machine\WorkflowManagerInterface $workflow_manager
   *   The workflow manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, PackageTypeManagerInterface $package_type_manager, WorkflowManagerInterface $workflow_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $package_type_manager, $workflow_manager);

    $this->services['default'] = new ShippingService('default', $this->configuration['rate_label']);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
        'rate_label' => '',
        'rate_description' => '',
        'rate_amount' => NULL,
        'services' => ['default'],
      ] + parent::defaultConfiguration();
  }

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

    $amount = $this->configuration['rate_amount'];
    // A bug in the plugin_select form element causes $amount to be incomplete.
    if (isset($amount) && !isset($amount['number'], $amount['currency_code'])) {
      $amount = NULL;
    }
    // A bug in the plugin_select form element causes $base_amount to be undefined.
    if (!empty($this->configuration['base_amount'])) {
      $base_amount = $this->configuration['base_amount'];
    }
    else {
      $base_amount = null;
    }

    $form['rate_label'] = [
      '#type' => 'textfield',
      '#title' => t('Rate label'),
      '#description' => t('Shown to customers when selecting the rate.'),
      '#default_value' => $this->configuration['rate_label'],
      '#required' => TRUE,
    ];
    $form['rate_description'] = [
      '#type' => 'textfield',
      '#title' => t('Rate description'),
      '#description' => t('Provides additional details about the rate to the customer.'),
      '#default_value' => $this->configuration['rate_description'],
    ];
    $form['base_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Base amount'),
      '#default_value' => $base_amount,
      '#required' => TRUE,
      '#description' => t('Charged once.'),
    ];
    $form['rate_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Rate amount'),
      '#default_value' => $amount,
      '#required' => TRUE,
      '#description' => t('Charged for each quantity of each shipment item.'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    if (!$form_state->getErrors()) {
      $values = $form_state->getValue($form['#parents']);
      $this->configuration['rate_label'] = $values['rate_label'];
      $this->configuration['rate_description'] = $values['rate_description'];
      $this->configuration['base_amount'] = $values['base_amount'];
      $this->configuration['rate_amount'] = $values['rate_amount'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateRates(ShipmentInterface $shipment) {
    $base_amount = Price::fromArray($this->configuration['base_amount']); // create base price
    $amount = Price::fromArray($this->configuration['rate_amount']);
    $quantity = $shipment->getTotalQuantity();
    $ship_price = $amount->multiply($quantity);
    $ship_price = $ship_price->add($base_amount); // add base
    $rates = [];
    $rates[] = new ShippingRate([
      'shipping_method_id' => $this->parentEntity->id(),
      'service' => $this->services['default'],
      'amount' => $ship_price,
    ]);

    return $rates;
  }

}

```

## Result
> 5 votes

---
Tags: 8, commerce
---


# Question
Title: How to clear image (or file) field data for specific node programmatically?
I need to clear/remove image (or file) field from specific node.
I have before:

I want to get after code execution for the field:

What code should I use to properly clear image (file) field data?

# Answer
I assume that your field accepts only one file at a time. This is the code you need to use:

```
// Replace this with the ID of the node you want to update.
$node_id = 123;

/** @var \Drupal\node\NodeInterface $node */
$node = \Drupal\node\Entity\Node::load($node_id);

// Step 1: remove the file. This will actually delete the file from the
// filesystem, so in case you want to keep it just remove the next two
// lines.
/** @var \Drupal\file\FileInterface $file */
$file = $node->get('field_NAME_OF_YOUR_FIELD')->entity;
$file->delete();

// Step 2: remove the field data.
// The 0 in this case is the index of the item you want to remove. It simply
// means the first value in that field needs to be removed.
$node->get('field_NAME_OF_YOUR_FIELD')->removeItem(0);
// We have to save the changes to the node.
$node->save();

```
> 6 votes

# Answer
Just to offer an alternate solution

```
$nid = 123;

// Load the node (EDIT:) while checking if it exists
if(!$node = \Drupal::service('entity_type.manager')
  ->getStorage('node')
  ->load($nid)) {
  // No results for the $nid, bail out early
  return;
}

// EDIT: To make sure there's a value on the field
if(!$node->hasField('field_name') || $node->get('field_name')->isEmpty(){
  return;
}

// Grab the file entity and make it temporary.
// Deletion will be handled by cron.
$file = $node->get('field_name')
  ->entity
  ->set('status', 0)
  ->save();

// Unset the value on the file ref field and save
$node->set('field_name', '')
  ->save()

```
> 1 votes

# Answer
A solution for multiple files (also good for avoiding errors when the field is empty):

```
$nid = 123;

$node = \Drupal\node\Entity\Node::load($nid);

// Grab the file entities and make them temporary.
// Deletion should be handled by cron.
$items = $node->get('field_NAME_OF_YOUR_FIELD');
foreach ($items as $item) {
  $file = $item->entity;
  $file->set('status', 0);
  $file->save();
}

// Unset the values on the file ref field and save
$node->set('field_NAME_OF_YOUR_FIELD', []);
$node->save();

```

This code is based on @Mrweiner great answer.
> 0 votes

---
Tags: 8, entities, files
---


# Question
Title: How do you target a specific type of content?
I have the content type (node), article, page, recipe.

The code below can be used to flag any type of content.

How do you target a specific type of content ?

For example I only want to flag the article and recipe content type.

```
<?php

/**
 * @file
 * Holds hook implementation for the Admin Task Notify module.
 */

use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\comment\Entity\Comment;

/**
 * Implements hook_node_update().
 */
function admin_task_notify_node_update(Node $node) {

    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $account = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $account);

}

```

# Answer
If you want your hook code to only run on specific content types, simply add a conditional

```
function admin_task_notify_node_update(Node $node) {

  if ($node->getType() == 'article' || $node->getType() == 'recipe') { // conditional
    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $account = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $account);
  }

}

```

---

> I have several types of content to add, is there a shorter way to do it ?

Using in\_array()

```
$allowed_c_types = ['article', 'recipe', 'some_other'];
$c_type = $node->getType();

if (in_array($c_type, $allowed_c_types)) { // conditional

```

But don't hard code, use `$flag->getBundles()` to get the list as mentioned by Shawn

```
$allowed_c_types = $flag->getBundles();

```
> 3 votes

# Answer
You need to configure your `moderate_node` flag in either the UI or in configuration management.

In the flag module, a flag entity is defined by the entity type (i.e. `node`) and bundles (e.g. `article`, `page`, `recipe`) that are allowed on it. If no bundles are specified, then all bundles are allowed.

In your example code, `$flag->getBundles()` method will return the bundles that are allowed (empty means all). Once set, the `$flag_service->flag` method will kickback exceptions if you try to flag bundles that do not apply to that flag. You'll need to adjust the code accordingly to handle those scenarios.
> 4 votes

---
Tags: 8, nodes, flags
---


# Question
Title: Unable to load class \Drush\VersionControl\Backup
I keep getting this error : *Unable to load class \Drush\VersionControl\Backup* every time i attempt to update my Drupal install from **8.4.0 to 8.4.2**.

I am running the composer provided drush **Drush Version : 8.1.15**

Now here is what i have tried:

* **drush up drupal --debug**
Unable to load class \Drush\VersionControl\Backup
* **drush up drupal --debug --version-control=svn**
No valid version control or backup engine found
* **drush up drupal --debug --version-control=git**
No valid version control or backup engine found
* **drush up drupal --debug --no-backup**
No valid version control or backup engine found

if anyone could answer any of these question for me, i would really appreciate it: How do i turn off version control? How do i set the valid version control that this thing is complaining about? How do i set the backup engine?

Note: some solutions out there mentioned that we have to remove the composer provided version and install drush to a different location. To be honest I do not want to use that solution.

Thanks.

# Answer
> I am running the composer provided drush **Drush Version : 8.1.15**

Drupal 8.4 requires Drush 9, so upgrade your Drush for starters.

```
composer global require drush/drush:master

```

> http://docs.drush.org/en/master/install/
> 4 votes

# Answer
# Install drush globally.

```
composer global require drush/drush:8.x

```

Works on Drupal 7 and 8.

You might have trouble locating the drush file to run as it will be at another location now. You can try to find it by running `composer global show drush/drush` Ideally change your PATH: settings to this.
> 0 votes

# Answer
## Remove Drush from the project composer and use globally installed Drush.

While working on a Drupal 7 install, with Drush 8 and using Drush launcher.
> -1 votes

---
Tags: drush
---


title: Open ajax dialog with JavaScript

text:
# Question
Title: Open ajax dialog with JavaScript
By adding `use-ajax` to a link we can open a modal using the Drupal ajax library as per the docs.

E.g.

```
<a class="use-ajax"
    data-dialog-options="{"width":400}"
    data-dialog-type="modal"
    href="/node/1">
    First article displayed in modal dialog.
</a>

```

This will use the ajax library to fetch node/1 and then display it in a modal.

There is also a Dialog API for JavaScript which allows opening modals using JavaScript.

E.g.

```
var myDialog  = Drupal.dialog(ADOMElement, settings);
myDialog.show();

```

The problem with this API is you need to pass in a existing DOM element.

My question is can I trigger opening a modal with JavaScript and utalise the internal Drupal ajax library to actually fetch the content?

E.g Can I do something like this?

```
var myDialog  = Drupal.dialog('/node/1', {useAjax: true});
myDialog.show();

```

I could just create an html link as per my first code block, hide it with css, and then trigger a click on it with JS but this seems a bit hacky - there must be a way to trigger this action using pure JS.

# Answer
You can trigger Ajax in custom javascript. See How to Trigger Existing, Non-Form Ajax from JavaScript Event

In your case an Ajax dialog:

```
var ajaxSettings = {
  url: '/node/1',
  dialogType: 'modal',
  dialog: { width: 400 },
};
var myAjaxObject = Drupal.ajax(ajaxSettings);
myAjaxObject.execute();

```
> 7 votes

---
Tags: ajax, modal-dialogs
---


# Question
Title: Drupal CKeditor image-upload plugins don't delete unused files
In my Drupal travels, I've used a number of *CKeditor instant image-upload plugins*; IMCE, Media, and another one (don't recall the name).

The three of them doesn't delete unused files (Like Drupal imagefield does automatically) and thus I sometimes need to upload the same file with them 6 or seven times and these duplicated can whey much gb's in a cumulative way.

Is there any way to make one of the *CKeditor instant image-upload plugins* delete the files automatically? or at least? Have you cam across something that does delete unused image files automatically? Thanks,

# Answer
> 1 votes
Try to check out the Fancy File Delete module. One of the things it can do based on the module page is

> Deleting unused files from the whole install that are no longer attached to nodes & the file usage table. AKA deleting all the orphaned files.

I think this would require a manual process of deletion but this may solve the issue of deleting orphaned or unused duplicate images in your site.

# Answer
> 0 votes
I don't think there's an easy way to do this. It seems like you want a cross between what Imagefield and the other modules do and there just isn't a module ilke it as far as I know.

You could write your own module which overrides hook\_presave to look at a node's body and determines all the images used, and adds that list to a filefield.

# Answer
> 0 votes
You just need to set `make_unused_managed_files_temporary` to `TRUE`.

```
/**
 * Prevent unused files from being deleted.
 */
function file_update_8300() {
  // Disable deletion of unused permanent files.
  \Drupal::configFactory()->getEditable('file.settings')
    ->set('make_unused_managed_files_temporary', FALSE)
    ->save();

  return t('Files that have no remaining usages are no longer deleted by default.');
}

```

Unused temporary files older than `temporary_maximum_age` (default of 6 hours) are removed automatically by cron.

https://www.drupal.org/node/2891902

> You can still opt out from this new default behavior, to go back to the old behavior (there is no user interface for going back, but it can be done using Drush or by making a site-specific code change to change the above configuration setting to `true`).

---
Tags: wysiwyg, files, media
---


# Question
Title: Troubleshooting a PluginNotFoundException exception
I have a Drupal 8 site on 8.8.6. I installed and tried to use the fancy\_file\_delete module version 2.0.1, however, in trying to load one of its views, `/admin/config/content/fancy_file_delete/list`, I got the exception

```
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "default_image" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 150 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

```

(I'm including the full stack trace at the bottom of this question).

I grepped in our site's configuration directory, and found that the the string `default_image` seems to be a key for the default image settings for image files. I found this in the storage of several file fields:

```
field.storage.user.user_picture.yml:17:  default_image:

 15 settings:
 16   uri_scheme: public
 17   default_image:
 18     uuid: null
 19     alt: ''
 20     title: ''
 21     width: null
 22     height: null
 23   target_type: file
 24   display_field: false
 25   display_default: false

```

So this doesn't seem to be the missing plugin causing the exception to be thrown. We have images on all of our content types, and we aren't getting exception thrown when they load.

I looked through the git log for our config directory and didn't find deleted file that had `default_image` in the name. So it doesn't appear that we had something in configuration that we deleted later on. If the deletion of this entity was the result of an action that I or another developer of our site did at one point, I don't recall and am not aware of it.

I googled the string of the exception message, and found a couple hits. However, none of them led me to be able to fix the exception. This issue remains an open issue on the entity browser module. This patch for the simple\_menu\_icons module provides a fix for the same exception, but the code replaces a `File::load()`, which I only find in the `src/FancyFileDeleteBatch.php`. I commented out lines 125-162 of `src/FancyFileDeleteBatch.php`, but that doesn't prevent the exeption from being thrown. Which makes sense-- it's the code for batch deletion, and I'm only trying to load the view.

How can I troubleshoot this exception? Is this an entry for a missing entity, that I can just delete? Or does the code of the module need to be rewritten?

---

What follows is the exception that I get and its full stack trace:

```
The website encountered an unexpected error. Please try again later.

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "default_image" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 150 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

Drupal\Core\Entity\EntityTypeManager->getHandler('default_image', 'storage') (Line: 208)
Drupal\Core\Entity\EntityTypeManager->getStorage('default_image') (Line: 139)
Drupal\views\Plugin\views\field\EntityLabel->preRender(Array) (Line: 1503)
Drupal\views\ViewExecutable->render() (Line: 183)
Drupal\views\Plugin\views\display\Page->execute() (Line: 1630)
Drupal\views\ViewExecutable->executeDisplay('page_1', Array) (Line: 77)
Drupal\views\Element\View::preRenderViewElement(Array)
call_user_func_array(Array, Array) (Line: 100)
Drupal\Core\Render\Renderer->doTrustedCallback(Array, Array, 'Render #pre_render callbacks must be methods of a class that implements \Drupal\Core\Security\TrustedCallbackInterface or be an anonymous function. The callback was %s. Support for this callback implementation is deprecated in 8.8.0 and will be removed in Drupal 9.0.0. See https://www.drupal.org/node/2966725', 'silenced_deprecation', 'Drupal\Core\Render\Element\RenderCallbackInterface') (Line: 781)
Drupal\Core\Render\Renderer->doCallback('#pre_render', Array, Array) (Line: 372)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 200)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 573)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 50)
Drupal\ban\BanMiddleware->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 708)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

# Answer
I am the module maintainer for Fancy File Delete. I fixed the issue in 2.0.3. If you want to update it, you should be good. Make sure to run drush updb and cex after to fix the issue with the config that was causing this.
> 1 votes

---
Tags: views
---


title: How can I programmatically flag a user?

text:
# Question
Title: How can I programmatically flag a user?
I am creating a new user programmatically in drupal7. At the time of user creation is there any way to flag the user automatically. I am using flags module.

I tried in the hook\_user\_presave

```
function MODULE_NAME_user_presave(&$edit, $account, $category) {
$flag = flag_get_flag('name_of_the_flag');
$flag->flag('flag', $account->uid);
}

```

# Answer
Have you checked that `$account->uid` exists? I'm not sure that a new user would have a UID inside of `hook_user_presave()`. You may want try setting the flag in `hook_user_insert()` instead. Also worth making sure that users are allowed to be flagged by your flag type.
> 0 votes

---
Tags: 7, users, flags
---


# Question
Title: Using PrivateTempStore for anonymous users with Internal Dynamic Page Cache & Internal Page Cache modules
I'm creating a module which interacts with an external API that handles authentication and completely bypasses the Drupal authentication system. This means that users logged-in from the API side are seen as anonymous users. The module utilizes the `PrivateTempStore` class to store user sessions. This works as expected.

At the moment, any user session sensitive blocks or pages that my module outputs are set to have a maximum cache lifetime of zero to ensure that the user's account page is not cached.

Is this the correct approach, or should I disable the Internal Page Cache module, which specifically targets anonymous users?

The site will be hosted on the Acquia platform; Varnish will be likely used.

# Answer
> 0 votes
Private TempStore always generate Anonymous Session. That means If you are using any Caching Layer for your Application it always break. either in Acquia or other platform.

May be you can use Browser LocalStorage for saving data and sync it when its required. it will help you to cache your pages.

In Acquia, cookie based cache variation Generation possible so you have to create cookie and based on that value you can generate cache tags.

---
Tags: 8, caching
---


# Question
Title: Content moderation - workflows / weird behavior
I have set a content moderation workflows for my content type : Draft and Published states. Pretty basic, i create a content in Draft which is not published, i can change the moderation\_state to Published to published it.

But when i do the following workflows : Draft -\> Published -\> Draft again, the content is still published. Is it a normal behavior ?

My core version is 8.8.3.

# Answer
What I did was create a new state called `Needs Review` to mimic draft state at `/admin/config/workflow/workflows`.

The one thing to note is to check `default revision`. Then set the permissions and you should be able to go from publish to unpublish.

After the change here is what your configuration should look like.
> 0 votes

---
Tags: 8, workflows
---


# Question
Title: "attempt to write a readonly database" with BrowserTestBase Functional tests
I have a functional test that is currently empty. I run it with the following command;

```
php core/scripts/run-tests.sh --sqlite /db/drupal.sqlite --php /usr/local/bin/php --verbose --directory modules/custom/

```

I have tried with and without the `--sqlite` command, as well as trying a non-existant file like `tmpfs/drupal.sqlite`, but I always get the same error:

> 1. Drupal\Tests\answers\Functional\AnswersTest::testAddContentPage Exception: Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[HY000\]: General error: 8 attempt to write a readonly database:

From that error I have gathered that the issue is that the user doesn't have write-access to the database, but without knowing *where* the database file is I'm not sure how to check this. I tried settings the permissions on */db/drupal.sqlite* to 777 but this didn't help either.

# Answer
> 1 votes
I don't quite understand *why* this fixes the problem, but in my case the issue was caused by my executing the `core/scripts/run-tests.sh` script as `root`. By running it as `www-data` instead the issue went away.

I can only assume that the sqlite DB gets created by `root` and then the script switches itself over to `www-data` and can't access the DB anymore.

---
Tags: testing, 9
---


# Question
Title: Custom block theme not appearing in QuickTabs content
I'm attempting to create a dashboard page that contains 4 tabs that are each a block that will contain a content based on the current user. I went ahead and created the 4 blocks (bl1, bl2, bl3, and bl4), added the blocks to `content` under `block layout` and then created the Quicktabs Instance to display these 4 blocks. So far so good.

However, when I go to customize the tab blocks in my theme, that theme is not getting picked up through quicktabs... My dashboard template looks like so:

**page--dashboard.html.twig**

```
{% block head %}
   {{ drupal_entity('block', 'navigationheader') }}
{% endblock %}

{% block content %}
  <div id="main-content" class="container">
    {{ drupal_entity('block', 'quicktabsdashboard') }}
  </div>
{% endblock %}

{% block footer %}
  {{ drupal_entity('block', 'footer') }}
{% endblock %}

```

Then I have 4 template files for each block: `block--bl1.html.twig`, `block--bl2.html.twig`, `block--bl3.html.twig`, and `block--bl4.html.twig`... (FWIW, this project is very customized and these blocks will only be displayed here)

The content from these template files are not being pulled into the quicktabs. If I load the block manually in dashboard like so: `{{ drupal_entity('block', 'bl1') }}` the expected block styling is there..

How do you get quicktabs to show your custom block templates?

*Perhaps I'm taking the wrong approach and shouldn't use quicktabs and instead just write my own tab bar in twig and display the different blocks directly in the dashboard template?*

**Update**

I've done what was suggested in the answer below and got rid of my usage of Twig Tweak and created a new region called `dashboard_tabs` for my quicktabs instance block. I also created a region called `dashboard_content` that contains the blocks I am putting into my quicktabs (so that I can template theme all by name instead of by Id).

Here is what I have now:

**page--dashboard.html.twig**

```
{% block head %}
  <div id="ytp-header">
    {{ page.header_navigation }}
  </div>
{% endblock %}

{% block content %}
  <div class="ytp-main-content">
    {{ page.dashboard_tabs }}
  </div>
{% endblock %}

```

**region.html.twig**

```
{%
  set classes = [
    'region',
    'region-' ~ region|clean_class,
  ]
%}
{% if content %}
  <section{{ attributes.addClass(classes) }}>
    {{ content }}
  </section>
{% endif %}
{% if dashboard_tabs %}
  <section{{ attributes.addClass(classes) }}>
    {{ dashboard_tabs }}
  </section>
{% endif %}
{% if dashboard_content %}
  <section{{ attributes.addClass(classes) }}>
    {{ dashboard_content }}
  </section>
{% endif %}

```

When I have it like this, this actually creates even more problems for me:

1. The blocks Quicktabs displays still do not use my template for those blocks -and-
2. Quicktabs now doesn't change the tab and instead just reloads the page (Ajax broke?)

This seems like it should be fairly simple, but I'm going wrong somewhere obviously. Any tutorials or guides on how to build quicktabs using blocks that have their own template file?

# Answer
> 3 votes
Your appraoch is wrong as you never should render anything with Twig Tweak when you can do it also with `{{ content }}`. If you render more complex things than a simple scalar value with something `{{ node.field_something.value }}` or any of Twig Tweak's functions like `{{ drupal_something() }}` you always have drawbacks like

* block not rendering with correct template
* content being incorrectly cached
* (referenced) entity being rendered in the wrong language

In your case the correct approach would be creating a region for the quicktab blocks, and then render those blocks in the region template file (not page template) with a plain `{{ content }}`.

Everyone of the above problems has a workaround (for Twig Tweak rendered blocks see the docs), but I'd defenitly advice not using workarounds when it easily can be done straight forward.

---
Tags: 8, theming, blocks
---


# Question
Title: Form API placeholder attribute rendered as "- Select -"
In a custom Drupal 8 module, I have a couple of Form API fields of `'#type' => 'select'`:

```
    $form['form-right']['field_role'] = [
      '#type' => 'select',
      '#title' => $this->t('Role'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Role Foo'),
        'bar' => $this->t('Role Bar'),
        'baz' => $this->t('Role Baz'),
        'quux' => $this->t('Role Quux'),
        'plugh' => $this->t('Role Plugh'),
        'xyzzy' => $this->t('Role Xyzzy'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Role'),
      ],
    ];

    $form['form-right']['field_contact_reason'] = [
      '#type' => 'select',
      '#title' => $this->t('Contact Reason'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Contact Reason Foo'),
        'bar' => $this->t('Contact Reason Bar'),
        'baz' => $this->t('Contact Reason Baz'),
        'other' => $this->t('Other'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Contact Reason'),
      ],
    ];

```

Before a value is selected, the dropdown select picklists display the string `'- Select -'`:

The client would like them to display the value in the placeholder attribute instead.

Have I done something wrong?

# Answer
> 5 votes
According to the documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Select.php/class/Select

> **#empty\_option**: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for a required field and "- None -" for an optional field.

---
Tags: 8, forms
---


# Question
Title: Why do functional tests require a running website?
I'm trying to set up functional tests in Drupal 9 using the `BrowserTestBase` class. The Type of Tests page on drupal.com and Browser test tutorial are quite clear that browser tests will build their own website and browser.

> Browser tests create a complete Drupal installation and a virtual web browser and then use the virtual web browser to walk the Drupal install through a series of tests, just like you would do if you were doing it by hand.

However, as soon as I try to run a browser test using `run-tests.sh` I get an error stating that the `--url` parameter needs to be provided (this led me down a rabbit hole: Curl error in basic functional test). There is a tutorial on running browser tests, which clarifies that the `--url` parameter is in fact needed.

> In phpunit.xml make the following changes:
>
> * Set the SIMPLETEST\_BASE\_URL variable to the URL of your site.
> * Set the SIMPLETEST\_DB variable to point to the URL of your Drupal database.
> * If you are placing phpunit.xml somewhere other than core, change the value of the phpunit tag's 'bootstrap' attribute to reflect the new location.
> * For kernel and functional tests, set the BROWSERTEST\_OUTPUT\_DIRECTORY.

The section titled Run All PHPUnit Tests The Way The Testbot Does It sheds a bit of light on this by clarifying that when testbot runs a Browser test, it sets up a drupal site with the testing module enabled.

> The first step is to make sure you have a fully working Drupal installation, with the Testing module enabled. The drupal.org testbot assumes that contributed modules will be installed inside the modules/contrib directory and Drupal's application root for unit tests is set to a value assuming this directory structure.

This seems to suggest that the browser test does not "*create a complete Drupal installation*" but rather *requires* one, but that leaves more questions about these tests.

* Can the URL be *any* drupal site with the testing module enabled?
* What changes does the test make to the website?
* Do I need a fresh site everytime I run the tests?
* Do I need to provide login details? Is that handled by the testing module?
* What about the database, what changes are made to it? How do I revert them?

Any kind of clarity on how this works would be appreciated, as I think it will probably answer my other question as well.

# Answer
> 3 votes
You can theoretically run a functional test on a production website. (I am not saying you should though.)

In my experience the testing framework will install a new Drupal site for every individual test and in the end remove these sites. This is done by creating testing tables in your existing database, for which you need to provide the credentials in SIMPLETEST\_DB.

As long as the tests do not error, all of this data will be cleaned up at the end of the test and you do not need to worry about anything. If the test unexpectedly stops you might need to clean op some items manually (previously could be done with simepletest module, but I believe there are plans to remove that).

I have no idea if you can use a different site. You need to have database access to that site to install the testing tables. Modules should be available, etc. I do not think it would be reliable.

---
Tags: testing, 9
---


# Question
Title: Deprecated Dependency Warning not removing
In my Drupal 8.9.6 (Installed with Lightning distribution) Status Admin Page, there are three warnings showing after updating several modules and core to the latest versions:

1. DEPRECATED DEPENDENCY: ENTITY EMBED Lightning Media 5.0 will not include the Entity Embed module. Please add it to your project directly: composer require drupal/entity\_embed:^1.0
2. DEPRECATED DEPENDENCY: VIDEO EMBED MEDIA Lightning Media 5.0 will not include the Video Embed Media module. Please add it to your project directly: composer require drupal/video\_embed\_field:^2.0.
3. DEPRECATED DEPENDENCY: VIEWS INFINITE SCROLL Lightning Media 5.0 will not include the Views Infinite Scroll module. Please add it to your project directly: composer require drupal/views\_infinite\_scroll:^1.6.

I have installed the latest versions of these contributed modules through composer. But the warning not going away from the admin status page. How to remove these warning?

# Answer
> 1 votes
The Lighting Media modules have hard-wired checks to report this information if it finds Video Embed Media or Entity Embed & Views Infinite Scroll installed. It doesn't check the Composer requirements to see if the warning message is still applicable.

Either ignore the warning until the 5.x release is out or patch away checks in `hook_requirements()` if it bothers you that much.

---
Tags: media, composer
---


title: Non-blocking HTTP request with Guzzle

text:
# Question
Title: Non-blocking HTTP request with Guzzle
Is there a Drupal 8 way to do non-blocking HTTP client request using Guzzle? I don't need to wait for the answer of The HTTP post, as that is slowing down the site.

I already seen Non-blocking asynchronous HTTP requests, but I want to know if someone have a Drupalier solution.

# Answer
There is no "Drupal 8 way." Drupal 8 relies on Guzzle as its HTTP client library so it doesn't have a built-in solution for this.

While the Guzzle client library has `GuzzleHttp\Client::requestAsync()`, it's not a non-blocking asynchronous method; the method will block once it has initiated the network request since it needs response data for promise methods.

In order to do something akin to your linked question (using `fsockopen()` / `fwrite()` to open a socket, send HTTP headers, & close) with Guzzle, you'll need to use a different handler than the default ones Guzzle provides. Guzzle has some documentation on to do this.

It should be noted, even the linked solution isn't non-blocking in the event there are network connection issues (e.g. if the host is unreachable, `fsockopen()` has `$timeout` set to `30`, so it would block for 30s before timeout was hit). PHP being single-threaded prevents true non-blocking asynchronous execution within PHP code.
> 1 votes

# Answer
One solution for this type of processing is as follows:

Enqueue the item to an async queue worker for processing, where the items are constantly being processed. In this case, using RabbitMQ, which improves upon the core cron queue with an immediate queue processing feature.

1. Install RabbitMQ and https://www.drupal.org/project/rabbitmq
2. Add the item to the queue (include `settings.php` `$settings['queue_service_my_queue_name'] = 'queue.rabbitmq.default';`)

```
// Some data to send to the queue
$data = ['nid' => 12, 'url' => 'https://example.com/api'];
// Get the queue config
$queue_factory = \Drupal::service('queue');
$queue = $queue_factory->get('my_queue_name');
// Send data to the queue
$queue->createItem($data);

```
3. Define your QueueWorker plugin (note: no need for `cron` in queue worker annotation)
4. Process the queue with `drush rabbitmq-worker my_queue_name`
5. Add a process manager, such as `supervisord`, or you can use `kubernetes`, to maintain the `drush` queue worker process.

This approach scales well and the queue items can be processed both immediately and asynchronously, in another queue worker process.
> 0 votes

---
Tags: 8, http-request
---


# Question
Title: How to get taxonomy term name/label from a field?
Ok, so I'm trying to populate a field based on the selection of a taxonomy term. I've mainly got it working thanks to this stack exchange article

```
use Drupal\taxonomy\Entity;

function module_entity_presave(EntityInterface $entity) {

  if($entity->bundle() == "node_type"){
    $bread_slice = $entity->get("field_taxonomy_term")->getString();
    $bread_butter = "- Additional Text for Reasons";
    $bread_title = $bread_slice." ".$bread_butter;
    $entity->field_title->value = $bread_title;
    //save is done automatically
  }

}

```

The issue is that, the resulting code doesn't print the name/label of the term, but instead the tid. So, it ends up showing as "757 - Additional Text for Reasons" I barely know any php, but I know enough to get around. I suppose my issue is the fact I'm not getting the correct value from the taxonomy array, yet I'm unsure how. I've tried finding the correct value using some twig debugging, {{dd(data.taxonomy\_term)}} but all the values for it show null. Please point me in the direction of how to solve this?

# Answer
The field only stores term IDs. So either get the term ID and load the term from it or load the referenced entities directly.

```
/**
 * Implements hook_entity_presave().
 */
function MYMODULE_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity instanceof \Drupal\node\NodeInterface && $entity->bundle() === 'MYBUNDLE') {

    if ($field = $entity->get('field_MYFIELD')) {

      if (!$field->isEmpty()) {

        $label = $field->referencedEntities()[0]->label();
        // dpm($label);
        // Code on...
      }
    }
  }
}

```

Consider installing Devel. It gives you some handy debugging helpers like `dpm($some_var)` to dump variables into core's status messages block so you can inspect them easily.
> 3 votes

# Answer
You can get the entity from entity reference fields like:

```
$entity->field_name->entity // or `$entity->get('field_name')->entity` whichever you prefer

```

if single value, or loop with `referencedEntities()` method on the field like:

```
foreach ($entity->field_name->referencedEntities() as $term)
// Or foreach ($entity->get("field_name")->referencedEntities() as $term)

```

if multi-value (or if you want to keep your code more "general purpose" as this also works for single value fields). Also check if there's anything to work with or exit early, so all together something like:

```

function module_entity_presave(EntityInterface $entity) {
  if ($entity->getEntityTypeId() !== 'node' || $entity->bundle() !== 'node_type') {
    // Not an entity or bundle we're concerned with.
    return;
  }

  if ($entity->get("field_taxonomy_term")->isEmpty()) {
    // No term to work with.
    return;
  }
  /** @var \Drupal\taxonomy\TermInterface $term */
  $term = $entity->get("field_taxonomy_term")->entity;
  // Translate the text. Term label should be already translated value so pass it
  // as a param.
  $entity->field_title->value = t('@label - Additional Text for Reasons', [
    '@label' => $term->label(),
  ];
}

```
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Some pages hide content unless "Read more" is clicked
If I have multiple pages on Drupal, some show the full page, and others say "Read more" and will only show the whole page when it is clicked. It doesn't seem to have anything to do with the size of the content of the page or how long it is. What's up with that?

# Answer
What you're probably looking at is a "View". This view is probably showing a list of "Content" (nodes).

Now each node is probably being set to render in "Teaser" view mode. But since some of your node types (`article` for example) doesn't have a "teaser" view mode configured, it shows the "Full" (or "Default") view mode, which renders the "whole" thing.

What you need to do is find the View Mode that your content listing View is using, the Node Type of the content that's showing up as Full, (for example 'Basic Page'), then go to:

**Structure \> Content Types \> \[Content Type you want to configure\] \> Manage Display**

And configure the view mode that your View is using to display the Read More link, show the body text as "Summary or Trimmed" etc.
> 0 votes

---
Tags: navigation
---


# Question
Title: doctrine/reflection conflicts with doctrine/common
My current Drupal version is 8.9.3, running on PHP 7.3.20, and updated from Drupal 8.9.2 (fresh install) using `compose update`.

I tried to upgrade to Drupal 9 used this https://www.drupal.org/docs/upgrading-drupal/upgrading-from-drupal-8-to-drupal-9-or-higher as guide. So in step 2, I ran `composer require "drupal/core:9.0.0 as 8.9.3" --no-update && composer update` instead of `composer require drupal/core-recommended:^9.0.0 drupal/core-composer-scaffold:^9.0.0 drupal/core-project-message:^9.0.0 --update-with-dependencies --no-update`, but then Composer throws a conflict report regarding doctrine/reflection which conflicts with doctrine/common.

```
  Problem 1
    - Conclusion: remove drupal/core-recommended 8.9.3
    - drupal/core-recommended 8.8.x-dev requires drupal/core 8.8.x-dev -> satisfiable by drupal/core[8.8.x-dev].
    - drupal/core-recommended 8.9.x-dev requires drupal/core 8.9.x-dev -> satisfiable by drupal/core[8.9.x-dev].
    - Can only install one of: drupal/core[9.0.0, 8.8.x-dev].
    - Can only install one of: drupal/core[9.0.0, 8.9.x-dev].
    - drupal/core-recommended 8.9.2 requires drupal/core 8.9.2 -> satisfiable by drupal/core[8.9.2] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.9.1 requires drupal/core 8.9.1 -> satisfiable by drupal/core[8.9.1] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.9.0-rc1 requires drupal/core 8.9.0-rc1 -> satisfiable by drupal/core[8.9.0-rc1] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.9.0-beta3 requires drupal/core 8.9.0-beta3 -> satisfiable by drupal/core[8.9.0-beta3] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.9.0-beta2 requires drupal/core 8.9.0-beta2 -> satisfiable by drupal/core[8.9.0-beta2] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.9.0-beta1 requires drupal/core 8.9.0-beta1 -> satisfiable by drupal/core[8.9.0-beta1] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.9.0 requires drupal/core 8.9.0 -> satisfiable by drupal/core[8.9.0] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.8 requires drupal/core 8.8.8 -> satisfiable by drupal/core[8.8.8] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.7 requires drupal/core 8.8.7 -> satisfiable by drupal/core[8.8.7] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.6 requires drupal/core 8.8.6 -> satisfiable by drupal/core[8.8.6] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.5 requires drupal/core 8.8.5 -> satisfiable by drupal/core[8.8.5] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.4 requires drupal/core 8.8.4 -> satisfiable by drupal/core[8.8.4] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.3 requires drupal/core 8.8.3 -> satisfiable by drupal/core[8.8.3] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.2 requires drupal/core 8.8.2 -> satisfiable by drupal/core[8.8.2] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.1 requires drupal/core 8.8.1 -> satisfiable by drupal/core[8.8.1] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.0-rc1 requires drupal/core 8.8.0-rc1 -> satisfiable by drupal/core[8.8.0-rc1] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.0-beta1 requires drupal/core 8.8.0-beta1 -> satisfiable by drupal/core[8.8.0-beta1] but these conflict with your requirements or minimum-stability.
    - drupal/core-recommended 8.8.0 requires drupal/core 8.8.0 -> satisfiable by drupal/core[8.8.0] but these conflict with your requirements or minimum-stability.
    - Installation request for drupal/core 9.0.0 as 8.9.3 -> satisfiable by drupal/core[9.0.0].
    - Installation request for drupal/core-recommended ^8.8 -> satisfiable by drupal/core-recommended[8.8.0, 8.8.0-beta1, 8.8.0-rc1, 8.8.1, 8.8.2, 8.8.3, 8.8.4, 8.8.5, 8.8.6, 8.8.7, 8.8.8, 8.8.x-dev, 8.9.0, 8.9.0-beta1, 8.9.0-beta2, 8.9.0-beta3, 8.9.0-rc1, 8.9.1, 8.9.2, 8.9.3, 8.9.x-dev].
    - drupal/core 9.0.0 requires doctrine/reflection ^1.1 -> satisfiable by doctrine/reflection[1.1.x-dev, 1.2.0, 1.2.1, 1.2.x-dev, 1.3.x-dev, v1.1.0].
    - doctrine/reflection 1.1.x-dev conflicts with doctrine/common[v2.7.3].
    - doctrine/reflection 1.2.0 conflicts with doctrine/common[v2.7.3].
    - doctrine/reflection 1.2.1 conflicts with doctrine/common[v2.7.3].
    - doctrine/reflection 1.2.x-dev conflicts with doctrine/common[v2.7.3].
    - doctrine/reflection 1.3.x-dev conflicts with doctrine/common[v2.7.3].
    - doctrine/reflection v1.1.0 conflicts with doctrine/common[v2.7.3].
    - drupal/core-recommended 8.9.3 requires doctrine/common v2.7.3 -> satisfiable by doctrine/common[v2.7.3].
    - Conclusion: remove doctrine/common v2.7.3

```

I don't know what to do as I assumed it is a core modules conflict issue.

How do I fix this upgrade issue?

`composer show` shows the following output.

```

asm89/stack-cors                     1.3.0           Cross-origin resource sharing library and stack middleware
composer/installers                  v1.9.0          A multi-framework Composer library installer
composer/semver                      1.5.1           Semver library that offers utilities, version constraint parsing and validation.
container-interop/container-interop  1.2.0           Promoting the interoperability of container objects (DIC, SL, etc.)
doctrine/annotations                 v1.4.0          Docblock Annotations Parser
doctrine/cache                       v1.6.2          Caching library offering an object-oriented API for many cache backends
doctrine/collections                 v1.4.0          Collections Abstraction library
doctrine/common                      v2.7.3          Common Library for Doctrine projects
doctrine/inflector                   v1.2.0          Common String Manipulations with regard to casing and singular/plural rules.
doctrine/lexer                       1.0.2           PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
drupal/admin_toolbar                 2.3.0           Provides a drop-down menu interface to the core Drupal Toolbar.
drupal/allowed_formats               1.3.0           Limit which text formats are available for each field instance.
drupal/amswap                        3.0.0           Allows the administration menu to be customised per user role.
drupal/asset_injector                2.7.0           Adds CSS or JS to the page output based on configurable rules.
drupal/auto_entitylabel              3.0.0-beta3     Allows hiding of entity label fields and automatic label creation.
drupal/basic_watermark               1.0.0-alpha3    Watermark image style effect for Drupal.
drupal/blazy                         2.1.0           Provides basic bLazy integration for lazy loading and multi-serving images.
drupal/bootstrap_barrio              5.0.1           Bootstrap 4 base theme.
drupal/bootstrap_library             1.13.0          Provides Bootstrap Integration.
drupal/captcha                       1.1.0           The CAPTCHA module provides this feature to virtually any user facing web form on a Drupa...
drupal/cdn                           3.5.0           Serves files (CSS, JS, images …) from a CDN.
drupal/colorbox                      1.6.0           A light-weight, customizable lightbox plugin for jQuery.
drupal/core                          8.9.3           Drupal is an open source content management platform powering millions of websites and ap...
drupal/core-composer-scaffold        8.9.3           A flexible Composer project scaffold builder.
drupal/core-project-message          8.9.3           Adds a message after Composer installation.
drupal/core-recommended              8.9.3           Locked core dependencies; require this project INSTEAD OF drupal/core.
drupal/ctools                        3.4.0           Provides a number of utility and helper APIs for Drupal developers and site builders.
drupal/ds                            3.8.0           Extend the display options for every entity type.
drupal/easy_breadcrumb               1.13.0          Adds configuration to the system breadcrumbs.
drupal/entity_browser                2.5.0           Entity browsing and selecting component.
drupal/entity_clone                  1.0.0-beta4     Add a clone action for all entities
drupal/entity_reference_revisions    1.8.0           Entity Reference Revisions
drupal/field_formatter_class         1.4.0           Provides custom HTML class settings for field formatters.
drupal/field_group                   3.1.0           Provides the field_group module.
drupal/field_permissions             1.0.0           The Field Permissions module allows site administrators to set field-level permissions to...
drupal/file_download_link            1.0.0           Adds field formatter to render file field as configurable download link.
drupal/file_mdm                      2.1.0           Provides a service to manage file metadata.
drupal/file_mdm_exif                 2.1.0           Provides a file metadata plugin for EXIF image information.
drupal/file_mdm_font                 2.1.0           Provides a file metadata plugin for TTF/OTF/WOFF font information.
drupal/flexslider                    2.0.0-rc2       FlexSlider 2 integration for Drupal
drupal/fontawesome                   2.17.0          The web's most popular icon set and toolkit.
drupal/fontyourface                  3.2.0           Web font management tools.
drupal/git_deploy                    2.3.0           Helps sites that are deployed directly from Git repositories.
drupal/google_analytics              3.1.0           Allows your site to be tracked by Google Analytics by adding a Javascript tracking code t...
drupal/image_effects                 3.0.0           Provides effects and operations for the Image API.
drupal/imagefield_tokens             2.21.0          Provides new widget type for Image field to allow to use tokens for filling Alt and Title...
drupal/libraries                     3.0.0-alpha1    Allows version-dependent and shared usage of external libraries in Drupal.
drupal/login_security                1.5.0           Enable security options in the login flow of the site.
drupal/mailsystem                    4.3.0           Mail System
drupal/maxlength                     1.0.0-rc1       Limit the number of characters in textfields and textareas and shows the amount of charac...
drupal/memcache                      2.1.0           High performance integration with memcache.
drupal/menu_item_role_access         2.0.0           Provide role based access to menu items.
drupal/metatag                       1.13.0          Manage meta tags for all entities.
drupal/paragraphs                    1.12.0          Enables the creation of Paragraphs entities.
drupal/paragraphs_collapsible        1.2.0           Improves the Paragraphs widget by applying CSS tweaks and collapsible feature
drupal/pathauto                      1.8.0           Provides a mechanism for modules to automatically generate aliases for the content they m...
drupal/pdf                           1.0.0           Display PDF file in Drupal without external readers and plugins.
drupal/phpmailer                     3.0.0-beta1     Integrates the PHPMailer library for SMTP e-mail delivery.
drupal/phpmailer_smtp                1.5.0           Uses the PHPMailer library to send emails via SMTP.
drupal/recaptcha                     3.0.0           Protect your website from spam and abuse while letting real people pass through with ease.
drupal/redirect                      1.6.0           Allows users to redirect from old URLs to new URLs.
drupal/remove_http_headers           1.0.0-beta3     Removes configured HTTP Response headers.
drupal/rename_admin_paths            2.0.0           The purpose of this module is to secure drupal backend by renaming the admin paths.
drupal/shs                           1.0.0-alpha4    Creates a simple hierarchical select widget for taxonomy fields.
drupal/slick                         2.2.0           Slick carousel, the last carousel you'll ever need.
drupal/slick_views                   2.3.0           Provides Slick carousel integration with Views. Slick carousel, the last carousel you'll ...
drupal/social_media                  1.8.0           Share current page to social media
drupal/stickynav                     1.1.0           Module to make navigation on the website sticky when you scroll down the page.
drupal/taxonomy_manager              1.0.0-beta2     Tool for administrating taxonomy terms.
drupal/taxonomy_menu                 3.4.0           Creates menu items based on associations to taxonomy vocabularies
drupal/token                         1.7.0           Provides a user interface for the Token API, some missing core tokens.
drupal/token_filter                  1.2.0           This is a very simple module to make global token values available as an input filter.
drupal/typed_data                    1.0.0-alpha5    Extends the core Typed Data API with new APIs and features.
drupal/upgrade_status                2.9.0           Review current status of known Drupal 9 incompatibilities on the site.
drupal/video_embed_field             2.4.0           A pluggable field type for storing videos from external video hosts such as Vimeo and You...
drupal/views_fieldsets               3.x-dev eea8080 Adds fieldsets to Views.
drupal/views_show_more               1.0.0           Provide a show more pager plugin for Views.
drupal/xmlsitemap                    1.0.0           Creates XML sitemaps for the site
easyrdf/easyrdf                      0.9.1           EasyRdf is a PHP library designed to make it easy to consume and produce RDF.
egulias/email-validator              2.1.17          A library for validating emails against several RFCs
google/recaptcha                     1.2.4           Client library for reCAPTCHA, a free service that protects websites from spam and abuse.
guzzlehttp/guzzle                    6.5.4           Guzzle is a PHP HTTP client library
guzzlehttp/promises                  v1.3.1          Guzzle promises library
guzzlehttp/psr7                      1.6.1           PSR-7 message implementation that also provides common utility methods
laminas/laminas-diactoros            1.8.7p2         PSR HTTP Message implementations
laminas/laminas-escaper              2.6.1           Securely and safely escape HTML, HTML attributes, JavaScript, CSS, and URLs
laminas/laminas-feed                 2.12.2          provides functionality for consuming RSS and Atom feeds
laminas/laminas-servicemanager       3.4.1           Factory-Driven Dependency Injection Container
laminas/laminas-stdlib               3.2.1           SPL extensions, array utilities, error handlers, and more
laminas/laminas-text                 2.7.1           Create FIGlets and text-based tables
laminas/laminas-zendframework-bridge 1.0.4           Alias legacy ZF class names to Laminas Project equivalents.
lsolesen/pel                         0.9.8           PHP Exif Library. A library for reading and writing Exif headers in JPEG and TIFF images ...
masterminds/html5                    2.3.0           An HTML5 parser and serializer.
mathieuviossat/arraytotexttable      v1.0.8          Display arrays in terminal
mglaman/phpstan-drupal               0.12.5          Drupal extension and rules for PHPStan
nette/finder                         v2.5.2           Nette Finder: find files and directories with an intuitive API.
nette/utils                          v3.1.2           Nette Utils: lightweight utilities for string & array manipulation, image handling, ...
nikic/php-parser                     v4.7.0          A PHP parser written in PHP
paragonie/random_compat              v9.99.99        PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
pear/archive_tar                     1.4.9           Tar file management class with compression support (gzip, bzip2, lzma2)
pear/console_getopt                  v1.4.3          More info available on: http://pear.php.net/package/Console_Getopt
pear/pear-core-minimal               v1.10.10        Minimal set of PEAR core files to be used as composer dependency
pear/pear_exception                  v1.0.1          The PEAR Exception base class.
phenx/php-font-lib                   0.5.2           A library to read, parse, export and make subsets of different types of font files.
phpmailer/phpmailer                  v6.1.7          PHPMailer is a full-featured email creation and transfer class for PHP
phpstan/phpstan                      0.12.36         PHPStan - PHP Static Analysis Tool
phpstan/phpstan-deprecation-rules    0.12.5          PHPStan rules for detecting usage of deprecated classes, methods, properties, constants a...
psr/container                        1.0.0           Common Container Interface (PHP FIG PSR-11)
psr/http-message                     1.0.1           Common interface for HTTP messages
psr/log                              1.1.3           Common interface for logging libraries
ralouphie/getallheaders              3.0.3           A polyfill for getallheaders.
stack/builder                        v1.0.5          Builder for stack middlewares based on HttpKernelInterface.
symfony-cmf/routing                  1.4.1           Extends the Symfony2 routing component for dynamic routes and chaining several routers
symfony/class-loader                 v3.4.41         Symfony ClassLoader Component
symfony/console                      v3.4.41         Symfony Console Component
symfony/debug                        v3.4.41         Symfony Debug Component
symfony/dependency-injection         v3.4.41         Symfony DependencyInjection Component
symfony/event-dispatcher             v3.4.41         Symfony EventDispatcher Component
symfony/http-foundation              v3.4.41         Symfony HttpFoundation Component
symfony/http-kernel                  v3.4.41         Symfony HttpKernel Component
symfony/polyfill-ctype               v1.17.0         Symfony polyfill for ctype functions
symfony/polyfill-iconv               v1.17.0         Symfony polyfill for the Iconv extension
symfony/polyfill-intl-idn            v1.17.0         Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions
symfony/polyfill-mbstring            v1.17.0         Symfony polyfill for the Mbstring extension
symfony/polyfill-php56               v1.17.0         Symfony polyfill backporting some PHP 5.6+ features to lower PHP versions
symfony/polyfill-php70               v1.17.0         Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions
symfony/polyfill-php72               v1.17.0         Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions
symfony/polyfill-util                v1.17.0         Symfony utilities for portability of PHP codes
symfony/process                      v3.4.41         Symfony Process Component
symfony/psr-http-message-bridge      v1.1.2          PSR HTTP message bridge
symfony/routing                      v3.4.41         Symfony Routing Component
symfony/serializer                   v3.4.41         Symfony Serializer Component
symfony/translation                  v3.4.41         Symfony Translation Component
symfony/validator                    v3.4.41         Symfony Validator Component
symfony/yaml                         v3.4.41         Symfony Yaml Component
twbs/bootstrap                       v4.5.2          The most popular front-end framework for developing responsive, mobile first projects on ...
twig/twig                            v1.42.5         Twig, the flexible, fast, and secure template language for PHP
typo3/phar-stream-wrapper            v3.1.4          Interceptors for PHP's native phar:// stream handling
webflo/drupal-finder                 1.2.0           Helper class to locate a Drupal installation from a given path.

```

# Answer
Unfortunately, `composer require` doesn't seem to resolve version conflicts in the way `composer update` does. Your problem here is that Drupal 9 (`drupal/core-recommended:9.0.0`) requires `doctrine/reflection:1.2.1`, but `doctrine/reflection`, but that packages indicates that it conflicts with `doctrine/common < 2.9`.

However, `doctrine/common:2.7.3` was required by Drupal 8, and this situation makes that you now must update `doctrine/common` and `doctrine/persistence` *at the same time*. `composer require` doesn't seem to handle this well.

Probably the best way to fix this would be to edit your `composer.json` file manually and replace the version of `drupal/core-recommended` by `^9.0.0` and then run `bin/composer update`.
> 0 votes

---
Tags: upgrading, 9
---


# Question
Title: Why does composer remove a folder it doesn't manage
I have the gesso theme installed in themes/contrib, and since I have not subthemed, all my components and templates live in within its folders. For that reason, I do not manage it with composer.

I needed to install a contrib module, and when I ran composer require, the first thing it did was remove gesso.

Why would this happen, and is there a way to tell it "hands off" ?

# Answer
> 1 votes
It isn't Composer, per se, that's removing your hacked gesso theme. Drupal uses the `composer/installers` Composer plugin to move different Drupal components (e.g. modules, themes, profiles) to the dir where Drupal needs them.

Once Composer has retrieved the `drupal/gesso` package, `composer/installers` will place it the contrib theme path in `extra.installer-paths`, thus overwriting your pre-existing hacked theme.

If you don't want Composer & the installers plugin replacing your hacked gesso theme, you could do a couple of things:

* Remove `drupal/gesso` from Composer management so it never tries to update or manage the theme again and add the hacked theme back to its previous location.
* Use the `cweagans/composer-patches` Composer plugin to patch the `drupal/gesso` theme with your component/template hacks so they're added with every update.

---
Tags: composer
---