# Question
Title: How to use entityQuery to find nodes with a specific multi-value field containing one specific value (and no others)?
I have a node type "group" with an entity reference field "field\_things" that can reference zero or more "thing" nodes. I'd like to use entityQuery to find all "groups" that have exactly one value for field\_things, and that value is a specific "thing".

I can't tell from the docs how to combine those two requirements.

# Answer
So it appears `entityQuery()` can't do this, but `entityQueryAggregate()` can. Below is an example that achieves the goal of the original post:

```
$thing_id = 101;
$q = \Drupal::entityQueryAggregate('node')
  ->condition('type', 'group')
  ->condition('field_things', $thing_id)
  ->groupBy('nid')
  ->conditionAggregate('field_things', 'COUNT', 1);
$res = $q->execute();

```

Running `dpm($res)` will show:

```
Array
(
  [0] => Array
    (
      [nid] => 85
      [field_things_count] => 1
    )

  [1] => Array
    (
      [nid] => 33
      [field_things_count] => 1
    )

  [2] => Array
    (
      [nid] => 57
      [field_things_count] => 1
    )

  [3] => Array
    (
      [nid] => 54
      [field_things_count] => 1
    )
)

```
> 5 votes

---
Tags: 8, entities, database
---


title: unset form error for specific field

text:
# Question
Title: unset form error for specific field
I have a a kind of conditional field for a sign up form where the user can optionally sign up with a mobile number or an email address.

I'm trying out a custom form validate eg.

```
  function signup_validate($form, FormStateInterface $form_state) {
    $mobile = $form_state->getValue('field_mobile');
    $email = $form_state->getValue('field_email_address');

    if ($email[0]['value'] != '' || $mobile[0]['value'] != '') {
      $form_state->clearErrors();
    }
  }

```

Now `clearErrors();` obviously clears all errors for the form even if other fields are invalid, I want to know how to clear the error only for `field_mobile` or `field_email_address`

# Answer
Instead of removing the error, you should make sure that only the needed validation errors are set in the first place.

For example, you could use '#states' in your form elements to set 'required' depending on the user input of the other field.
> 2 votes

# Answer
While I agree with the accepted answer, one way to accomplish your goal is to:

1. Assign the form errors to a variable, such as `$form_errors`
2. Clear all form errors from `$form_state`
3. Remove the particular form error from `$form_errors`
4. Loop through the remaining `$form_errors`, re-setting them to `$form_state`.

So to clear the `field_mobile` error you would use the following code:

```
// Temporarily store all form errors.
$form_errors = $form_state->getErrors();

// Clear the form errors.
$form_state->clearErrors();

// Remove the field_mobile form error.
unset($form_errors['field_mobile']);

// Now loop through and re-apply the remaining form error messages.
foreach ($form_errors as $name => $error_message) {
  $form_state->setErrorByName($name, $error_message);
}

```
> 27 votes

---
Tags: forms, 8
---


# Question
Title: How do I mark translation strings as non-customized?
Drupal 8 distinguishes between "customized" and "non-customized" translations.

A customized translation is a translation that has been imported from a module and then changed at `/admin/config/regional/translate`.

So, if I edit a translation that has been imported, it becomes **customized**.

What if I edited many translations, but then changed my mind and wanted to restore them to the default?

How can I revert a **customized** string into the original **non-customized** one? (And is it possible to do this to strings in batches?)

# Answer
> 0 votes
Based on 4k4's suggestion, I was able to do this with SQL:

```
drush sqlq < "UPDATE mydb.locales_target SET customized = 0 WHERE customized = 1;"

```

**Warning: This will unset the customized flag for all strings on your site, but leave the customized translations in place. This is what I wanted, but make sure it's what you want too before running the command. Always make a backup, etc.**

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


# Question
Title: Hide default "all" parameters from Views Querysting
By default Drupal Exposed Filters query string includes all filters even if they aren't selected i.e. www.example.com/?optiona=valuea&optionb=all&optionc=all

How do I adjust it not include default/all values in the query string?

For example, if the user does not touch "option b" just option a they would get

i.e. www.example.com/?optiona=valuea

The goal is to create a "cleaner" query string by not including the default values.

# Answer
This is a known issue that hopefully will be solved in Drupal 8.

I accomplished it with JS:

jQuery(document).ajaxComplete(function(e, xhr, settings) {

```
let src = window.location.href;
let url = new URL(src);
let title= document.title;
let re = /all/;
let props = [...new URLSearchParams(url.search)]
            .filter(([key, prop]) => !re.test(prop));
url = url.origin + url.pathname;
let params = new URLSearchParams();
props.forEach(([key, prop]) => params.set(key, prop));
url += "?" + params.toString();

history.pushState(null, null, ("/page?"+params.toString()))

});

```
> 1 votes

# Answer
You can use Views expost module which allows you to set the exposed filters forms in views to use method POST instead of GET.

Now when you submit the filters the form will be submitted to drupal using **POST** method which means any selections won't appear in the url.

You can have full control over the markup of these filters

> **views-exposed-form--view\_id--display\_id.tpl.php** views-exposed-form.tpl.php

Or attach JS code to achieve what you need

```
function yourtheme_form_alter(&$form, $form_state, $form_id) {
 switch ($form_id)  {
   case 'views_exposed_form':
     if($form['#id'] == 'views-exposed-form-viewid-displayid'){
         $form['#attached']['js'] = array(drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
     }
   break;
 }

```

}
> 0 votes

---
Tags: 7, views
---


title: drupal_add_js is removing jQuery

text:
# Question
Title: drupal_add_js is removing jQuery
I have the following in my module.

```
drupal_add_js(
    drupal_get_path('module', 'responsive_videos') . '/js/fluidvids.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'weight' => 10,
    )
);

```

For some reason, when this module is enabled, jQuery and jQuery Once get removed from the head and the JavaScript console logs many "Uncaught ReferenceError: jQuery is not defined". Can anyone clarify why this is happening, and how to fix it?

Here is the info file, responsive\_videos.info.

```
name = Responsive Video
description = Creates a fluid responsive video from YouTube or Vimeo embedded iframes.
core = 7.x

```

And here is the module file, responsive\_video.module.

```
<?php
/**
 * @file
 * Makes YouTube and Vimeo embedded iframe videos responsive.
 */

drupal_add_js(
    drupal_get_path('module', 'responsive_video') . '/js/fluidvids.js',
    array('scope' => 'footer')
);

```

The JavaScript file being added does not leverage jQuery, so I don't quite understand how or if it might interfere with jQuery being added to the page, but here is the source of the "fluidvids.js" file.

```
// http://toddmotto.com/fluid-and-responsive-youtube-and-vimeo-videos-with-fluidvids-js/
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory;
  } else {
    root.fluidvids = factory();
  }
})(this, function () {

  'use strict';

  var fluidvids = {
    selector: ['iframe'],
    players: ['www.youtube.com', 'player.vimeo.com']
  };

  var css = [
    '.fluidvids {',
      'width: 100%; max-width: 100%; position: relative;',
    '}',
    '.fluidvids-item {',
      'position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;',
    '}'
  ].join('');

  var head = document.head || document.getElementsByTagName('head')[0];

  function matches (src) {
    return new RegExp('^(https?:)?\/\/(?:' + fluidvids.players.join('|') + ').*$',     'i').test(src);
  }

  function getRatio (height, width) {
    return ((parseInt(height, 10) / parseInt(width, 10)) * 100) + '%';
  }

  function fluid (elem) {
    if (!matches(elem.src) || !!elem.getAttribute('data-fluidvids')) return;
    var wrap = document.createElement('div');
    elem.parentNode.insertBefore(wrap, elem);
    elem.className += (elem.className ? ' ' : '') + 'fluidvids-item';
    elem.setAttribute('data-fluidvids', 'loaded');
    wrap.className += 'fluidvids';
    wrap.style.paddingTop = getRatio(elem.height, elem.width);
    wrap.appendChild(elem);
  }

  function addStyles () {
    var div = document.createElement('div');
    div.innerHTML = '<p>x</p><style>' + css + '</style>';
    head.appendChild(div.childNodes[1]);
  }

  fluidvids.render = function () {
    var nodes = document.querySelectorAll(fluidvids.selector.join());
    var i = nodes.length;
    while (i--) {
      fluid(nodes[i]);
    }
  };

  fluidvids.init = function (obj) {
    for (var key in obj) {
      fluidvids[key] = obj[key];
    }
    fluidvids.render();
    addStyles();
  };

  return fluidvids;

});

fluidvids.init();

```

# Answer
The reason it was breaking is because you’re doing `drupal_add_js` outside of any function or listener hook.

You need to add it to the appropriate build, alter or preprocess hook that suits your needs.
> 1 votes

# Answer
Had the same problem. I solved it using page\_build hook.

Example:

-module file:

```
/**
 * Implements hook_page_build(&$page).
 */
function product_admin_link_control_page_build(&$page) {
    drupal_add_js(drupal_get_path('module', 'product_admin_link_control') . '/product_admin_link_control_init.js',
    array('type' => 'file', 'scope' => 'footer'));
}

```

-product\_admin\_link\_control\_init.js file:

```
(function ($) {
try{
  console.info("in");
}catch(oe){}
})(jQuery);

```

-info file:

```
; $Id: $
name = Product admin link control
description = Features: removes admin link from CK2 product title for non admins.
package = Commerce (contrib)
core = 7.x

; Base module files

datestamp = "1437076940"

```
> 0 votes

---
Tags: 7, javascript
---


title: Webform multiple conditions recipient

text:
# Question
Title: Webform multiple conditions recipient
I am on a Drupal 7 website and I have a webform with multiple fields, one field is a selectbox with :

* 1-10 employees
* 10-20 employees
* 20-30 empolyees
* ...

Another one is an open textfield Postcode.

Webform offers the possibility to choose the recipients (e-mail TO) based on a component but not on multiple components.

**For example,** I want the mail to be sent to john@doe.com if employees = 1-10 and Postcode = 75000 etc.. And one more thing, I want my client to be able to change and contribute these rules. So a solution with Webform Rules will be too difficult for them in my opinion. I hope to find a solution within the webform e-mail interface.

Have you any idea how is it possible to do that without building a new complete custom form and keep the power of Webform ?

Thanks.

# Answer
I suggest you try to avoid using simple textfield for the Postcode. Then you can use 2 dependent fields. The first field will be the select of employees number range. The second will be one of postcode selects, depending on the first choice. Then you can use the standard functionality: using select field key as the email.

If for a fixed employee number range you have individual emails for different postcode values then it is straitforward.

If not, still you can do it if all postcode values could be grouped into ranges, so that each range gets its own email (define select values for postcode ranges same as you did for employees number).
> 1 votes

---
Tags: 7, webforms, emails
---


title: How do I deploy a local site?

text:
# Question
Title: How do I deploy a local site?
I've been getting mixed messages and there is practically no solid up-to-date documentation, I just want to know the standard procedure for moving a locally developed Drupal 8 site to an online server.

Some say it's as easy as FTP'ing your files over and exporting your local database SQL code over and then connecting to the db via the settings.php, others say to put a fresh installation of Drupal 8 online and then move certain files over while exporting the database using the backup module and then importing it online, others still say I also need to export the local configuration and import it online, still others say I need to update the URL's in some parts of the SQL or configuration exports, etc.

I'm developing with the latest Drupal 8.4 with a custom theme in Windows 10 on XAMPP (I have drush) and migrating to a server subdirectory that my domain points to with php 5.6+ (no drush options online because there's no SSH access).

TLDR: What are the steps to move a locally developed Drupal 8.4 site and database to an online server and get it configured, up and running normally?

# Answer
There are many ways to migrate a local site to a server. Here are a few of the most common.

* SFTP/FTP is one way, you can "manually" move all the files up to the server and use PHPMyAdmin to import the database. Many hosts will also have automatic Drupal installs, in which case you can use that, only upload your theme, files, and modules, and then import database. **If you upload via FTP you will need to update settings.php to include the servers SQL log/pass as well as domain url**
* Set up a git repo which you can pull/push to from your local machine and the server is likely a better solution if you plan on making
changes. This allows you to more easily manage the files and is a
"safer" solution. **Set settings.php to .gitignore**
* There are also managed solutions such as Acquia Dev Desktop which
will allow you to push/pull files, code, and database simultaneously using a UI.
> 4 votes

---
Tags: deployment
---


title: Use services in controller

text:
# Question
Title: Use services in controller
I am trying to create a custom service and call it from a controller that is being used on a route. I use simple code, so I think I am missing something

The membership service: https://gist.github.com/betz/6e0cb7ce2712793711d4c9ed99a3a697

Controller: https://gist.github.com/betz/a9aa9db636cd9b9bffea3b4e255fb1df

services file: https://gist.github.com/betz/25aeb579c265bfba83a0e891aa883bf8

routing file: https://gist.github.com/betz/577a411a8ede77ecc0be614044ec1a44

The error I get:

> RuntimeException: Controller "Drupal\hsbxl\_members\Controller\Test::test()" requires that you provide a value for the "$container" argument (because there is no default value or because there is a non optional argument after this one). in Drupal\Core\Controller\ControllerResolver-\>doGetArguments() (line 165 of /var/www/drupalvm/web/core/lib/Drupal/Core/Controller/ControllerResolver.php).

So it seems the ContainerInterface $container is missing when the controller is being initiated. But how do i do this? Confused.

Cheers! Tom

# Answer
> 1 votes
In this example you should inject dependencies via the controller `create` method, pass the container there, and return an array. The first item in the array is the service you’re passing to the constructor.

Then, add a constructor that expects this object as an argument, and then set `$this->membership` to the container object you passed as an argument. This should also be a protected member of the class.

But to see your example actually work first, remove the container from the test method and remove the line about `$memebrship`. Clear cache and hit that route to see Hello world!

Here is a similar question demonstrating this: How do I use dependency injection on \Drupal::moduleHandler() to a Controller?

---
Tags: 8
---


title: Conditional state integer number

text:
# Question
Title: Conditional state integer number
Using Drupal 8 and the new webform module "8.x-5.0-beta19".

Like it a lot! Many options now to control the webforms.

Problem: I have one input field 'NUMBER'. When the web visitor enters a number greater than 0... the other input field should appear. So on the second input field, I do a conditional statement.

Make visible when Value is not ---\> 0

Seems to be this options only accepts integers greater than 0, but not 0. See image... When saving the 0 disappear and 2 he accepts and does save it....

Is this a bug... does somebody has a solution?

Thanks for reading.

# Answer
> 1 votes
This is issue has been fixed. @see https://www.drupal.org/node/2916409

---
Tags: webforms
---


# Question
Title: How to have a popup calendar in a date view exposed filter?
I am setting up a view, with the *Authored on* filter exposed. When selecting the box, there isn't any popup calendar.

Doesn't Drupal 8 come with a calendar popup in core? How can I turn this on for exposed filters with date?

# Answer
This can be done with the Better Exposed Filters module.

Enable the module, set it as the exposed form handler under Advanced -\> Exposed form style, on the BEF settings page dialog set the filter display option to "jQuery UI Datepicker". Save everything and you should be good to go.

Note that changing from the default date format may require you to implement `hook_better_exposed_filters_display_options_alter`.
> 2 votes

# Answer
You can use the Single Date Time Picker module.

> Date time picker form element using the xdan jQuery Plugin Date and Time Picker library - https://github.com/xdan/datetimepicker.
>
> It supports date/time and date fields. You can use it on Datetime and Datetime Range fields.
> 0 votes

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


title: How do I add UTM sources to RSS links?

text:
# Question
Title: How do I add UTM sources to RSS links?
I want to add UTM sources to RSS links. I have already tried to change the link display and modify the URL, but so far I am unable to see any sort of tracking in Google Analytics.

# Answer
my first question is what are you trying to track.

you say

> add UTM sources to RSS links

I'll assume you want to track those clicks to your rss feed.

theres a way to do this without pushing your feed to external places

your changing the link display is nearly there but you will want to put a click event track to fire a google analytics event

this is a good reference:

you could take it one step further and add 'autotrack' which does a whole bunch of good things for you including declarative event tracking, so rather than the above, you use declarative attributes in your html

*this will only track clicks on the link.* as it relies on the users browser loading and executing the javascript.

If you wanted to ensure tracking every request to that feed you have another option that doesn't rely on external services (other than google analytics). you could use the measurement protocol in google analytics that lets you post any type of event from any system.

you could then create a module and implement either hook\_init, or hook\_exit to make a call to the measurement protocol end point logging the request of the feed in your google analytics account
> 1 votes

# Answer
The question does not specify if this is for Drupal 8 or Drupal 7. So I will go ahead and share what I just implemented in Drupal 8 and should work closely in Drupal 7.

Basically I had to preprocess the Views RSS row and append my UTM information to the link. Here is how I am tagging taxonomy term feeds with an explicit check to see if it is my Drupal Planet feed.

```
function bootstrap_glamanate_preprocess_views_view_row_rss(&$variables) {
  /** @var \Drupal\views\ViewExecutable $view */
  $view = $variables['view'];
  if ($view->id() == 'taxonomy_term') {
    $term = \Drupal\taxonomy\Entity\Term::load($view->args[0]);
    $label = $term->label();
    if ($label == 'drupal') {
      $source = 'Drupal Planet';
    }
    else {
      $source = 'Term Feed';
    }
    $variables['link'] .= '?utm_source=' . $source . '&utm_medium=feed&utm_campaign=' . $term->label();
  }
}

```
> 1 votes

---
Tags: feeds, google-analytics
---


# Question
Title: reCaptcha get the code & use in custom module
How to setup reCaptcha to appear on the registration form?

I followed above link & able to setup reCaptcha for Login form. It works fine.

Now for login I'm creating my custom Multi-Step form. 4-5 steps.

How we can define where to show this captcha or which code needs to be use so we can show it whenever it requires?

# Answer
> 1 votes
The following will add the captcha,

```
public function buildForm(array $form, FormStateInterface $form_state) {
...
  $form['captcha'] = array (
    '#type' => 'captcha',
    '#captcha_type' => 'recaptcha/reCAPTCHA'
  );
  return $form;
}

```

---
Tags: 8, captcha
---


# Question
Title: Ho to use devel on commerce_cart_order_refresh or similar
I want to implement the solution on this link Alter cart unit price and total amount. I want to use dpm on devel to look for available fields on line items but I doesnt show on.

Code that I used: function mymodule\_commerce\_cart\_order\_refresh($order\_wrapper) { dpm($order\_wrapper); }

function mymodule\_calculate\_product\_price\_cart($order) { dpm($order); }

Both of these doesnt show the devel on the page.

# Answer
> 0 votes
1. Make sure that Commerce cart context is loading in the particular page you wanted to dpm/dsm for function hook\_commerce\_cart\_order\_refresh($order\_wrapper) &
2. And where you declared this **function mymodule\_calculate\_product\_price\_cart($order) { dpm($order); }** can you brief this for more clarity.

---
Tags: debugging
---


title: How do I update core to 8.4?

text:
# Question
Title: How do I update core to 8.4?
I checked the other questions related to this topic, but half of them didn't get any useful answer and the other half didn't help me out.

I face with several issues building up a site using Drupal 8:

1. The view exposed date filter doesn't work properly in 8.3.x
2. The administrative theme doesn't work for roles other than administrator users

I wanted to upgrade a site from 8.3 to 8.4 as most of the patches are provided for 8.4, and I hoped that I would get less troubles.

Drupal 8.4 is just available as development snapshot, at this moment, and Drush didn't let me update the site to this version.

On top of all, the installed Drush version (v8.1.9) is not compatible with Drupal 8.4.

How do I update Drupal to 8.4 using the version of Drush I installed?

# Answer
> 6 votes
1. Make a database backup.
2. Make a Drupal code source backup.
3. I had to know which drush I use:

```
$ drush version
Drush Version   :  8.1.9

```

which isn't good for me.
4. I had to find out whether it is a local or a global installation

```
$ locate drush
/usr/local/bin/drush
$ dpkg -l | grep drush
rc  drush    5.10.0-2ubuntu1

```

it looks like the ubuntu package was removed before and it wasn't installed by pear:

```
$ pear list

Installed packages, channel pear.php.net:
=========================================
Package          Version State
Archive_Tar      1.4.0   stable
Console_Getopt   1.4.1   stable
HTTP_Request2    2.2.1   stable
Net_URL2         2.2.0   stable
PEAR             1.10.1  stable
PEAR_Manpages    1.10.0  stable
PHP_CodeSniffer  2.5.1   stable
Structures_Graph 1.1.1   stable
XML_Util         1.3.0   stable

```

So, it can be only a global phar installation.

5. I chose the **WRONG WAY** of the installation in the beginning which resulted a lot of more issues (I don't list them here) and finally a drush installation which I wasn't able to update my drupal
Just for the record here is the wrong way: I decided I install drush by composer and if the global version confuses its functionality I will remove the old one from the file system manually
I ran this command from the root directory of my drupal project
`$ composer require drush/drush`
This installed a lot of other packages and updated my drush from 8.1.9 to 8.1.12. Everything looked good at this point.
`$ drush version`

```
Drush Version   :  8.1.12

```

`$ drush up drupal`
resulted

```
Unable to load class \Drush\VersionControl\Backup.

```

I removed the drush 8.1.12 and installed the drush 9.x version.
I wasn't able to update my drupal site, so I removed the local drush package and its dependencies.

6. **the WORKING WAY**
remove the composer version if that exists and install drush globally by phar

```
# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

```
7. I updated my drupal from 8.3.4 to 8.3.5
`$ drush up drupal`
8. I got the package name of the drupal 8.4 by this command
`$ drush dl drupal-8 --select`

```
 [0]  :  Cancel
 [1]  :  8.4.x-dev  -  2017-Jul-22  -  Development
 [2]  :  8.3.5      -  2017-Jul-05  -  Supported, Recommended
 [3]  :  8.3.4      -  2017-Jun-21  -  Security

```

I chosed 0

9. I updated my drupal from 8.3.5 to 8.4
`$ drush pm-update drupal-8.4.x-dev`

```
Update information last refreshed: Mon, 06/26/2017 - 18:31
 Name    Installed Version  Proposed version  Message
 Drupal  8.3.5              8.4.x-dev         Specified version available

Do you really want to continue? (y/n): y

```

At the end I got 3 errors, but the update was successful.
Unfortunately the drupal 8.4.x-dev version didn't fix any of my issues.

# Answer
> 5 votes
It's best to update dependencies using composer:

```
composer update drupal/core --with-dependencies

```

Have a look at https://www.drupal.org/docs/8/update/update-procedure-in-drupal-8

Note that you'll also need drush 9.x: composer require drush/drush:9.\*

See https://github.com/drush-ops/drush/issues/2738.

# Answer
> 2 votes
A tutorial is related to the update of 8.3 to 8.4 'Update to Drupal core 8.4, a step by step guide'

Also, not a direct answer to the question, but a good place to mention that this Drupal Composer helper intends to facilitate the update process.

> The motive behind writing this plugin was to make a Drupal composer based setup more maintainable. It is easy to start with the template provided by drupal-composer/drupal-project but upgrading it is difficult. The plugin solves that problem by keeping all the code outside your project and in the plugin which would make upgrading as easy as running composer update.

# Answer
> 1 votes
When I ran `composer update drupal/core --with-dependencies`, I got the following error:

> Package "drupal/core" listed for update is not installed. Ignoring.

So I moved `"drupal/core": "~8.3"` from the *replace* to the *require* section of the composer.json file.

I think it isn't recommended, but it works.

---
Tags: 8, drush, updating
---


# Question
Title: How to cancel user accounts without e-mail confirmation?
I want to allow users to cancel their accounts immediately instead of having to confirm the cancellation by email (because users forget passwords, lose access to email, and other problems).

There is a great answer to the Drupal 7 version of this question and it inspired a module.

So I attempted to adopt the code in the module for Drupal 8.

First, though, **you need to prevent the "account cancellation confirmation email** from being sent; otherwise, users will receive an email to click a link when they don't need to.

You can do this as follows:

1. `drush cex`
2. Edit `user.settings.yml`
3. Change `cancel_confirm` to `false`
4. `drush cim`

Here is my code with a problem:

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

function MYMODULE_user_cancel_form_submit(&$form, &$form_state) {
  $uid = $form['uid']['#value'];
  $user = \Drupal::currentUser();
  if (!$user->hasPermission('administer users') && $uid == $user->id()) {
    // Hide "A confirmation request to cancel your account has been sent to your email address."
    $messages = drupal_get_messages('status', FALSE);
    if (!empty($messages['status'])) {
      unset($_SESSION['messages']['status']);
    }

    // Cancel the account, from user_cancel_confirm()
    user_cancel($form_state->getValues(), $uid, $form_state->getValue('user_cancel_method'));

    // Since user_cancel() is not invoked via Form API, batch processing needs
    // to be invoked manually and will redirect to the front page after
    // completion.
    batch_process('');

  }
}

```

The **main problem** is that after calling the submit callback, I get the message "The update has been performed.", but the user account is not cancelled.

I used `kint()` to debug and the submit callback is evaluated and `user_cancel` is called, but the account is not actually blocked. Users do have permission to cancel their own accounts.

# Answer
Please use this code snippet it works for me

```
 function simple_pass_reset_form_user_cancel_form_alter(&$form, &$form_state, $form_id) {
  //  dsm($form);
  $form['actions']['submit']['#submit'][] = 'simple_pass_reset_user_cancel_form_submit';
}

function simple_pass_reset_user_cancel_form_submit(&$form, &$form_state) {
  $uid = $form['uid']['#value'];
  // exit;
  $user = \Drupal::currentUser();
  if (!$user->hasPermission('administer users') && $uid == $user->id()) {
    // Hide "A confirmation request to cancel your account has been sent to your email address."
    $messages = drupal_get_messages('status', FALSE);
    if (!empty($messages['status'])) {
      unset($_SESSION['messages']['status']);
    }

    // Cancel the account, from user_cancel_confirm()
    user_cancel($form_state->getValues(), $uid, $form_state->getValue('user_cancel_method'));

    // Since user_cancel() is not invoked via Form API, batch processing needs
    // to be invoked manually and will redirect to the front page after
    // completion.
//You need to run batch process
    $batch = &batch_get();
    $batch['progressive'] = FALSE;
    batch_process('');
  }
}

```
> 3 votes

---
Tags: 8, users
---


# Question
Title: Mathematical operations and Twig variables
Is it legal to do this in a node template with Drupal 8?

```
{% set percentVariable = content.field_my_customfield.0 * 100 / content.field_my_second_customfield.0 %}

```

which will be output like this

```
<div style="width:{{ percentVariable }}{{'%'}}"></div>

```

Both fields deliver integer values to that variable

Is there any major syntax error or misunderstanding in doing so?

# Answer
> 2 votes
Yes, it is *legal* to do mathematical operations in Twig (and in PHP as well). The issue you have is you are trying to calculate render arrays, which doesn't work, no matter which programming language you use. You need to do this on the field values. For example the first value you are looking for:

in PHP:

```
$value = $node->field_my_customfield->value;

```

or in Twig:

```
{% set value = node.field_my_customfield.value %}

```

This code should work then in Twig:

```
{% set percentVariable = node.field_my_customfield.value * 100 / node.field_my_second_customfield.value %}
<div style="width:{{ percentVariable|round }}%"></div>

```

---
Tags: theming
---


# Question
Title: Join table query in hook_views_query_alter not selecting field from joined table
I have the following query

```
SELECT
    node.nid AS nid,
    node.created AS node_created,
    'node' AS field_data_field_gm_tanknummer_node_entity_type,
    'node' AS field_data_field_gm_naam_node_entity_type,
    'node' AS field_data_field_gm_adres_node_entity_type,
    'node' AS field_data_field_gm_postcode_node_entity_type,
    'node' AS field_data_field_gm_jaar_node_entity_type,
    'node' AS field_data_field_gm_bedrijf_levensduur_node_entity_type,
    'node' AS field_data_field_gm_bedrijf_antibiotica_node_entity_type,
    'gemiddelde_waarden:page' AS view_name
FROM
    {node} node
left JOIN
    {field_data_field_gm_tanknummer} field_data_field_gm_tanknummer
ON
    node.nid = field_data_field_gm_tanknummer.entity_id
WHERE
    (( (node.status = :db_condition_placeholder_0)
AND
    (node.type IN (:db_condition_placeholder_1))
AND
    (field_data_field_gm_tanknummer.field_data_field_gm_tanknummer_value IN (:db_condition_placeholder_2)) ))
ORDER BY
    node_created DESC LIMIT 10 OFFSET 0

```

where I join the table `field_data_field_gm_tanknummer`.

I want to select the field `field_data_field_gm_tanknummer_value` from that table but the query cannot find this field.

This is my function

```
function misc_views_query_alter(&$view, &$query) {
  if ($view->name == 'gemiddelde_waarden') {

    //create the join
    $join = new views_join();
    $join->table = 'field_data_field_gm_tanknummer';
    $join->field = 'entity_id';
    $join->left_table = 'node';
    $join->left_field = 'nid';
    $join->type = 'left';
    //add the join the the view query
    $view->query->add_relationship('field_data_field_gm_tanknummer',$join,'node');

    $query->where[1]['conditions'][2]['field'] = 'field_data_field_gm_tanknummer.field_data_field_gm_tanknummer_value';
    $query->where[1]['conditions'][2]['value'] = array(
      0 => _misc_tanknummers()
    );
    $query->where[1]['conditions'][2]['operator'] = 'IN';
  }
}

```

Is there something wrong with the join?

# Answer
There a typo in your SQL query: instead of

```
field_data_field_gm_tanknummer.field_data_field_gm_tanknummer_value

```

you need to specfiy:

```
field_data_field_gm_tanknummer.field_gm_tanknummer_value

```
> 2 votes

---
Tags: 7, views, hooks
---


# Question
Title: How to hide all tabs (local tasks) except the user account tabs?
I want to hide all tabs (local tasks) for non-admin users except the tabs on the user account page (for example, I want to hide tabs on nodes of all content types).

To hide the tabs, I added a check for admin permission in my theme template: `templates/menu/menu-local-tasks.html.twig`

```
{% if user.hasPermission('administer nodes') %}
  {% if primary %}
    <h2 class="visually-hidden">{{ 'Primary tabs'|t }}</h2>
    <ul class="tabs--primary nav nav-tabs">{{ primary }}</ul>
  {% endif %}
  {% if secondary %}
    <h2 class="visually-hidden">{{ 'Secondary tabs'|t }}</h2>
    <ul class="tabs--secondary pagination pagination-sm">{{ secondary }}</ul>
  {% endif %}
{% endif %}

```

This works, but it hides the tabs on the user account page as well.

I tried to find a more specific template of `menu-local-tasks` for the user account. I turned on twig debugging, but these were the suggestions:

```
<!-- FILE NAME SUGGESTIONS:
   * block--mytheme-local-tasks.html.twig
   x block--local-tasks-block.html.twig
   * block--core.html.twig
   * block.html.twig
-->

```

All of these affect the entire site; there is no way to target just the user account local tasks.

Is there a way to do this with theme templates? I chose this approach rather than trying to unset the local tasks in a hook because in a template you can do it in just a line or two of code.

# Answer
> 1 votes
I wouldn't recommend not doing this by code, this can be achieved using built-in configuration settings, by using a second block with proper rules. Try this:

1. Go to `Structure > Block layout`
2. Select your theme
3. Place a second tabs block where-ever you want it
4. Limit the visibility on the block fitting your requirements
    * Most likely limit `Pages` to something like `user/*`
    * and by `Roles`, e.g. `Authenticated user`
    * (remember that administrators are authenticated users too, so you might need more specific roles to to prevent admins seeing tabs block twice; or add the "hide"-option on user-pages for the first, original tabs block )

---
Tags: theming, 8
---


title: Connection process

text:
# Question
Title: Connection process
I have a D7 site online on linux server. I made a backup of it on my Win PC usine Xampp server.

I cannot connect (as user 1) despite i have the correct password.

How to follow to connection process to check where the problem could arise ?

Thank you in advance for your help

Nicolas

# Answer
> 0 votes
As mentioned above, you can reset the password. However if you are syncing with your production site frequently, this will be a pain.

I think the underlying problem is that you did not copy the password hash salt value to your local site.

This is the $drupal\_hash\_salt variable in your settings.php file.

It is used in combination with the password to generate the hash code used to validate your login. So if the salt on Server A is different than Server B, the hash will be different for the same password.

Note that some hosting services might be setting the drupal hash salt for you in an external file. Make sure to check there as well.

---
Tags: configuration
---


# Question
Title: Show <div> on user page if user page belongs to current user
I have made a page that displays information about a user, much like a profile page.

Now I want users to be able to edit their information, so I added a button using twig tweak in `user.html.twig`:

```
{% if logged_in %}
<div class = "row">
    <a href ="{{ drupal_token('current-user:edit-url') }}" class = "edit-profile-btn col-lg-12">
      <div>Edit profile</div>
    </a>
</div>
{% endif %}

```

This works fine, however the button is displayed on every profile page. I want to hide the button if a user is viewing another user's page.

> Can this be done using an `{{ if statement }}` to check if the viewed page belongs to the logged in user?

# Answer
To do this right you will need to use this combination of tests.

Is the user logged in {% if logged\_in %} ?

Does the user have the permission needed to edit their profile with {% if user.hasPermission('depends on your site setup') %}?

Is the owner of the node the same as the current user? {% if node.ownerId == user.id %}

NOTE: The snippets above are not tested. You may have to tweak to get the correct info (e.g. getOwnerId SHOULD equal node.ownerId.. but twig may have a different opinion).
> 1 votes

---
Tags: theming, 8, users
---


# Question
Title: Add a button in user orders view requesting info about current order Drupal Commerce 7
I have an automated e-shop in Drupal 7 and drupal commerce.

I am trying to add an action button in user orders view, which on "pressing" by every current user is sending email(alert with replacement tokens about current selected order) to administrator of eshop.

Any ideas to implement action button?

I tried VBO and Views Send modules but i didn't succeded.

# Answer
> 0 votes
You can use the Rules module.

1. Create a component with the **Action** *Send mail*. Use tokens to customize the subject and message body as you like.
2. Edit the view and use VBO to trigger the rules component.

---
Tags: 7, commerce, views
---


# Question
Title: How to create a rule that checks an extra profile field created with the core profile module?
I have a Drupal 7 site with the Honeypot module installed. Honeypot removes or prevents many spam registrations, but not all. I have extra fields added to the profile e.g. 'profile\_field1'. I'd like to build a rule using the Rules modules that either deletes an account or prevents it from being created if the content of the 'profile\_field1' doesn't match a certain regular expression. I cannot find how to create a rule that can handle an extra profile field. What I'd like to create:

```
'before saving a new user account'
if profile_field1 does not match RegExPattern
then prevent account from being created

```

I can find how to create a condition based on the 'regular' fields in the account (such as the name), but I cannot find how to test for the extra fields.

**Update 1**: the field 'profile\_field1' is part of the Users profile, i.e. the Drupal Profile module is enabled. This module is part of D7 and similar in functionality to drupal.org/project/profile (for D8). It's found in \[drupal\]/modules/profile. Configuration settings are in admin/config/people/profile.

**Update 2**: I checked in the database. There is no table called 'profile\_field1'. The info is in 'profile\_field' which defines all fields and in profile\_value, which contains all values. So, e.g. profile\_field1 would be fid=1 in table profile\_field. Then user 5 (uid = 5) would have a record in profile\_value with fid = 1, uid = 5, value = 'content of field'.

**Update 3**: With the suggestions in the answer I was able to migrate the information from the old Profile to the Profile2 fields. Write up is here: https://www.drupal.org/node/2916659

**Update 4**: At least I can create a Rules rule now. Just wondering if this is the best:

```
{ "rules_prevent_spam_registration" : {
    "LABEL" : "Prevent spam registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_presave" : [] },
    "IF" : [
      { "entity_has_field" : {
          "entity" : [ "account-unchanged:profile-personal" ],
          "field" : "field_profile_field1"
        }
      },
      { "AND" : [
          { "text_matches" : {
              "text" : [ "account-unchanged:field-profile-field1" ],
              "match" : "<regexPattern>",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [ { "entity_delete" : { "data" : [ "account-unchanged" ] } } ]
  }
}

```

# Answer
> 1 votes
With the limited info provided in your question, the best bet is that you cannot test for that extra field because you forgot to add a Rules Condition like "entity has field" (related to your `profile_field1` field). So add that Rules Condition first (as your very first Rules Condition), and then try again.

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

**Update**:

As per your updates to your question, I now understand that you're using the deprecated (core) `profile` module. This is a quote from its .info file:

> ; The Profile module is deprecated, and included in Drupal 7 for legacy
>
> ; purposes only. By default, the module will be hidden from the UI unless you
>
> ; are upgrading a site that uses the Profile module to extend user profiles.

Because of that, I doubt that there is a way to use the Rules module to check "*if the content of the 'profile\_field1' doesn't match a certain regular expression*" (as in your question). Mostly because the Rules Condition like "entity has field" (= typical prereq to configure these kinds of Rules Conditions) will not have any effect for such `profile_field1`-field. Maybe not the answer you would want to hear/read, but I'm afraid it explains that what you're asking for cannot be done with Rules.

**Plan-b**:

Give it some thought to consider switching to the Profile 2 module. Quote from its project page:

> Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!
>
> **Features**
>
> ... Thanks to the foundational entity API the module integrates well with Rules ...

If you do, pretty sure my original answer (= add a Rules Condition like "entity has field") will turn out to be the solution for what you try to achieve.

---
Tags: 7, users, rules
---


# Question
Title: */ appearing at end of body text in modules
I am managing a Drupal site and when I add new content (usually events in a calendar) \*/ always appears at the end of the text field (see example below). I have deleted extra lines and spaces as I thought that might be the cause, but that hasn't worked. I can't locate it in the html but I might be looking in the wrong place. I'm really a novice in all things Drupal.

# Answer
> 0 votes
It looks like a CSS comment end tag. So I am guessing a syntax error. I would inspect the source and find out exactly were the tag is coming from. Then fix the syntax (either by removing the comment tag or adding correct starting comment tag)

# Answer
> 0 votes
This could also be appearing in the php template itself. You can verify this by switching the site theme to one of the included themes with your Drupal installation and seeing if it still appears; if not, it's definitely in your custom/modified theme.

Then, you can switch your theme back on and inspect the source code of some of the impacted pages to determine if it appears consistently in a particular DOM element/section on the page.

Based on that, you can narrow down and determine if it's inline css in a template file or some other random block comment from javascript or php that isn't properly wrapped.

Presuming you haven't added several custom templates, common templates to check in your theme are:

* html.tpl.php
* page.tpl.php
* node.tpl.php

and any variants of those.

---
Tags: theming
---


title: How to delete all unpublished comments?

text:
# Question
Title: How to delete all unpublished comments?
I have literally thousands of unpublished comments. I am wondering what is the easiest way to git rid of them altogether.

Thanks

# Answer
> 1 votes
For Drupal 6, run the following PHP code:

```
db_query('DELETE FROM {comments} WHERE status = 1');

```

For Drupal 7, run the following PHP code:

```
db_query('DELETE FROM {comment} WHERE status = 0');

```

You can also execute the query using Drush's sql-query command, for example

```
drush sql-query "DELETE FROM {comment} WHERE status = 0"

```

# Answer
> 6 votes
The better way I think is to use Views and Views Bulk Operations and you can do a simple admin interface to delete all of them.

Otherwise, you still can delete directly throw a SQL query.

# Answer
> 2 votes
For those using Drupal 7, using VBO has changed and the above comments about choosing Bulk Operations as the view style is not correct. Here are the steps to create a VBO page with Drupal 7 (I'll use the example of deleting all comments)

* Create a view where you show Comments and create a page
* You'll need to format it in a way that allows you to add fields (table is a handy format)
* Add a Bulk operations: Comment field and for the settings for this field, under SELECTED BULK OPERATIONS choose Delete item (you can opt to skip the confirmation step here)
* If you have a lot of comments, under Pager for this view display something like 200 at a time (it will be slow but you won't have to repeat your deletes lots of times)
* Save your view and then go to the page you created. You should be able to select all the items and then choose Delete under operations. You can then confirm the delete and repeat as necessary.

# Answer
> 1 votes
you can review this steps

* Install the views bulk operations module,
* create a page view of comments, and choose "Bulk Operations" as the view style.
* Make sure you select "Delete comment" as one of the selected operations.
* When you view the view page you created, you'll be able to bulk delete comments.

Regards

# Answer
> 0 votes
For Drupal 7, this is really easy to achieve.

1. Navigate to `Content > Comments > Unapproved comments`.
2. Select the upper left radio button to select all rows in the table.
3. Select "Delete the selected comments" in the drop down list at the top.
4. Hit the 'Update' button.

# Answer
> 0 votes
I would usually recommend to use VBO to delete comments or nodes in bulk but if you are in a situation when you have hundreds of thousands of comments and you don't have too much time, here is a sql query which will delete all unapproved comments along with all the revisions and data related to those comments which in my case was taking 1.2Gb of space in DB

```
DELETE c, rcb, dcb
FROM
    comment AS c
JOIN field_revision_comment_body AS rcb ON (c.cid = rcb.entity_id)
JOIN field_data_comment_body AS dcb ON (rcb.entity_id = dcb.entity_id)
WHERE
    c. STATUS = 0

```

# Answer
> 0 votes
Actually this worked for me:

```
drush sql-query "DELETE FROM comment WHERE status = 0"

```

i.e. no curly braces required.

However as explained elsewhere there are other tables in the db that reference comments so this approach is not advisable.

maybe there needs to be a module to do this properly, including field\_data\_comment\_body, field\_revision\_comment\_body etc Would be useful if you have a gazillion unpublished comments.

In the meantime this post here shows a better way:

DELETE FROM field\_data\_comment\_body USING field\_data\_comment\_body JOIN comment ON comment.cid=field\_data\_comment\_body.entity\_id AND comment.status=0;

DELETE FROM field\_revision\_comment\_body USING field\_revision\_comment\_body JOIN comment ON comment.cid=field\_revision\_comment\_body.entity\_id AND comment.status=0;

DELETE FROM comment WHERE status=0;

https://www.drupal.org/forum/general/general-discussion/2010-05-16/mass-delete-spam-comments#comment-10964889

---
Tags: comments
---


# Question
Title: How to disable adding new terms via the autocomplete deluxe module for taxonomy terms?
I'm using the autocomplete deluxe module for taxonomy terms in my fields. I want to prevent users from creating new terms during content creation. How can this be done?

# Answer
You can use the content taxonomy module: https://www.drupal.org/project/content\_taxonomy

On the content type fields that are taxonomy reference fields there will now be an extra option that says: **Deny any new terms** checkbox

It will throw this error when creating a new term:

**Client: new terms are not allowed. Please choose from the suggested options.**

---

Apparently there are other solutions I found aswell:

https://www.drupal.org/project/taxonomy\_autocomplete\_permission -- but it isn't working for autocomplete deluxe.

And there were a few discussions where it involved hacking core to disable it. The content taxonomy module seems to be the only way. It would be better if we didn't have to install another module.
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: Programmatically load the page variant being used on path or node object
I'm attempting to be able to load a page variant given a specific path. My ultimate goal is to loop through all the links in a menu, find out what page\_manager variant is being used and load the context data from that variant. I'm able to grab the data just fine if I manually supply a page id. Below is me obtaining the data from the about page I've created in page manager.

```
$page_storage = \Drupal::entityTypeManager()->getStorage('page');
$variant_storage = \Drupal::entityTypeManager()->getStorage('page_variant');
$about = $page_storage->load('about');
$about_variant = $about->getVariants();
$about_variant = reset($about_variant);
foreach($about_variant->getContexts() as $context){
    $label = $context->getContextDefinition()->getLabel();
    if($label == 'Icon'){
        var_dump($context->getContextValue());
    }
}

```

This works just fine. But what if I want to load the context data of each link in a menu? These are links that I can't anticipate. Also some of these links will be regular pages and some will be actual nodes that also have their own variant.

I can load the nodes from the route like so

```
$params = \Drupal\Core\Url::fromUserInput($path)->getRouteParameters();
if (isset($params['node'])) {
    $node = \Drupal\node\Entity\Node::load($params['node']);
    //We have a node which I don't know how to get the variant of
} else {
    //We have a regular page that I don't know obtain the id of
}

```

But even though I have the node I have no idea of a way to interface with it in a way that allows me to obtain the page variant I'm using. If it's a regular page, then as long as I have the page id of it I can load the page variant like I have done before, but I don't know how to obtain that.

So ultimately I suppose I need to be able to programmatically obtain two things

* How to obtain the page id from a page given its path
* How to see the page variant being used on a node

UPDATE: I did manage to obtain the page with this line

```
$page = \Drupal::entityTypeManager()->getStorage('page')->loadByProperties(['path' => $link]);

```

Still not sure how to grab the variant the node is using yet though.

# Answer
In order to get the variant being used by the node I was able to retrieve the info inside the array returned by

```
$node->panelizer->getValue()

```

And to get the page I used

```
$page = \Drupal::entityTypeManager()->getStorage('page')->loadByProperties(['path' => $link]);

```
> 1 votes

---
Tags: 8, panels
---


# Question
Title: How can I remove the %20 from a URL evaluted by a contextual filter?
I have a contextual filter that is set to evaluate the "Raw value from URL" against my taxonomy term name. The issue is that a few of my taxonomy terms are two or three words long. This results in a URL like:

https://example.com/category/my%20taxonomy%20term

What I want is for my url to be:

https://example.com/category/my-taxonomy-term (but this currently returns no results).

Is there a way to use dashes instead of the %20 in a views contextual filter that uses the "Raw value from URL" setting?

# Answer
Don't worry, Drupal won't leave you hanging with ugly urls.

1) Open your contextual filter in the admin interface.

2) Expand the "More" section at the bottom.

3) Check "Transform spaces to dashes in URL"

Terms like "my-taxonomy-term" will now be processed as "my taxonomy term"

Bonus: If you need that term to be capitalized for the page title, change "Case" to "Capitalize each word" (also in the "More" section).
> 5 votes

---
Tags: 7, views
---


# Question
Title: How to inject a service in another service?
I am building a custom service, a membership service. This service can be called from a controller. But what I don't seem to get working, is to use another service, the QueryFactory, to use in that custom service.

the membership service:

```
namespace Drupal\hsbxl_members;
use Drupal\Core\Entity\Query\QueryFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class MembershipService.
 */
class MembershipService {
  protected $hsbxl_member;
  protected $entityQuery;

  public function __construct(QueryFactory $entityQuery) {
    $this->entity_query = $entity_query;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity.query')
    );
  }

  public function MembershipsAll() {
    $query = $this->entity_query->get('node');
    $query->condition('status', 1);
    $nids = $query->execute();
    return "Hello World!";
  }
}

```

services file:

```
services:
  hsbxl_members.membership:
    class: Drupal\hsbxl_members\MembershipService
    arguments: ['@entity.query']

```

Can anyone point me out on this? What am I doing wrong / am I missing?

Tom

# Answer
> 7 votes
The service you need is `entity_type.manager`:

.services.yml

```
services:
  hsbxl_members.membership:
    class: Drupal\hsbxl_members\MembershipService
    arguments: ['@entity_type.manager']

```

MembershipService.php

```
namespace Drupal\hsbxl_members;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Class MembershipService.
 */
class MembershipService {
  protected $hsbxl_member;
  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public function MembershipsAll() {
    $query = $this->entityTypeManager->getStorage('node')->getQuery();
    $query->condition('status', 1);
    $nids = $query->execute();
    return "Hello World!";
  }
}

```

The `create()` method is unnecessary as services use constructor injection.

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: How to selectively import and export specific content without overriding existing destination database?
I want my client to contribute content to the website, but the problem is, I'm simultaneously doing work on the site, modules, theming, adding stuff also etc...

I'm aware of the features module and can import and export selective tables with backup migrate or even phpmy admin, but it's tedious and error prone...

What data I want to import and export is:

```
- Content type
- Taxonomies
- Content itself including text and images(can ftp them manually no problem)

```

What would be an easy and simple solution for this without getting into code or shell access?

# Answer
As you already mentioned, use features module to transfer configuration.

For actual content, you will need to use Views Data Export to export stuff. Make a CSV file.

VDE tutorial

Then use Feeds module to import the CSV file content into your other site.

Feeds Tutorial

Alternatively, for nodes you could just use Node Export, but you will still need feeds for the taxonomy importing.
> 1 votes

---
Tags: 7, importing-exporting
---


# Question
Title: Redirect After User Registration if Referred from Specific URL
I have been trying to redirect users after filling out the user registration if referred from a specific page on the site with form\_alter like so

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

if($form_id == 'user_register_form' && strpos($_SERVER['HTTP_REFERER'],
'/resources/price-sheets') > 0 ) {

    $form_state['redirect'] = 'node/50';

    }
}

```

If I `dpm($form_state)` on the user/registration page it shows the `$form_state['redirect'] = 'node/50';` as it should. But when I submit the form it redirects me to the home page. I also tried replacing `$form_state['redirect'] = 'node/50';` with `$_GET['destination'] = 'node/50';` with the same results. I've found a few similar questions, but none of those answers are working for me either, does anyone have a good working solution?

# Answer
The user register form isn't a normal form in the sense that its validation and submit are overridden by a number of functions in core's user.module including creating the account, sending out the confirm email, and then logging the user in. So I don't think a simple form\_alter for the form redirect will help you because it will be overridden later by the login function.

Also you can't simply replace `$form_state['redirect'] = 'node/50';` with `$_GET['destination'] = 'node/50';` The destination querystring needs to be part of the page's url BEFORE the register form is served. So adding it as part of the form\_alter I don't think will change anything. What you can do is:

```
if($form_id == 'user_register_form' && strpos($_SERVER['HTTP_REFERER'],
'/resources/price-sheets') > 0 && !isset($_GET['destination'])) {
    drupal_goto('user/register?destination=node/50';
    }
}

```

Alternately, you can also try to use the hook\_user\_login, detailed in user.api.php and add your redirect there which will fire after the user has registered successfully (and is now logged in).

One other solution would be to use the Login Destination module which:

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them.
> 2 votes

# Answer
I think you need to set the redirect in a submit handler. Add your custom submit handler to `$form` and then in your custom submit handler set `$form_state['redirect']` to where you want it to go. Doing it in a `form_alter` could be why it's not working. See Redirecting a Form

```
function my_redirect_form_my_content_type_node_form_alter(&$form, &$form_state){
  $form['#submit'][] = 'my_redirect_node_form_submit';
}

function my_redirect_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/10'; // the address of your thank you page
  // if you are really, really determined to force the redirect, even if a destination has been set in the url, add this:  unset($_GET['destination']);
  // you could also add a message (this is in addition to whatever message is produced by the nodeapi function): drupal_set_message(t('Congratulations!'));
}

```
> 2 votes

---
Tags: 7, users, redirection
---


# Question
Title: How do I show the contact form in panels?
I have installed panels and Panelizer modules and used the core contact form.

There is no feature available for adding contact form in the panels.

How do I add the contact form in Panels without using the form Block module or other moudle?

# Answer
> 1 votes
This can be achieved by creating new block type without using any contributed modules.

In Block Layout,

1. Create a new block type.
2. Add a new field and choose other in entity reference.
3. Choose Contact Form in the Types of item to reference.

then this will be used to create the entity as block.

And then the block can be assigned in the particular region in Panels.

# Answer
> 1 votes
Please use contact\_block, because `ctools` use blocks please see module `ctools_block` in module `ctools`.

---
Tags: 8, panels, emails
---


# Question
Title: I cannot upgrade from RC1 - "drupal/commerce_price locked at 2.0.0-rc1" or "nothing to install or update"
I started from scratch for a new site, using Composer for all of it. Drupal core is at 8.3.7, and Commerce is at 2.0-RC1 (because those were the levels of another site that I was having trouble with that I needed to correct). All is working well.

In another post over on Drupal.org someone advised me not to make updates of Commerce that jump more than one release. So I planned to go to RC2, then RC3, then the move to 8.4 and the full 2.0 version of Commerce.

Try as I might, I cannot get any type of Commerce upgrade to work (I'm still staying at Core 8.3.7 for the time being) - either to RC2, RC3 or 2.0. I've tried every possible permutation of update and require, specifying the product as simply drupal/commerce and drupal/commerce:2.0-rc2, leaving the rest of the command blank or using `--with-dependencies` or `--update-with-dependencies`, etc.

No matter what I do, it keeps telling me that drupal/commerce\_price is locked at 2.0.0-rc1, or that there is nothing to do.

For example, when I run `composer require "drupal/commerce:2.0-rc2" --update-with-dependencies`, I get:

> ./composer.json has been updated
> Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.
>
> ### Problem 1
>
> * drupal/commerce\_price 2.0.0-rc1 requires drupal/commerce 2.0.0-rc1 -\> satisfiable by drupal/commerce\[2.0.0-rc1\] but these conflict with your requirements or minimum-stability.
> * drupal/commerce\_price 2.0.0-rc1 requires drupal/commerce 2.0.0-rc1 -\> satisfiable by drupal/commerce\[2.0.0-rc1\] but these conflict with your requirements or minimum-stability.
> * drupal/commerce\_price 2.0.0-rc1 requires drupal/commerce 2.0.0-rc1 -\> satisfiable by drupal/commerce\[2.0.0-rc1\] but these conflict with your requirements or minimum-stability.
> * Installation request for drupal/commerce\_price (locked at 2.0.0-rc1) -\> satisfiable by drupal/commerce\_price\[2.0.0-rc1\].

If I run `composer update drupal/commerce --with-dependencies`, I get:

> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Nothing to install or update
> Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

When I try `composer require drupal/commerce --update-with-dependencies`, I get:

> Using version ^2.0 for drupal/commerce
> ./composer.json has been updated
> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Nothing to install or update
> Writing lock file
> Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

These are the commerce-related entries returned from `composer outdated`.

> drupal/commerce 2.0.0-rc1 2.0.0 \> Drupal Commerce is a flexible eCommerce solution. drupal/commerce\_order 2.0.0-rc1 2.0.0 \> Defines the Order entity and associated features. drupal/commerce\_payment 2.0.0-rc1 2.0.0 \> Provides payment functionality. drupal/commerce\_price 2.0.0-rc1 2.0.0 \> Defines the Currency entity. drupal/commerce\_store 2.0.0-rc1 2.0.0 \> Defines the Store entity and associated features.

So there is work to be done. Why won't Composer allow me to make to upgrades?

To provide a little more information, this is the main part of the *composer.json* file.

```
"require": {
    "composer/installers": "^1.0.24",
    "wikimedia/composer-merge-plugin": "~1.4",
    "drush/drush": "^8.1",
    "drupal/ctools": "^3.0",
    "drupal/embed": "^1.0",
    "drupal/token": "^1.0",
    "drupal/addtoany": "^1.8",
    "drupal/admin_toolbar": "^1.20",
    "drupal/admin_toolbar_tools": "^1.20",
    "drupal/back_to_top": "1.x-dev",
    "drupal/contact_block": "^1.4",
    "drupal/contact_storage": "1.x-dev",
    "drupal/copyright_block": "1.x-dev",
    "drupal/ds": "^3.1",
    "drupal/entity_browser": "^1.3",
    "drupal/entity_embed": "1.x-dev",
    "drupal/honeypot": "^1.27",
    "drupal/social_media_links": "^2.5",
    "drupal/textarea_widget_for_text": "^1.0",
    "drupal/video_embed_field": "^1.5",
    "drupal/webform": "5.x-dev",
    "drupal/panelbutton": "^1.1",
    "drupal/colorbutton": "^1.1",
    "drupal/ckeditor_font": "^1.0",
    "drupal/google_analytics": "^2.2",
    "drupal/google_analytics_reports": "3.x-dev",
    "drupal/metatag": "^1.3",
    "drupal/pathauto": "^1.0",
    "drupal/redirect": "1.x-dev",
    "drupal/sitemap": "^1.3",
    "drupal/w3c_validator": "^1.3",
    "drupal/commerce": "^2.0",
    "drupal/search_api": "^1.5",
    "drupal/commerce_authnet": "1.x-dev",
    "drupal/commerce_paypal": "1.x-dev"
},
"replace": {
    "drupal/core": "~8.3"
}

```

Note that the entry for drupal/commerce has been added after I ran the commands listed above. I checked my archive and its value started out as `"drupal/commerce": "2.0-rc1"`.

These are parts of the *composer.lock* file after I ran those commands.

```
        "name": "drupal/commerce_store",
        "version": "2.0.0-rc1",
        "require": {
            "drupal/commerce": "self.version",
            "drupal/commerce_price": "*",
            "drupal/core": "*"
        },
        "type": "metapackage",
        "extra": {
            "branch-alias": {
                "dev-2.x": "2.x-dev"
            },
            "drupal": {
                "version": "8.x-2.0-rc1",
                "datestamp": "1504208045",
                "security-coverage": {
                    "status": "not-covered",
                    "message": "RC releases are not covered by Drupal security advisories."
                }
            }
        },

       "name": "drupal/commerce",
        "version": "2.0.0-rc1",
        "source": {
            "type": "git",
            "url": "https://git.drupal.org/project/commerce",
            "reference": "8.x-2.0-rc1"
        },
        "dist": {
            "type": "zip",
            "url": "https://ftp.drupal.org/files/projects/commerce-8.x-2.0-rc1.zip",
            "reference": "8.x-2.0-rc1",
            "shasum": "e82857cd23c7eebe32a7fa14002d7ab2156dc0a6"
        },
        "require": {
            "commerceguys/intl": "~0.7",
            "drupal/address": "~1.0",
            "drupal/core": "~8.3",
            "drupal/entity": "~1.0",
            "drupal/entity_reference_revisions": "~1.0",
            "drupal/inline_entity_form": "~1.0",
            "drupal/profile": "~1.0",
            "drupal/state_machine": "~1.0",
            "ext-bcmath": "*"
        },
        "require-dev": {
            "drupal/commerce_cart": "*",
            "drupal/commerce_order": "*",
            "drupal/commerce_payment": "*",
            "drupal/commerce_price": "*",
            "drupal/commerce_product": "*",
            "drupal/commerce_store": "*",
            "drupal/entity_reference_revisions": "*",
            "drupal/inline_entity_form": "*",
            "drupal/profile": "*",
            "drupal/state_machine": "*"
        },
        "type": "drupal-module",
        "extra": {
            "branch-alias": {
                "dev-2.x": "2.x-dev"
            },
            "drupal": {
                "version": "8.x-2.0-rc1",
                "datestamp": "1504208045",
                "security-coverage": {
                    "status": "not-covered",
                    "message": "RC releases are not covered by Drupal security advisories."
                }
            }

        "name": "drupal/commerce_order",
        "version": "2.0.0-rc1",
        "require": {
            "drupal/commerce": "self.version",
            "drupal/commerce_price": "*",
            "drupal/commerce_store": "*",
            "drupal/core": "*",
            "drupal/entity_reference_revisions": "*",
            "drupal/profile": "*",
            "drupal/state_machine": "*"
        },
        "type": "metapackage",
        "extra": {
            "branch-alias": {
                "dev-2.x": "2.x-dev"
            },
            "drupal": {
                "version": "8.x-2.0-rc1",
                "datestamp": "1504208045",
                "security-coverage": {
                    "status": "not-covered",
                    "message": "RC releases are not covered by Drupal security advisories."

       "name": "drupal/commerce_price",
        "version": "2.0.0-rc1",
        "require": {
            "drupal/commerce": "self.version",
            "drupal/core": "~8.0"
        },
        "type": "metapackage",
        "extra": {
            "branch-alias": {
                "dev-2.x": "2.x-dev"
            },
            "drupal": {
                "version": "8.x-2.0-rc1",
                "datestamp": "1504208045",
                "security-coverage": {
                    "status": "not-covered",
                    "message": "RC releases are not covered by Drupal security advisories."
                }
            }

        "name": "drupal/commerce_store",
        "version": "2.0.0-rc1",
        "require": {
            "drupal/commerce": "self.version",
            "drupal/commerce_price": "*",
            "drupal/core": "*"
        },
        "type": "metapackage",
        "extra": {
            "branch-alias": {
                "dev-2.x": "2.x-dev"
            },
            "drupal": {
                "version": "8.x-2.0-rc1",
                "datestamp": "1504208045",
                "security-coverage": {
                    "status": "not-covered",
                    "message": "RC releases are not covered by Drupal security advisories."
                }
            }

```

# Answer
I tried what Patrick Kenney suggested in the comments:

```
Delete composer.lock
delete /vendor
composer install

```

and it didn't work. It was still complaining about **commerce\_price** being locked at the RC1 version.

So I reloaded my backup and tried it again, only this time I made sure the line for **drupal/commerce** was also removed from the **composer,json** file. Then I did a **composer require drupal/commerce**. All seems OK now - fingers crossed.

In addition, I seem to recall reading this elsewhere, but to make sure the install of Drupal core for 8.4 worked correctly, I also had to move the **drupal/core** entry in **composer.json** from the **replace** to the **require** section.

Thanks for the help, Patrick!
> 0 votes

# Answer
There are indeed some issues with updating Commerce with Composer. These are related to how packages.drupal.org is implemented. The reason of this issue is that contributed Commerce modules depend on a 'submodule' of Commerce. Commerce Shipping for example depends on Commerce Order and on Commerce Price.

Solution from https://www.drupal.org/node/2906495#comment-12254258:

1. Run `composer why drupal/commerce` to see which packages depend on Drupal Commerce, for example:

```
drupal/commerce_order    2.0.0-rc1               requires  drupal/commerce (self.version)
drupal/commerce_payment  2.0.0-rc1               requires  drupal/commerce (self.version)
drupal/commerce_price    2.0.0-rc1               requires  drupal/commerce (self.version)
drupal/commerce_store    2.0.0-rc1               requires  drupal/commerce (self.version)
.....

```
2. Run composer update and include every composer package that says 'self.version', for example:

```
composer update drupal/commerce drupal/commerce_order drupal/commerce_payment drupal/commerce_price drupal/commerce_store

```

This gets around composer insisting that you need exactly the version that is installed for the subcomponents, despite the fact that they should all be satisfied with whatever version is already installed.

**Alternative solution: `composer update`**

An alternative solution is to run just `composer update`. Composer will then update all packages, including Symfony components. There is a little risk in doing this: the latest versions of Symfony components are not guaranteed to be compatible with the latest Drupal version.
> 0 votes

---
Tags: commerce, composer
---


# Question
Title: How to override a ctools plugin from another module
I want to modify some logic of a ctools plugin defined in the `entityqueue` module.

The file that contains the ctools plugin definition I want to modify is: `/entityqueue/plugins/entityreference/behavior/entityqueue.inc`link to file

This file makes use of the class `EntityReferenceBehavior_EntityQueue` which is defined here. I want to modify the logic in the presave function.

Is there a way to hook into it without patching the file?

# Answer
> 0 votes
I am not entirely sure if this is the best solution but I ended up doing the following:

* implemented hook\_ctools\_plugin\_pre\_alter()

```

function my_module_ctools_plugin_pre_alter(&$plugin, &$info) {
      if ($info['type'] == 'behavior' && $info['module'] == 'entityreference' && $plugin['class'] == 'EntityReferenceBehavior_EntityQueue') {
        $plugin['class'] = 'EntityReferenceBehavior_EntityQueue';
        $plugin['path'] = drupal_get_path('module', 'my_module')  . '/plugins/entityreference/behavior';
        $plugin['file'] = 'entityqueue.inc';
        module_load_include('php', 'my_module', '/plugins/entityreference/behavior/EntityReferenceBehavior_EntityQueue.class');
      }
    }

```
* Then I copied the files ('/plugins/entityreference/behavior/EntityReferenceBehavior\_EntityQueue.class' and '/plugins/entityreference/behavior/entityqueue.inc') in my module and modified the code of presave function.

---
Tags: 7, chaos-tool-suite
---


# Question
Title: Search not finding search term from page title
Using the default database search index in drupal 8, when I search for a term from the a page title, sometimes it shows the result and sometimes it shows nothing, even though i enter the exact page title in the search. All pages have been indexed.

How can I debug why the search term is not being returned?

# Answer
> 0 votes
This is easy to debug, because the search index is built of rendered nodes with the view mode `search_index`. So you could build a view displaying all nodes with this view mode and check the result:

Edit:

The node search plugin adds the title to the rendered node, so if the page title is the node label, it should be included in the search index:

*NodeSearch::updateIndex():*

```
  $build = $node_render->view($node, 'search_index', $language->getId());
  ...
  // Add the title to text so it is searchable.
  $build['search_title'] = [
    '#prefix' => '<h1>',
    '#plain_text' => $node->label(),
    '#suffix' => '</h1>',
    '#weight' => -1000
  ];
  $text = $this->renderer->renderPlain($build);

```

---
Tags: 8, search
---


# Question
Title: How to debug and fix error [fcgid:warn] (OS 109)The pipe has been ended , get overlap result error, [core:error] End of script output before headers
I’m using :

* Drupal 8 on Acquia DevDesktop version 2 with php 7.0.15.
* php\_mode is set to FAST CGI (mod\_fcgid).
* Info from the phpinfo() Apache/2.4.18 (Win32) OpenSSL/1.0.2j mod\_fcgid/2.3.9

The problem is I’m getting 500 internal errors very frequently.

In the apache log this is displayed for each 500 error log as follows

```
[Thu Nov 09 09:24:36.140248 2017] [fcgid:warn] [pid 17112:tid 1268] (OS 109)The pipe has been ended.  : [client 127.0.0.1:56192] mod_fcgid: get overlap result error, referer: http://inzicht5.dd:8083/

[Thu Nov 09 09:24:36.140750 2017] [core:error] [pid 17112:tid 1268] [client 127.0.0.1:56192] End of script output before headers: index.php, referer: http://inzicht5.dd:8083/

```

Therefore I added into php.ini

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

And I added in php.ini

```
error_log = C:\php_errors.log

```

Activated error.log in php.ini. Checked by phpinfo(). But still no php error is shown up. Yes, I restarted the server

I already installed MS distribution C++ 2015 version 14.024215

But still I do not get more information. Also I googled a lot of sites for this error but none of them are giving me directions.

How to get more debug information about this error? How to solve it?

# Answer
> 1 votes
This issue should be fixed in the newest Varbase release. See: https://www.drupal.org/node/2912709

---
Tags: 8, acquia-dev-desktop
---


title: How do I use composer with modules?

text:
# Question
Title: How do I use composer with modules?
I'm working on a custom module and want to use phpoffice/phpexcel

I can install the library just fine with `composer require phpoffice/phpexcel`, but what if I update Drupal-Core to a new version and by doing so override the composer.json? I would have to remember to do another `composer require ...` to add the dependency again.

What is the right way of doing this? I have a similar problem with the address-Module, which also requires to be installed with composer.

# Answer
To avoid overriding composer.json file you should update drupal/core using composer too.

https://www.drupal.org/docs/8/update/update-procedure-in-drupal-8

To update only drupal/core you will have something like

`composer update drupal/core --with-dependencies`

Which will only update the composer.json file, not overriding it.

\[EDIT\] **Before you begin** ( from documentation )

1. Always take a backup of your files and db before updating.
2. If you're using composer and version control, also commit and push composer.json and composer.lock. Use mysqldump to backup your database. Modules such as Backup and Migrate are also available.
3. Alternatively, you can create a .tar.gz of files and the database with drush archive-dump (however this is a legacy command, slated for removal in Drush 9, which only covers files under /web).
4. Read the core release notes and, as a precaution, check the project page for each contributed module, theme or plugin: some may need updating to work with a new "minor" version (e.g. 8.3) of core. Patch releases (e.g. 8.3.1) shouldn't require this, but it's advisable to test in a development environment first.
5. Activate maintenance mode when updating production servers.
> 0 votes

---
Tags: composer
---


# Question
Title: Adding 'Add to Cart' to 'Collection Products' view
I want to add an Add to Cart button to my products when they are still in the Collection Products view (Category overview). By default, when you navigate to a category like `/commerce_kickstart/product-category/sample-category-1`, you will find the single products display like this:

I would like to have all of the single products be shown like this:

In the Product Display content type, the add-to-cart-form is stored in `$content` variable. It is pretty easy to access via `field_product`and I can for example add multiple forms and stuff. But how can I get the form in the Collections Product view? I went to Structure -\> Views -\> Collection Products -\> Field and looked through the available fields. I found `field_product` but when I add this, everthing that changes is that a link to the product is shown underneath the price.

So how can I add this to the Category overview?

Edit:

I have added this field (because the name appeared to be familiar scince the cart form is stored in this variable (`field_product`) in `node--product_display`

https: //i.stack.imgur.com/CaNo9.png

And that caused this to appear, wich only adds a link to the product underneath the price.

https: //i.stack.imgur.com/1vbWW.png

And this is basically all the configuration besides some more irrelevant stuff:

https: //i.stack.imgur.com/fk9BB.png

# Answer
In your view, can you add a relationship to the product category in your cart? It should be visible as Referenced Entity or Referenced Product... basically in views you need to join your node/product to its related store/product, once you have done that you should see an available field "% to buy" with the formatter "add to cart button"
> 0 votes

---
Tags: 7, views, commerce
---


title: Taxonomy term route name?

text:
# Question
Title: Taxonomy term route name?
I am trying to make a custom taxonomy breadcrumbs based the code from this question: Drupal 8 How to do a custom taxonomy breadcrumb?

This line adds a new breadcrumb for the home page:

```
$breadcrumb->addLink(Link::createFromRoute(t('Home'), 'front'));

```

PS: I removed parenthesis from front to display line here.

I want to add another breadcrumb with the text of the name of a taxonomy term and the URL of the same term:

```
$breadcrumb->addLink(Link::createFromRoute(t($term->getName()), $url));

```

I cannot figure out how to replace "front" with the route name of the `$term` object.

# Answer
Since taxonomy terms are entities, you can simply do this:

```
$link = $term->toLink();
$breadcrumb->addLink($link);

```

As a side-note, the route name for taxonomy terms is "entity.taxonomy\_term.canonical".
> 4 votes

---
Tags: 8, taxonomy-terms, routes, breadcrumbs
---


# Question
Title: How do I revert the changes made by a specific user?
I want to revert the changes made by a specific admin user in Drupal 6.37. In all the pages that I want to revert, the create new revision box was not selected. Hence, I have no way of finding out the changes.

# Answer
If you don't have revisions you can't rollback the changes unless you have a database backups that you can use to restore and old copy of your site.

If you don't have any strategy to save your database you can consider use the Backup and Migrate module, for Drupal 6 the last release is the 6.x-2.8

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
> 0 votes

---
Tags: views, 6
---


title: Connecting to a remote database in D8

text:
# Question
Title: Connecting to a remote database in D8
I have the following params in **settings.php** to connect to an external database .

```
$databases['d8243']['default'] = array (
  'database' => 'drupal8',
  'username' => 'root',
  'password' => '123123',
  'prefix' => '',
  'host' => '192.168.1.243',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

And am using the following code to access some data from the db .

```
\Drupal\Core\Database\Database::setActiveConnection('d8243');
$query = "Select * from node__field_target_config_controller";
$result = db_query($query);
$obj = $result->fetchObject();
echo json_encode($obj);
exit;

```

My current server and the external db server are in a **`same network`** .

But am geting the following error :

> exception 'PDOException' with message 'SQLSTATE\[28000\] \[1045\] Access denied for user 'root'@'192.168.1.245' \[error\] (using password: YES)' in /var/www-drupal/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php:149

Is there a different method to connect to remote db in D8 ? or how to do it ?

When i checked d6/d7 versions have an option to specify remote db like

**`$db_url = 'mysql://username:password@quranschools.org/databasename';`**

how to do this in D8 ?

# Answer
> 3 votes
You can use like:

```
$other_database = array(
  'database' => 'drupal8',
  'username' => 'root', // assuming this is necessary
  'password' => '123123', // assuming this is necessary
  'host' => '192.168.1.243', // assumes localhost
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql', // replace with your database driver
);
// replace 'YourDatabaseKey' with something that's unique to your module
Database::addConnectionInfo('d8243', 'default', $other_database);
db_set_active('d8243');
// execute queries here
db_set_active()

```

You can access your other database like above. For reference check this link.

# Answer
> 0 votes
Set up your main database and external database in your settings file:

```
$databases['default']['default'] = array (
  'database' => 'mysite_local',
  'username' => 'root',
  'password' => 'root',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['migration_database']['default'] = array (
  'database' => 'drupal8',
  'username' => 'root',
  'password' => '123123',
  'prefix' => '',
  'host' => '192.168.1.243',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

Then in your code that needs to access the other database, you can switch between databases, using:

```
db_set_active('migration_database');

```

and to switch back:

```
db_set_active('default');

```

---
Tags: 8, database, configuration
---


title: Content type drop down filter types

text:
# Question
Title: Content type drop down filter types
In the content page, there is a filter that shows the page, and other types of content.

Is there a way for me that will allow me to show only certain types of items in the content type.

Thank you, Kevin

# Answer
You can use Administer views but to quickly achieve this I would use the `hook_form_alter`.

Do something like this, Although I would recommend you set this restriction to specific role but for this example I am going to ignore roles. Within `hook_form_alter` you do

```
if($form['#form_id] == 'node_admin_content') {
   unset($form['filter']['filters']['status']['filters']['type']['#options']['article']);
}

```

You can change the `['article']` to whatever the machine name of your content type is. use devel to find out what elements the `$form` variable contains.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Commerce- Show the attribute label instead of product title?
Drupal Commerce add-to-cart attribute dropdown list shows product titles, instead of label of the attribute.

One thing that could be causing this is two product types with the same attribute field on the product display. This is required as one product is downloadable and requires a different product type than the second product type used for shippable items.

Is there a way to change the dropdown to contain attribute labels?

Current: https://www.dropbox.com/s/ib03wn7qd7hpwqm/add-to-cart-dropdown.png?dl=0 Desired: https://www.dropbox.com/s/5js29glqqbxuqiz/desired-dropdown.png?dl=0

Drupal Commerce 7.x-1.13

# Answer
Here's how this was accomplished in a custom module. This will use the taxonomy terms vs the product titles.

```
function custom_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {

```

$vocabulary = taxonomy\_vocabulary\_machine\_name\_load('product\_type'); $terms = taxonomy\_get\_tree($vocabulary-\>vid); $terms\_name = array(); foreach ($terms as $term) { $terms\_name\[$term-\>tid\] = $term-\>name; }

foreach ($form\['edit\_attributes'\] as $key =\> $line\_item) { if (isset($line\_item\['product\_id'\]\['#options'\]) && $line\_item\['product\_id'\]\['#options'\]) { $options = array\_keys($line\_item\['product\_id'\]\['#options'\]); $products = commerce\_product\_load\_multiple($options); foreach ($line\_item\['product\_id'\]\['#options'\] as $id =\> $name) { $form\['edit\_attributes'\]\[$key\]\['product\_id'\]\['#options'\]\[$id\] = $terms\_name\[$products\[$id\]-\>field\_product\_type\['und'\]\[0\]\['tid'\]\]; } $form\['edit\_attributes'\]\[$key\]\['product\_id'\]\['#title'\] = 'Format'; } } }

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

```

if (strpos($form\_id, 'commerce\_cart\_add\_to\_cart\_form') === 0) { $vocabulary = taxonomy\_vocabulary\_machine\_name\_load('product\_type'); $terms = taxonomy\_get\_tree($vocabulary-\>vid); $terms\_name = array(); foreach ($terms as $term) { $terms\_name\[$term-\>tid\] = $term-\>name; }

```
if (isset($form['product_id']['#options'])) {
  $options = array_keys($form['product_id']['#options']);
  $products = commerce_product_load_multiple($options);
  foreach ($options as $key) {
    $form['product_id']['#options'][$key] = $terms_name[$products[$key]->field_product_type['und'][0]['tid']];
  }
  $form['product_id']['#title'] = 'Format'; // added by Lynn. Works on product page, but no in cart
}

```

} }
> 0 votes

---
Tags: commerce
---


# Question
Title: Issue with options in ICME file uploader missing
I'm using Drupal 8 and I added IMCE so that we could upload files. But, some things seem to be missing. First I can only upload images now, there's not option to search the website directories which means that if I have a icon I use in many places I have to upload it each time. You can search the website directories when you link to files though.

Secondly there are no link options like choosing targets like \_blank. Is this the way the module works or is something conflicting with it?

# Answer
> 0 votes
I have the same issue. This is a big headache. We want to make all off-site (external) links have target = \_blank.

Solution: The CKeditor Anchor Link module, anchor\_link, adds the other link properties (as it existed in Drupal 7). You have to edit the text formats and include the new buttons that anchor\_link creates. However, these buttons are identical to the ones created by the Link module (in core D8), so make sure to remove them and drag the new ones (from anchor\_link) in.

---
Tags: files
---


# Question
Title: "No Drupal site found" -- Windows and SQL Server
So I'm trying to upgrade our system from using Drush 6 to Drush 8, as that is the currently supported version of Drush that supports Drupal 7. I have managed to get drush working, however it does not recognize any of our environments as a Drupal environment.

If I run `drush cc all` I get back:

> No Drupal site found, only 'drush' cache was cleared.

If I run any other Drush command (from my sites directory) I get back:

> Command 'command' needs a higher bootstrap level to run.

Running `drush status` returns no DB information at all.

Now there seems to be quite a few questions out there like this, and lots of recommended solutions, but nothing is pertinent to my environment. I'm using IIS on a Windows Server machine, with SQL Server (not MySQL), so none of the solutions are applicable. I'm wondering if anyone has any ideas for solving this within my current environment?

---

Keeping in mind, all of these environments worked fine with no issue prior to upgrading to Drush 8 (using Drush 6).

Output of `drush -v status`:

```
Loading outputformat engine.                                 [notice]
 PHP configuration      :  "C:\Program Files (x86)\PHP\5.6.26\php.ini"
 PHP OS                 :  WINNT
 Drush script           :  location/of/drush
 Drush version          :  8.1.13
 Drush temp directory   :  temp/location
 Drush configuration    :
 Drush alias files      :
Command dispatch complete                                    [notice]

```

`settings.php` file database settings:

```
$databases['default']['default'] = array(
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'hostName',
  'driver' => 'sqlsrv',
);

```

---

Executing `drush sql-connect` command returns:

> Unable to load class `Drush\Sql\Sql`.
>
> Unable to find matching SQL Class.
>
> Drush cannot find your database connection details.

I should also mention that `drush site-install` works fine, it's just running Drush inside a newly created area that doesn't work.

---

To clarify, I am using a multi-tenant install, so I have multiple tenants such as `sites/tenant`, `sites/tenant2`, `sites/tenant3`, etc.

For example I am running `drush` from the `sites/tenant` directory and Drush doesn't recognise my Drupal installation. Traditionally, before updating, I could run `drush` from inside any of those and everything would work.

# Answer
This patch worked for me, https://github.com/drush-ops/drush/pull/3000.

For reference this is the fix, within Drush, in includes/environment.inc, add this line:

```
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);

```

Just before:

```
$path = explode(DIRECTORY_SEPARATOR, $path);

```
> 0 votes

# Answer
You should perform the following checks:

* For *SQL Server*, review README file of SQL Server driver for Drupal 7 to confirm the right requirements and installation steps. See also: Can I use MS SQL with Drupal.
* Make sure that your database client (such as `sqlcmd`) command exists globally (from the command-line). Otherwise make sure its path is added into your PATH system variable. See: `Sqlsqlsrv.php`.
* Clear Drush internal caches and try again:

```
drush cc drush

```
* If you're using a multisite environment, make sure to specify the right Drupal site to use, e.g.

```
drush --uri=http://site1.example.com status

```

or:

```
drush -l http://site2.example.com status

```

Note: By default Drush uses `sites/default` unless you will run the command in specific `sites/` folder.

Note: To define URI of the Drupal site, set `$base_url` in your settings file per given site (or `drushrc.php`).
* Run `drush status` (add `-d` for debugging output) to check whether `Drupal root`, `Database name` and `Database driver` has been detected correctly. If not, run the command again, but in the same folder where is your `settings.php` file and verify that `Drupal Settings File` has been recognized. Verify it has the right read permissions
* Check the output of `drush sql-connect` command whether it returns the right command and there are no errors.

If there is no matching *SQL Class*, this suggests `drush` can't detect the db driver from your settings file. So confirm the following command returns the current site path (folder containing `settings.php`):

```
drush ev "echo drush_site_path();"

```

If it's empty, make sure you're running `drush` command in the right folder and your `settings.php` exists.
* Check whether Drupal bootstrap object is properly loaded by:

```
drush ev "print_r(drush_get_bootstrap_object());"

```

If so, check whether your settings file is readable:

```
drush ev 'echo file_get_contents(drush_get_bootstrap_object()->conf_path()."/settings.php");

```

Otherwise if your bootstrap object is *EmptyBoot*, please review how Drush defines Drupal root as valid (candidates are: `DrupalBoot6`, `DrupalBoot7`, `DrupalBoot8`), for Drupal 7 the logic is as below:

```
function valid_root($path) {
  if (!empty($path) && is_dir($path) && file_exists($path . '/index.php')) {
    // Drupal 7 root.
    // We check for the presence of 'modules/field/field.module' to differentiate this from a D6 site
    $candidate = 'includes/common.inc';
    if (file_exists($path . '/' . $candidate) && file_exists($path . '/misc/drupal.js') && file_exists($path . '/modules/field/field.module')) {
      return $candidate;
    }
  }
}

```

So make sure that you've the following files present: `includes/common.inc`, `misc/drupal.js` and `modules/field/field.module` in your Drupal root (where `$path` is your Drupal root, but it can be specified manually by `--root=path/to/drupal`). Also make sure the files are readable by the user (in case of symlinks, they're pointing to the right files; right permissions in case of network share or Linux file system). Otherwise edit Drupal boot class file (e.g. `DrupalBoot7.php`, part of Drush) and try to debug the above `valid_root()` method by checking which condition exactly fails and why.

Example Drush command to verify whether `index.php` exists:

```
drush ev '$path = drush_get_context("DRUSH_SELECTED_DRUPAL_ROOT"); var_dump(file_exists($path . "/index.php"));'

```
* Finally check whether SQL class can be loaded by:

```
drush ev 'var_dump(drush_sql_get_class());'

```
* You may consider re-testing in different PHP versions, e.g.

### Debugging

Assuming `drush status` doesn't return the right details, here are the suggested steps to debug drush (shell commands).

1. Install and enable PHP `xdebug` extension. Verify by `php71 -i | grep xdebug`.

Consider these xdebug ini settings: `xdebug.ini` for better visibility.
2. On empty folder, install clean Drupal, e.g.

```
drush -y qd --no-server --core=drupal-8
cd quick-drupal-*/drupal*

```
3. Verify *Drupal root*, *Settings File* and *Database* are present in `drush status`.
4. Generate trace file for the working bootstrap process:

```
drush ev "xdebug_start_trace(); print_r(_core_site_status_table()); echo xdebug_get_tracefile_name(); xdebug_stop_trace();"

```

If xdebug is enabled for different PHP version, specify with `DRUSH_PHP=/path/to/php`.

If successful, trace output file should be printed at the end, so take a note of it.
5. Generate another trace file for the same command above, but in the location which doesn't work.
6. Now compare these two trace files (working with non-working) using some diff tool (*Meld*, *DiffMerge*, *`opendiff`*, etc.) and check the differences. For better format, remove first 40 columns from these files (e.g. `ex +'%norm 40dl' -scwq file.xt`).

---

If you believe you found a Drush bug, please report it with details at GitHub issue page.
> 0 votes

---
Tags: database, drush, multi-sites, bootstrapping
---