# Question
Title: Stuck in my config import because of guzzlehttp/guzzle error
I am trying to import the config from another of my Drupal 9.1.4 projects with Composer / Drush (drush config-import from a folder source, all two websites on my local repository on Xampp), but a guzzlehttp/guzzle error is thrown in the middle of the process, whatever I try...

```
Error: Call to undefined method GuzzleHttp\Utils::chooseHandler() in GuzzleHttp\choose_handler() (line 61 of C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\guzzlehttp\guzzle\src\functions.php).

```

I have tried to reinstall everything from the beginning (including composer, drush, modules' dependencies...), to test with a fresh drupal/core install, to investigate guzzlehttp/guzzle dependencies, but at the end this error keeps showing up... Raaaaaahhhh !! I wonder if it could be related with multiple version requirements of guzzlehttp/guzzle caused by a faulty installation with consolidation/cgr in different places of my repository (i.e "6.5.5" in my project but "7.2" globally)?

When I try to update guzzlehttp/guzzle to 7.2 version in my project, the error message seems to confirm this, but I can't figure out what to do:

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - drupal/core-recommended is locked to version 9.1.4 and an update of this package was not requested.
    - drupal/core-recommended 9.1.4 requires guzzlehttp/guzzle 6.5.5 -> found guzzlehttp/guzzle[6.5.5] but it conflicts with your root composer.json require (^7.2).
  Problem 2
    - drupal/core 9.1.4 requires guzzlehttp/guzzle ^6.5.2 -> found guzzlehttp/guzzle[6.5.2, ..., 6.5.x-dev] but it conflicts with your root composer.json require (^7.2).
    - drupal/views_url_path_arguments 1.1.0 requires drupal/core ^8 || ^9 -> satisfiable by drupal/core[9.1.4].
    - drupal/views_url_path_arguments is locked to version 1.1.0 and an update of this package was not requested.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

```

I'm a beginner with Composer / Drush-managed installs: some tips would be most welcome. Thank you by advance for your help!

If needed, here are my installed packages:

```
asm89/stack-cors                        1.3.0
clue/stream-filter                      v1.5.0
commerceguys/addressing                 v1.1.1
composer/installers                     v1.10.0
composer/semver                         3.2.2
davedevelopment/stiphle                 0.9.2
doctrine/annotations                    1.11.1
doctrine/cache                          1.10.2
doctrine/collections                    1.6.7
doctrine/common                         2.13.3
doctrine/event-manager                  1.1.1
doctrine/inflector                      1.4.3
doctrine/lexer                          1.2.1
doctrine/persistence                    1.3.8
doctrine/reflection                     1.2.2
drupal/address                          1.9.0
drupal/admin_toolbar                    3.0.0
drupal/advanced_text_formatter          2.0.0
drupal/allowed_formats                  1.3.0
drupal/asset_injector                   2.7.0
drupal/auto_entitylabel                 3.0.0-beta4
drupal/backup_migrate                   5.0.0-rc2
drupal/better_exposed_filters           5.0.0-beta1
drupal/boolean_single_state_formatter   1.1.0
drupal/bootstrap_business               1.0.0-beta4
drupal/calendar                         1.0.0-alpha3
drupal/calendar_datetime                1.0.0-alpha3
drupal/charts                           5.0.0-alpha2
drupal/color_field                      2.4.0
drupal/colorbox                         1.6.0
drupal/colorbutton                      1.2.0
drupal/composer_deploy                  1.6.0
drupal/conditional_fields               1.0.0-alpha10
drupal/config_update                    1.7.0
drupal/context                          4.0.0-beta5
drupal/core                             9.1.4
drupal/core-composer-scaffold           9.1.4
drupal/core-project-message             9.1.4
drupal/core-recommended                 9.1.4
drupal/core-vendor-hardening            9.1.4
drupal/crop                             2.1.0
drupal/css_editor                       1.3.0-rc1
drupal/csv_serialization                2.0.0
drupal/ctools                           3.4.0
drupal/custom_formatters                3.0.0-beta1
drupal/date_recur                       3.0.0
drupal/date_recur_modular               3.0.0
drupal/devel                            4.1.1
drupal/ds                               3.9.0
drupal/duration_field                   2.0.0
drupal/edux                             8.0.5
drupal/entity_browser                   2.5.0
drupal/entity_clone                     1.0.0-beta4
drupal/entity_reference_exposed_filters 1.0.0-alpha3
drupal/entity_reference_revisions       1.8.0
drupal/entity_update                    2.0.0-rc2
drupal/entity_usage                     2.0.0-beta3
drupal/eva                              2.1.0
drupal/feeds                            3.0.0-alpha10
drupal/feeds_ex                         1.0.0-alpha4
drupal/feeds_tamper                     2.0.0-beta2
drupal/field_delimiter                  1.1.0
drupal/field_group                      dev-3.x 9f59f95
drupal/field_group_table                dev-1.x 53814f5
drupal/file_mdm                         2.1.0
drupal/file_mdm_exif                    2.1.0
drupal/file_mdm_font                    2.1.0
drupal/filefield_sources                1.0.0-alpha4
drupal/focal_point                      1.5.0
drupal/focal_point_focus                1.10.0
drupal/geocoder                         3.14.0
drupal/geofield                         1.20.0
drupal/image_effects                    dev-3.x 82c47d5
drupal/inline_entity_form               1.0.0-rc8
drupal/jquery_ui                        1.4.0
drupal/jquery_ui_accordion              1.1.0
drupal/jquery_ui_datepicker             1.0.0
drupal/jquery_ui_draggable              1.2.0
drupal/jquery_ui_droppable              1.2.0
drupal/jquery_ui_slider                 1.1.0
drupal/jquery_ui_touch_punch            1.0.0
drupal/leaflet                          2.1.11
drupal/leaflet_geojson                  1.5.0
drupal/leaflet_more_maps                2.1.0
drupal/ludwig                           1.7.0
drupal/material_base                    1.8.0
drupal/media_entity_pinterest           2.5.0
drupal/migrate_plus                     5.1.0
drupal/migrate_source_csv               3.4.0
drupal/migrate_tools                    5.0.0
drupal/multiple_selects                 1.0.0
drupal/name                             1.0.0-rc3
drupal/node_export                      1.0.0-alpha1
drupal/office_hours                     1.3.0
drupal/optimizedb                       1.0.0-rc3
drupal/page_manager                     4.0.0-beta6
drupal/panelbutton                      1.3.0
drupal/panels                           4.6.0
drupal/paragraphs                       1.12.0
drupal/paragraphs_edit                  2.0.0-alpha8
drupal/paragraphs_ee                    1.7.0
drupal/paragraphs_features              1.11.0
drupal/pathauto                         1.8.0
drupal/pcr                              1.3.0
drupal/prepopulate                      2.3.0
drupal/range                            1.3.0
drupal/reference_table_formatter        1.1.0
drupal/require_on_publish               1.4.0
drupal/responsive_views_grid            dev-1.x b27f63a
drupal/rules                            dev-3.x 7d1833f
drupal/rules_token                      dev-1.x ad08411
drupal/search_api                       1.19.0
drupal/selective_better_exposed_filters 2.0.0-beta6
drupal/shs                              1.0.0-alpha5
drupal/smtp                             1.0.0
drupal/superfish                        1.4.0
drupal/svg_image                        1.14.0
drupal/table_field_group                dev-1.x be676c6
drupal/tamper                           1.0.0-alpha2
drupal/taxonomy_manager                 2.0.4
drupal/telephone_formatter              dev-1.x 0916a01
drupal/telephone_validation             2.3.0
drupal/term_reference_tree              1.0.0
drupal/thex                             8.0.6
drupal/token                            1.9.0
drupal/token_filter                     1.2.0
drupal/tvi                              1.0.0-rc2
drupal/typed_data                       1.0.0-alpha5
drupal/vefl                             3.0.0
drupal/viewfield                        3.0.0-beta6
drupal/views_accordion                  2.0.0
drupal/views_block_filter_block         1.0.0
drupal/views_bulk_edit                  2.5.0
drupal/views_bulk_operations            dev-3.x 84442e9
drupal/views_conditional                1.2.0
drupal/views_contextual_filters_or      1.2.0
drupal/views_data_export                1.0.0
drupal/views_entity_form_field          1.0.0-beta9
drupal/views_exposed_filter_blocks      1.1.0
drupal/views_field_formatter            1.13.0
drupal/views_field_view                 dev-1.x 91f01e9
drupal/views_fieldsets                  dev-3.x eea8080
drupal/views_flipped_table              1.4.0
drupal/views_geojson                    1.0.0
drupal/views_templates                  1.1.0
drupal/views_url_path_arguments         1.1.0
egulias/email-validator                 2.1.22
enshrined/svg-sanitize                  0.14.0
giggsey/libphonenumber-for-php          8.12.18
giggsey/locale                          1.9
guzzlehttp/guzzle                       6.5.5
guzzlehttp/promises                     1.4.0
guzzlehttp/psr7                         1.7.0
jetbrains/phpstorm-stubs                v2019.3
laminas/laminas-diactoros               2.5.0
laminas/laminas-escaper                 2.7.0
laminas/laminas-feed                    2.13.0
laminas/laminas-stdlib                  3.3.0
laminas/laminas-zendframework-bridge    1.1.1
league/csv                              9.6.2
lsolesen/pel                            0.9.10
masterminds/html5                       2.7.4
mehrpadin/superfish                     2.1
mtdowling/jmespath.php                  2.6.0
nikic/php-parser                        v4.10.4
pear/archive_tar                        1.4.12
pear/console_getopt                     v1.4.3
pear/pear-core-minimal                  v1.10.10
pear/pear_exception                     v1.0.1
phayes/geophp                           1.2
phenx/php-font-lib                      0.5.2
php-http/guzzle6-adapter                v2.0.1
php-http/httplug                        2.2.0
php-http/message                        1.11.0
php-http/message-factory                v1.0.2
php-http/promise                        1.1.0
phpdocumentor/reflection-common         2.2.0
phpdocumentor/reflection-docblock       5.2.2
phpdocumentor/type-resolver             1.4.0
phpmailer/phpmailer                     v6.2.0
psr/container                           1.0.0
psr/http-client                         1.0.1
psr/http-factory                        1.0.1
psr/http-message                        1.0.1
psr/log                                 1.1.3
querypath/querypath                     3.0.5
ralouphie/getallheaders                 3.0.3
rlanvin/php-rrule                       v1.6.3
roave/better-reflection                 4.3.0
roave/signature                         1.2.0
skaught/jquery-focuspoint               v1.1.3.1
softcreatr/jsonpath                     0.7.2
stack/builder                           v1.0.6
symfony-cmf/routing                     2.3.3
symfony/console                         v4.4.16
symfony/debug                           v4.4.16
symfony/dependency-injection            v4.4.16
symfony/error-handler                   v4.4.16
symfony/event-dispatcher                v4.4.16
symfony/event-dispatcher-contracts      v1.1.9
symfony/http-client-contracts           v2.3.1
symfony/http-foundation                 v4.4.16
symfony/http-kernel                     v4.4.16
symfony/mime                            v5.1.8
symfony/polyfill-ctype                  v1.20.0
symfony/polyfill-iconv                  v1.20.0
symfony/polyfill-intl-idn               v1.20.0
symfony/polyfill-intl-normalizer        v1.20.0
symfony/polyfill-mbstring               v1.20.0
symfony/polyfill-php72                  v1.22.1
symfony/polyfill-php73                  v1.22.1
symfony/polyfill-php80                  v1.20.0
symfony/process                         v4.4.16
symfony/psr-http-message-bridge         v2.0.2
symfony/routing                         v4.4.16
symfony/serializer                      v4.4.16
symfony/service-contracts               v2.2.0
symfony/translation                     v4.4.16
symfony/translation-contracts           v2.3.0
symfony/validator                       v4.4.16
symfony/var-dumper                      v5.1.8
symfony/yaml                            v4.4.16
twig/twig                               v2.14.1
typo3/phar-stream-wrapper               v3.1.6
webflo/drupal-finder                    1.2.2
webmozart/assert                        1.9.1
willdurand/geocoder                     4.4.0

```

EDIT 2021-02-17 at 1:39 PM (complete error message + 1 line before):

```
[notice] Synchronized configuration: create field.field.media.pinterest_post.feeds_item.
 [error]  Error: Call to undefined method GuzzleHttp\Utils::chooseHandler() in GuzzleHttp\choose_handler() (line 61 of C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\guzzlehttp\guzzle\src\functions.php) #0 C:\xampp\htdocs\D9e\vendor\guzzlehttp\guzzle\src\HandlerStack.php(42): GuzzleHttp\choose_handler()
#1 [internal function]: GuzzleHttp\HandlerStack::create()
#2 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\DependencyInjection\Container.php(253): call_user_func_array(Array, Array)
#3 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\DependencyInjection\Container.php(447): Drupal\Component\DependencyInjection\Container->createService(Array, 'private__2i5Fjk...')
#4 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\DependencyInjection\Container.php(235): Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)
#5 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\DependencyInjection\Container.php(171): Drupal\Component\DependencyInjection\Container->createService(Array, 'http_client_fac...')
#6 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\DependencyInjection\Container.php(432): Drupal\Component\DependencyInjection\Container->get('http_client_fac...', 1)
#7 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\DependencyInjection\Container.php(247): Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)
#8 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\DependencyInjection\Container.php(171): Drupal\Component\DependencyInjection\Container->createService(Array, 'http_client')
#9 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Feeds\Fetcher\HttpFetcher.php(89): Drupal\Component\DependencyInjection\Container->get('http_client')
#10 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Plugin\Factory\ContainerFactory.php(21): Drupal\feeds\Feeds\Fetcher\HttpFetcher::create(Object(Drupal\Core\DependencyInjection\Container), Array, 'http', Array)
#11 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Plugin\Type\FeedsAnnotationFactory.php(21): Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('http', Array)
#12 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\Plugin\PluginManagerBase.php(83): Drupal\feeds\Plugin\Type\FeedsAnnotationFactory->createInstance('http', Array)
#13 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Plugin\DefaultSingleLazyPluginCollection.php(62): Drupal\Component\Plugin\PluginManagerBase->createInstance('http', Array)
#14 C:\xampp\htdocs\D9e\core\lib\Drupal\Component\Plugin\LazyPluginCollection.php(80): Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->initializePlugin('http')
#15 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Plugin\DefaultSingleLazyPluginCollection.php(83): Drupal\Component\Plugin\LazyPluginCollection->get('http')
#16 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Feeds\FeedsSingleLazyPluginCollection.php(47): Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->setConfiguration(Array)
#17 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Plugin\DefaultSingleLazyPluginCollection.php(99): Drupal\feeds\Feeds\FeedsSingleLazyPluginCollection->setConfiguration(Array)
#18 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Plugin\DefaultSingleLazyPluginCollection.php(55): Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->addInstanceId('http', Array)
#19 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Feeds\FeedsSingleLazyPluginCollection.php(38): Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->__construct(Object(Drupal\feeds\Plugin\Type\FeedsPluginManager), 'http', Array)
#20 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Entity\FeedType.php(534): Drupal\feeds\Feeds\FeedsSingleLazyPluginCollection->__construct(Object(Drupal\feeds\Plugin\Type\FeedsPluginManager), 'http', Array, Object(Drupal\feeds\Entity\FeedType))
#21 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Entity\FeedType.php(449): Drupal\feeds\Entity\FeedType->getPluginCollections()
#22 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Entity\FeedType.php(412): Drupal\feeds\Entity\FeedType->getPlugin('fetcher')
#23 C:\xampp\htdocs\D9e\modules\contrib\feeds\src\Entity\FeedType.php(562): Drupal\feeds\Entity\FeedType->getPlugins()
#24 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Entity\EntityStorageBase.php(494): Drupal\feeds\Entity\FeedType->preSave(Object(Drupal\Core\Config\Entity\ConfigEntityStorage))
#25 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Entity\EntityStorageBase.php(449): Drupal\Core\Entity\EntityStorageBase->doPreSave(Object(Drupal\feeds\Entity\FeedType))
#26 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Config\Entity\ConfigEntityStorage.php(263): Drupal\Core\Entity\EntityStorageBase->save(Object(Drupal\feeds\Entity\FeedType))
#27 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Entity\EntityBase.php(339): Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object(Drupal\feeds\Entity\FeedType))
#28 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Config\Entity\ConfigEntityBase.php(591): Drupal\Core\Entity\EntityBase->save()
#29 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Config\Entity\ConfigEntityStorage.php(364): Drupal\Core\Config\Entity\ConfigEntityBase->save()
#30 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Config\ConfigImporter.php(990): Drupal\Core\Config\Entity\ConfigEntityStorage->importCreate('feeds.feed_type...', Object(Drupal\Core\Config\Config), Object(Drupal\Core\Config\Config))
#31 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Config\ConfigImporter.php(776): Drupal\Core\Config\ConfigImporter->importInvokeOwner('', 'create', 'feeds.feed_type...')
#32 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Config\ConfigImporter.php(603): Drupal\Core\Config\ConfigImporter->processConfiguration('', 'create', 'feeds.feed_type...')
#33 C:\xampp\htdocs\D9e\core\lib\Drupal\Core\Config\ConfigImporter.php(507): Drupal\Core\Config\ConfigImporter->processConfigurations(Array)
#34 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\src\Drupal\Commands\config\ConfigImportCommands.php(335): Drupal\Core\Config\ConfigImporter->doSyncStep('processConfigur...', Array)
#35 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\includes\drush.inc(206): Drush\Drupal\Commands\config\ConfigImportCommands->doImport(Object(Drupal\Core\Config\StorageComparer))
#36 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\includes\drush.inc(197): drush_call_user_func_array(Array, Array)
#37 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\src\Drupal\Commands\config\ConfigImportCommands.php(306): drush_op(Array, Object(Drupal\Core\Config\StorageComparer))
#38 [internal function]: Drush\Drupal\Commands\config\ConfigImportCommands->import(NULL, Array)
#39 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\consolidation\annotated-command\src\CommandProcessor.php(257): call_user_func_array(Array, Array)
#40 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\consolidation\annotated-command\src\CommandProcessor.php(212): Consolidation\AnnotatedCommand\CommandProcessor->runCommandCallback(Array, Object(Consolidation\AnnotatedCommand\CommandData))
#41 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\consolidation\annotated-command\src\CommandProcessor.php(176): Consolidation\AnnotatedCommand\CommandProcessor->validateRunAndAlter(Array, Array, Object(Consolidation\AnnotatedCommand\CommandData))
#42 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\consolidation\annotated-command\src\AnnotatedCommand.php(311): Consolidation\AnnotatedCommand\CommandProcessor->process(Object(Symfony\Component\Console\Output\ConsoleOutput), Array, Array, Object(Consolidation\AnnotatedCommand\CommandData))
#43 C:\xampp\htdocs\D9e\vendor\symfony\console\Command\Command.php(255): Consolidation\AnnotatedCommand\AnnotatedCommand->execute(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#44 C:\xampp\htdocs\D9e\vendor\symfony\console\Application.php(1027): Symfony\Component\Console\Command\Command->run(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#45 C:\xampp\htdocs\D9e\vendor\symfony\console\Application.php(273): Symfony\Component\Console\Application->doRunCommand(Object(Consolidation\AnnotatedCommand\AnnotatedCommand), Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#46 C:\xampp\htdocs\D9e\vendor\symfony\console\Application.php(149): Symfony\Component\Console\Application->doRun(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#47 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\src\Runtime\Runtime.php(118): Symfony\Component\Console\Application->run(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#48 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\src\Runtime\Runtime.php(48): Drush\Runtime\Runtime->doRun(Array, Object(Symfony\Component\Console\Output\ConsoleOutput))
#49 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\drush.php(72): Drush\Runtime\Runtime->run(Array)
#50 C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\drush\drush\drush(4): require('C:\\Users\\Clemen...')
#51 {main}.
Error: Call to undefined method GuzzleHttp\Utils::chooseHandler() in C:\Users\Clement\AppData\Roaming\Composer\global\drush\drush\vendor\guzzlehttp\guzzle\src\functions.php on line 61 #0 C:\xampp\htdocs\D9e\vendor\guzzlehttp\guzzle\src\HandlerStack.php(42): GuzzleHttp\choose_handler()

```

# Answer
I have succeeded in re-importing my config and content through the UI instead of drush, on the advice of @patrick-kenny. (That's what I tried at first but a memory limit issue incited me to try the drush config-import way)

Here is what I did:

* created a new root folder, copied composer.json file from site #1
* command 'composer update'
* installed the site through the UI
* removed manually default shortcut links in the UI
* copied uuid from system.site.yml to my new site with command 'drush cset'
* copied subfolders "libraries" and "default/files" from site #1
* runned config import from file in the UI
* imported database from #1

...and now everything seems at its right place!

This said, I will not be completely at ease until I understand precisely what's wrong with my drush setup...

Thank you for your kind help, Patrick!
> 0 votes

# Answer
I had the same error using a simple vanilla 9 version of Drupal, when using my computer's drush to run the site-install command.

I overcame this problem by requiring drush in the project and using it.

```
$ drush si
...
Error: Call to undefined method GuzzleHttp\Utils::chooseHandler()
$ composer require drush/drush
$ ./vendor/bin/drush si
 ...
Success!

```
> 0 votes

# Answer
I was having same issue (same error message) on my LANDO local instance.

Here is my file structure i.e

```
My-Project/lando.yml
My-Project/composer.json
My-Project/docroot

```

'docroot' folder has drupal core files/folders.

I was using composer to install drush (composer require drush/drush) at this path 'My-Project/composer.json' which executes other drush commands fine except 'drush cim' was generating errors.

When I used 'My-Project/docroot/composer.json' path instead, 'drush cim' works absolutely fine without any error.

In short, we should use composer.json file which comes with drupal core to install drush and this should fix this issue.
> 0 votes

---
Tags: drush, importing-exporting, composer
---


# Question
Title: Dynamically load the menu items created from the links.task.yml file
I need to programmatically load the links that are generated from my\_module.links.task.yml on another page.

My exact use case is that I have a set of links that are shown when viewing my node page. The links will be shown and hidden based on the current user's access and the access control is handled through the options in the my\_module.routing.yml file.

I need to create a separate page that displays node data in a table and I need to show these links in a drop-down option (similar to how the edit button functions when viewing content as an admin).

Is there a way to dynamically get the links so I can then display them in that drop-down?

# Answer
> 1 votes
You can load **all** module defined menu links (i.e. links defined in **.menu.links.yml* with the MenuLinkManager service's `getDefinitions()` method and then parse the list for only links defined by your module.

```
$all_module_link_definitions = \Drupal::service('plugin.manager.menu.link')
  ->getDefinitions();

// Next parse the list for only links defined by my_module.
$my_module_link_definitions = [];
foreach ($all_module_link_definitions as $plugin_id => $plugin_definition) {
  if ($plugin_definition['provider'] === 'MY_MODULE') {
    $my_module_link_definitions[$plugin_id] => $plugin_definition;
  }
}

```

Similarly, you can load **all** module defined local tasks with the LocalTaskManager service's `getDefintions()` method and then parse the list for only tasks defined by your module.

```
$all_module_task_definitions = \Drupal::service('plugin.manager.menu.local_task')
  ->getDefinitions();

// Next parse the list for only tasks defined by my_module.
$my_module_task_definitions = [];
foreach ($all_module_task_definitions as $plugin_id => $plugin_definition) {
  if ($plugin_definition['provider'] === 'MY_MODULE') {
    $my_module_task_definitions[$plugin_id] => $plugin_definition;
  }
}

```

---
Tags: 8, navigation
---


# Question
Title: How can I build a specific data structure?
I have a *Course* content type which has several "modules." (A module is just a name.) There are also several "units," which may or not belong to a module. A unit has several fields, for example *Location*, *Description*.

I have created a *Course unit* paragraph type, and a *Units* field in the "course" content type, which references this paragraph type. That way I can create units that belong to the course.

However, I'm not sure how to deal with modules. I could create a *Course module* paragraph type, but I don't think it would enable me to attach a unit to a module, since there's no way to select an existing paragraph.

Basically I need to create several modules inside a node, then several units, and optionally attach these units to one of the modules I've created.

# Answer
Given what you have done so far I would recommend:

* Create a "Modules" taxonomy.
* Make this a hierarchical taxonomy that includes course names (as if courses were top level modules) and then add the modules under those.
* Add a taxonomy reference field to your Unit paragraph
* This will be flexible in a couple of ways:
    + It will let modules receive descriptive fields as needed later.
    + It will allow site search and filter by module in a hierarchy that includes courses.
    + It will allow for modules within modules if that becomes a later requirement.

Optional improvements

* Make the module selector field on the Unit paragraph form use a view that filters by the current course name as parent (with depth)
> 1 votes

---
Tags: paragraphs
---


# Question
Title: How can I customize the "H5P - Create and Share Rich Content and Applications" module?
I need to modify the behavior of the H5P - Create and Share Rich Content and Applications module in Drupal 8, but (as far as I can see) there is a description of the hooks used from the Drupal 7 version of the module. There isn't a similar file for the Drupal 8 version.

What hooks should I use for the Drupal 8 version of the module? If the module doesn't use hooks, how can I customize the module?

# Answer
> 4 votes
All the hooks listed in the h5p.api.php file for the Drupal 7 version are still supported from the Drupal 8 version. The Drupal 8 branch doesn't have a *h5p.api.php* file to document the used hooks, but the code invokes the same hooks. See the following list, which reports where each hook is invoked.

* `hook_h5p_semantics_alter()`: src/H5PDrupal/H5PDrupal.php

```
$version = $majorVersion . '.'. $minorVersion;
\Drupal::moduleHandler()->alter('h5p_semantics', $semantics, $name, $version);

```
* `hook_h5p_filtered_params_alter()`: src/H5PDrupal/H5PDrupal.php

```
$moduleHandler = \Drupal::moduleHandler();
$filteredAsJson = json_decode($filteredParameters);
$moduleHandler->alter('h5p_filtered_params', $filteredAsJson);

```
* `hook_h5p_styles_alter()` and `hook_h5p_scripts_alter()`: src/Controller/H5PEmbed.php

```
$mode = 'external';
\Drupal::moduleHandler()->alter('h5p_scripts', $files['scripts'], $library_list, $mode);
\Drupal::moduleHandler()->alter('h5p_styles', $files['styles'], $library_list, $mode);

```
* `hook_h5p_library_installed()`: src/H5PDrupal/H5PDrupal.php

```
\Drupal::moduleHandler()->invokeAll('h5p_library_installed', array($libraryData, $new));

```

---
Tags: 8
---


# Question
Title: How can I delete a file served by a custom controller after it has been downloaded?
Starting from How do I create a file download URL? I've build a custom controller that allows users to download a PDF file.

### my\_module.routing.yml

```
my_module.pdf_link:
  path: '/my-module/pdf/download'
  defaults:
    _title: 'PDF download'
    _controller: '\Drupal\my_module\Controller\MyModuleController::downloadPDF'
  requirements:
    _role: 'authenticated'

```

### MyModuleController

```
public function downloadPDF() {
  $pdf_stream = $this->restCallThatReturnAPdfStream();

  $headers = [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'attachment;filename="download.pdf"'
  ];

  $temporary_pdf_file = $this->fileSystem->saveData($pdf_stream, 'temporary://mytempfile.pdf', FileSystemInterface::EXISTS_REPLACE);

  return new BinaryFileResponse($temporary_pdf_file, 200, $headers, TRUE);
}

```

This file must be private per user, so other users shouldn't be able to download it.

I think I could delete the file after the controller returns the response, instead of implementing some complex access control check for the file, but I've no clue how I can easily do.

For example, I could set a Cron queue to delete those files every N minutes, but it seems an overkill.

I cannot also change when temporary files are deleted because those files are used elsewhere in the site and I wouldn't risk to break some other existing logic.

# Answer
> 2 votes
You're looking for `BinaryFileResponse::deleteFileAfterSend`:

```
$response = new BinaryFileResponse($temporary_pdf_file, 200, $headers, TRUE);
return $response->deleteFileAfterSend(TRUE);

```

---
Tags: files, 9, page-controller
---


title: Taxonomy term relationships

text:
# Question
Title: Taxonomy term relationships
I have 3 taxonomy terms that I would like to expose as filters but I would like to use JavaScript to disable filters as you make selections in the other related exposed filters. For example:

| Styles | Makes | Models |
| --- | --- | --- |
| Cars | BMW | 750i |
| Trucks | Ford | F-150 |

If you select "Cars" then the "Makes - Ford" and "Models - F-150" would be disabled. I currently have each item assigned a proper CSS class for hooks but I am needing to find a way to add a CSS class to each "Makes" item and "Models" item that would be available if the user selected "Styles - Cars".

I need to do this on form field change and without refreshing the page. Is this possible?

Much thanks in advanced.

# Answer
> 0 votes
@beltouche, thanks for the module ideas. I ended up going another route because I needed the filters to update as each one changed. Basically, just like a facet but without reloading the page. I'm sure there are a few ways to go about this and probably in a more efficient way but for the amount of items and the functionality I needed this seems to be working pretty good.

For anyone else that is looking to try and accomplish the same, here are the steps I took to accomplish what I needed.

1. I have a content type called "inventory" that hold about 700 entries
2. There are 3 fields in "inventory" that I would like to use to filter by
3. I created a view showing content of type "inventory"
4. Name the view "Custom Quick Search"
5. Check to "create a block"
6. Set the view to "show Fields"
7. Add the 3 fields, style, make, model
8. Set items per page to "all"
9. Create custom view templates:
10. views-view-unformatted--custom-quick-search
11. views-view-fields--custom-quick-search
12. views-view-field--field-style
13. views-view-field--field-make
14. views-view-field--field-model

The code for each are as follows: **views-view-unformatted--custom-quick-search**

```
{% for row in rows %}
  {% if row|render|trim is not empty %}
    {{ row.content }}
  {% endif %}
{% endfor %}

```

**views-view-fields--custom-quick-search**

```
{% set category_name = fields.field_category.content|striptags %}
{% set category_id = fields.field_category.content|preg_replace('(<a href="/taxonomy/term/)','$1') %}
{% set category_id = category_id|preg_replace('(" hreflang="en">.*)','$1') %}

{% set make_name = fields.field_make.content|striptags %}
{% set make_id = fields.field_make.content|preg_replace('(<a href="/taxonomy/term/)','$1') %}
{% set make_id = make_id|preg_replace('(" hreflang="en">.*)','$1') %}

{% set model_name = fields.field_model.content|striptags %}
{% set model_id = fields.field_model.content|preg_replace('(<a href="/taxonomy/term/)','$1') %}
{% set model_id = model_id|preg_replace('(" hreflang="en">.*)','$1') %}

<div class="item" style="display: none;" data-category="{{ category_name|clean_class }}" data-make="{{ make_name|clean_class }}" data-model="{{ model_name|clean_class }}">

  <div class="-styles" data-category="{{ category_name|clean_class }}">
    <label for="{{ category_name|clean_class }}" data-category="{{ category_name|clean_class }}" data-make="{{ make_name|clean_class }}" data-model="{{ model_name|clean_class }}">
      <input type="checkbox" name="{{ category_name|trim }}" value="{{ category_id|trim }}" class="{{ category_name|trim|clean_class }}" id="{{ category_name|trim|clean_class }}" />
    {{ category_name|trim }}</label>
  </div>

  <div class="-makes" data-category="{{ category_name|clean_class }}" data-make="{{ make_name|clean_class }}">
    <label for="{{ make_name|clean_class }}" data-category="{{ category_name|clean_class }}" data-make="{{ make_name|clean_class }}" data-model="{{ model_name|clean_class }}">
      <input type="checkbox" name="{{ make_name|trim }}" value="{{ make_id|trim }}" class="{{ make_name|trim|clean_class }}" id="{{ make_name|trim|clean_class }}" />
    {{ make_name|trim }}</label>
  </div>

  <div class="-models" data-category="{{ category_name|clean_class }}" data-make="{{ make_name|clean_class }}" data-model="{{ model_name|clean_class }}">
    <label for="{{ model_name|clean_class }}" data-category="{{ category_name|clean_class }}" data-make="{{ make_name|clean_class }}" data-model="{{ model_name|clean_class }}">
      <input type="checkbox" name="{{ model_name|trim }}" value="{{ model_id|trim }}" class="{{ model_name|trim|clean_class }}" id="{{ model_name|trim|clean_class }}" />
    {{ model_name|trim }}</label>
  </div>

</div>

```

**views-view-field--field-style views-view-field--field-make views-view-field--field-model**

```
{{ output }}

```

---

**Place the block on a page wrapped in the following:**

```
<div class="quickSearch hidden">
    <div class="quickSearch__content">
        <div class="quickSearch__filters">
            <div class="filters-widget -styles">
                <div class="filters-widget__items">
                    <div class="filters-widget__item">
                    <div class="filters-widget__header">
                        <h4>Styles</h4>
                        <i class="fas fa-expand-alt"></i>
                        <i class="far fa-compress-alt"></i>
                    </div>
                    <div class="filters-widget__copy">
                    </div>
                    </div>
                </div>
            </div>

            <div class="filters-widget -makes">
                <div class="filters-widget__items">
                    <div class="filters-widget__item">
                    <div class="filters-widget__header">
                        <h4>Makes</h4>
                        <i class="fas fa-expand-alt"></i>
                        <i class="far fa-compress-alt"></i>
                    </div>
                    <div class="filters-widget__copy">
                    </div>
                    </div>
                </div>
            </div>

            <div class="filters-widget -models">
                <div class="filters-widget__items">
                    <div class="filters-widget__item">
                    <div class="filters-widget__header">
                        <h4>Models</h4>
                        <i class="fas fa-expand-alt"></i>
                        <i class="far fa-compress-alt"></i>
                    </div>
                    <div class="filters-widget__copy">
                    </div>
                    </div>
                </div>
            </div>

            <div class="unsorted__styles" style="display: none;"></div>
            <div class="unsorted__makes" style="display: none;"></div>
            <div class="unsorted__models" style="display: none;"></div>

            <div data-drupal-selector="edit-actions" class="form-actions js-form-wrapper form-wrapper" id="edit-actions">
            <input data-drupal-selector="edit-submit-custom-search-inventory" type="submit" id="edit-submit-custom-search-inventory" value="Search" class="button js-form-submit form-submit -brand-01">
            </div>
            {{ drupal_entity('block', 'views_block__custom_quick_search_block_quick_search', check_access=false) }}
        </div>
        <div class="quickSearch__links">
            {{ drupal_entity('block_content', '8') }}
        </div>
    </div>
</div>

```

---

**The rest of the code is the JavaScript that swaps out the fields**

```
/**
     * Clear disabled from makes and models on front page
     * Clone makes into unsorted
     * Remove duplicate entries
     * Reorder into alpha desc and move into dropdown
     */
 function loadMakes(show_styles){
  console.log(show_styles);
  if( show_styles == 'all' ){
    jQuery('.quickSearch .item .-makes').clone().prependTo('.quickSearch .unsorted__makes');
  }
  else{
    jQuery('.quickSearch .item .-makes[data-category="'+show_styles+'"]').clone().prependTo('.quickSearch .unsorted__makes');
  }
  //
  // Remove duplicates from makes dropdown.
  var makes = {};
  jQuery('.unsorted__makes .-makes').each(function() {
    var make = jQuery(this).attr('data-make');
    if (makes[make])
      jQuery(this).remove();
    else
      makes[make] = true;
  });
  // Reorder alpha and move to drop downs.
  jQuery(function(){
    jQuery('.unsorted__makes .-makes').sort(sort_makes).clone().prependTo('.filters-widget.-makes .filters-widget__copy');
    function sort_makes(a, b){
      return(jQuery(b).data('make')) < (jQuery(a).data('make')) ? 1 : -1;
    }
  });
}

/**
 *
 * Clone models into unsorted
 * Remove duplicate entries
 * Reorder into alpha desc and move into dropdown
 */
function loadModels(show_styles,show_makes){
  if( show_makes == 'all' ){
    jQuery('.quickSearch .item .-models').clone().prependTo('.quickSearch .unsorted__models');
  }
  else{
    jQuery('.quickSearch .item .-models[data-category="'+show_styles+'"][data-make="'+show_makes+'"]').clone().prependTo('.quickSearch .unsorted__models');
  }
  //
  // Remove duplicates from models dropdown.
  var models = {};
  jQuery('.unsorted__models .-models').each(function() {
    var model = jQuery(this).attr('data-model');
    if (models[model])
      jQuery(this).remove();
    else
      models[model] = true;
  });
  // Reorder alpha and move to drop downs.
  jQuery(function(){
    jQuery('.unsorted__models .-models').sort(sort_models).clone().prependTo('.filters-widget.-models .filters-widget__copy');
    function sort_models(a, b){
      return(jQuery(b).data('model')) < (jQuery(a).data('model')) ? 1 : -1;
    }
  });
}

/**
         * Move styles into unsorted
         * Remove empty entries
         * Remove duplicate entries
         * Reorder into alpha desc and move into dropdown
         */
        // Remove empty entries
        jQuery('.quickSearch .item').each(function(){
            if( jQuery(this).data('make') == undefined || jQuery(this).data('make') == null || jQuery(this).data('make') == ''){
                jQuery(this).remove();
            }
        });
        jQuery('.quickSearch .item .-styles').prependTo('.quickSearch .unsorted__styles');
        // Remove duplicates from styles dropdown.
        var styles = {};
        jQuery('.unsorted__styles .-styles').each(function() {
            var style = jQuery(this).attr('data-category');
            if (styles[style])
                jQuery(this).remove();
            else
                styles[style] = true;
        });
        // Reorder alpha and move to drop downs.
        jQuery(function(){
            jQuery('.unsorted__styles .-styles').sort(sort_styles).prependTo('.filters-widget.-styles .filters-widget__copy');
            function sort_styles(a, b){
                return(jQuery(b).data('category')) < (jQuery(a).data('category')) ? 1 : -1;
            }
        });

        // Show and hide makes and models based on selected style
        var show_styles = '';
        jQuery('.-styles input[type=checkbox]').change(function(){
            jQuery('.-styles input[type=checkbox]').not(this).prop('checked', false);
            jQuery('.-makes .filters-widget__copy, .-models .filters-widget__copy').html('');
            jQuery('.unsorted__makes, .unsorted__models').html('');
            show_styles = jQuery(this).parent().data('category');
            loadMakes(show_styles);
            loadModels(show_styles,show_styles);
        });

        // Show and hide makes and models based on selected style
        var show_makes = '';
        jQuery('.-makes').on('change', 'input[type=checkbox]', function(){
            jQuery('.-makes input[type=checkbox]').not(this).prop('checked', false);
            jQuery('.-models .filters-widget__copy').html('');
            jQuery('.unsorted__models').html('');
            show_styles = jQuery(this).parent().data('category');
            show_makes = jQuery(this).parent().data('make');
            loadModels(show_styles,show_makes);
        });

        // Quick Search submit button
        jQuery('.quickSearch .form-submit').on('click', function(){
            styles = jQuery('.-styles input:checked').val();
            makes = jQuery('.-makes input:checked').val();
            models = jQuery('.-models input:checked').val();
            var quick_search_url = '';
            if( styles && !makes && !models ){
                quick_search_url = 'category/'+styles;
            }
            else if( styles && makes && !models ){
                quick_search_url = 'category/'+styles;
                quick_search_url += '/make/'+makes;
            }
            else if( styles && !makes && models ){
                quick_search_url = 'category/'+styles;
                quick_search_url += '/model/'+models;
            }
            else if( styles && makes && models ){
                quick_search_url = 'category/'+styles;
                quick_search_url += '/make/'+makes;
                quick_search_url += '/model/'+models;
            }
            else if( !styles && makes && !models ){
                quick_search_url += '/make/'+makes;
            }
            else if( !styles && makes && models ){
                quick_search_url += '/make/'+makes;
                quick_search_url += '/model/'+models;
            }
            else if( !styles && !makes && models ){
                quick_search_url += '/model/'+models;
            }

            window.location.href = '/inventory-search/'+quick_search_url;
        });

        loadMakes('all');
        loadModels('all','all');

    }

```

---
Tags: views, taxonomy-terms
---


# Question
Title: Modify sorting criteria using views_query_alter
I have a view for the content type `events` with fields `event_name`, `description`, `summary`, `event_start_date`, etc. What my requirement is:

1. Sort the events in ascending order of `event_date equal or greater than the current date` (upcoming events)
2. Sort the events in descending order of `event_date less than the current date` (past events)

**NOTE: the upcoming data should come first and then the past data.**

# eg data and expected output

# example data

# expected result

Through the normal view UI settings, I couldn't achieve this. so I tried the `views_query_alter` hook to modify the sorting criteria. but I couldn't achieve this. Any help?

# What I have tried

```
/**
 * Implements hook_views_query_alter
 */
function news_t1_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if($view->id() == 'events'){
    $query->orderby[0]['field'] = "CASE node__field_st_field_st_value WHEN DATE(node__field_st_field_st_value) >= CURDATE()  END";
    $query->orderby[0]['direction'] = "ASC";
    $query->orderby[1]['field'] = "CASE node__field_st_field_st_value WHEN DATE(node__field_st_field_st_value) < CURDATE()  END";
    $query->orderby[1]['direction'] = "DESC";
    //$view->set_items_per_page(5);
  }
}

```

`node__field_st` is the event\_date field name.

# Update after @Patrick Kenny's Answer

Your solution works great. thanks!. I added a `Global: View area (Global: View area)` in the footer of the main display. But there is a small glitch to be removed. I have contextual and exposed filters in the master view which is inherited (this part is okay). But the problem is heading is repeated in the attached display. any way to get rid of this? screenshot attached.

# Answer
Objective: Show upcoming events, then past events.

The simplest way to implement this entirely through the View UI is to add a second display to the view.

Basic steps

1. Create the main view display. Configure the events to display as you like.
2. Set to sort by upcoming events, and filter so that only upcoming events are displayed.
3. Add an **Attachment** display. For this display, modify the filter (*This page: override*) to only show past events, and modify the sort in the same way.
4. In the **Footer** of the main view display, add the attachment.
> 1 votes

---
Tags: 8, views, hooks
---


# Question
Title: Is the following code secure when saving data to database?
I have a form that I want to save to database. Do you consider the following code safe? I get the value directly from the $form\_state and pass it into query. My understanding, it query will do the safe filter for me.

```
       $db = \Drupal::service('database');

        $result = $db->insert('invitation')
        ->fields([
            'guest_email' => $form_state->getValue('email'),
            'guest_name' => $form_state->getValue('name'),
            'guest_type' => $form_satte->getValue('type'),
            'created' => \Drupal::time()->getRequestTime(),
        ])
        ->execute();

```

# Answer
> 1 votes
As long as the values entered from users aren't concatenated directly into the string used for the SQL statement, there should not be any security risk.

The code shown in the question is safe because it uses the methods that take care of handling the values entered by users to avoid any possible issue.

The following code is an example of what to avoid.

```
$db = \Drupal::service('database');
$db->query("SELECT * FROM {users} WHERE name = '" . $form_state->getValue('name') . "'");

```

If the value entered for *name* were `' OR '1'='1' --`, the executed query would became the following one. (`--` is the comment start.)

```
SELECT * FROM {users} WHERE name = '' OR '1'='1' --

```

If multiple statements are allowed, the value entered from the user could also, for example, delete a database table, which could be possible by entering `a'; DROP TABLE {users}; --`. In this case the executed query would become the following one. (The comment at the end is just to let the database engine ignore the rest of the query.)

```
SELECT * FROM {users} WHERE name = 'a'; DROP TABLE {users}; --

```

Values entered by users need to be appropriately sanitized when output in a page. They should not be sanitized for that when saved in the database.

---
Tags: 8
---


# Question
Title: Cannot update Group module with composer
We are using the Group module on our D8 site. We use composer to manage our modules and dependencies. I am somewhat of a composer novice, so it's possible that the solution is right in front of me, but I cannot see it.

The Group module refuses to be updated. It's currently at 1.0, and I'd like to update it to 1.4. I've tried running a simple `composer update drupal/group`, using `--with-dependencies` and `--with-all-dependencies` I've tried manually updating the `composer.json` to require both "1.4" and "^1.\*". I've tried running the `why-not` command and all I get is "`There is no installed package depending on "drupal/group" in versions not matching 1.4`" Yet when I try to update the group module after changing the version in the composer file, all I get is the following.

```
$ composer update drupal/group --with-all-dependencies
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package flow/jsonpath is abandoned, you should avoid using it. Use softcreatr/jsonpath instead.
Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.
Generating autoload files 35 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

```

If I try to update using the version in the command, however I get the following.

```
$ composer update drupal/group:1.4
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Unable to find a compatible set of packages based on your non-dev requirements alone.
Your requirements can be resolved successfully when require-dev packages are present.
You may need to move packages from require-dev or some of their dependencies to require.

  Problem 1
    - Root composer.json requires drupal/group 1.*, 1.4, found drupal/group[1.0.0] but it does not match the constraint.

```

My composer.json is here, but I can't find anything that should be stopping this.

```
{
    "name": "drupal/recommended-project",
    "description": "Project template for Drupal 8 projects with a relocated document root",
    "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": {
        "composer/installers": "^1.2",
        "drupal/adaptivetheme": "^3.1",
        "drupal/address": "^1.8",
        "drupal/allowed_formats": "^1.3",
        "drupal/at_tools": "^3.2",
        "drupal/auto_entitylabel": "^3.0@beta",
        "drupal/better_exposed_filters": "^4.0@beta",
        "drupal/calendar": "^1.0-alpha2",
        "drupal/conditional_fields": "^4.0@alpha",
        "drupal/core-composer-scaffold": "^8.9",
        "drupal/core-project-message": "^8.9",
        "drupal/core-recommended": "^8.9.17",
        "drupal/cshs": "^3.0",
        "drupal/date_recur": "^2.0",
        "drupal/date_recur_modular": "^2.0",
        "drupal/ds": "^3.5",
        "drupal/emptyparagraphkiller": "^1.0@alpha",
        "drupal/encryption": "^1.0",
        "drupal/facets": "1.7",
        "drupal/facets_range_dropdowns": "^1.0@beta",
        "drupal/feeds": "^3.0@alpha",
        "drupal/feeds_ex": "^1.0@alpha",
        "drupal/feeds_tamper": "^2.0@beta",
        "drupal/field_group": "^3.0",
        "drupal/field_permissions": "^1.0@RC",
        "drupal/file_extractor": "^2.0",
        "drupal/flag": "^4.0@beta",
        "drupal/fullcalendar_view": "^2.6",
        "drupal/group": "1.*",
        "drupal/group_permissions": "1.0.0-alpha7",
        "drupal/honeypot": "^1.30",
        "drupal/image_widget_crop": "^2.2",
        "drupal/inline_entity_form": "^1.0@RC",
        "drupal/login_destination": "^1.0@alpha",
        "drupal/name": "^1.0@RC",
        "drupal/node_view_permissions": "^1.2",
        "drupal/optional_end_date": "^1.0",
        "drupal/pathauto": "^1.6",
        "drupal/publishcontent": "^1.2",
        "drupal/quick_node_clone": "^1.12",
        "drupal/redirect_after_login": "^2.5",
        "drupal/scheduler": "^1.1",
        "drupal/search_api": "1.x-dev",
        "drupal/search_api_attachments": "^1.0@beta",
        "drupal/search_api_solr": "^4.2",
        "drupal/search_autocomplete": "^1.1",
        "drupal/simplify": "^1.2",
        "drupal/smart_trim": "^1.2",
        "drupal/swiftmailer": "^2.0",
        "drupal/twig_tweak": "^2.7",
        "drupal/twigsuggest": "^1.0@beta",
        "drupal/userprotect": "^1.1",
        "drupal/verf": "^1.0@beta",
        "drupal/view_unpublished": "^1.0",
        "drupal/views_bulk_operations": "^3.9",
        "drupal/views_exposed_filter_blocks": "^1.1",
        "drupal/views_ical": "^1.0@alpha",
        "drupal/webform": "^5.8",
        "wikimedia/composer-merge-plugin": "^2.0"
    },
    "require-dev": {
        "drupal/devel": "^3.0.0-beta1",
        "drush/drush": "^10.3"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "extra": {
        "drupal-scaffold": {
            "locations": {
                "web-root": "web/"
            },
            "file-mapping": {
                "[web-root]/.htaccess": false
            }
        },
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/contrib/{$name}": ["type:drupal-drush"],
            "web/modules/custom/{$name}": ["type:drupal-custom-module"],
            "web/themes/custom/{$name}": ["type:drupal-custom-theme"]
        },
        "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/recommended-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"
            ]
        },
        "merge-plugin": {
            "include": [
                "web/modules/contrib/webform/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "ignore-duplicates": false,
            "merge-dev": true,
            "merge-extra": false,
            "merge-extra-deep": false,
            "merge-scripts": false
        }
    }
}

```

# Answer
When this happens I typically will do this:

```
rm -rf vendor
rm -rf web/modules/contrib
composer clearcache

```

Then run your command again...

```
composer require 'drupal/group:^1.4'

```
> 1 votes

---
Tags: 8, composer, group
---


title: Proper usage of config_split

text:
# Question
Title: Proper usage of config_split
I am trying to use config\_split so we can ignore/disable some modules/configurations on our dev environments, and we don't want them to carry over to our production environments.

I think I am setting things up wrong, as whenever I make config changes on my dev and push things up to production and import, it's overwriting the settings on production for modules we are ignoring in config\_split. (For example, if I make a views change locally, and export the config). When I import that config change into prod, it also disables the modules (and removes their settings we provided) we have on production that aren't on the dev environments.

For example, we have Drupal Shield and Drupal Password Policy set on production, but we don't want to set it on development. We have the 'shield' and 'password\_policy' module selected in the 'dev' configuration split we made, as well as the common 'devel' and 'admin\_toolbar\_extras' etc modules.

Now because we have them ignored, it ignores our settings in dev environments (if its disabled on our local dev, it stays disabled after import, visa versa), but once we push up to production and import config, it tries to disable shield and password\_policy on production, and change all of our custom settings we have set for it.

Do we need to create a special 'prod' with the modules that only apply to production to prevent that from happening?

A little stuck on using it, and can't make heads or tails of the documentation.

# Answer
> For example, we have Drupal Shield and Drupal Password Policy set on production, but we don't want to set it on development. We have the 'shield' and 'password\_policy' module selected in the 'dev' configuration split we made

This is your problem. This will enable the modules on Dev, not on PROD. You need to create a separate split for production, and add those modules. Then you will need to push your configuration. You will likely also need to manually enable the modules on PROD after pushing that split. Then it will not be overwritten on your next push.

I wrote this, it may help you out some: https://www.morpht.com/blog/drupal-8-configuration-part-4-extending-api-contributed-modules
> 1 votes

---
Tags: 8, configuration
---


# Question
Title: We need to check for and capture a URL parameter that may on any page so we need a efficient way to do this?
We need to track some **anonymous** users coming to the site with a URL parameter, like "?utc=1234". This could be on any page though so I don't know what the most resource-efficient way to accomplish this is.

We are also using Cloudflare and Memcached so I don't know how this may affect anonymous users.

The use case is, upon a page load, to check if the URL parameter exists and, if it does, then save it to a cookie for later retrieval.

# Answer
You need to create an event subscriber: https://www.drupal.org/docs/creating-custom-modules/subscribe-to-and-dispatch-events
> 0 votes

---
Tags: cookies
---


title: Add a class to main menu links

text:
# Question
Title: Add a class to main menu links
I've searched and found variations of this question but I've never found an answer that seemed to work. I need to add a class to the `<li>` elements, currently the main menu is rendered like this:

```
print theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
        'id' => 'slidemenu',
        'class' => array(
            'links',
            'inline',
            'clearfix'
        )
    ),
    'heading' => t('')
));

```

As far as I can tell, this only sets up the `<ul>` element of the main menu, so I was wondering if there's a way to edit the attributes of the `'links'` part.

---EDIT---

Alright, I think I solved it. Apparently you can use `theme_links__system_main_menu` in templates to override the whole thing. I ended up doing this:

```
function mytheme_links__system_main_menu($variables) {
    $html = '<div id="mainmenu">';
    $html .= '  <ul id="slidemenu" class="clearfix">';

    static $linkClass = 1;

    foreach ($variables['links'] as $link) {
        $html .= '<li class="themastyle' . $linkClass . '">' . l($link['title'], $link['href'], $link) . '</li>';
        ++$linkClass;
    }

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

    return $html;
}

```

Not entirely sure if this is correct Drupal, though it did solve my issue!

# Answer
> 1 votes
`print_r($main_menu);` each `$main_menu` items should have this structure:

```
array(
    'title' => 'xxx',
    'href' => 'xxx',
    'attributes' => array(
        'class' => array('xxx'),
    ),
);

```

so you can add class to li by altering `$main_menu` array.

# Answer
> 3 votes
Menu Attributes is another great module that allows you to set `class`, `id`, `rel` and other attributes on either the `a` or `li` element.

# Answer
> 1 votes
if your looking for a D8+ fix, the Menu Link Attributes module saves a lot of time. You can specify attributes and classes through a YML file or directly to individual links in Admin Menu UI.

# Answer
> 0 votes
If you don't mind using a existing module, you could also use Menu Names CSS. This module adds the target path of a menu item as a sanitized css-class to the li-item.

A second benefit is, that the module is good template how to put your functionality in a module instead of the template.php file, to increase the re-useability of your code.

---
Tags: 7, routes, navigation
---


# Question
Title: Why do I get "An invalid selection has been identified." from the form my code creates?
I am using the following code for a form.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $region_options = static::getFirstDropdownOptions();
  $form['vvv_region'] = [
    '#type' => 'select',
    '#title' => $this->t('region select field'),
    '#options' => $region_options,
    '#empty_option' => t('- Select region -'),
    '#ajax' => [
      'callback' => '::myAjaxCallback',
      'disable-refocus' => FALSE,
      'event' => 'change',
      'wrapper' => 'edit-output',
      'progress' => [
        'type' => 'throbber',
        'message' => $this->t('Verifying entry...'),
      ],
    ]
  ];

  $region_selected = $form_state->getValue('vvv_region');
  $city_options = static::getSecondDropdownOptions($region_selected);

  $form['output'] = [
    '#type' => 'select',
    '#title' => $this->t('city select field'),
    '#options' => $city_options,
    '#prefix' => '<div id="edit-output">',
    '#suffix' => '</div>',
    '#empty_option' => t('- Select city -'),
    '#default_value' => '',
    '#ajax' => [
      'callback' => '::cityAjaxCallback',
      'disable-refocus' => FALSE,
      'event' => 'change',
      'wrapper' => 'edit-city',
      'progress' => [
        'type' => 'throbber',
        'message' => $this->t('Verifying entry...'),
      ],
    ]
  ];

  $city_select = $form_state->getValue('output');
  $suburb_options = static::getSuburbDropdownOptions($city_select);

  $form['sur'] = [
    '#type' => 'select',
    '#options' => $suburb_options,
    '#prefix' => '<div id="edit-city">',
    '#suffix' => '</div>',
    '#empty_option' => t('- Select sururb -'),
    '#default_value' => array(''),
  ];
  return $form;
}

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  $region_selected = $form_state->getValue('vvv_region');
  $city_options = static::getSecondDropdownOptions($region_selected);

  if ($form_state->getErrors()) {
    \Drupal::messenger()->addError($region_selected);
    $form_state->setRebuild();
  }

  $form['outpout']['#options'] = $city_options;

  return $form['output'];
}

public function cityAjaxCallback(array &$form, FormStateInterface $form_state) {
  $city_select = $form_state->getValue('output');
  $sur_data = static::getSuburbDropdownOptions($city_select);

  if ($form_state->getErrors()) {
    \Drupal::messenger()->addError($city_select);
    $form_state->setRebuild();
  }

  $form['sur']['#options'] = $sur_data;

  return $form['sur'];
}

```

When the form is submitted, I get the following error.

> An invalid selection has been identified. Please contact the site administrator.

What's wrong with the code I am using?

# Answer
> 2 votes
There are two errors in the code shown in the question.

It's only the form builder that can add options to form elements. Differently, you will get the error you quoted.

> An invalid selection has been identified. Please contact the site administrator.

What the AJAX callback does is simply returning the form element that needs to be changed. In your case, the code is the following one.

```
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  return $form['output'];
}

public function cityAjaxCallback(array &$form, FormStateInterface $form_state) {
  return $form['sur'];
}

```

AN AJAX callback for a form doesn't usually handle validation errors.

The second error is in the form builder, which uses the following code.

```
$region_selected = $form_state->getValue('vvv_region');

```

When the form is first built, `$form_state->getValue('vvv_region')` doesn't return any value, as the form isn't yet submitted, even via AJAX. It's only when the form is submitted via AJAX that `$form_state->getValue('vvv_region')` returns a value. That line needs to be changed as follows.

```
$region_selected = $form_state->hasValue('vvv_region') ? $form_state->getValue('vvv_region') : key($region_options);

```

Similarly, `$city_select = $form_state->getValue('output');` needs to be changed.

```
$city_select = $form_state->hasValue('output') ? $form_state->getValue('output'): key($city_options);

```

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


title: Sum the grouped results in the template

text:
# Question
Title: Sum the grouped results in the template
I have an aggregated view result grouped by taxonomy terms and shown like the following.

> TaxonomyTerm1
> 1
> 1
> TaxonomyTerm2
> 1
> TaxonomyTerm3
> 1
> 1
> 1

I want the result to be added and shown like the following.

> TaxonomyTerm1
> 2
> TaxonomyTerm2
> 1
> TaxonomyTerm3
> 3

I tried to calculate the result in views-view-fields--reports.html.twig file with the following code.

```
{% set total = 0 %}
{% for field in fields -%}
  {% set total = total + 1 %}
{%- endfor %}
{{ total }}

```

Instead of the expected result, I get the original values again.

# Answer
> 1 votes
I have solved the problem with using **View Aggregator Plus** module. These are the settings I used on *Views \> View Aggregator Plus Module \> Style \> Settings*.

* For the taxonomy column
    1. In *Apply group functions* for the taxonomy column the result must be grouped by, select the *Group and compress* option
    2. In the *Render column* section, select the taxonomy column you want to shown as label
* For the total number column
    1. In *Apply column function*, select *Count (having regexp) **
    2. In the *Render column* section, select the title, for example as a field, because any field that repeats will be counted as total number with these options

To make it clearer, these are my fields.

* TaxonomyColumn (which is being grouped by)
* Title (the titles for the nodes with the taxonomy column)

Most importantly, make sure the default aggregation is disabled. It is by default, since the *View Aggregator Plus* module provides many aggregation options.

---
Tags: 8, views
---


# Question
Title: Redirect User to their Profile Page After Saving
Each user has a "Edit" tab/button on their profile. They click it, edit their profile, and when it is saved, they are kept on that page. I want the user to be taken back to his/her "View" or profile page.

# Answer
> 5 votes
As @Aboodred, if you already have the Rules module installed, adding a simple rule can do the job.

1. Create a rule with the React on event type `After updating an existing user account`.
2. Add a `Page redirect` action. Set the 'Data selector' field to `account:url` (either manually or using the dropdown).

# Answer
> 3 votes
If you want to do it with code instead of rules you can take a look at how the `user_edit_cancel_submit` function does it in user.pages.inc.

First you define an submit function: `$form['#submit'][] = 'custom_redirect_after_save';`

Then you add the function:

```
function custom_redirect_after_save($form, &$form_state) {
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }
  $form_state['redirect'] = array("user", array());
}

```

# Answer
> 2 votes
In Drupal 8/9:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_user_form_alter(&$form, &$form_state) {
  // Redirect users to their profile pages.
  $form['actions']['submit']['#submit'][] = 'MYMODULE_user_edit_form_submit';
}

/**
 * Redirect users to their profile pages when submitting the edit form.
 */
function MYMODULE_user_edit_form_submit($form, &$form_state) {
  $form_state->setRedirect('entity.user.canonical', ['user' => \Drupal::currentUser()->id()]);
}

```

# Answer
> 0 votes
You can add additional submit function to `user_profile_form` by using `hook_form_alter` to return back to profile page after editing user profile.

Your code should look like the following:

```
function MODULE_NAME_form_user_profile_form_alter(&$form, $form_state, $form_id) {
  $form['#submit'][] = 'MODULE_NAME_user_profile_form_submit';
}

function MODULE_NAME_user_profile_form_submit($form, &$form_state) {
  global $user;
  drupal_goto('user/' . $user->uid);
}

```

# Answer
> 0 votes
On my system (Drupal 6) it was

1) Install Rules Module:

https://www.drupal.org/project/rules

2) Activate Rules Module in Administration Console

\[site url\]/admin/build/modules (Look for a new Module category called Rules)

3) Enable the following Module(s):

Rules Administration UI 6.x-1.5 Provides the administration UI for rules. Depends on: Rules (enabled)

Rules Forms support 6.x-1.5 Provides events, conditions and actions for rule-based form customization. Depends on: Rules (enabled)

Rules Scheduler 6.x-1.5 Schedule the execution of rule sets. Depends on: Rules (enabled)

4) Navigate to Rules area and configure the rule:

Rules | Triggered Rules | Add a new rule

....fill in as per Obliquely's instructions...

BUT - There was no DATA SELECTOR or dropdown.

Instead I had to fill it in by hand, which was easy:

To: \[account:account-url\]

# Answer
> -1 votes
It worked in Drupal 8

```
use Symfony\Component\HttpFoundation\RedirectResponse;

function YOUR_MODULE_user_update($account) {
  $uid = \Drupal::currentUser()->id();
  $url = '/u/' . $uid;
  $response = new RedirectResponse($url);
  $request = \Drupal::request();
  $request->getSession()->save();
  $response->prepare($request);
  \Drupal::service('kernel')->terminate($request, $response);
  $response->send();
}

```

---
Tags: users, nodes
---


# Question
Title: How to block the IP that requests excessive 404 page not found?
On my site often I see thousands of requests thats ends up 404 - page not found error.

How can I block the IP that exceeds more than certain number of requests within a span of time from Drupal?

# Answer
> 0 votes
What you want is called fail2ban. There is a Drupal 7 module, but you would need to update it to Drupal OOP: https://www.drupal.org/project/fail2ban

But here's a recipe for integrating the Honeypot module with fail2ban: https://www.drupal.org/docs/contributed-modules/honeypot/integrate-honeypot-with-fail2ban

---
Tags: log-messages
---


# Question
Title: Pathauto alias full path for hierarchical taxonomy terms
My client has content tagged by a hierarchical taxonomy of arbitrary depth.

Currently the maximum depth is three, but that could change:

```
ParentTerm
└── ChildTerm
    └── GrandchildTerm

```

Each Term has a unique TID (of course), but many Terms (especially descendants) share identical strings for Name.

However, the full Taxonomy tree path to each term is guaranteed to be unique (two adjacent Terms will never be identically named.)

All nodes tagged with `GrandchildTerm` of TID = 42 appear in a View at `/taxonomy/term/42`.

I would like to use Pathauto to generate aliases for each Term at the full taxonomy tree path, like so:

```
/ParentTerm/ChildTerm/GrandchildTerm

```

I was looking for Tokens to accomplish this.

I found instead that the paths are set by a View which generates the list of Nodes tagged with the Term ID.

The View has a contextual filter which accepts `{{ arguments.tid }}`.

Under Page Settings, the value for Path is `/taxonomy/term/%`.

Someone on this forum said setting up two contextual filters would help, but that does not apply here.

I do not want `/taxonomyname/taxonomyterm` as the path; I want `/ParentTerm/ChildTerm/GrandchildTerm` as the path (or, if necessary, `/tags/ParentTerm/ChildTerm/GrandchildTerm`).

It is possible to set a contextual filter `Content: Has taxonomy term ID (with depth)` but I haven't been able to get the path I seek this way.

Also, I would like a `ParentTerm` taxonomy page to return results for its descendants, but the current View only displays items for the specific TID. (The Views Tree module would help here, but it does not work with Drupal 9 yet.)

If this were not a requirement, I might try flattening the taxonomy and using term names like `ParentTerm-ChildTerm-GrandchildTerm` to differentiate identically named descendant terms. (This would solve another problem the client has: the ambiguity of selecting the correct term from the "Tags" vocabulary when tagging content.)

# Answer
> 3 votes
I think you are really going to struggle to get this to work using the default taxonomy term page view. However, you can disable the view and then use the default entity full content display for terms and do whatever you'd like for it (just like a node page).

1. Disable the taxonomy term display that controls `/taxonomy/term/%tid`. This will allow the term's entity canonical route to control itself.
2. Create a pathauto alias for your terms with your desired pattern. I think you can probably use existing tokens for the parent piece of the path, something like `[term:parent:url:path]/[term:name]`. (Or just create a custom token if an existing token doesn't work.)
3. Clone the display disabled in step 1 (as a block or embed - depending on how you want to place it) and place it on your taxonomy term pages (via block layout, context, preprocess, twig, or whatever). I don't think it'll be an issue, but if you're having trouble getting the correct tid set for the contextual filter using views' default options, you can use hook\_views\_pre\_view() to get the tid from the route and pass it to the view programmatically.

---
Tags: views, taxonomy-terms, path-aliases
---


title: How can I disable these URLs?

text:
# Question
Title: How can I disable these URLs?
In Drupal 7, the following URLs show the same node.

This doesn't happen in Drupal 8.

How can those URLs be disabled?

# Answer
When users try to access a path that doesn't exist, for example /node/5/random-text-2, Drupal will show the parent page. More exactly, it will show the page for the first of the following paths that exists. (*%* is the wildcard character, used for paths defined from modules.)

* node/5/%
* node/%/random-text-2
* node/%/%
* node/5
* node/%
* node

Normally, Drupal would show the page for node/5 (which is considered the parent page for node/5/random-text-2), but when a module defines a page for node/%/%, Drupal will instead show that page.

A module could add a `hook_menu()` implementation similar to the following one.

```
function mymodule_menu() {
  $items['node/%/%'] = array(
    'page callback' => 'mymodule_page',
  );

  return $items;
}

```

`mymodule_page()` could just show a 404 or a 403 error.

```
function mymodule_page() {
  // Return a 404 error.
  return MENU_NOT_FOUND;
}

```

This would stop Drupal from showing a node page every time users access a path like node/\[node-id\]/\[random-string\], where the random string doesn't match with any menu defined from any module. (For example, if *\[random-string\]* is equal to *edit*, Drupal will show the node edit form.)

Returning a 403 error is simpler. Using the following hook implementation, a module would get that without writing much code (except eventually an empty function for the page callback).

```
function mymodule_menu() {
  $items['node/%/%'] = array(
    'page callback' => 'mymodule_page',
    'access callback' => FALSE,
  );

  return $items;
}

```
> 1 votes

---
Tags: 7, uri
---


# Question
Title: Why does my shopping cart item not have a label?
I'm working on D8 site with Drupal Commerce. I have to create a dynamic product variation and add it to cart for the user checkout.

The problem I have, is when you land on the cart page, the line item doesn't have a label (title) it replaced with the price of the item. Please refer to the attached image.

Here's my code:

```
   //create variation
            $variation = ProductVariation::create([
                'type' => 'fk_payment',
                'sku' => 'FK'.$faid,
                'status' => TRUE,
                'price' => new Price($trans->getTotal(), $trans->getCurrency()),
                'title' => "Example item label title",
              ]);

            $variation->save();

            //Load the product
            $product_id = 4;
            $product = Product::load($product_id);
            $product->addVariation($variation);
            $product->save();

            //load store
            $storeId = $product->get('stores')->getValue()[0]['target_id'];
            $store = \Drupal::entityTypeManager()
            ->getStorage('commerce_store')
            ->load($storeId);

            //prepare cart
            $cart = \Drupal::service('commerce_cart.cart_provider');
            $cart = $cart->getCart('default', $store);

            if (!$cart) {
                $cart = \Drupal::service('commerce_cart.cart_provider');
                $cart = $cart->createCart('default', $store);
            }

            // Process to place order programatically.
            $cart_manager = \Drupal::service('commerce_cart.cart_manager');

            //empty the cart
            if (!empty($cart)) {
                $cart_manager->emptyCart($cart);
            }

            $cart_manager->addEntity($cart, $variation);

```

# Answer
> 0 votes
Just found the answer. I have to edit the cart "Views" and change the field "item" to display label. That's it.

---
Tags: 8, commerce
---


# Question
Title: Using Twig in global custom text to check for a specific content type
I am filtering for two content types to display in a view: *Artwork Page* and *Cover Page*. I want to change the HTML markup for *Cover Page*.

I have researched and tried many field names for *Content Type*, but with none of them I get what I am trying to achieve. In this instance, the replacement pattern for *Content Type* is `{{ type }}`; using it doesn't work. I've tried both the machine name (*cover\_page*) and the name (*Cover Page*), but neither of them worked.

```
{% if type == 'cover_page' %}
  <h1>THIS IS THE BEGINNING</h1>
{% endif %}

{% if type == 'Cover Page' %}
  <h1>THIS IS THE BEGINNING</h1>
{% endif %}

```

# Answer
> 0 votes
The content type field is a reference field and contains the machine name of the content type as target id.

Configure the field formatter *Entity ID*:

> Configure field: Content: Content type
>
> **Formatter**
> Entity ID ▼

Or use the property target\_id when rewriting the field itself:

```
{{ type__target_id }}

```

You can add a second instance of the field and hide it if you only want to use the machine name for logic and don't want to display it.

---
Tags: views, theming, 9
---


# Question
Title: How to set URL for image with view method properly?
Image formatter should accept `image_style` and `url` parameters.
I've got `image_style` working but not `url`.

```
function mymodule_preprocess_views_view_field(&$variables) {
  // ...
  $variables['image'] = $node->get('field_image')->get($delta)->view(['settings' => ['image_style' => '195', 'url' => '/test']]);
  kint($variables['image']);
  // ...
}

```

Why **url** is NULL (instead of **/test**)?

# Answer
`$node->get('field_image')->get($delta)->view(['settings' => ['image_style' => '195', 'url' => '/test']]);` doesn't set `#url` because it doesn't handle the *url* key passed in *settings*.

Given the content of the `$variables['image']` array, you just need to set `$variables['image']['#url']` after you obtain the image render array. Remember that the value of `#url` is expected to be a `\Drupal\Core\Url` object.

```
// Add the following line at the beginning of the file.
use  Drupal\Core\Url;

function mymodule_preprocess_views_view_field(&$variables) {
  // ...
  $variables['image'] = $node->get('field_image')->get($delta)->view(['settings' => ['image_style' => '195']]);
  $variables['image']['#url'] = Url::fromUserInput('/test');
}

```

Given the code used by `ImageFormatter::viewElements()`, and the comment before the code, I would "investigate" to understand if setting the cache context is necessary to avoid cache issues in some cases.

```
// @todo Wrap in file_url_transform_relative(). This is currently
// impossible. As a work-around, we currently add the 'url.site' cache
// context to ensure different file URLs are generated for different
// sites in a multisite setup, including HTTP and HTTPS versions of the
// same site. Fix in https://www.drupal.org/node/2646744.
      $url = Url::fromUri(file_create_url($image_uri));
      $cache_contexts[] = 'url.site';

```

The comment describes it as work-around to use `file_url_transform_relative()`, but invalidating the cache for different sites in a multisite setup or for HTTP and HTTPS versions of the same site, could be still something that needs to be done.
> 0 votes

---
Tags: 8
---


# Question
Title: Why does a query string return a 404 error?
I recently upgraded from Drupal 8 to Drupal 9 and noticed a problem that occurs when the URL has a query string. For example for the following URL Drupal throws a 404 page not found.

`https://example.com/2021/07/how-drive-cruise-ship&ct=ga&cd=EAEYACoTMzczMDU5MTUxNjcwNDQyMzUxNzIcN2RiZjYwOGY4MzE2NmM3OTpjby51azplbjpHQg&usg=AFQjCNEa2-Hx3zqnQ59AJFnde_ORtLTvgA`

# Answer
> 2 votes
The query string is badly formatted. It needs a `?`:

`https://example.com/2021/07/how-drive-cruise-ship?&ct=ga&cd=EAEYACoTMzczMDU5MTUxNjcwNDQyMzUxNzIcN2RiZjYwOGY4MzE2NmM3OTpjby51azplbjpHQg&usg=AFQjCNEa2-Hx3zqnQ59AJFnde_ORtLTvgA`

---
Tags: uri, 9
---


# Question
Title: Is it possible to create an action with derivatives?
Is it possible to create an action in Drupal 8 and point it at a deriver class to generate them automatically?

For example with Custom Publishing Options I have a ConfigurableActionBase action that lets a user create an advanced action, select the publishing option and the value, and save the action.

Ideally, I would like to have a generic action derived from all existing publishing options so that admins don't have to create the action manually every time they add a new custom publishing option. Along with that, if they deleted the entity, I would want the action to be removed as well.

I was able to create a class extended DeriverBase and define plugin derivatives, but was having issues getting it to pick up in my class extending ActionBase with deriver set in the annotation. My example code is on my home laptop, will post it when I have a chance.

# Answer
> 1 votes
You've probably figured this out by now as this was asked in 2016, but you can indeed use a plug-in deriver to create actions. The part that trips people up (including myself) is that you also need to create an action config for Drupal to even list the action, as mentioned in this answer by mpp. I think there's some additional trickery that might be required to make it work with derivatives that I haven't figured out entirely yet.

---
Tags: 8, actions, plugins
---


# Question
Title: Twig template for just one page in a view
I have a Drupal view (*Product Section*) where I have a master view. This is the view I'm currently using for *Computers*, *Cell Phone*, and other pages I am still creating.

>

I also have a *Product Shop* page, which is almost like the parent page. For this page, the path is */products*, for *Computers* is */products/computers*, and so forth.

In my theme folder, inside of the *templates* folder, I created a *page--products.html* template. This works great, but this template gets used not only by the */products* pages but also the *products/page-name-here* pages.

1. How do I change this template to only target */products* and not *products/page-name-here*. Would I just have to change the template name to something more specific?
2. Inside of this template, can I do an if statement something like the code below that will only target that */product* page? Let's say I end up keeping the template on all the pages, but I want to add code that only shows up if it's on */products* and not *products/page-name-here*. Maybe I could target it by its unique ID. How can I achieve this?

```
{% if page = 'page-name' %}
  // This will only show on /products.
{% endif %}

```

# Answer
You can use the display name as part of the template name to confer specificity to your Views templates, e.g., `[base template name]--[view machine name]--[view display id].html.twig`,

In your case, you could have names like `views-list--products_section--product_shop.html.twig`, `views-list--products_section--computers.html.twig`, `views-list--products_section--cell_phones.html.twig`, etc.

There's lot's of documentation out there, including Create a template for a specific view, which may serve as a good jumping off point.
> 0 votes

---
Tags: views, theming
---


# Question
Title: jquery.ui libraries-override > Incomplete library definition
I tried to remove the core jquery.ui theme.css by writing into mytheme.libraries.yml the following lines.

```
libraries-override:
  core/jquery.ui:
    css:
      theme:
        assets/vendor/jquery.ui/themes/base/theme.css: false

```

```
 stylesheets-remove:
  - core/assets/vendor/jquery.ui/themes/base/theme.css

```

Both versions return an *Incomplete library definition* error. I cleared the cache but the errors remain. Does anybody know the solution?

After further reading, I put the code in mytheme.info.yml (instead of mytheme.libraries.yml). This avoids the error, but the "overriden" theme.css is still loading.

# Answer
What the OP worked for me but I needed to override additional libraries:

```
libraries-override:
  core/jquery.ui:
    css:
      theme:
        assets/vendor/jquery.ui/themes/base/theme.css: false
  core/drupal.dialog:
    css:
      theme:
        assets/vendor/jquery.ui/themes/base/theme.css: false
  core/jquery.ui.dialog:
    css:
      theme:
        assets/vendor/jquery.ui/themes/base/theme.css: false
  core/drupal.autocomplete:
    css:
      theme:
        assets/vendor/jquery.ui/themes/base/theme.css: false

```

The `stylesheets-override` didn't do anything for me. This should work for Drupal 8 and Drupal 9.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: What controls the placement of links relative to the body?
I am struggling with getting the "Read more" and "Add new comment" links placed *below* the body on a custom node content type called "Wikitext" that has been created using the GUI on a Drupal 8.9.17 website.

The site is running the default theme (Bartik) and I have not edited any templates. The built-in content type "Article" shows these links below the body. "Wikitext" is supposed to be identical to "Article", but displays them *above* the body.

I've unticked "Show reply form on the same page as comments" on the comment settings form for both content types.

Below the acreenshot is a copy of the "Manage display" form. It is identical for both content types, and has "Links" and "Comments" as the last two fields to display.

I have looked very carefully, but cannot locate anywhere in the GUI where I can control the placements of these links. Does anybody know where to look?

# Answer
> 2 votes
It's the *Links* field that appears also the question's screenshot, but for the *Teaser* view mode, whose settings are on /admin/structure/types/manage/wikitext/display/teaser, for the *Wikitext* content type. (I assume *wikitext* is the machine name for that content type.)

I changed the *Teaser* view mode for the *Article* content type and re-ordered the fields as follows.

>

This is how an article appears now in the front page, once it's promoted on front page.

>

---
Tags: 8
---


# Question
Title: Cannot update: "No available releases found"
I cannot update some of the modules and the Drupal core itself from "Available Updates" menu. The error is "No available releases found". However, I can list the updates with `drush ups`.

>

>

Why?

# Answer
# Solution 1: SQL Query

While checking updates Drupal creates some rows inside the `key_value` table which should be deleted after checking is complete but looks like they doesn't for some reason. So deleting the related rows manually solved my problem:

```
DELETE FROM key_value WHERE collection = 'update_fetch_task';

```

# Solution 2: hook\_update\_N()

If it is not possible to execute SQL queries via MySQL CLI on your server, then you might want to create a `hook_update_N()` in a custom module:

```
$database = \Drupal::database();
$database
  ->delete('key_value')
  ->condition('collection', 'update_fetch_task')
  ->execute();

```
> 36 votes

# Answer
```
drush sql-query "DELETE FROM key_value WHERE collection='update_fetch_task'"

```

using drush Fixed for me
> 5 votes

# Answer
Use the Devel module, and in /devel/php enter the following code.

```
$query = \Drupal::database()->delete('key_value');
$query->condition('collection', 'update_fetch_task' , '=');
$query->execute();

```
> 1 votes

# Answer
I couldn't find the key\_value table anywhere.

After a lot of research, I stumbled upon this article by Marius Cârneală. https://www.mariusc.name/content/no-available-releases-found-drupal-error-fix

His SQL command worked for me: truncate cache\_update

You can run it via this drush command:

```
drush sqlq "truncate cache_update;"

```
> 1 votes

# Answer
According to this post https://www.drupal.org/project/drupal/issues/3120168, if you click on "Check manually", it fixes the problem. I tried it and it worked.

Edit: I used this method on Drupal ^8.8
> 1 votes

# Answer
DELETE FROM key\_value WHERE collection = 'update\_fetch\_task' worked where "update manually", "update cron" and "clear all caches" didn't.
> 0 votes

---
Tags: 8, updating
---


# Question
Title: How to use form_set_error if no form field is involved in the error?
In a form\_validate hook, I have some custom validation and I'm using

```
form_set_error('field_foo', "error_message");

```

to show validation errors. If the validation returns an error that is not linked to a particular form field, how do I show the error, indipendently? (For example: the error is you compiled more that three times the form.)

EDIT: I though to use:

```
drupal_set_message("error_message", 'error');

```

From the documentaion for 7.x

> When a validation error is detected, the validator calls form\_set\_error() to indicate which element needs to be changed and provide an error message.

So, form\_set\_error() produce an error linked to a particular field of the form. I needed to display error indipendently in a custom complex validation, being errors not really about a field. I though to use form\_set\_error() on a random field, but it is not the perfect solution, for the field was highlighted and only the last error produced this way was visible. drupal\_set\_message solves this two problem, but the validation success and the form continues like there was no error.

# Answer
The way core Drupal does this is to use `''` for the first parameter of `form_set_error()`. So in the example you give, `form_set_error('', "error_message");` would set the error message for the form, not tied to any specific form element.

This is an undocumented feature of `form_set_error()`, but it's a feature that core Drupal has used forever, over many different versions of Drupal core (including the current Drupal 9 version!). There is currently an issue open in the core Drupal issue queue asking for this feature to be documented. See https://www.drupal.org/project/drupal/issues/2780209
> 1 votes

# Answer
There is a plain solution

```
form_set_error('form',$error_messages);

```

Does not highlight any field, and the validation fails as expected. It doesn't allow multiple message, but this can be solved using a little hack

```
$error_messages = "";
if (type_error_1)
   $error_messages .= "Error Message on First Line <br/>";
}
if (type_error_2){
   $error_messages .= "Error Message on Another Line <br/>";
}
if(strlen($error_messages) > 0){
  form_set_error('form',$error_messages);
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to programmatically add a paragraph item to a user account?
I already added the *Check in/out History* field to the user account, which has the *check-in date* and *check-out date* fields.

How can I programmatically add new items to *Check in/out History*?

I need to create some history for users.

| Check-in date | Check-out date |
| --- | --- |
| 04/05/21 | 05/07/21 |
| 03/05/20 | 04/14/20 |

# Answer
> 0 votes
I have been able to achieve the task using the following code.

```
$paragraph = Paragraph::create([
  'type' => 'checkin_history',
  'field_checkin' => $checkin_date,
  'field_checkout' => format_date(time(), 'html_date')
]);
$paragraph->save();

$current = $account->get('field_check_in_out_history')->getValue(); $current[] = [
  'target_id' => $paragraph->id(),
  'target_revision_id' => $paragraph->getRevisionId(),
];

$account->set('field_check_in_out_history', $current);
$account->save();

```
* *field\_check\_in\_out\_history* is the user account field
* *checkin\_history* is the paragraph type
* *field\_checkin* and *field\_checkout* are paragraph fields

---
Tags: 8, paragraphs
---


# Question
Title: Should I use a new core version that doesn't yet have its first stable release for production?
I want to start using Drupal 8.

Can I use it in its current state for a simple blog site built with views?

# Answer
> 1 votes
We should always prefer the latest stable release. You may know that the alpha, beta versions are not completed so after all the issues are fixed & testing everything the author will update the stable release. Once we got the stable release then we can update our site later.

# Answer
> 9 votes
The real question is: what's the Drupal core lifecycle look like?

First, we have feature thaw. During this time it's really a bad idea to even try to build anything on it. It's likely to be broken, buggy, and so on. (Although now we have extensive test coverage so it's less broken than you'd think.)

Then there's a feature freeze. People with some knowledge, patience and not too important sites -- say, a blog :) -- could start testing. It'd be great if this happened. You need to understand that there is still no guarantee that your data can stay intact from one git pull to the next. (This is where we are now.)

The next step is beta. From beta and on we support upgrades. So while it's not the quality you'd expect from a released product, it's time to begin serious testing. If you start testing when release happened, your problems will take a lot longer to be fixed.

---
Tags: 8
---