# Question
Title: Drush 8.1.9+ with Drupal 6 results in "Drush command terminated abnormally due to an unrecoverable error" followed by the site home page source code
My sites are hosted on a Linux server with Apache 2.2, PHP 5.5, MySQL 5.6 installed. I use Drush 8.1.8 which I installed via composer and which works correctly with my D6, D7 and D8 sites. I can update some D6 site modules by using Drush 8 combined with the myDropWizard module.

I've recently tried to update Drush to 8.1.9 version then to 8.1.10 version, but none works with the D6 sites, while still working correctly with the D7 and D8 sites.

Each time I try to use a Drush command for a D6 site, this message is displayed:

> Drush command terminated abnormally due to an unrecoverable error. \[error\]

It is weirdly followed by the display of the whole home page source code of this site.

I've also tried reproducing this on localhost; in that case, Drush is stuck and displays nothing.

Does Drush 8 still work with Drupal 6?

**Edit:**

`[~/public_html/en/sites/en.mysite.com]# drush -dv up`

Passed with Drush 8.1.8:

```
Using the Drush script found at /home/myuser/.composer/vendor/drush/drush/drush.launcher using proc_open
Drush preflight prepare loaded autoloader at                         [preflight]
/home/myuser/.composer/vendor/autoload.php [0.01 sec, 2.5 MB]
Starting Drush preflight. [0.01 sec, 2.5 MB]                         [preflight]
Loading drushrc "/home/myuser/.drush/drushrc.php" into "home.drush"[bootstrap]
scope. [0.01 sec, 2.8 MB]
Cache HIT cid: 8.1.8-commandfiles-0-6f2a323a6de1242729a7e3fe6aad3d20     [debug]
[0.02 sec, 2.86 MB]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.07        [debug]
sec, 5.56 MB]
Scanning into /etc/drush for /self\.alias\.drush(8|)rc\.php$/ [0.07      [debug]
sec, 5.56 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /.*aliases\.drush(8|)rc\.php$/ [0.07 sec, 5.56 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /self\.alias\.drush(8|)rc\.php$/ [0.07 sec, 5.56 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.08 sec, 5.56 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.56 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/sites/default for            [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/sites/default for            [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Bootstrap to phase 0. [0.25 sec, 9.19 MB]                            [bootstrap]
Bootstrap to phase 6. [0.26 sec, 9.2 MB]                             [bootstrap]
Drush bootstrap phase : bootstrap_drupal_root() [0.26 sec, 9.57 MB]  [bootstrap]
Initialized Drupal 6.38 root directory at                            [bootstrap]
/home/myuser/public_html/en [0.27 sec, 9.74 MB]
Find command files for phase 1 (max=6) [0.28 sec, 7.06 MB]               [debug]
Cache MISS cid: 8.1.8-commandfiles-1-b9fee8b15dbf25a4d90112dcde868368    [debug]
[0.28 sec, 7.06 MB]
Cache SET cid: 8.1.8-commandfiles-1-b9fee8b15dbf25a4d90112dcde868368     [debug]
[0.28 sec, 7.06 MB]
Cache MISS cid:                                                          [debug]
8.1.8-annotationfiles-1-90bcfd4c83aa04b96148e19f9b6d112b [0.28 sec,
7.06 MB]
Cache SET cid:                                                           [debug]
8.1.8-annotationfiles-1-90bcfd4c83aa04b96148e19f9b6d112b [0.28 sec,
7.06 MB]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.28        [debug]
sec, 7.07 MB]
Scanning into /etc/drush for /self\.alias\.drush(8|)rc\.php$/ [0.28      [debug]
sec, 7.07 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /.*aliases\.drush(8|)rc\.php$/ [0.28 sec, 7.07 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /self\.alias\.drush(8|)rc\.php$/ [0.28 sec, 7.07 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.29 sec, 7.07 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.29 sec, 7.08 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.29 sec, 7.08 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.29 sec, 7.08 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.29 sec, 7.08 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.29 sec, 7.08 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.29 sec, 7.08 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.29 sec, 7.09 MB]
Scanning into                                                            [debug]
/home/myuser/public_html/en/sites/en.mysite.com for
/.*aliases\.drush(8|)rc\.php$/ [0.29 sec, 7.09 MB]
Scanning into                                                            [debug]
/home/myuser/public_html/en/sites/en.mysite.com for
/self\.alias\.drush(8|)rc\.php$/ [0.29 sec, 7.09 MB]
Drush bootstrap phase : bootstrap_drupal_site() [0.3 sec, 7.09 MB]   [bootstrap]
Initialized Drupal site en.mysite.com at                   [bootstrap]
sites/en.mysite.com [0.3 sec, 7.09 MB]
Find command files for phase 2 (max=6) [0.3 sec, 7.09 MB]                [debug]
Drush bootstrap phase : bootstrap_drupal_configuration() [0.3 sec,   [bootstrap]
7.09 MB]
Find command files for phase 3 (max=6) [0.3 sec, 7.1 MB]                 [debug]
sql-query: SELECT 1; [0.31 sec, 7.25 MB]                                [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_OIe8xv --database=myuser_dru600en-3 --host=localhost --silent  < /tmp/drush_9CYvzv
  1
sql-query: SHOW TABLES; [0.32 sec, 7.25 MB]                             [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_8JGzyv --database=myuser_dru600en-3 --host=localhost --silent  < /tmp/drush_dAplyv

----------

Drush bootstrap phase : bootstrap_drupal_database() [0.34 sec, 7.28  [bootstrap]
MB]
Successfully connected to the Drupal database. [0.34 sec, 7.49 MB]   [bootstrap]
Find command files for phase 4 (max=6) [0.34 sec, 7.49 MB]               [debug]
Drush bootstrap phase : bootstrap_drupal_full() [0.34 sec, 7.49 MB]  [bootstrap]
session_start(): Cannot send session cookie - headers already sent by[1;33;40m[1m[warning][0m
(output started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:1182 [0.34 sec, 7.53 MB]
session_start(): Cannot send session cache limiter - headers already [1;33;40m[1m[warning][0m
sent (output started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:1182 [0.34 sec, 7.53 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:736 [0.36 sec, 9.19 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:737 [0.36 sec, 9.19 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:738 [0.36 sec, 9.19 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:739 [0.37 sec, 9.19 MB]
Cache MISS cid:                                                          [debug]
8.1.8-install_profile-e90a16a83d52c8b645801f9d680294e7 [0.64 sec,
27.29 MB]
Cache SET cid: 8.1.8-install_profile-e90a16a83d52c8b645801f9d680294e7    [debug]
[0.64 sec, 27.29 MB]
Find command files for phase 5 (max=6) [0.64 sec, 27.3 MB]               [debug]
Cache HIT cid: 8.1.8-install_profile-e90a16a83d52c8b645801f9d680294e7    [debug]
[0.64 sec, 27.3 MB]
Cache MISS cid: 8.1.8-commandfiles-5-a9080126c9c73166bca2cdbd6b3b0237    [debug]
[0.65 sec, 27.43 MB]
Cache SET cid: 8.1.8-commandfiles-5-a9080126c9c73166bca2cdbd6b3b0237     [debug]
[0.74 sec, 27.44 MB]
Cache MISS cid:                                                          [debug]
8.1.8-annotationfiles-5-fa617a1a276a4dad2c17877d766b9665 [0.76 sec,
27.81 MB]
Cache SET cid:                                                           [debug]
8.1.8-annotationfiles-5-fa617a1a276a4dad2c17877d766b9665 [0.76 sec,
27.81 MB]
Drush bootstrap phase : bootstrap_drupal_login() [0.77 sec, 27.77 MB][bootstrap]
Find command files for phase 6 (max=6) [0.77 sec, 27.8 MB]               [debug]
Found command: pm-update (commandfile=pm) [0.77 sec, 27.8 MB]        [bootstrap]
Calling hook drush_pm_update [0.94 sec, 31.04 MB]                        [debug]
Loading release_info engine. [0.94 sec, 31.08 MB]                       [notice]
Loading version_control engine. [0.94 sec, 31.08 MB]                    [notice]
Loading package_handler engine. [0.94 sec, 31.1 MB]                     [notice]
Executing: wget --version
Loading update_status engine. [0.95 sec, 31.09 MB]                      [notice]
Including                                                            [bootstrap]
/home/myuser/.composer/vendor/drush/drush/commands/pm/updatecode.pm.inc
[0.96 sec, 31.09 MB]
Calling hook drush_pm_updatecode_validate [0.96 sec, 31.19 MB]           [debug]
Returned from hook drush_pm_updatecode_validate [0.96 sec, 31.2 MB]      [debug]
Calling hook drush_pm_updatecode [0.97 sec, 31.21 MB]                    [debug]
Cache MISS cid: 8.1.8-alias-path--03cb329adb374664ee9dca020716dbe1       [debug]
[0.97 sec, 31.24 MB]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.97        [debug]
sec, 31.24 MB]
Scanning into /etc/drush for /.*\.alias\.drush(8|)rc\.php$/ [0.97        [debug]
sec, 31.24 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /.*aliases\.drush(8|)rc\.php$/ [0.97 sec, 31.24 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /.*\.alias\.drush(8|)rc\.php$/ [0.97 sec, 31.25 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.98 sec, 31.25 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/.*\.alias\.drush(8|)rc\.php$/ [0.98 sec, 31.25 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.98 sec, 31.25 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/.*\.alias\.drush(8|)rc\.php$/ [0.98 sec, 31.25 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.98 sec, 31.25 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/.*\.alias\.drush(8|)rc\.php$/ [0.98 sec, 31.26 MB]
Scanning into                                                            [debug]
/home/myuser/public_html/en/sites/en.mysite.com for
/.*aliases\.drush(8|)rc\.php$/ [0.98 sec, 31.26 MB]
Scanning into                                                            [debug]
/home/myuser/public_html/en/sites/en.mysite.com for
/.*\.alias\.drush(8|)rc\.php$/ [0.98 sec, 31.26 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.98 sec, 31.26 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/.*\.alias\.drush(8|)rc\.php$/ [0.98 sec, 31.26 MB]
Cache SET cid: 8.1.8-alias-path--03cb329adb374664ee9dca020716dbe1        [debug]
[0.99 sec, 31.28 MB]
Backend invoke: /usr/bin/php-cli                                       [command]
/home/myuser/.composer/vendor/drush/drush/drush.php
--php=/usr/bin/php-cli  --backend=2 --verbose --debug
--root=/home/myuser/public_html/en
--uri=http://en.mysite.com
--db-url='mysql://myuser_en:en123@localhost/myuser_dru600en-3'
pm-updatestatus 2>&1 [0.99 sec, 31.27 MB]
/usr/bin/php-cli                                                        [notice]
/home/myuser/.composer/vendor/drush/drush/drush.php
--php=/usr/bin/php-cli  --backend=2 --verbose --debug
--root=/home/myuser/public_html/en
--uri=http://en.mysite.com
--db-url='mysql://myuser_en:en123@localhost/myuser_dru600en-3'
pm-updatestatus 2>&1 [0.99 sec, 31.27 MB]
Update information last refreshed: February 26, 2017 - 12:14

----------

```

Failed with Drush 8.1.10:

```
Using the Drush script found at /home/myuser/.composer/vendor/drush/drush/drush.launcher using proc_open
Drush preflight prepare loaded autoloader at                         [preflight]
/home/myuser/.composer/vendor/autoload.php [0.01 sec, 2.5 MB]
Starting Drush preflight. [0.01 sec, 2.5 MB]                         [preflight]
Loading drushrc "/home/myuser/.drush/drushrc.php" into "home.drush"[bootstrap]
scope. [0.01 sec, 2.8 MB]
Cache HIT cid: 8.1.10-commandfiles-0-6f2a323a6de1242729a7e3fe6aad3d20    [debug]
[0.02 sec, 2.86 MB]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.07        [debug]
sec, 5.56 MB]
Scanning into /etc/drush for /self\.alias\.drush(8|)rc\.php$/ [0.07      [debug]
sec, 5.56 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /.*aliases\.drush(8|)rc\.php$/ [0.07 sec, 5.56 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.56 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.08 sec, 5.56 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.08 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.09 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.09 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.09 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.09 sec, 5.57 MB]
Scanning into /home/myuser/public_html/en/sites/default for            [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.09 sec, 5.58 MB]
Scanning into /home/myuser/public_html/en/sites/default for            [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.09 sec, 5.58 MB]
Bootstrap to phase 0. [0.27 sec, 9.53 MB]                            [bootstrap]
Bootstrap to phase 6. [0.27 sec, 9.54 MB]                            [bootstrap]
Drush bootstrap phase : bootstrap_drupal_root() [0.28 sec, 9.91 MB]  [bootstrap]
Initialized Drupal 6.38 root directory at                            [bootstrap]
/home/myuser/public_html/en [0.28 sec, 10.08 MB]
Find command files for phase 1 (max=6) [0.29 sec, 7.37 MB]               [debug]
Cache HIT cid: 8.1.10-commandfiles-1-b9fee8b15dbf25a4d90112dcde868368    [debug]
[0.29 sec, 7.37 MB]
Cache HIT cid:                                                           [debug]
8.1.10-annotationfiles-1-90bcfd4c83aa04b96148e19f9b6d112b [0.29 sec,
7.37 MB]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.29        [debug]
sec, 7.38 MB]
Scanning into /etc/drush for /self\.alias\.drush(8|)rc\.php$/ [0.29      [debug]
sec, 7.38 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /.*aliases\.drush(8|)rc\.php$/ [0.29 sec, 7.38 MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/..    [debug]
for /self\.alias\.drush(8|)rc\.php$/ [0.3 sec, 7.38 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.3 sec, 7.39 MB]
Scanning into /home/myuser/.drush for                                  [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.3 sec, 7.39 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.31 sec, 7.39 MB]
Scanning into /home/myuser/public_html/en/../drush for                 [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.31 sec, 7.39 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.31 sec, 7.39 MB]
Scanning into /home/myuser/public_html/en/drush for                    [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.31 sec, 7.39 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/.*aliases\.drush(8|)rc\.php$/ [0.31 sec, 7.4 MB]
Scanning into /home/myuser/public_html/en/sites/all/drush for          [debug]
/self\.alias\.drush(8|)rc\.php$/ [0.31 sec, 7.4 MB]
Scanning into                                                            [debug]
/home/myuser/public_html/en/sites/en.mysite.com for
/.*aliases\.drush(8|)rc\.php$/ [0.31 sec, 7.4 MB]
Scanning into                                                            [debug]
/home/myuser/public_html/en/sites/en.mysite.com for
/self\.alias\.drush(8|)rc\.php$/ [0.31 sec, 7.4 MB]
Drush bootstrap phase : bootstrap_drupal_site() [0.31 sec, 7.4 MB]   [bootstrap]
Initialized Drupal site en.mysite.com at                   [bootstrap]
sites/en.mysite.com [0.31 sec, 7.4 MB]
Find command files for phase 2 (max=6) [0.31 sec, 7.4 MB]                [debug]
Drush bootstrap phase : bootstrap_drupal_configuration() [0.31 sec,  [bootstrap]
7.4 MB]
Find command files for phase 3 (max=6) [0.32 sec, 7.41 MB]               [debug]
sql-query: SELECT 1; [0.32 sec, 7.56 MB]                                [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_0zQeYL --database=myuser_dru600en-3 --host=localhost --silent  < /tmp/drush_yLhbDp
  1
sql-query: SHOW TABLES; [0.33 sec, 7.56 MB]                             [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_gUe2Gu --database=myuser_dru600en-3 --host=localhost --silent  < /tmp/drush_CJUCk8
  access
  accesslog
  actions
  actions_aid
  advanced_help_index
  aggregator_category
  aggregator_category_feed
  aggregator_category_item
  aggregator_feed
  aggregator_item
  antispam_counter
  antispam_moderator
  antispam_spam_marks
  authmap
  bad_behavior_log
  batch
  better_formats_defaults
  blocks
  blocks_roles
  book
  boxes
  cache
  cache_block
  cache_content
  cache_emfield_xml
  cache_filter
  cache_form
  cache_media_youtube_status
  cache_menu
  cache_mollom
  cache_mydropwizard
  cache_page
  cache_panels
  cache_update
  cache_views
  cache_views_data
  captcha_points
  captcha_sessions
  client
  client_system
  comment_notify
  comment_notify_user_settings
  comments
  contact
  contemplate
  contemplate_files
  content_field_additional_information
  content_field_description
  content_field_illustration
  content_field_rubric
  content_group
  content_group_fields
  content_node_field
  content_node_field_instance
  content_type_book
  content_type_content_publication
  content_type_event
  content_type_illustration
  content_type_image
  content_type_issue
  content_type_meeting
  content_type_page
  content_type_panel
  content_type_podcast
  content_type_simplenews
  content_type_story
  content_type_video
  content_type_weblink
  ctools_css_cache
  ctools_object_cache
  date_format_locale
  date_format_types
  date_formats
  discussthis
  discussthis_forums
  drupal_install_test
  excerpt
  fb_app
  fb_user
  filefield_paths
  files
  filestore2
  filter_formats
  filters
  flood
  forum
  fscache
  history
  imagecache_action
  imagecache_preset
  imce_files
  inline
  languages
  links
  links_monitor
  links_node
  locales_meta
  locales_source
  locales_target
  media_youtube_metadata
  media_youtube_node_data
  menu_custom
  menu_links
  menu_router
  moderation_filters
  moderation_roles
  moderation_votes
  mollom
  mollom_form
  node
  node_access
  node_comment_statistics
  node_counter
  node_revisions
  node_type
  nodequeue_nodes
  nodequeue_queue
  nodequeue_roles
  nodequeue_subqueue
  nodequeue_types
  nodewords
  old_revisions
  openid_association
  openid_nonce
  page_manager_handlers
  page_manager_pages
  page_manager_weights
  panels_display
  panels_layout
  panels_mini
  panels_node
  panels_pane
  panels_renderer_pipeline
  path_redirect
  permission
  pm_index
  pm_message
  poll
  poll_choices
  poll_votes
  print_mail_node_conf
  print_mail_page_counter
  print_node_conf
  print_page_counter
  profile_fields
  profile_values
  queue
  relatedlinks
  relatedlinks_tracker
  role
  search_dataset
  search_index
  search_keywords_log
  search_node_links
  search_total
  security_review
  semaphore
  sequences
  sessions
  simplenews_mail_spool
  simplenews_newsletters
  simplenews_scheduler
  simplenews_scheduler_editions
  simplenews_snid_tid
  simplenews_subscriptions
  stylizer
  system
  taxonomy_context_term
  taxonomy_context_vocabulary
  taxonomy_manager_merge
  term_autotagging_data
  term_data
  term_hierarchy
  term_node
  term_relation
  term_synonym
  upload
  url_alias
  users
  users_roles
  variable
  view_argument
  view_exposed_filter
  view_filter
  view_sort
  view_tablefield
  view_view
  views_data_export
  views_data_export_object_cache
  views_display
  views_object_cache
  views_view
  vocabulary
  vocabulary_node_types
  watchdog
  webform
  webform_component
  webform_emails
  webform_last_download
  webform_roles
  webform_submissions
  webform_submitted_data
  weblink
  weblinks
  weblinks_node
  wysiwyg
  wysiwyg_user
  xmlsitemap
  xmlsitemap_sitemap
  xmlsitemap_term
Drush bootstrap phase : bootstrap_drupal_database() [0.35 sec, 7.6   [bootstrap]
MB]
Successfully connected to the Drupal database. [0.36 sec, 7.8 MB]    [bootstrap]
Find command files for phase 4 (max=6) [0.36 sec, 7.8 MB]                [debug]
Drush bootstrap phase : bootstrap_drupal_full() [0.36 sec, 7.8 MB]   [bootstrap]
session_start(): Cannot send session cookie - headers already sent by[1;33;40m[1m[warning][0m
(output started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:1182 [0.36 sec, 7.84 MB]
session_start(): Cannot send session cache limiter - headers already [1;33;40m[1m[warning][0m
sent (output started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:1182 [0.36 sec, 7.85 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:770 [0.38 sec, 9.5 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:771 [0.38 sec, 9.5 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:774 [0.38 sec, 9.5 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:775 [0.38 sec, 9.5 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:797 [0.38 sec, 9.5 MB]
Cannot modify header information - headers already sent by (output   [1;33;40m[1m[warning][0m
started at
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:41)
bootstrap.inc:797 [0.38 sec, 9.5 MB]
Drush command terminated abnormally due to an unrecoverable error.   [31;40m[1m[error][0m
[0.38 sec, 9.53 MB]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <title>Site off-line | </title>
    <link type="text/css" rel="stylesheet" media="all" href="/files/en/css/css_efc0c05aa0cad4c9108b9319f85db325.css" />
<link type="text/css" rel="stylesheet" media="print" href="/files/en/css/css_27bf2b59a4b65e1feaeb43135d7e990a.css" />
    <script type="text/javascript" src="/files/en/js/js_d2fed660346f255db8897c2b7ca69b33.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, { "basePath": "/", "fb_connect": { "front_url": "/", "fbu": 0, "uid": 0 }, "nice_menus_options": { "delay": 800, "speed": 1 } });
//--><!]]>
</script>
    <!--[if lt IE 7]>
      <link type="text/css" rel="stylesheet" media="all" href="/themes/garland/fix-ie.css" />    <![endif]-->
  </head>
  <body>

<!-- Layout -->
  <div id="header-region" class="clear-block"></div>

    <div id="wrapper">
    <div id="container" class="clear-block">

      <div id="header">
        <div id="logo-floater">
        <h1><a href="/" title=" mysite!"><span></span> mysite!</a></h1>        </div>

      </div> <!-- /header -->

      <div id="center"><div id="squeeze"><div class="right-corner"><div class="left-corner">
          <h2>Site off-line</h2>                              <div class="clear-block">
            down for maintenance          </div>
          <div id="footer"></div>
      </div></div></div></div> <!-- /.left-corner, /.right-corner, /#squeeze, /#center -->

    </div> <!-- /container -->
  </div>
<!-- /layout -->

  </body>
</html>

```

# Answer
This usually happens when some code calls `exit()`, e.g. due to a redirect. Any call to `exit()` or `drupal_goto()` must be guarded by `php_sapi_name() === 'cli'` so that it is never called from Drush. You can see that the tests for the 8.x branch are still passing for Drupal 6.
> 1 votes

---
Tags: 6, drush
---


# Question
Title: Limit payments from only certain types of cards
Unfortunately, there was no response to similar question in the Commerce Stripe module's issues queue on https://www.drupal.org/node/2853642, so reposting it here.

For one of the projects I am working on I need to limit to accept only debit cards refusing credit cards. I contacted Stripe and asked if they supported card type limitations and here is what they responded with:

> While there’s no simple setting you can enable or API call that you can make to block certain card types, this can definitely be done with just a bit of programming in your back-end.
>
> Once you’ve created a card token using Stripe.js (or Stripe Checkout), you’ll be able to see the card type by looking at the token object’s `funding` parameter. From here, you could programmatically decide if you want to charge that specific card based on the what that field is populated with. You can read more about token objects at:
>
> https://stripe.com/docs/api#token\_object-card-funding

How do I make it possible to limit payments based on the types of cards used by customers? If there are no ready to use ways, any hints on which exact function to override in a custom module to implement the above suggestion?

# Answer
> 0 votes
Based on the Stripe suggestion I've made the following changes to commerce\_stripe.module file and it works perfectly for us:

```
534,548c534,540
<
<     // According to https://stripe.com/docs/api#token_object-card-funding cards can be of credit, debit, prepaid and unknown types.
<     // For purpose of our project let's decline all card types except debit.
<     if ($card->funding != "debit") {
<       drupal_set_message(t('Only debit cards can be accepted. Please use a debit card.'), 'error');
<       drupal_goto('checkout');
<     } else {
<       // If the card is not declined or otherwise is error-free, we can save it.
<       if ($card && !empty($card->id)) {
<         $stripe_card_id = $card->id;
<         $stripe_customer_id = $card->customer;
<         $c['card'] = $stripe_card_id;
<         $c['customer'] = $stripe_customer_id;
<         $save_card = TRUE;
<       }
---
>     // If the card is not declined or otherwise is error-free, we can save it.
>     if ($card && !empty($card->id)) {
>       $stripe_card_id = $card->id;
>       $stripe_customer_id = $card->customer;
>       $c['card'] = $stripe_card_id;
>       $c['customer'] = $stripe_customer_id;
>       $save_card = TRUE;

```

---
Tags: commerce
---


# Question
Title: How to display parent Taxonomy ID in REST export
I want to configure REST export View in which I display taxonomy term name, id and parent ID. How to insert parent taxonomy term id, why it's not available in FIELDS?

Here is current REST export settings, I only missing parent term ID.

# Answer
> 0 votes
Unfortunately, this is currently not yet supported. We're working to add that capability in https://www.drupal.org/node/2543726.

Long story short: the `$term->parent` field is a special snowflake: it's *not* an entity reference field as you would expect!

---
Tags: views, 8
---


# Question
Title: Price not updating on custom theme template
I have a theme with a custom product display template. I created a product display with different product variations; when different variations are selected, the price doesn't seem to be updated to reflect the product variation chosen.

It seems to be a problem with the theme as it works with standard themes.

I tried different jQuery versions and doesn't seem to be any JavaScript error. I've read somewhere that it could be the the price not being wrapped with the appropriate classes. If that's the case, how do I fix that?

# Answer
What you've heard is correct: Drupal Commerce adds classes around product fields that allow the Add to Cart form to target those rendered fields for replacement when attributes are selected. This is why in their absence you won't see prices updated at all.

The simplest way to illustrate it will be to simply look at the HTML on a site with a working theme and your custom theme to see what those classes look like.

The classes exist in the render arrays for these fields, so you simply need to ensure your theme is properly including the HTML element attributes for these rendered fields. Again, for that I'd simply advise you to look at working theme code to see how it's done elsewhere.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to load a view with ajax with all js files needed?
I am using this function to load three views which are loading comments of a node in three tabs by three different sort types by ajax:

```
function sort1(){
var nid='<?php echo $node->nid; ?>';
$.ajax({
    url: 'http://www.example.com/views/ajax',
    type: 'post',
    data: {
        view_name: 'comments_views',
        view_display_id: 'block_3',
        view_args: nid,
    },
    dataType: 'json',
    success: function(response){
        $('#cm').html(response[1].data);
    }
});
    return false;
}

```

And for other two views there exist a similar function.

Now what is the problem?

These comments can be replied and voted. But after switching between tabs nether reply nor vote works by ajax. I am using ajax\_comment module in order to make it work by ajax and voteAPI and Rate module for rating comments.

I think views is failing in loading js of views.

what is the solution?

# Answer
> 0 votes
What you did is a HardCode solution ,I suggest you instead of loading JS on block, put your JS in `.JS` files and add ( or attached) to page you want, with simple if your JavaScript just works for you, and remain only one problem, how pass NID to JS?

Pass it with something like

```
drupal_add_js(array('YOURMODULE' => array('nid' => $nid)), array('type' => 'setting'));

```

and get it on your js with

```
nid = Drupal.settings.YOURMODULE.nid;

```

1 down vote

There is a lot of documentation about how to include a JS file into a custom module or into your theme in general. Here is the official article: https://www.drupal.org/node/304255

There are plenty of examples and you can inspire yourself with it.

---
Tags: 7, views, ajax, comments, rating
---


# Question
Title: How to give anonymous users access to only certain nodes?
I am trying to implement the following: Anonymous users are not allowed to view all nodes but only certain nodes.

I am using tac lite (https://www.drupal.org/project/tac\_lite) to make this happen.

However, the only way I am currently able to control permissions to view nodes is the following:

not giving anonymous user the role 'View published content' and configuring tac\_lite or other content access module to allow access to anonymous user to certain pages =\> doesn't work, access denied when testing nodes that user should has access to see

giving anonymous user the role 'View published content' =\> doesn't work, now anonymous users will see all the nodes regardless of settings of any other content access modules

Problem is not related to tac\_lite. It also happens with for example node view permissions -module https://www.drupal.org/project/node\_view\_permissions.

Also, when trying to solve the problem this page caught my eye: https://www.drupal.org/node/270000 It says: "Only users who have 'access content'/'view published content' and not 'administer nodes'/'bypass node access' are eligible for the wild world of node access module control.."

I have understood that access control with Drupal is additive. Thus I should not give the anonynomous user the permission to 'view published content'. Yet, the text from https://www.drupal.org/node/270000 seems to contradict with this approach.

This is what devel node access shows when

* I have set 'view published content' permission off for anonymous user
* I have configured tac lite to show that page to anonymous user
* I visit the page as anonymous user

# Answer
> 1 votes
You can use the Rules module for this.

Here is a prototype of a rule (in Rules export format) to get you going:

```
{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "some\/path1",
                  "some\/path2"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/something",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed for Anonymous users.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

Adapt the paths in it to fit your own needs, to reflect all the paths that anonymous users should ***not*** be able access. And for any access module you have enabled, allow access for anonymous users also (any paths that fit in the Rules Conditions will be blocked by the above rule, while any path that does not fit can be accessed by anonymous users). Obviously, using the "negate" facilities or Rules, you could also rework this prototype rule so that you only specify the paths allowed for anonymous users.

# Answer
> 1 votes
You could use the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

For details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?". With these roles in mind, you could configure access to group content like so:

* ***Members*** and ***Outsiders*** have access to all nodes.
* ***Anonymous users*** do not have access to any nodes.

With this configuration, for any node that belongs to a group the Group module will block access for anonyous user (of course). But for those "certain nodes" (as in your question) that you do want anonymous users to be able to access them, just do not assign these nodes to a group (so that the Group access rules don't apply at all).

### Resources:

---
Tags: 7, nodes, users
---


# Question
Title: How can I set up Drupal so people can collaborate on content development prior to making it public
I have a small website which, from a modules perspective, I want to keep as simple as possible.

Apart from displaying content, a main purpose of the site is to facilitate collaborative authoring and publishing of: articles, product updates and case studies.

To achieve this I would like individual contributors to be able to create & edit content prior to public release (just to be clear, I'm not looking for concurrent editing here).

This seemingly simple requirement leaves me stumped because unpublished content seems unavailable for further editing by the original creator, let alone co-collaborators.

Similarly, some items of content will need periodic updating. To achieve this I expect they will need to be reviewed, updated & debated offline, but in a way that leaves the current version public. The update process needs to allow multiple authors to edit in private prior to republishing / making the updated content public.

I'm at a loss as to how this is most easily achieved - would appreciate any advise that leads to a simple solution.

# Answer
> 5 votes
The near defacto-standard for this in Drupal 7 is the Workbench Moderation module, which is part of the broader Workbench suite. From the module page:

> Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.

and about Workbench in general:

> Workbench is a suite of modules which provide easier content management for content administrators. Each of the "Workbench" modules has been tested to work with the main Workbench module, and with the other modules in the Workbench suite. The Workbench suite is modular, allowing site builders to build the workflow that best suits the content administrators on their site. The Workbench suite provides authors, editors, and publishers with a unified interface for managing content relevant to them. It allows people to focus on content, rather than on learning Drupal.

This is highly tailorable to your particular organization, and all organizations differ. You didn't list out a lot of additional requirements, but typically you would create roles (Author, Editor, Publisher, Admin), and then define which role can do what (eg, Authors can only edit their own content, Editors can edit all, but only Publishers can make nodes public). Additional controls can be implemented with Workbench Access.

I have deployed solutions based on this for many organizations, mostly with success. I also like this solution, compared to others, as this module suite is "site-builder friendly". This means, that I can get the basics going for a site, and then have non-developers on the team work with clients to tailor it for their needs.

When it doesn't work well, it is usually because the organization doesn't really *want* content workflows as opposed to *needing* them.

This solution is also providing the base for the Content Moderation initiative for Drupal 8.

That said, depending on your situtation Groups / Organic Groups may be a better fit (as described in another answer). I would take both solutions for a test drive to see what works best for you.

# Answer
> 0 votes
A commonly suggested solution for this often *starts* with using the Workbench Moderation module. However, IMO only using that module is often not sufficient to address things such as "collaboration" (as in your question). Read on for some other options that are available using existing modules which integrate pretty well with each other.

### Option 1

Have a look at my answer to "How to implement a multi step approval with webforms/entityforms based on form components?". It explains how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

### Option 2

Another alternative you may want to consider (or combine with the previous approach) is to start using the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?".

Resources:

---
Tags: 7
---


# Question
Title: How do I add Google Scholar meta tags to a custom content type?
I use drupal 7 and I have custom content type named "Journal"
I want add Google Scholar meta tags to "Journal" nodes.
Like this:

```
<meta name="citation_journal_title" content="Journal Name">
<meta name="citation_authors" content="Last Name1, First Name1; Last Name2, First Name2">
<meta name="citation_title" content="Article Title">
<meta name="citation_date" content="01/01/2007">
<meta name="citation_volume" content="10">
<meta name="citation_issue" content="1">
<meta name="citation_firstpage" content="1">
<meta name="citation_lastpage" content="15">
<meta name="citation_doi" content="10.1074/jbc.M309524200">
<meta name="citation_pdf_url" content="http://www.publishername.org/10/1/1.pdf">
<meta name="citation_abstract_html_url" content="http://www.publishername.org/cgi/content/abstract/10/1/1">
<meta name="citation_fulltext_html_url" content="http://www.publishername.org/cgi/content/full/10/1/1">
<meta name="dc.Contributor" content="Last Name1, First Name1">
<meta name="dc.Contributor" content="Last Name2, First Name2">
<meta name="dc.Title" content="Article Title">
<meta name="dc.Date" content="01/01/2007">
<meta name="citation_publisher" content="Publisher Name">
<meta name="robots" content="noarchive">

```

I tried the Metatag and Custom Meta modules. With the Metatag module, I can't add custom meta tags; with the Custom Meta module, I can't add custom meta tags to a content type.

How can I achieve this?

# Answer
> 2 votes
There is a module that allows adding Google Scholar meta tags: https://www.drupal.org/project/metatag\_google\_scholar . However, it is only available for Drupal 8.

I post this answer anyway, in case it might be useful (as an inspiration for a backport, for instance).

# Answer
> 1 votes
The Metatag module doesn't provide a UI for custom tags, but it does have an API for defining new tags. If you want to go down this route, look at the included Darwin Core sub-module for how it implements `hook_metatag_info()`. That should give you enough of a head start for the Google Scholar schema.

Once you have defined your custom `hook_metatag_info()` with all of the field you need, they will appear in the normal places where you can add Metatag information, and also be able to use the normal tokens as defaults, if desired.

I have used this technique for other formal taxonomy metadata (eg, Darwin Core).

---
Tags: 7, meta-tags
---


# Question
Title: How to format JSON data response from a view defined by relationships to content types related by entity reference fields
I have a content type **event** with content name of the event, event image, a relatioship to **organizer** another relatioship to **participant** and another relationship to self **event** that i call programs. Now I want to make a view which return me a datasource json like

```
{
    date:"10/10/2017"
    event:[
        {
            img:"image",
            description:"description",
            date:"date complet",
            program:[
                {
                    title:"titre",
                    description:"description",
                    date:"",
                },
                {
                    title:"titre",
                    description:"description",
                    date:"",
                }
            ],
            organizer:[
                {
                    name:"chis",
                    description:"description"
                },
                {
                    name:"chis1",
                    description:"description"
                }
            ],
            participant:[
                {
                    name:"zina lacina",
                    titre:"consultant"
                }
            ]
        }
    ]
}

```

The result is grouping by the date.

# Answer
> 0 votes
Try the Views Field View module. It gives you exactly what you need. Just add a view in your view wherever you have 1:n relationships. Setup views for program, organizer and participant and add a contextual filter for the event.

The result will be one event appearing once in your view.

---
Tags: entities, services, views
---


# Question
Title: Shopping cart not cleared after checkout
I have had several customers who have been able to make changes to previously placed orders. Even though the order status is set to pending after checkout is complete and their payments are processed, they are able to go back into the shopping cart (which should be empty but is not) and delete items from the cart. They then believe that the payment amount will be adjusted to reflect the new total of items left in the cart, but of course it will not, as the original amount has already been charged to their card by Elavon. Why does the cart still contain items already ordered? How do I prevent this from happening?

# Answer
This looks like a permission issue. Check the permissions page `admin/people/permissions` and make sure only relevant roles can edit orders.

By default, **only the following permissions should be granted** to authenticated users, and to any *customer role* you may have created :

* *Create Order orders*, optionally *Create orders of any type*
* *View own Order orders*, optionally *View own orders of any type*

About the items remaining in shopping cart after checkout, have you tested yourself ? I'd more believe your customers edited orders from their orders page if they had permission to... Else, a custom rule or a custom module may cause that behaviour.

As explained in drupalcommerce.org

> At the heart of Drupal Commerce is the ubiquitous Order. This Order is first created when a user adds a product to a cart. The Order is actually the "cart" when it has a status of "Shopping Cart."

Cart is only one of the possible states of an order.
> 0 votes

---
Tags: commerce
---


# Question
Title: Why is the View import option not shown in the views UI?
I'm trying to export/import a view from a dev site to a qa site. Views UI is enabled. However, when I go to structure\>views I don't see the "+ import view" option, only:

"+ Add new view" "+ Add new view from template"

Anybody any idea?

# Answer
1. If the user you are logged in has the **Administer Views** permission, if not then give this permission.
2. Also enable the 'PHP filter' core module.
3. Give the relevant user role the **Use PHP for settings** permission.
4. Paste the below url after your current url and you will see the import views page.

admin/structure/views/import
> 32 votes

# Answer
You should either have sufficient permissions ("administer views" permission) or be logged in as user #1. If you not logging in as user #1, you will also need to have the permission "use PHP for settings" because of an issue in Views.

Then you should be able to go `admin/structure/views/import` and import your view.
> 2 votes

# Answer
Most likely you're looking in the wrong place. The Export option you used is in the drop down on the View line in your list of Views, while the Import option is at the top of the Views master page as a tab. Took me a while to notice that as I expected the Import option to be in the same drop-down as Export.
> 1 votes

# Answer
Another reason might be that you are using the paranoia module, which disables a lot of php-run features like this.
> 0 votes

---
Tags: views
---


# Question
Title: How to migrate multilingual content from CSV to Drupal 8?
I come from read Using the new Drupal 8 Migration API / Module and Content Migration: CSV to Drupal 8 the process to create a migration is very clear and its works, but I can't find how to migrate content to a Multilingual site. In the Migrate API overview I can't find any information about this.

So, how can I migrate multilingual content?

**UPDATE:** I found an example: https://github.com/drupal/drupal/tree/8.3.x/core/modules/migrate/tests/modules/migrate\_external\_translated\_test

I was able for the moment to migrate the english content but not the translations.

# Answer
**Migrate from CSV basics**

As stated elsewhere, the migration code has only recently (as of 8.2.x or 8.3.x) seemed to settle down and there are loads of old, outdated and incorrect instructions in blog posts around the web. That being said, I've had about 75% success following the instructions on these two sets of blog posts from Lucas Hedding and Ada Hernández at Mtech.

There is an accompanying example codebase Lucas setup at Github that covers the basics of the first CSV blog post example, but it doesn't include any helpers with the image or file migrations.

There is another example repository from Wunderkraut that does include a CSV example migration with user, taxonomy, articles and images migration here:

**Multilingual migration from CSV**

I recommend starting with the CSV basics above, then moving to this section. You really need to have separate migration scripts for each language.

I got an additional 20% of the way there with this blog post, that outlines the details how to modify a migration yaml file to support *multilingual content* including, to enable `translations: true` in the `destination` section, to add the the `langcode:` field in the `process` section for proper multi-lingual entities (like nodes and terms), and to add the `language:` parameter for specific multi-language field processing.

I've found the most difficult part to be figuring out how to import file or image fields (the remaining 5% for me). Neither of the examples above demonstrate how to import image alt fields properly. In my case I have an image field that shares the image, but the alt attribute is translatable. I figured out how to import the basic alt field to the default language node on my own, but I'm having trouble getting the import to use the same fid but different alt text for other languages. The solution was figured out by user @Vasi by adding an additional field called `content_translation_source` on the process step of the foreign language migration YAML. More details with complete example here:

**Additional Discussion**

Finally, there is some discussion going on here as well:
> 4 votes

# Answer
you need both migration-tasks, the yml files in the migration folder:

```
migrate.migration.external_translated_test_node.yml
migrate.migration.external_translated_test_node_translation.yml

```

Then in the Plugin (MigrateExternalTranslatedTestSource.php), you need to read your .csv (in `initializeIterator()`) into the structure of the import array:

```
  /**
   * The data to import.
   *
   * @var array
   */
   protected $import = [
    ['name' => 'cat', 'title' => 'Cat', 'lang' => 'English'],
    ['name' => 'cat', 'title' => 'Chat', 'lang' => 'French'],
    ['name' => 'cat', 'title' => 'Gato', 'lang' => 'Spanish'],
    ['name' => 'dog', 'title' => 'Dog', 'lang' => 'English'],
    ['name' => 'dog', 'title' => 'Chien', 'lang' => 'French'],
    ['name' => 'monkey', 'title' => 'Monkey', 'lang' => 'English'],
   ];

```
> 3 votes

---
Tags: 8, migrations, importing-exporting
---


# Question
Title: Where do I set the HTML that wraps a module's config $form inputs?
I am transferring a module from one site to another. All is well except the modules form (where I set settings, upload images, etc). On the original site this is nicely wrapped in a table with each section being a row, but on my new site the form elements are just placed in one after the other, appearing vertically. This is despite me copying the modules .inc, .tpl and .module files almost verbatim.

I'm new to Drupal in general so am struggling with this a bit. Would anyone know where this is set (what file, what function)?

```
function gallery_grid_theme($existing, $type, $theme, $path) {
  $items = array();

  $items['gallery_grid'] = array(
    'render element' => 'element',
    'path' => drupal_get_path('module', 'gallery_grid') . '/plugins/content_types/gallery_grid/templates',
    'template' => 'gallery-grid',
    'variables' => [],
  );

  // Draggable table for gallery-grid admin form.
  $items['gallery_grid_draggable_form'] = array(
    'render element' => 'fieldset',
    'file' => drupal_get_path('module', 'gallery_grid') . '/plugins/content_types/gallery_grid/gallery_grid.theme.inc',
  );

  return $items;
}

```

Contents of gallery\_grid.theme.inc:

```
function theme_gallery_grid_draggable_form($variables) {
  $fieldset = $variables['fieldset'];
  $rows = array();

  // Table for the items.
  foreach (element_children($fieldset) as $key) {
    $fieldset[$key]['weight']['#attributes']['class'] = array('item-weight');
    $rows[] = array(
      'data' => array(
        render($fieldset[$key]['image_file']),
        render($fieldset[$key]['image_url']) . render($fieldset[$key]['image_title']),
        render($fieldset[$key]['delete_row']),
        render($fieldset[$key]['weight']),
      ),
      'class' => array('draggable'),
    );
  }

  // Header and render.
  $header = array(t('Image *'), t('Image Settings'), t('Actions'), t('Weight'));
  $table_id = 'items-table';
  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => $table_id),
    'sticky' => FALSE,
  ));

  // Add tabledrag.
  drupal_add_tabledrag($table_id, 'order', 'sibling', 'item-weight');
  return $output;
}

```

# Answer
Did you look at form templates? The steps change a little if you are using a starter theme, but the basics are the same.

http://themery.com/dgd7/advanced-theming/forms/with-templates
> 0 votes

---
Tags: 7, theming, configuration
---


title: Converting Image Map to Drupal Content

text:
# Question
Title: Converting Image Map to Drupal Content
We have an old site that was are migrating to drupal. On the old site we have an image map: http://www.seguridadidl.org.pe/districts.html

Wondering if there is a more dynamic way of adding an image map such as this to drupal, rather than just adding the html in a node.

Does the "onMouseOver" work in Drupal?

# Answer
> 1 votes
I think the Google Maps Tools module is the right solution. Just parse or migrate your data into it.

> This project integrates the Google Maps API and Google Static Maps API. It makes possible to add addresses and/or coordinates (points) to nodes through CCK fields, display these geographical informations on node pages as text or interactive map or static map and use them on GeoRSS feeds. The project provides style plugins and row style plugins for views to build both interactive and static maps.

# Answer
> 1 votes
You can add the image map to any full HTML enabled text area... so you could drop it into content, put it in an text area field, or put it in a block. You can also drop it in a template file....

# Answer
> 0 votes
An imagemap is just a set of coordinates that map a mouseover to an area in your map.

A quick google and I dont see any Drupal related imagemap modules. You could try to store coordinates as a field in your node. But, that sounds messy. An imagemap basically assumes a user has intimate knowledge of the image to properly build the coordinate sets.

`onMouseOver` is a Javascript event. HTML, CSS, the HTTP protocol, Javascript all work together to power the internet nowadays; so of course you can use Javascript code in a Drupal website. Drupal is simply a PHP CMS making use of all these things ... So long as the client browser supports it -- you're fine.

---
Tags: media
---


title: Image source path - secure way

text:
# Question
Title: Image source path - secure way
which is the secure way of displaying the image\_path in src ?

```
`a. <img src = "<?php print check_url($image_path) ?>" />`
b. <img src = "<?php print check_plain($image_path) ?>" />
c. <img src = “<?php print htmlspecialchars($image_path) ?>” />
d. <img src= “<?php print strip_tags($image_path)?>” />

```

# Answer
> 0 votes
check\_url basically checks for dangerous protocols in the url and escapes any special characters as HTML entities for output. Normally it's not needed unless outputting a raw external / absolute URL. For relative URLs, Drupal adds the base url automatically.

better to use first(a) option.

---
Tags: theming, media
---


# Question
Title: Display all nodes with actually viewed taxonomy term
I have an taxonomy term.

I want to display all nodes that has this term assigned just under the taxonomy term description.

So when user goes to page with the taxonomy he can see the description (that works by default) but also e.g. teasers of all nodes that has this term in field. I guess I have to somehow use view with some filter, but I cannot get it working.

I added the view with block that I've put into structure -\> block layout.

I can display all the nodes that has `field1` set to `term A` by adding (to view) Filter criteria `field1 = term A`. But this is "hardcoded" and I need `term A` to be another term based on which term page am I visiting.

For example, when I visit page of `term A` I want to display all nodes that has `field1` set to `term A`. But when I look for `term B` page, I want to list all nodes with `field1 = term B` in my view.

# Answer
> 0 votes
There is a default view related to taxonomy term u can make use of it and change accordingly it will solve ur problem.

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


# Question
Title: How to disable a test.php file without deleting it?
In D8 I have failing automated tests due to a depend modules code problems. The tests should not be deleted as they will be reinstated when the other module is fixed. I tried changing the test function names to start with something other than 'test' but this gave the warning "there are no tests in this class" and failed just the same. The tests are based on BrowserTestBase.

I want to commit a change so that the rest our automated tests can run, as this problem is making it appear that every patch fails. I do not want to comment out the entire test file - there must be a better way to highlight the fact that these tests should not be run when the rest of the test suite is

# Answer
> 0 votes
It can be done by editing the info file, in Drupal 7.

```
name = myModule
description = My module
core = 7.x
testing_api = 2.x // remove this line
files[] = myModule.module
files[] = myModule.install
files[] = tests/myModule.test // remove this line

```

I am not sure in the case of Drupal 8.

---
Tags: testing
---


title: Upload an image to a node and term

text:
# Question
Title: Upload an image to a node and term
I need to upload an image to a term as well as to a node using BEHAT with Drupal API. How this can be possible?

# Answer
> 2 votes
You need to define a Behat step for it. A possible way would be to define a method to be executed before creating a node (labelled with `@beforeNodeCreate`), to upload the file first and then to attach its `fid` to the appropriate file field of the node or term.

A possible way of doing it (for Drupal 8) is explained in detail here: https://webscope.co.nz/testing-image-and-file-fields-with-behat

---
Tags: testing
---


# Question
Title: How to pass data from a Rules Action to a subsequent Rules Action?
How I can add actions in the Rules module in which they have a relationship with each other sequentially.

I mean a 1st Rules Action sequentially passes data to a next Rules Action and in that next Rules Action I can use those passed data from previous data.

# Answer
> 0 votes
I think you can pass data with `Variables` , in one action set variable(s) and in next action get that variable(s),this have one bug if concurrent event occur data will return mistake values, a solution for this is using unique variable name per user(or action), I get you a clue (maybe you get idea from it)

**in Action1**
set Php action

```
 global $user;
 // some job here
 // $result= .....
 variable_set("action1_result-".$user->uid, $result);

```

**in Action2**
set Php action

```
 global $user;
 variable_get("action1_result-".$user->uid);

```

# Answer
> 0 votes
***Assumption***:

Your rule has 2 Rules Actions (Action 1 and Action 2). And you want to pass "some data" created by Action 1 as input to Action 2.

***Solution***:

1. Create a Rules Component which does the same as "Action 1", say you name it "*RulesComponentAction1*".
2. Create a Rules Component which does the same as "Action 2", say you name it "*RulesComponentAction2*".
3. Adapt your original rule so that you replace Action1 in it by the execution of Rules Component named *RulesComponentAction1*.
4. Adapt your original rule so that you replace Action2 in it by the execution of Rules Component named *RulesComponentAction2*.
5. Improve your *RulesComponentAction1*, by adding within its *Settings* an extra variable with `Usage=Provided` (and whatever Data Type that fits your needs). Say you name it `VarFromAction1`.
6. Improve your *RulesComponentAction2*, by adding within its *Settings* an extra variable with `Usage=Parameter` (and a Data Type that matches the data type you selected in the previous step). Say you name it `VarForAction2`
7. Adapt your original rule so that you pass the extra parameter `VarForAction2` to your Rules Component *RulesComponentAction2*, using as a token ... you guessed it ... the value of `VarFromAction1`.

**Note**: By using the Rules Session Variables module you might be able to further extend the above solution to 2 separate rules that get executed one after the other.

---
Tags: 7, rules, actions
---


# Question
Title: Submitting a form, when using the same form with different ID are on a page
Here is what happens: I've create a content type poll, which admin can create polling questions and answers. Then this polling node will be rendering in a new Page node with node reference (using paragraph).

I manage to create a paragraph preprocess on .theme which will pass the NID to the buildForm.

Here is how it looks like on preprocess:

```
function THEME_preprocess_paragraph__poll_and_sidebar(&$variables) {
  $paragraph = $variables['paragraph'];
  $poll_form = '';
  if (!$paragraph->field_poll_content->isEmpty()) {
    $node_id = $paragraph->field_poll_content->getValue();
    $nid = $node_id[0]['target_id'];
    $poll_form = \Drupal::formBuilder()->getForm('Drupal\mypoll\Form\PollForm', $nid);
  }
  $variables['poll_form'] = $poll_form;
}

```

The myPoll buildForm module:

```
 public function buildForm(array $form, FormStateInterface $form_state, $nid= null) {

if (!$nid == null) {

  // check if user have voted
    $get_count_voter = $this->queryVoter($_COOKIE['cusid'],$nid);

  // Function on node load
    $poll_form_result = $this->getPollDetail($nid);

    $each_answer = [];

    foreach ($poll_form_result['answers'] as $answer_value) {
      $each_answer_id = $answer_value->id();
      $each_answer['answer'][$each_answer_id] = $answer_value->get('field_polling_answers')->value;
      $each_answer['calc'][$each_answer_id] = $answer_value->get('field_answers_calculation')->value;
    }

    $answer_type = 'checkboxes';

    if ($poll_form_result['poll_type'] == 'linear' || $poll_form_result['poll_type'] == 'multiple_2') {
      $answer_type = 'radios';
    }

    $form['poll_'.$nid] = [
      '#markup' => '',
    ];

    $form['poll_'.$nid]['headline'] = [
      '#markup' => '<h3>' . $poll_form_result['headline'] . '</h3>'
    ];

    $form['poll_'.$nid]['question'] = [
      '#markup' => '<p>' . $poll_form_result['question'] . '</p>'
    ];

    $form['poll_'.$nid]['sub_question'] = [
      '#markup' => '<p class="poll__question">' . $poll_form_result['sub_question'] . '</p>'
    ];

  if ($get_count_voter == true) {

    $form['poll_'.$nid]['answers'] = array(
      '#type' => $answer_type,
      '#options' => $each_answer['answer'],
    );

    $form['poll_'.$nid]['poll_type'] = [
      '#type' => 'hidden',
      '#value' => $poll_form_result['poll_type'],
    ];

    $form['poll_'.$nid]['poll_user_cookie'] = [
      '#type' => 'hidden',
      '#value' => $_COOKIE['cusid'],
    ];

    $form['poll_'.$nid]['poll_nid'] = [
      '#type' => 'hidden',
      '#value' => $nid,
    ];

     $form['poll_'.$nid]['actions']['#type'] = 'actions';
      $form['poll_'.$nid]['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#button_type' => 'primary',
      '#name' => 'submit-'.$nid,
      '#attributes' => array(
        'class' => array(
          'button--darkblue'
       ),
        'id' => array(
          'submit-'.$nid
        ),
      ),
   );

  } else {

    $form['poll_'.$nid]['result'] = [
    '#markup' => $this->t('RESULT'),
  ];

  }
    return $form;
}
}

```

On 1 page there will be more than 1 polls, for this example, I will have 2 sets of polling and it was successfully display 2 sets of forms but when I click submit button on the 2nd form , and trying to dump `$form_state`, it always pickup the 1st form value.

Is there a way I can define the Form ID by NID or any suggestion on fix?

Thanks, Queenie

# Answer
> 4 votes
You need to call your form like this:

```
$form = new Drupal\mypoll\Form\PollForm($nid);
$poll_form = \Drupal::formBuilder()->getForm($form);

```

Then add this methods to your form class:

```
protected $nid;

public function __construct($nid)
{
  $this->nid = $nid;
}

public function getFormId()
{
  return 'my_form-' . $this->nid;
}

```

And you need to make sure that $nid is different each time the form is on the page.

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


# Question
Title: How can I set default value (prepopulate) for field in views exposed filter?
I've tried to use solution from Can I prepopulate an exposed filter text field? but failed. Cache clearing does not help.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-test-populate-page" ) {
    $form['title']['#default_value'] = 'test title';
    dpm($form);
  }
}

```

# Answer
> 1 votes
I figured it out as below with **hook\_views\_pre\_build**.

```
function module_views_pre_build(&$view, &$display_id, &$args) {
    if ($view->name == 'VIEW_NAME') {
        $view->display['page_1']->handler->handlers['filter']['title']->value = 'Test title';
    }
}

```

Replace 'page\_1' with the correct display\_id.

# Answer
> 0 votes
Dimetry. Since it is a drupal view you can add the default value in views itself. Please open your view and in the **Filter Criteria** section select the field you want to add the default value. It opens up a popup in that you can able to see "Value" field. Please give your default value there.

Please see the below picture for your reference.

---
Tags: 7, views
---


# Question
Title: How can I schedule a rule to always be run at a specific hour of the day?
I have a rules component that sends me an e-mail containing a view that contains certain statistics about my site.

I'd like to have this e-mail sent at midnight every day.

The rule looks like this:

**Component: Action set**

1. Send e-mail
2. Schedule the component again for evaluation (+1 day)

I then triggered the rule manually at midnight and waited for it to evaluate again. This worked for the first several days but now the e-mail is arriving at 3 or 4 in the morning instead of at midnight. I really want the e-mail to be sent at the same time every day (or as close to the same time as possible every day). Is there a way to do this?

# Answer
To finally answer the original question in the title, you can run a rule at a specific hour of the day by writing for example

```
today + 9 hour

```

"today" is always the actual day at 0:00:00, "+ X hour" adds any number of hours to this. Note that "hour" is written in singular. Other keywords could be "month", "week", "day", "minute" or "second". You can combine keywords. There's a lot more, refer to this page for further details:

http://php.net/manual/en/datetime.formats.relative.php
> 2 votes

# Answer
How about this:

When you're setting the time in the "Scheduled Evaluation Date" section, change it from 'Direct input' to 'Selection mode', and scroll down to where it gives you the option for 'PHP Evalution'

Paste in the following:

```
<?php
$midnight = strtotime('midnight');
echo date("Y-m-d h:i:s", $midnight);
?>

```

This should return something like '**2013-03-25 12:00:00**' // That's what it's returning for today!

You have to include the php brackets. The strtotime() function should return back midnight of the **current day**, so it should work for you. I'm thinking since this is based on your cron running, it will not be exact and this should evaluate a little past midnight and 'midnight of the current' day should be exactly what you need. Maybe you can find a php tweak that makes this better...

Anyway, let us know if that works!
> 5 votes

# Answer
I've written a module that might do what you want more reliably:

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

The rule event is triggered by cron, but you can specify which hour of the day the event occurs, and it will be run the first time cron runs after that hour.

As well as specifying which hour of the day the event triggers after, there are also day-of-the-week conditions to allow you to specify which days the event can run on.
> 3 votes

---
Tags: 7, rules
---


# Question
Title: Copy same content date fields values to separate content types by rules
What i want to do is this...

I have a content type (A) with two date fields (date\_1 and date\_2) Then i have two more content types with existent date\_1 field created. (Must be this way)

Schema: A: date\_1 and date\_2 B: date\_1 C: date\_1

An existing rule creates (every time a new node of content type A is created) a new content node of type B, copying the A:date\_1 value to the B:date\_1 value. That was easy... and it works just perfect.

Now, what i want to do is the (almost the) same with the content type C. Except for the source field to be copied, that should be date\_2

The rule should be something like this: "Every time a node of content Type A is created: Create a new node of content type C and copy the date\_2 value from node A, then paste it into the new entity field date\_1...

Almost the same, except that when i want to select the source field, date\_2 is not listed and i cant select him.

Is there any way to solve this?

Thanks a lot

# Answer
> 0 votes
field: date\_2 is not listed because of a field configuration mismatch between both fields. Everything MUST match between them.

---
Tags: entities, rules, datetime
---


title: Custom container.html.twig

text:
# Question
Title: Custom container.html.twig
I need to delete a div made by the container.html.twig. How can I rename this template to this specific region?

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'container' -->
<!-- BEGIN OUTPUT from 'themes/newbikes/templates/system/container.html.twig' -->
<div class="form-group">

```

thx.

# Answer
Copy core template to your theme template folder (yourtheme/templates) core/themes/stable/templates/form/container.html.twig and clear caches.
> 1 votes

---
Tags: views, theming, 8
---


# Question
Title: How to get block layout programmatically?
Sorry there won't much details but the title is self explanatory.

I need to fetch the block layout of the front page and build a menu from it.

So the question is: How can I get that list programmatically?

# Answer
You can get the block layout programmatically from the configured blocks by going through each region defined in the current theme:

```
  $block_layout = [];
  $theme = \Drupal::theme()->getActiveTheme();
  $regions = $theme->getRegions();
  foreach ($regions as $region) {
    $blocks = \Drupal::entityTypeManager()
      ->getStorage('block')
      ->loadByProperties(['theme' => $theme->getname(), 'region' => $region]);
    uasort($blocks, 'Drupal\block\Entity\Block::sort');
    $block_layout[$region] = array_keys($blocks);
  }

```

This is without checking if the blocks are visible on the front page. That would be difficult, because the visibility condition plugins are context aware and only provide a correct result when they are called in a real front page context.
> 1 votes

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


# Question
Title: Is there any option to add file upload/attachment field in webform?
Is there any option to add file upload/attachment field in webform for Drupal 8?

My webform version is 8.x-5.0-beta7+20-dev

# Answer
> 4 votes
Will need to define the private file system to get the web form upload fields. By default the private file system was not defined that's why the upload fields were not showing up. After defining the private file system through the settings.php file and clearing the cache I found several upload fields option to add in the form.

---
Tags: 8, webforms
---


# Question
Title: How do I programmaticaly get the name/ID of the shipping method for an order?
I need to get the name of the shipping method for a given order in my module. I have the id of the order. After I get the shipping info by means of `commerce_customer_profile_load($commerce_order->commerce_customer_shipping['und'][0]['profile_id'])` i do get the info about the address, but I do wonder how to get the name / id of the shipping method.

# Answer
> 0 votes
I found a good answer at https://drupalcommerce.org/discussions/8274/get-shipment-services-object-flat-rate-order-object

```
// Be sure there are line_items
if (!empty($order->commerce_line_items["und"])){
  $line_items = array();
  // Gather together the IDs of the line items
  foreach($order->commerce_line_items["und"] AS $line_item){
    $line_items[] = $line_item["line_item_id"];
  }
  // load_multiple allows us to use $conditions so we only load the entity of type "shipping"
  $shipping_line_item = commerce_line_item_load_multiple($line_items, array('type' => "shipping"), FALSE);
}

```

---
Tags: commerce
---


title: How can I run a database query in code?

text:
# Question
Title: How can I run a database query in code?
I want something like `SELECT nid FROM node WHERE type = "blablabla"`.

How do I do this in Drupal 8 PHP code?

# Answer
You would use the database abstraction layer.

```
$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute();

```

As for executing the query, you can also fetch results in various ways.

Examples:

```
$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAll();

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAllAssoc('nid');

```

If you are within a class, you should inject the appropriate classes in your constructor instead of use the static Drupal container. But since you are in a preprocess function, `\Drupal::database()` is fine.

From `core/lib/Drupal.php`:

```
 /**
   * Returns the current primary database.
   *
   * @return \Drupal\Core\Database\Connection
   *   The current active database's master connection.
   */
  public static function database() {
    return static::getContainer()->get('database');
  }

```

Depending on your use case(s), you can also leverage EntityQuery:

```
$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$results = $query->execute();

```

Please note that you may want to use `node_field_data` table instead of `node`, but your query is pretty generic so it is hard to tell without a better query.

Example, get all nodes of type that are published:

```
$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->addField('nfd', 'nid');
$query->condition('nfd.type', 'blablabla');
$query->condition('nfd.status', 1);
$results = $query->execute();

```

Or:

```
$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$query->condition('status', 1);
$results = $query->execute();

```
> 17 votes

---
Tags: 8, database
---


# Question
Title: How can I prevent HTML tags getting rendered as plain text?
I have my data from SQL with table HTML tags e.g. `<tr>` and `<td>`.

When I render it in Views it displaying all the HTML table tags without rendering it.

I put some code in `.module` file to pass this data using `hook_views_post_execute` I tried all the solution but nothing seems to work.

My views field is not rendering as table.

# Answer
> 0 votes
You need to unescape HTML. There are two working ways to accomplish this. First you can mark your field as "raw" and the html would render correctly. `{{ your_field | raw }}` should render ok.

As a second resort you can use twig's autoescape functionality:

```
{% autoescape false %}
{{ your_field }}
{% endautoescape %}

```

By this way you are telling twig not to escape html markup.

---
Tags: views, theming
---


# Question
Title: Domain Access and One.com hosting (funny subdomain rewrite)
I have a D7 installation that uses Domain Access to distinguish between a main website `example.com` and a minisite `event.example.com`. They share the same document root / Drupal installation and the same database. I use Domain Path to have subdomain-specific aliases.

This worked fine, until I decided to move this website to a webspace at One.com. They do this thing were you can create a subdomain just by creating a directory in the document root. So `/folder/` can automatically be accesssed in three ways:

* `http://folder.example.com/`
* `http://example.com/folder/`
* `http://www.example.com/folder/`

By default, there is an `A` wildcard DNS-record for `*.example.com`.

The relevant part of my `/.htaccess` currently looks like this:

```
Options +FollowSymLinks

<IfModule mod_rewrite.c>
  RewriteEngine on

  #strip www.
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  #pass all requests that do not refer to files to index.php
  RewriteCond %{HTTP_HOST} ^(event\.)?example\.com [NC]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]
</IfModule>

```

This messes up all static files on `event.example.com`. When `http://event.example.com/sites/default/files/css/css_*.css` is accessed, Apache tries to find an `/event/` directory, which doesn't exist and gives a 404.

I attempted to fix this by symlinking `/event/` to `/`. Now the static files work, but domain paths on `event.example.com` no longer work (they all give 404s) and links tend to get rewritten to `http://event.example.com/event/somelink`.

I also tried to fix this by adding the following, but that didn't help.

```
RewriteCond %{REQUEST_URI} ^/event(.*)$ [NC]
RewriteRule ^ http%{ENV:protossl}://event.example.com%1 [L,R=301]

```

Any ideas?

# Answer
It turned out that my symlink from `/event/` to `/` was correct, but that I additionally needed to specify `RewriteBase /` to fix the link rewriting part.
> 0 votes

---
Tags: path-aliases, .htaccess, domain-access, subsites
---


title: Programmatically setting a link

text:
# Question
Title: Programmatically setting a link
I am trying to programmatically set a link in a Drupal 8 view. The client wants an external link used if a certain link field is set, otherwise default the link to the node.

I am trying to figure out how to set this, and despite looking at hook\_views\_pre\_render() and hook\_views\_post\_render(), I'm not seeing any method to make this happen. I'm trying to go into result -

```
foreach ($view->result as $key => $value) {

}

```

However Kint is giving me data like this:

```
public _relationship_entities -> array(0)
public index -> integer7
public node_field_data_langcode -> string(2) "en"
public nid -> string(2) "99"

```

for each ResultRow.

I don't remember this being particularly difficult in Drupal 7 - is there something I'm missing here? How do I programmatically set a link in Drupal 8 dependent on certain conditions for a view row/field in a row?

# Answer
> 8 votes
The hook you're looking for is hook\_views\_view\_field().

This hook allows you to alter the output of the field, and still is early enough to have the entity data for for that field.

In the example below, I'm checking if the node has a link field, field\_my\_link set, and if it's set, I alter the title output (which is normally linked to the node) to output to the link field's uri, but only if it's an external link.

```
function mymodule_preprocess_views_view_field(&$vars) {
  if ($vars['view']->id() != 'testview') {
    return;
  }
  $node = $vars['row']->_entity;
  if ($vars['field']->getField() == '.title' && $node->field_my_link->isEmpty() === FALSE) {
    if ($node->field_my_link[0]->isExternal()) {
      $link = $node->field_my_link[0]->view();
      $link['#title'] = $node->label();
      $vars['output'] = $link;
    }
  }
}

```

If you want to alter the output of one views field based on the output of another, use hook\_views\_view\_fields():

```
function mymodule_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->id() != 'testview') {
    return;
  }

  // Cast Markup object to string.
  $field_one_content = (string) $vars['fields']['field_1']->content;

  // Check if first field contains a substring, if so, update second field.
  if (strpos($field_one_content, 'my search string') > -1) {
    $vars['fields']['field_2']->content = \Drupal\Core\Render\Markup::create('hello world');
  }

}

```

# Answer
> 1 votes
If you're able to reconfigure the view to use "Rendered Content" instead of fields, it might be dead simple to create a view mode, configure the fields that display, and then provide a `node--node-type--view-mode.html.twig` template. Then you can preprocess the node, by view mode, and add/check variables before they are rendered in the template.

I say that, because it is easier than trying to wrestle with views at this level.

Here are similar questions revolving around this sort of thing:

Then, you would be able to reuse this view mode in other areas and create new Views to use this view mode, without configuring *every* View fields and doing the same overrides again and again. And, as you see, it is hard to debug. But debugging at the node / view mode level, much easier.

# Answer
> 1 votes
**A recipe for doing this via the Views UI**

**You will need 3 fields,**

* one to get the NID
* one to get the field\_certain\_link
* one to render the link

**You set up each field like this:**

a) NID field: Hide it from display.

b) field\_certain\_link: Hide it from display and rewrite its value to be the raw URI, e.g. `{{ field_certain_link__uri }}`. You have to set a rewrite value for the no results part, this should be `node/{{ nid }}`, with nid coming from the first field.

c) This is a 'Global: Custom Text' views field. Enter the text of the link and select the rewrite\>output as a custom link option. The link's value should be the value of the field\_certain\_link, sth like `{{ field_certain_link }}`

The views configuration should look sth like this now (the fields section):

That's it basically, after you are done, your custom text field is rendered as a link and depending on the value of field\_certain\_link, it links to the external link or the node.

This should look like this (first and second columns are visible only for debugging reasons). The second column demonstrates the conditional rewriting of the field, based on whether it has a value set or not. The first row has not value set for the field\_certain\_link field, and is therefore linked to the node:

Good luck!

P.S.: You could probably use only one field and rewrite using twig to write the conditions. This is an D7 recipe actually.

# Answer
> 0 votes
You might have to create a custom views formatter. These plugins take the data that is returned by a view and prepares it for display on the page. The 'Table' and 'Grid' formatter a are examples. I recently created one to take the results from a view and create a pie chart. In your case, you could query the important pieces and use the formatter to assemble them and render as a URL.

Another solution is to create a new field formatter. The formatter would accept the field, look up this other piece of information, and create the appropriate link.

---
Tags: views, 8
---


# Question
Title: creating a function that can create GET url variables as object when I need it
I am trying to parse my form's GET method and create a function that can get all the parameters from the URL in DRUPAL 8. I have a form that I am gonna use it to filter my library items as search( I know I can use search api or advanced search but my client wants this way ) So I have a few fields such as keyword, title, description, location, author, from, to, collection. and when I add all the fields after the redirection to result page

```
http://example.com/advancedsearchresult?keyword=test1&title=test2&description=test3&author=test4&location=test5&from=&to=&collection=&media=all

```

I would like to do nice job with using OOP and Symfony service features. My question is how could i create a function in my controller for this result page that is gonna parse all the parameters from the URL so I can use them to create an object in service to create individual query for each parameters to make search mechanism for this form?

UPDATED:

After @oknate pointed out, I updated my controller like this:

```
namespace Drupal\advancedsearch\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\advancedsearch\AdvancedSearchQuery;

class SearchResultController extends ControllerBase {
 protected $advancedsearchSearchResult;

public function __construct(AdvancedSearchQuery $advancedsearch_search_result ) {
 $this->advancedsearchSearchResult = $advancedsearch_search_result;
}

public static function create(ContainerInterface $container) {
return new static(
  $container->get('advancedsearch.search.result')
);
}
private function setupAdvancedSearchQuery() {
$params = \Drupal::request()->query->all();
foreach ($params as $key => $value) {
  if (!empty($value)) {
    $params[$key] = $value;
  }
}
}
}

```

on the other hand, I created my service file, I created my variables which matches with parameters, so am I gonna be able to use setupAdvancedSearchQuery() when I call the object for each parameters, if so can anyone give a hint?

# Answer
> 2 votes
If these $\_GET parameters are also route parameters (set up in a module's routing configuration), you can use

```
 \Drupal::routeMatch()->getParameters();

```

Or for a specific parameter:

```
$keyword = \Drupal::routeMatch()->getParameters()->get('keyword');

```

If the $\_GET parameters are not route parameters, you can get all the parameters this way:

```
$params = \Drupal::request()->query->all();

```

If you want to set default parameters for parameters that aren't in the URL, you can merge the $params with an array of defaults. Then depending on how you're going to use the parameters, you may want to XSS filter the params to prevent cross-site scripting attempts. As @Berdir points out, this is rarely necessary, as twig auto escapes and if you are passing parameters into the query abstraction layer properly, it will also filter your input. But you could filter your params this way:

```
foreach ($params as $key => $value) {
  if (!empty($value)) {
    $params[$key] = Xss::filter($value);
  }
}

```

(If you are using arrays in your $\_GET params, this foreach loop would need to be altered to handle that use case.)

Here's some more info on XSS security.

After you have pulled-in and cleaned up your $\_GET variables, you could then save these parameters to your object, and then use them conditionally in your query.

Since you asked specifically about Controllers, you can pass the request object to controller in the constructor:

```
  public function __construct(Request $request) {
    $this->request = $request;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack')->getCurrentRequest()
    );
  }

```

Then you could use the request object from the container.

If you set up the parameters as route parameters, you can just pass them in as arguments to the controller.

---
Tags: forms, page-controller, 8
---


title: Creating a dynamic menu

text:
# Question
Title: Creating a dynamic menu
I'd like to make a Drupal 8 menu dynamic so it can i.e. point to the latest node of the articles or news or hide another from the menu if it doesn't have an entry at all.

How can I achieve this?

# Answer
> 2 votes
You can't really have dynamic menus that point to different things. You can write a deriver and so on, but that will be persisted and not updated until you tell it to. You can trigger the necessary updates also without a full cache clear, see how MenuLinkContent does it, but it's still persisted.

Another approach would be to not make the route/output dynamic and not the menu. Point to a custom controller, and there you either dynamically display the latest node (can easily be done with a view, for example) or you redirect to the latest content, to avoid duplicate content.

# Answer
> 1 votes
You need to implement a deriver, the class looks like this:

```
<?php

namespace Drupal\YOUR_MODULE\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides menu links.
 */
class MyLinks extends DeriverBase implements ContainerDeriverInterface {

  /**
   * The team storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $myStorage;

  /**
   * Constructs a XX instance.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The storage.
   */
  public function __construct(EntityStorageInterface $storage) {
    $this->myStorage = $storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity.manager')->getStorage('node')
    );
  }
  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $links = array();

    $base_plugin_definition = array(
      'enabled' => 1
    ) + $base_plugin_definition;

    // use injected storage !
    $nodes = $this->myStorage->loadMultiple();

    $links['custom_link'] = array (
            'id' =>  'custom_link',
            'title' => t('Click me'),
            'route_name' => 'entity.node.canonical',
            'route_parameters' => array(
              'nid' => 123,
            ),
            'menu_name' => 'main',
            'parent' => 'parent:menu:id',
          ) + $base_plugin_definition;

    return $links;
  }

}

```

Add this class in a custom module in the src/Plugin/Derivative Folder, and it will be picked up.

> This code only runs during/after cache-rebuild.

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


# Question
Title: Destination fields not filled from custom migration process plugin
I'm working on a D6 -\> D8 migration, and my destination has a custom video upload field (field\_video\_upload) that contains three pieces of data: video, thumbnail, and poster (field\_video\_upload\_video, field\_video\_upload\_thumbnail, field\_video\_upload\_poster respectively in the db). I'm attempting to migrate that data from my source table (actually a MySQL view) that has the data in a serialized format, and I'm using a custom source plugin to get the data.

```
  public function prepareRow(Row $row) {
    //TODO: Extract url from video_data field and video_thumb from thumbnail_data.
    $video_data = get_object_vars(unserialize($row->getSourceProperty('video_data')));
    $thumbnail_data = unserialize($row->getSourceProperty('thumbnail_data'));
    // Get the array values. Seems to be the best way to work around having an
    // array key of 0000000.
    $video_data = reset($video_data);
    $video_url = $video_data->url;
    $video_thumb = $thumbnail_data['video_thumb'];

    // Set the source properties.
    $row->setSourceProperty('video_url', $video_url);
    $row->setSourceProperty('video_thumb', $video_thumb);
  }
}

```

Here is the relevant portion of the migration configuration .yml file:

```
  field_video_upload:
    plugin: video_upload
    source:
      - video_url
      - video_thumb

```

and here is the custom process plugin video\_upload to get the data:

```
namespace Drupal\migrate_mrctv\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * This plugin gets values for the video upload field.
 *
 * @MigrateProcessPlugin(
 *   id = "video_upload"
 * )
 */
class videoUpload extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $video = array();

    list($video_url, $video_thumb)  = $value;

    $video['video'] = $video_url;
    // Use the same source thumb value for poster and thumb.
    $video['thumbnail'] = $video_thumb;
    $video['poster'] = $video_thumb;

    return $video;
  }
}

```

The source plugin works fine, and the data from the plugin is available in $value in videoUpload::transform(). However, none of the data is getting into this field in the node itself. The main node data is there, but no data for this field.

What do I need to change to get the data to import into my custom field?

Thanks.

**UPDATE:** In stepping through the Migrate code, I came across this line in `Row->setDestinationProperty`:

```
NestedArray::setValue($this->destination, explode(static::PROPERTY_SEPARATOR, $property), $value, TRUE);

```

and since `PROPERTY_SEPARATOR = '/'`, I tried this in my configuration:

```
'field_video_upload/video': video_url
'field_video_upload/thumbnail': video_thumb
'field_video_upload/poster': video_thumb

```

but no difference.

**UPDATE 2:** Based on the answer from @heddn below, I'm using the iterator plugin as part of a pipeline, since this is a multivalue field, even though it's set to only allow one value.

```
  field_video_upload:
    -
      plugin: video_upload
      source:
        - video_url
        - video_thumb
    -
      plugin: iterator
      process:
        video: video
        thumbnail: thumbnail
        poster: thumbnail

```

and modifying my plugin:

```
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $video = array();

    list($video_url, $video_thumb)  = $value;

    $video[] = array(
      'video' => $video_url,
    // Use the same source thumb value for poster and thumb.
      'thumbnail' => $video_thumb,
       'poster' => $video_thumb
    );

    return $video;
  }
}

```

This appears to work in that I the array from the video\_upload plugin is passed as $value to the iterator plugin, but I'm still not getting values in field\_video\_upload. What else am I missing?

# Answer
It turns out that the problem with this was that the field schema had a couple of other subfields required, even though the db columns weren't required. This, combined with the fact that the error message gave no indication that this was the problem, made it very hard to track down.

My final field settings in the migrate config look like this:

```
  field_video_upload:
    -
      plugin: video_upload
      source:
        - video_url
        - video_thumb
        - vid
        - shows_ads
    -
      plugin: iterator
      process:
        video: video
        thumbnail: thumbnail
        poster: thumbnail
        vid: vid
        show_ads: show_ads

```
> 2 votes

# Answer
That last part where you are doing the mapping like:

'field\_video\_upload/video': video\_url 'field\_video\_upload/thumbnail': video\_thumb 'field\_video\_upload/poster': video\_thumb

is probably the closest. Is the destination field a multi-valued field? Then you'll need to follow the pattern as espoused in https://www.mtech-llc.com/blog/charlotte-leon/migration-csv-data-paragraphs

You need to create an array of data, then iterator over it and insert each record into the destination.

Namely (this is completely untested, but the idea of it should work if the destination is multi-valued):

```
   combination:
    plugin: get
    source:
      - video_url
      - video_thumb
  field_video_upload:
    plugin: iterator
    source: @combination
    process:
      video: video_url
      thumbnail: video_thumb
      poster: video_thumb

```
> 2 votes

---
Tags: 8, migrations, plugins
---