# Question
Title: Updating entities/posting data via ajax?
I've got a handful of entities that need to updated on user interaction, such as:

1. Tracking user progress through a video, such that a listener checks playhead position every x seconds and posts information to an entity containing data on that user's progress on that video.
2. A collection of checkboxes that, when clicked, automatically update the state of a corresponding value on a related entity. For the sake of argument, I don't yet know if this will be the actual entity form or a generic form/set of forms.

In the past I attempted #1 by having a hidden, ajax-enabled form whose field values were updated every x seconds and the submit button automatically clicked, but this caused assorted ajax errors for some iOS users that were difficult/impossible to debug. Ideally I think I'd like to bypass having a form there at all. I know how to setup the js to track the data, but I'm not sure how to then pass it along to Drupal from the front-end. I'd assume I want to do something like this (via http://hayageek.com/jquery-ajax-post/), but not sure exactly how to determine the `AJAX_POST_URL` or how the data should be formatted.

```
$.ajax({
    url : "AJAX_POST_URL",
    type: "POST",
    data : formData,
    success: function(data, textStatus, jqXHR)
    {
        //data - response from server
    },
    error: function (jqXHR, textStatus, errorThrown)
    {

    }
});

```

For #2, I suppose it might be enough to just have a form that autosubmits via ajax when the checkbox is clicked, but given the misc errors I hit above I'm curious whether or not there might be a better way to handle it.

Happy to update this issue as needed if it's deemed too generic.

# Answer
> 1 votes
The AJAX callback URL will be a route you define in a module. The route will call a controller, which can optionally return an AjaxResponse. First define the route.

example.routing.yml:

```
example.ajax_callback:
  path: '/example/ajax'
  defaults:
    _controller: '\Drupal\example\Controller\AjaxController::ajaxCallback'
  requirements:
    _permission: 'some permission'

```

The path to set in your $.ajax() call is set above.

Then create the controller:

example/src/Controller/AjaxController.php:

```
namespace Drupal\example\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;

class AjaxController extends ControllerBase {

  public function ajaxCallback($nid, $key, $value) {
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
    $node->set($key, $value);

    return new AjaxResponse(['success' => TRUE]);
  }
}

```

---
Tags: 8, ajax
---


# Question
Title: Commenting or replying a specific node without the possibility of commenting others?
I built a website sort of like an online directory for restaurants in my home town, and I am letting the users to leave their reviews about a specific restaurant, and what I need is to give access to the manager or owner of a specific restaurant to reply those reviews or to leave a comment on his node "restaurant", and he cannot reply or comments other restaurants except his. is their any way to achieve that?

# Answer
IMO the Message module would be a possible solution to answer this question. Using this module, you can create your own custom "*Reviews*", which can be used to store (save) the data about them in relevant (custom) fields such as dates, contact info, scores and what not).

About *Message types*: think of them as equivalent to Content types, whereas you create messages (instead of nodes) of a specific Message type (instead of Content type).

### Example included in Commerce Kickstart

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create "*Events logging*". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

### More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views, etc. And there is also quite a few questions about it on drupal.SE, many of them tagged with .

Though there is ***not a lot of documentation about it*** (which is what makes it a hidden gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

**Tutorials:**
> 0 votes

---
Tags: comments
---


# Question
Title: Symfony's getQueryString method doesn't return modified query parameters
Symfony's getQueryString method doesn't return modified query parameters. So how should someone go about getting a modified query parameter string?

Example code:

```
   $request = \Drupal::request();
   $parameter_bag = $request->query;
   $parameter_bag->remove('destination');

   $query = \Drupal::request()->getQueryString();
   $query_array_modified = $parameter_bag->all();

```

`$query` in this instance will return the `destination` query parameter even though it was removed from the ParameterBag. `$query_array_modified` in this instance will not return the destination query parameter ... as expected.

PS - Feel free to replace `\Drupal::request();` with Symfony's request object in example code below if you are using Symfony.

# Answer
Symfony's Request object has a query property that is of type ParameterBag, this maintains an iterable list of parameters. The ParameterBag however is not directly translatable to a query string. This causes issues when trying to use the getQueryString() method after modifying the ParameterBag parameters.

Solution 1 - Create a new query string:

```
   $request = \Drupal::request();
   $parameter_bag = $request->query;
   $parameter_bag->remove('destination');

   // This has to be http_build_query() because
   // \Drupal::request()->getQueryString() returns the original query string
   // but here we need the modified query string (without destination).
   $query = http_build_query($parameter_bag->all());

```

Solution 2 - Update all global variables:

```
    \Drupal::request()->query->remove('destination');
    \Drupal::request()->overrideGlobals();
    $query = \Drupal::request()->getQueryString();

```

Reference to overrideGlobals()

The main issue is that `getQueryString()` returns the global server variable query string which doesn't reflect changes to the parameter bag. So editing the parameters is not as straight forward as it used to be. We either have to build a new query string or override ALL global variables. In my particular use case I thought that overwritting all globals was too wide reaching and it would overwrite any changes that other modules implemented that our specific code has no control over so I went with solution 1 above as it is generally a safer piece of code to implement.

My two options for solving this the right way is that:

1) ParameterBag either needs a method to build a query string

2) The request object needs to be able to return modified query parameters. Probably by deprecating / defaulting the existing function to returning the output of a new function called getQueryStringOriginal() and creating another new function called getQueryStringModified().
> 1 votes

---
Tags: 8, symfony-services
---


# Question
Title: How to get a certain header on FunctionalJavascript tests
Since Drupal 9 is around the corner I'm working on puhsing some contrib modules (and a couple of my own) to be Drupal 9 ready. That involves on updating my tests to use replace deprecated code. Currently I'm working on this issue from Devel module, which replaces `\Drupal\FunctionalJavascriptTests\JavascriptTestBase` with `\Drupal\FunctionalJavascriptTests\WebDriverTestBase` but since this I cannot get headers during FunctionalJavascript.

My question what is the proper way to get them. I've checked tests in core but I just can't figure it out.

The code I'm working on is like so:

```
/**
 * Wait until the toolbar is present on page.
 */
protected function waitForToolbar() {
  $session = $this->getSession();
  $token = $this->getToken();
  $page = $session->getPage();

  $toolbar = $page->findById('webprofiler' . $token);
  $this->assertTrue($toolbar->hasClass('sf-toolbar'), 'Toolbar loader is present in page');

  $session->wait(1000, 'null !== document.getElementById(\'sfToolbarMainContent-' . $token . '\')');

  return $token;
}

/**
 * Return the Webprofiler token.
 *
 * @return null|string
 *   The page token
 */
 protected function getToken() {
   $token = $this->getSession()->getResponseHeader('X-Debug-Token');

   if (NULL === $token) {
     throw new PHPUnit_Framework_AssertionFailedError();
   }

   return $token;
 }

```

As shown the header is required in order to get an element that is generated using Javascript. Perhaps theres another workaround than fetching the header, but not sure how right now.

Thanks in advance.

# Answer
> 0 votes
I was getting all wrong. This is the key, copied from https://www.drupal.org/node/2857562

> All assertions within these tests must be done by checking the UI. Assertions that don't relate to UI should be added to other types of tests, a BrowserTestBase for example.

I should break this test in two one Functional to check proper header setting and the other pure FunctionalJavascript to check the element (whereas the token is set or not) is present on the page. Also does not make sense in this specific case to have two Webprofiler bars present on the page so a simple `document.querySelector('[id^="sfToolbarMainContent-"]')` should do the trick.

---
Tags: 8, testing
---


# Question
Title: How to query a custom content entity with fields added with UI?
In a custom module (assoc), I have a custom Content Entity (Person) with some fields:

```
$fields['lastname'] = BaseFieldDefinition::create('string')
$fields['firstname'] = BaseFieldDefinition::create('string')
$fields['email'] = BaseFieldDefinition::create('email')
$fields['cellphone'] = BaseFieldDefinition::create('telephone')

```

I added a field to this entity using the UI:  I have a query on this entity:

```
  $database = \Drupal::database();
  $query = $database->select('person', 'ap');
  $query->fields('ap', ['id', 'lastname', 'firstname'])
    ->condition('ap.id', 11, '>=')
    ->orderBy('id', 'ASC');
  $results = $query->execute()->fetchAll();

```

I would like to add to the query the field `field_sel_initial_credit`.
How can I do that?

# Answer
You can try code below:

```
$query->join('person__field_sel_initial_credit','person__field_sel_initial_credit','ap.id=person__field_sel_initial_credit.entity_id');
$qeury->fields('person__field_sel_initial_credit',['field_sel_initial_credit_value']);

```
> 0 votes

---
Tags: 8, database
---


# Question
Title: What's the right way to have Drush make automatically add version numbers to my info files?
Everything I read says Drush should be able to automatically rewrite my info files to add version numbers (and the only switch I see is the switch to disable this, --no-gitinfofile), yet nothing I am doing seems to make this work.

The Drush make command being run is:

```
drush make --working-copy --no-core -y --contrib-destination=. profile.make

```

A sample project in the make file would look like this:

```
; Sample Project
projects[sample_project][type] = "module"
projects[sample_project][download][type] = "git"
projects[sample_project][download][url] = "gitlab@git.example.com:cms/sample_project.git"
projects[sample_project][download][tag] = "7.x-1.5"
projects[sample_project][subdir] = "custom"

```

Googling around, I found the following options to maybe try, none of which worked:

```
projects[sample_project][download][version] = "7.x-1.5"
projects[sample_project][download][full_version] = "7.x-1.5"
projects[sample_project][version] = "7.x-1.5"
projects[sample_project][full_version] = "7.x-1.5"

```

The Drush version is 6.2.0.

# Answer
> 1 votes
I have this in my makefile:

```
api = 2
core = 7.x

projects[drupal][version] = "7.26"

;===============================================================================
; Ctools
;===============================================================================

projects[ctools][type] = module
projects[ctools][subdir] = "contrib"
projects[ctools][download][type] = git
projects[ctools][download][revision] = e720f61
projects[ctools][download][branch] = 7.x-1.x
projects[ctools][download][full_version] = 7.x-1.x-dev

```

I run it like so: drush make --working-copy --no-cache --no-core my\_make\_file.make

For a good overview of the drush make flags: http://www.drushcommands.com/drush-6x/make/make

In my case version info wasn't written because I had --no-gitinfofile in my script for some reason. I hope this helps!

# Answer
> 1 votes
Apparently there's been a bug report about it and it can work in Drush 7.

Issue about it here: https://github.com/drush-ops/drush/pull/368

Fixed by this commit: https://github.com/drush-ops/drush/commit/26f44a44caa0284f052873023ae08f457da5e5d1

Fixed in Drush 6 by pulling in the commit and using the --force-gitinfofile switch.

# Answer
> 0 votes
Starting with Drush 7, you can use the `drush make` switch `--force-gitinfofile` to get the version numbers added to .info files.

```
--force-gitinfofile : Force a modification of .info files when cloning from Git even if repository isn't hosted on Drupal.org.

```

Once you have that switch, then the version number like below will work:

`projects[sample_project][version] = "7.x-1.5"`

I have found that this works even if you specify a git path and revision:

```
projects[sample_project][version] = "7.x-1.5"
projects[sample_project][download][type] = "git"
projects[sample_project][download][url] = "https://git.drupalcode.org/project/sample_project.git"
projects[sample_project][branch] = "7.x"
projects[sample_project][revision] = "9320560c"

```

---
Tags: drush
---


# Question
Title: How to render element array piece by piece
I have template form.html.twig Drupal commerce is using it to render cart form. I made override of that template, to be able to change it only for cart form, without affecting other forms. That part works well.

Form template looks like this:

```
<form class{{ attributes }}>
  {{ children }}
</form>

```

Where "children" is markup. But (even not documented in template it self) there is also "element" array. So I can print the it instead of children and get the same results:

```
<form class{{ attributes }}>
  {{ element }}
</form>

```

This also works well. Now, I need to print it piece by piece. If I put loop like this:

```
  {% for single in element %}
    {{ single }}
  {% endfor %}

```

I get some form elements doubled, so obviously some elements must be excluded. But which ones?

Here is the list of all element keys inside this "element" array:

```
#action
#prefix
#suffix
#pre_render
#cache
#attached
#substitutions
#form_id
#type
#build_id
#token
#id
#attributes
#method
#theme_wrappers
#defaults_loaded
#tree
#parents
#validate
#submit
#theme
#processed
#required
#title_display
#description_display
#errors
#array_parents
#printed
show_view_elements
output
footer
edit_quantity
remove_button
form_build_id
form_token
form_id
actions
#sorted
#children
#render_children

```

How can I find out what elements should I print and what to exclude to get the same result (valid form) as when printing top element:

```
{{ element }}

```

**Update**: purpose of this is to render cart page a bit differently. Now, inside the form element I have first table with purchased items, then, bellow table goes div with sub-total and total prices and then div with "Update" and "Checkout" buttons. What I want is to display those 3 elements in 2 columns. In left one there should be only table with items and in right prices, buttons and some additional info.

BTW, I'm already displaying another form that way. It's template file looks like this:

```
<form{{ attributes }}>
  {{ title_prefix }}

  {{ element.pages }}
  {{ element.elements }}
  {{ element.form_build_id }}
  {{ element.form_token }}
  {{ element.form_id }}
  {{ element.footer }}
  {{ element.actions }}
  {{ element.children }}
  {{ element.progress }}

  {{ title_suffix }}

</form>

```

There I print progress bar bellow the other form elements. But I have problem achieving the same with cart form.

# Answer
> -1 votes
Succeeded it "my way". Template now looks like this:

```
<form class{{ attributes }}>

{{ element.output }}
{{ element.footer }}
{{ element.form_build_id }}
{{ element.form_token }}
{{ element.form_id }}
{{ element.actions }}

</form>

element.output prints the table
element.footer prints the prices
element.actions prints the buttons
and other fields are printing necessary hidden fields

```

I know that @4k4 is right and I even tried solution he proposed before, but for some reason it didn't work for me (probably my mistake) and I didn't have more time to spend on this and this solution works well.

Posted this, because it's answer to this question and IMHO this should be "legal" way to print form, achieved only from twig without forcing on creating theme function and other stuff.

Please be gentle with minuses.

---
Tags: 8, theming, webforms
---


title: How to implement a duration field?

text:
# Question
Title: How to implement a duration field?
I am constructing a content type that will 'wrap' a video, either youtube, vimeo or file upload. One of the fields required is a 'duration' field. Obviously a requirement is also for the videos to be sortable in a view based on that field.

How would I go about doing that? A format of `H:i:s` or `i:s` would be prefered in a textfield as an input method.

# Answer
> 6 votes
Posting my comment as answer - Check for HMS (Hours Minutes Seconds) Field module.

> Displays a integer formatted as Hours, Minutes or Seconds. The field stores values as integer. Both input and output can be formatted as Hours, Minutes and/or Seconds. Alter functions provides developers a way to add their own format.

# Answer
> 1 votes
You can use the Date module. It will provide a cck date field, which you can configure as duration field

# Answer
> 1 votes
You can use **format\_interval()**:

```
return format_interval(strtotime("2009-07-06") - strtotime("2007-06-01"));
// 2 years 1 month

```

# Answer
> 0 votes
Also for Drupal 8 you can use - Duration field module

---
Tags: 7, entities, datetime
---


title: How do I theme a webform email?

text:
# Question
Title: How do I theme a webform email?
I have a subscription form created with webform. When the user submits the form I want to send a customised confirmation e-mail that includes some social links, images and site logo. I have looked for multiple solutions but none of them makes any sense?

Any help?

# Answer
> 0 votes
The Drupal module, Easy Email, might be worth looking at. A YouTube presentation of the Easy Email module is at https://www.youtube.com/watch?v=5V3rMJwPhY8

# Answer
> -3 votes
This was pretty easy in the end. Webform by default doesn't provide you an option of sending HTML emails. Here is a list of contrib modules you can use to send richly formatted HTML Emails:- https://medium.com/@OPTASY.com/how-to-send-richly-formatted-html-emails-in-drupal-8-deliver-the-experiences-that-your-customers-1a29626b7f2e

I used HTML MAIL because it is pretty easy to work around and also integrates contrib modules like Mail MIME modules, echo, Transliteration etc. and provides you much more options to customise your emails. You can download it here https://www.drupal.org/project/htmlmail. Also check for requirements.

Here is the documentation for HTML MAIL https://www.drupal.org/docs/8/modules/html-mail.

To make it simple. All you need to do is.
1. Download and enable the HTML Mail module.
2. Copy the `htmlmail--htmlmail.html.twig` template to your theme directory.
3. You can follow the naming convention from the above documentation. e.g:- if your form name is newsletter than your template name for that specific form will be `htmlmail--webform--newsletter_email.html.twig`
4. You also need to enable Mail system module. And in `admin/config/system/mailsystem` add the module specific configuration which in my case was webform.

---
Tags: 8, webforms
---


title: Commerce 1 or Commerce 2?

text:
# Question
Title: Commerce 1 or Commerce 2?
I am not a developer although I have been using Drupal since it came out 19 years ago.

I have an existing D7 Ubercart site that works well, but I want to move to Drupal Commerce.

I have installed Drupal 8 Commerce 1 at one site, and Drupal 8 Commerce 2 (commerce 8.x-2.16) at a second site.

I know that Commerce 2 requires composer, but at the moment I have set up the Commerce 2 site with the above module (commerce 8.x-2.16) with Ludwig and it seems to function just fine.

Here is my question:

Would it be advisable to start my new site with Commerce 1 or Commerce 2?

Commerce 1 is stable, and I am thinking that perhaps I should start there and eventually migrate to a stable version of Commerce 2.

Thank you for any insights or advice.

# Answer
> 2 votes
As @No Sssweat points out in a comment on your original post, there is no Commerce 1 for Drupal 8, so if you're upgrading your site to Drupal 8, Commerce 2 is your only option.

But even if that weren't the case, Commerce 2 is stable and it's where all the current improvements in Commerce are happening. While Commerce 1 may have a larger contrib ecosystem at present, I find that once developer energy has moved on to the latest version of Drupal, it's frustrating to try and solve contrib problems on the old version. So my advice is always to go with the more recent version, once contrib has progressed enough that they key functionality you need has been developed and is reasonably stable. I believe Commerce 2 is there.

Finally, the migration process is kind of a bear (especially if you're migrating historical order data), so personally I'd only want to do that once, D7 Ubercart directly to D8 Commerce 2, rather than the two step process of D7 UC -\> D7 Commerce 1 -\> D8 Commerce 2. I think you'd be creating a lot of extra work for yourself without much benefit.

# Answer
> 0 votes
With your existing D7 Ubercart site, you only need to create a local version of your site along with a new local version 7 with Commerce 1 since Drupal 7 doesn't reach end of life until November 2021.

The best way to learn Commerce 1 on Drupal 7 is by downloading the latest Drupal Commerce Kickstart 2.x which you can only activate the modules you need, or activate a local version of the example store.

Then learning Drupal 8 with Composer: It is necessary to have a local compose installation to manage Drupal 8. Drupal 8 is based off of Symfony PHP framework, which is broken into little pieces, and Composer is required for modules like the Commerce modules with third-party libraries, per Drupal https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies.

Then you can learn Drupal 8 building for your website using composer.

If you prefer a video discussion on why ubercart to commerce, and why 8 vs 7 when you have the time I've included https://www.youtube.com/watch?v=mlNor8ZiOZM, Post at https://blog.acromedia.com/ubercart-is-dead-why-a-migration-is-needed-asap.

Drupal 8 to Drupal 9 will just be newest version of Drupal 8, which is a bonus of Drupal going to Object oriented.

I hope this helps.

---
Tags: 8, commerce
---


# Question
Title: Webform Query Confirmation Email Tokens Not Passing
Has anyone else encountered this behavior? I can pass static tokens but not values using \[current-page:query:?\] in the Webform 8 Confirmation URL. I'm trying to append an email address.

If I use: ?email=\[current-page:query:email\] it returns ?email=?e=%5Bcurrent-page%3Aquery%3Aemail%5D

but ?email=\[site:mail\] returns ?email=correctemail%40email.com

I can pass any static variables, but not from the current query.

# Answer
I figured it out. The documentation suggests \[current-page:query:email\] but the working token is \[webform\_submission:values:email:urlencode\]
> 0 votes

---
Tags: webforms
---


# Question
Title: Webform show custom composite result at their own line in submissions download
I have a webform with a `custom composite` field THE `custom composite` has one text field that can be repeated an unlimited amount of times

here is an image of the form:

What I want is to show each student name in a separate line when I download the results. Is it possible to do it using a module? if not I will be glad to hear if there are hooks that can manipulate the downloaded data

# Answer
> 5 votes
I solved the above issue by creating a new Webform Exporter plugin, extending the default "Delimited text" in a custom module. I assume you download them in either CSV or MS Excel file format. I've only tried the below for the CSV export, but I see no reason for it not working for MS Excel ones as well.

The idea in a short summary is:

* Create a custom `WebformExporter` plugin extending the default "Delimited text" exporter (class `DelimitedWebformExporter`)
* Override the `writeSubmission` method which adds the data to the CSV string and make it run once for every sub-element of your composite element

# How to create a custom `WebformExporter` plugin

In a custom module, create the file

`<custom_module_root>/src/Plugin/WebformExporter/CustomDelimitedWebformExporter.php`

And in it create a class `CustomDelimitedWebformExporter` with the necessary annotations in order to define the `WebformExporter` plugin. Also since we want to extend the default exporter for delimited text, our class should extend the "Delimited text" class `DelimitedWebformExporter`.

```
<?php

namespace Drupal\custom_module\Plugin\WebformExporter;

use Drupal\webform\Plugin\WebformExporter\DelimitedWebformExporter;

/**
 * Defines a delimited text exporter.
 *
 * @WebformExporter(
 *   id = "custom_delimited",
 *   label = @Translation("Custom Delimited text"),
 *   description = @Translation("Exports results as delimited text file, splitting the composite element's multiple values to different rows."),
 * )
 */
class CustomDelimitedWebformExporter extends DelimitedWebformExporter {

}

```

If you did this correctly you should see (after clearing cache) a new option in the "Export format" dropdown in the Results Download page of the webform.

# How to override the submission writing to loop for each subelement

Now override the `writeSubmission` method. That method in the parent class builds a new row of results for each submission and then puts the data in the CSV handler. Since we want the results in different rows, we therefore need to call the parent method just as many times and print each subelement.

```
use Drupal\webform\WebformSubmissionInterface;

const COMPOSITE_ELEMENT_KEY = 'composite_element_key';

/**
 * {@inheritdoc}
 */
public function writeSubmission(WebformSubmissionInterface $webform_submission) {
  $element = $webform_submission->getElementData(self::COMPOSITE_ELEMENT_KEY);
  if ($element) {
    for ($i = 0; $i < sizeof($element); $i++) {
      $webform_submission->setElementData(self::COMPOSITE_ELEMENT_KEY, [0 => $element[$i]]);
      parent::writeSubmission($webform_submission);
    }
  } else {
    parent::writeSubmission($webform_submission);
  }
}

```

**A couple of notes:**

* The above works for one specific composite element in your webform. You can adjust the behaviour if you need it for more that one or for an arbitrary one (i.e. by checking if the element type is composite)
* As the above does not change anything for the rest of the webform's elements, the rest of the columns in the results will have their data copied in every extra row created.

# End result

```
<?php

namespace Drupal\custom_module\Plugin\WebformExporter;

use Drupal\webform\Plugin\WebformExporter\DelimitedWebformExporter;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Defines a delimited text exporter.
 *
 * @WebformExporter(
 *   id = "custom_delimited",
 *   label = @Translation("Custom Delimited text"),
 *   description = @Translation("Exports results as delimited text file, splitting the composite element's multiple values to different rows."),
 * )
 */
class CustomDelimitedWebformExporter extends DelimitedWebformExporter {

  const COMPOSITE_ELEMENT_KEY = 'composite_element_key';

  /**
   * {@inheritdoc}
   */
  public function writeSubmission(WebformSubmissionInterface $webform_submission) {
    $element = $webform_submission->getElementData(self::COMPOSITE_ELEMENT_KEY);
    if ($element) {
      for ($i = 0; $i < sizeof($element); $i++) {
        $webform_submission->setElementData(self::COMPOSITE_ELEMENT_KEY, [0 => $element[$i]]);
        parent::writeSubmission($webform_submission);
      }
    } else {
      parent::writeSubmission($webform_submission);
    }
  }

}

```

---
Tags: 8, webforms
---


# Question
Title: How can you change the temporary directory?
I migrated the site from the local server to live server. But the images do not appear - the website logo and some PDFs. I've been seeing the problem could be here "Config" \>\> "file system" and my temporary directory is: `/Applications/MAMP/tmp/php` because I need to change that. But I do not know how. if you can help me. please

> Warning: move\_uploaded\_file(temporary://logo\_verde\_maior.png): failed to open stream: "Drupal\Core\StreamWrapper\TemporaryStream::stream\_open" call failed in Drupal\Core\File\FileSystem-\>moveUploadedFile() (line 81 of core/lib/Drupal/Core/File/FileSystem.php).

This is error:

> Warning: move\_uploaded\_file(): Unable to move '/tmp/php9al1tV' to 'temporary://logo\_verde\_maior.png' in Drupal\Core\File\FileSystem-\>moveUploadedFile() (line 81 of core/lib/Drupal/Core/File/FileSystem.php). File upload error. Could not move uploaded file.

# Answer
> 1 votes
In https://www.drupal.org/node/3039026 / https://www.drupal.org/node/3039255, which was introduced in Drupal 8.8.0, the ability to configure the temp directory was removed from the UI and moved to `settings.php`.

From the change record:

> The following lines are now in default.settings.php
>
> ```
> /**
>  * Temporary file path:
>  *
>  * A local file system path where temporary files will be stored. This directory
>  * must be absolute, outside of the Drupal installation directory and not
>  * accessible over the web.
>  *
>  * If this is not set, the default for the operating system will be used.
>  *
>  * @see \Drupal\Component\FileSystem\FileSystem::getOsTemporaryDirectory()
>  */
> # $settings['file_temp_path'] = '/tmp';
>
> ```

So, you should edit your settings file.

If your temp directory is different in your environments, you need a mechanism to handle this. I typically use `.env` files for this, the database connection info, and some other settings.

# Answer
> 0 votes
Check if the new temp folder has the required permissions in order for Drupal to read-write files/folders.

Does the browser console gives you any hints on this issue?

Also from 8.8, the path for tmp folder is being set via `settings.php`, so make sure you have this set up correctly

---
Tags: deployment
---


# Question
Title: How can I mock a class during a functional request that is called from within a controller?
I am working on a custom module that from a controller calls Elastic search and returns a search result. I am trying to write a simple Functional Php Unit test just to make sure the results are displaying correctly.

Here is a simplified version of my funtional php unit test code:

```
public function testSearchResulsShowUp() {
  $account = $this->drupalCreateUser(['access content']);
  $this->drupalLogin($account);
  $this->drupalGet('/search/term1');
  $this->assertResponse(200);
  $this->assertText('Term 1');
}

```

Here is a simplified version of my controller:

```
/**
 * Search controller.
 */
class SearchController extends ControllerBase {

  public function getContent(search) {
    $client = Client::getClient();

    // Client connects to Elastic search and then returns
    // a result.

    ...
    ...

    // Will return Term 1
  }

}

```

Here is a simplified version of my Client class:

```
/**
 * Class Client.
 */
class Client {

  /**
   * Get client.
   */
  public static function getClient() {
    $cluster_id = \Drupal::state()->get('elasticsearch_connector_get_default_connector');
    $elasticsearchCluster = \Drupal::entityManager()->getStorage('elasticsearch_cluster')->load($cluster_id);
    $clientManager = \Drupal::service('elasticsearch_connector.client_manager');
    $client = $clientManager->getClientForCluster($elasticsearchCluster);
    return $client;
  }
}

```

I would like to be able to somehow mock my getClient method so when it is called in the Controller or anywhere going forward it would call the mock instead of the original method. I know that if this was a true Unit test we would be able to do it but since it is a functional test I am not sure how to do it.

# Answer
> 2 votes
Since the request your test is making spins up a completely new PHP process to deliver the contents of that request, nothing you do in-memory during the execution of the test will be reflected in the new HTTP request process.

Fortunately there are some techniques to create HTTP clients that *can* be used inside functional tests that span longer than a single request. The technique involves creating a test module, which replaces the HTTP client in the container, for all requests that happen while the module is enabled.

Your test may then:

1. Switch the module on during setup.
2. Use the new HTTP client in HTTP requests during the lifetime of the test.
3. Switch the module off, if you're required to clean-up.

The key parts of a test module like this are:

`my_module/tests/modules/my_module_http_client/my_module_http_client.services.yml`

```
services:
  my_module_http_client.http_client:
    decorates: 'http_client'
    class: 'Drupal\my_module_http_client\MockHttpClient'

```

`my_module/tests/modules/my_module_http_client/src/MockHttpClient.php`

```
<?php

namespace Drupal\my_module_http_client;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;

/**
 * Test HTTP client for the air quality test.
 */
class MockHttpClient extends Client {

  /**
   * {@inheritdoc}
   */
  public function get($uri, array $options = []) {
    return new Response(200, ['type' => 'text/xml'], file_get_contents(__DIR__ . '/some-test-fixture.xml'));
  }

}

```

Of course in the body of `::get`, you can program any logic you like. A common pattern is to use the state API to allow the test to specify a behavior for the client. An example might be something like, setting which response fixture to return.

Example for setting a state in a functional test (see: https://www.drupal.org/project/drupal/issues/2066993):

```
  /** @var \Drupal\Core\State\State $state */
  $state = \Drupal::service('state');
  $state->set('your_module_state_key', $value);

```

These kind of functional tests are really valuable to ensure your whole system is working end to end. I would however caveat this with saying, it is also valuable to identify units in your controller which can be tested in isolation. Unit tests can often test a lot more scenarios at a might higher speed than a fully bootstrapped implementation might be able to.

---
Tags: 8, testing
---


title: Undefined function json_decode()

text:
# Question
Title: Undefined function json_decode()
When attempting to update a Drupal 7 site through the UI or Drush, I get `Error: Call to undefined function json_decode() in home/xxxxx/drush/includes/output.inc, line 403 , code: 255)`

The server is running PHP 7.3 with json enabled - I've verified this with phpinfo(). I'm at a loss here, and even if I apply updates by ftp, I still can't run database updates. Shared hosting without root access.

* PHP 7.3.13
* Drush 5.9
* Drupal 7.x

# Answer
> 0 votes
So I finally found the culprit. A php symlink in the bin directory linking to an old version of php. I guess even though drush showed it was using version 7.3, those scripts used that symlink and was pulling in an older php version. Error is gone and I can finally update through drush.

---
Tags: 7, drush
---


# Question
Title: On content, choose the taxonomy parent and display all the children
I have a content type with a taxonomy field based on a hierarchical taxonomy with 3 levels. I use Simple Hierarchical Select (SHS) to select and display the terms.

I want to have a view that displays the chosen terms on each content page, but I also want when I choose the parent term to show all its children without selecting every one of them.

I made a content view with a Content:ID contextual filter. As a formatter I use SHS but it displays only the selected term at the selected depth, no other options. I tried with another contextual filter on the taxonomy depth, also with another taxonomy view to take the children of a term and then use views field view to embed it on the primary view, no success at all.

Any ideas?

# Answer
For anyone interested in the future, I managed to solve this using the Entity Reference Tree Widget module, which provides the exact functionality as described on question.
> 0 votes

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


# Question
Title: composer won't update 8.7.10 to 8.8.2 - "Nothing to install or update"
When I try to use composer to update Drupal, it fails to follow through, and gives me several abandoned items.

Not sure where to go from here, but maybe someone can give pointers on what might be causing the issues, and how to resolve the abandoned packages?

Sorry if this is vague. I don't know what next steps should be.

```
[user@ip-000-00-00-000 sitefolder]$ sudo -u nginx composer update drupal --with-dependencies
No composer.json in current directory, do you want to use the one at /var/lib/nginx/sitefolder? [Y,n]? Y
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Package "drupal" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Package webflo/drupal-core-require-dev is abandoned, you should avoid using it. Use drupal/core-dev instead.
Package zendframework/zend-diactoros is abandoned, you should avoid using it. Use laminas/laminas-diactoros instead.
Package zendframework/zend-escaper is abandoned, you should avoid using it. Use laminas/laminas-escaper instead.
Package zendframework/zend-feed is abandoned, you should avoid using it. Use laminas/laminas-feed instead.
Package zendframework/zend-stdlib is abandoned, you should avoid using it. Use laminas/laminas-stdlib instead.
Writing lock file
Generating autoload files

```

I also did "composer outdated -Dm" to see what I'd get, if it helps:

```
sudo -u nginx composer outdated -Dm
No composer.json in current directory, do you want to use the one at /var/lib/nginx/sitefolder? [Y,n]? Y
drupal/browserclass            1.0.0-alpha1 1.0.0-alpha2 Adds a browser class to the body tag.
drupal/core                    8.7.10       8.8.2        Drupal is an open source content management platform powering millions of websites...
webflo/drupal-core-require-dev 8.7.10       8.8.1        require-dev dependencies from drupal/core

```

I tried composer why-not drupal/core:8.8.1, and 8.8.2 and got:

```
webflo/drupal-core-require-dev  8.7.10  requires          drupal/core (8.7.10)
drupal/core                     8.8.1   requires          typo3/phar-stream-wrapper (^3.1.3)
drupal-composer/drupal-project  -       does not require  typo3/phar-stream-wrapper (but v2.1.3 is installed)
drupal/core                     8.8.1   requires          pear/archive_tar (^1.4.9)
drupal-composer/drupal-project  -       does not require  pear/archive_tar (but 1.4.8 is installed)

```

I've also attempted to replace the webflow/drupal-core-require-dev item, and when I did the reinstall, using "composer require --dev drupal/core-dev", I ran into a confusing result:

```
 Problem 1
    - Conclusion: don't install drupal/core-dev 8.8.2
    - Conclusion: don't install drupal/core-dev 8.8.1
    - Conclusion: don't install drupal/core-dev 8.8.0
    - Conclusion: don't install drupal/core-dev 8.8.0-rc1
    - Conclusion: don't install drupal/core-dev 8.8.0-beta1
    - Installation request for webflo/drupal-core-require-dev (locked at 8.7.10, required as ^8.7.0) -> satisfiable by webflo/drupal-core-require-dev[8.7.10].
    - Conclusion: don't install drupal/core-dev 8.9.x-dev
    - Conclusion: don't install drupal/core-dev 8.8.x-dev
    - Can only install one of: drupal/core[8.8.0-alpha1, 8.7.10].
    - Can only install one of: drupal/core[8.8.0-alpha1, 8.7.10].
    - Can only install one of: drupal/core[8.8.0-alpha1, 8.7.10].
    - drupal/core-dev 8.8.0-alpha1 requires drupal/core 8.8.0-alpha1 -> satisfiable by drupal/core[8.8.0-alpha1].
    - Installation request for drupal/core-dev ^8.8 -> satisfiable by drupal/core-dev[8.8.0, 8.8.0-alpha1, 8.8.0-beta1, 8.8.0-rc1, 8.8.1, 8.8.2, 8.8.x-dev, 8.9.x-dev].
    - Installation request for drupal/core (locked at 8.7.10, required as ^8.7.0) -> satisfiable by drupal/core[8.7.10].

Installation failed, reverting ./composer.json to its original content.

```

# Answer
> 2 votes
Sleepingmonk's answer is good, above. What most helped me, though, was to follow the information in the link, provided by stevekeiretsu in one of the sub-comments:

https://www.drupal.org/docs/8/update/update-core-via-composer#s-special-considerations-for-upgrading-to-drupal-880-and-later

For me, it was a combination of removing "webflo/drupal-core-require-dev" as well as the 'composer.lock' file.

# Answer
> 4 votes
As other's have mentioned, `drupal/core-recommended` should be used going forward.

Try:

`composer remove webflo/drupal-core-require-dev --no-update` `composer require drupal/core-recommended --no-update` `composer update webflo/drupal-core-require-dev drupal/core drupal/core-recommended --with-dependencies`

You could also try adding `composer require drupal/core:8.8.1` specifically, before running the update command.

# Answer
> 2 votes
I had the same problem. You have to migrate from webflo/drupal-core-strict to drupal/core-recommended.

Solution and steps are here : https://www.drupal.org/docs/8/update/update-core-via-composer#migrate-webflo-drupal-core-strict-to-core-recommended

> The simplest way to accomplish this migration and avoid conflicts is to remove your composer.lock file entirely as part of the update. However, doing so will mean that other dependencies (e.g. contributed Drupal modules) might be updated, too. Following these steps will ensure that you update exactly what you intend:
>
> > 1. composer update # To update any dependencies as a separate step.
> > 2. git add composer.lock; git commit # Save the updates as a separate commit.
> > 3. composer remove webflo/drupal-core-strict --no-update
> > 4. composer remove drupal/core --no-update
> > 5. composer require 'composer/installers:^1.7' --no-update
> > 6. rm composer.lock
> > 7. rm -rf vendor # Also helps avoid conflicts.
> > 8. composer require drupal/core-recommended:^8.8 --update-with-dependencies
> > 9. git add composer.json composer.lock; git commit -m "Update Drupal to 8.8.0 and use drupal/core-recommended instead of webflo/drupal-core-strict"

# Answer
> 0 votes
For a strange reason, I couldn't **upgrade from 8.8.1 to 8.8.2 with webflo/drupal-core-require-dev installed**. To resolve it quickly I just:

```
// Remove webflo
composer remove --dev webflo/drupal-core-require-dev

// Add drupal/core-dev  (This step is not mandatory, only for dev purpose)
composer require --dev drupal/core-dev

// Update Drupal core from 8.8.1 to 8.8.2
composer update drupal/core --with-dependencies

```

Hope this helps.

# Answer
> 0 votes
As other answered, you can try to migrate to `drupal/core-recommended`. I found this Composer plugin very easy to use :

https://github.com/grasmash/composerize-drupal

I've successfully tested it on several Drupal installation.

---
Tags: 8, updating
---


# Question
Title: Content type export with drupal console not working
I have a content type called slider as the image below shows:

I tried the following to export the content-type:

```
drupal config:export:content:type slider

```

when I enter the command, I am prompted to type a module name, which doesn't sound right.

```
Enter the module name [admin_toolbar]:

```

How can I export a specific content type using the drupal console?

# Answer
> 0 votes
Drupal console will create a new module for you and export the content type as configuration in new module under config folder. Eg. drupal config:export:content:type slider \ --module="new\_module"

# Answer
> 0 votes
Drupal console `config:export:content:type` is to

> Export a specific content type and their fields.

and required 4 arguments:

1. **--module** : The Module name where config will exported.
2. **--optional-config** : Export content type as an optional YAML configuration in your module.
3. **--remove-uuid** : If set, the configuration will be exported without uuid key.
4. **--remove-config-hash** If set, the configuration will be exported without the default site hash key.

So you can execute it like :

```
drupal config:export:content:type article \
--module="YOURMODULE" \
--optional-config -y \
--remove-uuid -n \
--remove-config-hash -y

```

**-y** to set value of argument to **yes**
**-n** to set value of argument to **no**

for more info check config:export:content:type documentation page

---
Tags: console
---


# Question
Title: How do I attach CSS styles to all the pages?
i have a theme installed his name is 'businessplus\_lite' i want to add some custom style to my sub theme , but i can't see any css applicable , can anyone help me please !

> .info.yml

```
name: mysub-theme
type: theme
description: 'my sub-theme Commissions'
core: 8.x
base theme: businessplus_lite

libraries:
  - my-sub-theme-name/my-sub-theme-style

```

> libraries.yml

```
my-sub-theme-style:
  css:
    component:
      css/components/style.css: {}

```

# Answer
> 0 votes
Please try using below code **info.yml :**

```
name: mysub-theme
type: theme
description: 'my sub-theme Commissions'
core: 8.x
base theme: businessplus_lite

libraries:
  - mysub-theme/my-sub-theme-style

```

**mysub-theme.libraries.yml :**

```
my-sub-theme-style:
  version: 1.x
  css:
    theme:
      css/style.css: {}

```

---
Tags: 8
---


# Question
Title: How do I change the javascript loading order
I am using mixitup.js for my custom module. But it gives error when firing because it needs to load the jQuery before loading the mixitup.js. But my jQuery files are in my site folder which are loading in the end of the page. Is there way to load my mixitup.js in the end of the page. mixitup.js should be in my custom module too.

# Answer
> 4 votes
To add a js library to the header, define your library in `my_module.libraries.yml` with the `header: true` property.

```
my_library:
  header: true
  etc ...

```

Any dependencies defined for your library will always be loaded before your library whether loading your js in the header or footer.

See Asset loading order section here.

# Answer
> 4 votes
As mentionned above, one way to control the order is to declare in your library the dependencies of other libraries containing the js you want to be loaded before

```
agenda:
  version: 1.x
  css:
    component:
      css/agenda.css: {}
  js:
    js/agenda.js: {}
  dependencies:
    - fullcalendar_view/fullcalendar

```

---
Tags: 8, javascript
---


# Question
Title: reseting the hook_update_n status of a module
I'm extending a module I've previously written and it needs some schema changes which I implement in `hook_update_N`.

I've updated the module's version from `7.x-1.0` to `7.x-1.1` and implemented the `foo_update_7100` and it works fine.

The problem is that I've made a mistake inside `foo_update_7100` and now that I've fixed it I cannot rerun the 7100 update. I need to create a 7101 one but that doesn't make sense because all my changes are not committed yet.

I've tried reseting the status of the hook\_update\_n via:

```
update system set schema_version=-1 where name='foo';

> Query OK, 1 row affected (0.01 sec)
> Rows matched: 1  Changed: 1  Warnings: 0

```

Then I do `drush cc all` but `drush updatedb -y` still gives me "No database updates required".

How can I solve this instead of simply incrementing the `hook_update_N` number?

# Answer
> 15 votes
Setting it to 0 should work. `system_schema()` says the value should be:

> -1 if the module is not installed (its tables do not exist); 0 or the largest N of the module's hook\_update\_N() function that has either been run or existed when the module was first installed.

# Answer
> 23 votes
FYI, in Drupal 8, the system table has been removed, and this information is now stored in the **key\_value** table.

```
UPDATE key_value SET value='i:8000;' WHERE collection = 'system.schema' AND name = 'module_name';

```

*(As noted above, the actual value should be less than the **hook\_update\_N()** you want to repeat, but higher than or matching the last update that does not need to be repeated.)*

# Answer
> 3 votes
I did this so much that I ended up writing a drush module to roll back the update version in the system table. Called "uroll" for update rollback.

https://github.com/danshumaker/drush-uroll

Usage: drush uroll --module=mycustommodule --version=5

It's super simple but I use it all the time. This combined with a database backup reload script allows you to rinse and repeat when writing update functions.

Hopefully helpful to you. Good luck.

# Answer
> 1 votes
For anyone who is still looking for an answer you can achieve this in 3 ways:

* SQL: UPDATE system SET schema\_version = \[N\*\] WHERE name = '\[Name of module\]';
* Drush: drush ev "drupal\_set\_installed\_schema\_version('\[Name of module\]', \[N\*\])"
* Drush uroll drush uroll --module=\[Name of module\] --version=N\*

\*N being the update function you want to revert to (i.e the last successful update function)

# Answer
> 0 votes
To get your update hook to run again, you should set the schema\_version to **1 below the sequence number of your hook**.

Technically, anything below the hook you wish to rerun and *above* the update hook you do not need/want to rerun (but at least 0; -1 means the module is not installed) is OK; if there are no other update hooks, that means that even 0 falls between those boundaries, but in the typical case, update hooks are increased by one, so only going 1 lower is the only safe option if you do not want to run more code than the current highest update hook.

The update process simply checks that value, and sees if there are any update hooks with a higher sequence number. If so, it will run them in sequence. (This also means that the installation process sets the schema version to that corresponding to the highest available update hook; it assumes that upon installation, your module will have a state corresponding to that last update hook).

---
Tags: 7, database, updating
---


title: Line break Twig question

text:
# Question
Title: Line break Twig question
I want to add line breaks in title field I managed to use the replace functions in the template \>

```
{{ node.getTitle()|replace({'|': '<br />'}) }}

```

Replacement works, but outputs the field as non-HTML. Do you know about a way to force an HTML output? Or any other way to be the
a real line break instead?

# Answer
> 4 votes
It should help to use the raw filter, like @leymannx commented, but then your template is unsafe, because you should never use the raw filter on template variables containing user input.

So escape the node title first, then add the HTML (which you know is safe because it's hardcoded), before passing it through the raw filter:

```
{{ node.getTitle()|e|replace({'|': '<br />'})|raw }}

```

---
Tags: 8, theming
---


# Question
Title: Combined Fields filters and missing custom search api fields
Drupal 8

I am using Search API and Views to search several fields from several content and media types. For example, I have a custom "description" field for Media-\>files so users can add a searchable summary field to pdfs they upload to a website.

While I can get it set up to search all the fields using exposed filters and an "OR" filter grouping, this leads to an exposed filter for each field... which is not ideal. I would rather a single input box that allows several search terms to be passed to each of the filters.

I have tried to use combined field filter however it is missing a number of the fields passed from the Search API index. For example, below is a simple example searching only pdfs with a custom description field.

Media type and Name are available but not Description or even filename. Is there a way to make these available in the combined filter?

Any other method to achieve the desired result of a single search box for multiple filters would also useful. Just to re-iterate. The filters work, I just want them in a single search field.

# Answer
It's kind of a beginner error here but in case it's useful to anyone the solution is you want to use the Search API `Search` filter rather than the combined filter.

It handles the search of the provided index all as a single input field by design.
> 0 votes

---
Tags: views, 8, search
---


# Question
Title: How do I render content "as is" from custom controller
I've created a custom controller that pulls content from another node (the body). That content is defined in the node as Raw HTML.

```
  public function page(Request $request): array {

    $nid = $request->attributes->get('_nid');
    $node_storage = $this->entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);
    $content = $node->get('field_content')->value;

    // Load Entity using passed NID from key.
    $build = $content;
    // Return new Response($build);
    $render_array['snippet'] = [
      '#theme' => 'webpart_snippet',
      '#content' => $build,
      '#prefix' => '<div class="webpart_outer_wrapper">',
      '#suffix' => '</div>',
    ];
    return $render_array;

  }

```

I would like to render that content as if it were a native Symfony response. (e.g., correctly parse and HTML tags AND scripts)

In the node that I'm pulling in, I have, for example

```
<h1>This is text</h1>

```

and that is exactly what is showing on the page

It should be

# This is text

I have defined a custom theme as well as twig template

```
/**
 * Implements hook_theme().
 * Declare a new theme
 */
function custom_webpart_snippet_theme() {
  return [
    'webpart_snippet' => [
      'variables' => [
        'content' => '',
      ],
    ],
  ];
}

```

# Answer
> 1 votes
Since this is a text area field, you need to specify a type of render element, processed\_text.

```
$render_array['snippet'] = [
  '#theme' => 'webpart_snippet',
  '#type' => 'processed_text',
  '#text' => $node->field_content->value,
  '#format' => $node->field_content->format,
  '#prefix' => '<div class="webpart_outer_wrapper">',
  '#suffix' => '</div>',
];

```

# Answer
> 0 votes
The problem was in the template (twig) Simply the ***raw*** filter see doc description here

**Non-working code**

```
<div class="snippet-wrapper">
  <div>{{ content }}</div>
</div>

```

**Working code**

```
<div class="snippet-wrapper">
  <div>{{ content | raw }}</div>
</div>

```

---
Tags: 8
---


title: Programmatically User login not working

text:
# Question
Title: Programmatically User login not working
I am trying to login users programmatically in Drupal 8. Here goes my code:

```
if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
  exit(0);
}

```

I am getting the message 'Session opened for...' in watchdog. But the user is not logged in. Can someone tell me whats wrong with my code?

# Answer
your code is Ok.

just add the following namespace:

```
use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

```

delete in your code:

```
 user_login_finalize($user);

```

and

```
 exit(0);

```

A complete example would be.

```
use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

$uid=1;

if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
ksm($user);
}

```

if you have installed the

> devel

module and the

> Kint

submodule, You can use the function

> ksm()

, to show the information of a variable.
> 8 votes

# Answer
Here is the full code that you can paste into a new file and run

```
<?php
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// ID of the user.
// REPLACE WITH WHATEVER ID YOU WANT TO LOGIN AS;
$uid = 100;
$user = Drupal\user\Entity\User::load($uid);

// This is required to call user_login_finalize here.
$kernel->prepareLegacyRequest($request);
user_login_finalize($user);

$response->send();

$kernel->terminate($request, $response);

```

Ref: http://www.drupal8.ovh/en/tutoriels/76/login-programmatically-as-a-user
> 1 votes

---
Tags: 8, users
---


# Question
Title: How do I change the default '- Any -' option in views exposed filter?
I have exposed filters in a view as select lists. How can I change the text for the default filter option of "- Any -"? In previous versions it was suggested to use a preprocess function like this:

```
if($form['#id'] == 'views-exposed-form') {
      foreach ($form['FIELDNAME']['#options'] as $key => &$option) {
        if ($key === 'All') {
          $option = 'All';
        }
      }
    }

```

But in Drupal 8, instead of a modifiable key/value, it is stuck inside a protected class.

```
protected string -> string(7) "- Any -"

```

How can I modify this?

Note: I also tried Better Exposed Filters, but it is unable to rewrite the "- Any -" option.

# Answer
Better Exposed Filters works for me well in my Drupal 8. On *Better Exposed Filters \> Settings \> More Options \> Rewrite results*, replace *\- Any -* with the text you want, following this format: *\- Any -|your replacement*.
> 8 votes

# Answer
The *All* key contains an translatable object, so it works as before. You just need to use code similar to the following one.

```
$form['field_your_field']['#options']['All'] = t('Text you want');

```
> 6 votes

# Answer
I figured out a way to do this at the theme level. You could change '- Any -' to a particular value or some other variable.

Copy select.html.twig to your theme. Modify the template to check if option.label equals '- Any -' and if so change it to whatever you'd like. In the code below it is set to the value for the filter's label.

```
{% elseif option.type == 'option' %}
  {# custom if statement #}
  {% if option.label == '- Any -' %}
    {% set option = option|merge({ 'label': element['#title'] }) %}
  {%  endif %}
  <option value="{{ option.value }}"{{ option.selected ? ' selected="selected"' }}>{{ option.label }}</option>
{% endif %}

```
> 2 votes

# Answer
The other answer pointed me in the right direction.
The merge filter didn't work for me. I don't know what I was doing wrong, so I used a simpler solution.

```
{% elseif option.type == 'option' %}
  {# custom if statement #}
  {% if option.label == '- Any -' %}
    <option value="{{ option.value }}"{{ option.selected ? ' selected="selected"' }}>- All -</option>
  {% else %}
    <option value="{{ option.value }}"{{ option.selected ? ' selected="selected"' }}>{{ option.label }}</option>
  {%  endif %}
{% endif %}

```
> 1 votes

# Answer
As an option, you can use select.html.twig in your custom theme with the following code.

```
{% spaceless %}
  {% if input_group %}
    <div class="input-group">
  {% endif %}

  {% if prefix %}
    {{ prefix }}
  {% endif %}

  {# Browsers do not recognize pseudo :after selectors, we must create a wrapper
   # around the select element to style it properly.
   # @see http://stackoverflow.com/q/21103542
   #}
  {% if not attributes.offsetExists('multiple') %}
  <div class="select-wrapper">
  {% endif %}
  {% set classes = ['form-control'] %}
  <select{{ attributes.addClass(classes) }}>
    {% for option in options %}
      {% if option.type == 'optgroup' %}
        <optgroup label="{{ option.label }}">
          {% for sub_option in option.options %}
            <option
              value="{{ sub_option.value }}"{{ sub_option.selected ? ' selected="selected"' }}>{{ sub_option.label }}</option>
          {% endfor %}
        </optgroup>
      {% elseif option.type == 'option' %}
        {# custom if statement #}
        {% if option.label == '- Any -' %}
          {% set option = option|merge({ 'label': '-All-' }) %}
        {% endif %}
        <option value="{{ option.value }}"{{ option.selected ? ' selected="selected"' }}>{{ option.label }}</option>
      {% endif %}
    {% endfor %}
  </select>
  {% if not attributes.offsetExists('multiple') %}
  </div>
  {% endif %}

  {% if suffix %}
    {{ suffix }}
  {% endif %}

  {% if input_group %}
    </div>
  {% endif %}
{% endspaceless %}

```
> 1 votes

# Answer
You can put it in your *themename.theme* file in your theme directory. This worked for me.

```
/**
 * Implements hook_form_alter().
 */
function nameofwebtheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id']=='views-exposed-form-what-s-on-page-1') {
    $form['field_date_range_value']['#options']['All'] = t('Text you want');
  }
}

```
> 1 votes

# Answer
When you click on *Better exposed Filters: Settings*, you will see a *Rewrite filter options* drop-down under *More options for...*.

Add *\- Any -|All* or change it to anything you need. This works.
> 0 votes

---
Tags: 8, views
---


title: How do I configure a Kernel test?

text:
# Question
Title: How do I configure a Kernel test?
Currently I am able to run the Unit test from the below command

```
C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\bin>phpunit -c
 ../../core/phpunit.xml.dist ../../modules/custom/lse_demo/tests/src/Unit

PHPUnit 6.5.0 by Sebastian Bergmann and contributors.
......                                                              6 / 6
(100%)
Time: 10.62 seconds, Memory: 6.00MB
OK (6 tests, 12 assertions)

```

But When I tried to do the same with Kernel test I get below error

```
C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\bin>phpunit -c ../../core/phpunit.xml.dist ../../modules/custom/lse_demo/tests/src/Kernel
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

EEEEEE                                                              6 / 6 (100%)

Time: 11.43 seconds, Memory: 6.00MB

There were 6 errors:

1) Drupal\Tests\lse_demo\Kernel\DefaultControllerKernelTest::testDefaultController with data set #0 ('work', 'User', 'Welcome User to Work')
PHPUnit\Framework\Exception: PHP Fatal error:  Uncaught PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist".

  thrown in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

Fatal error: Uncaught PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist".

  thrown in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist". in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

```

# Answer
Ensure your connection string in the phpunit.php.dist is correct. The correct format is:

```
mysql://username:password@localhost/databasename#table_prefix

```
> 0 votes

# Answer
example

put phpunit.xml.dist to root directory

path inside the above file name is

./core/tests/TestSuites/UnitTestSuite.php ./core/tests/TestSuites/KernelTestSuite.php ./core/tests/TestSuites/FunctionalTestSuite.php

./vendor/bin/phpunit --no-coverage UnitTest ./modules/custom/helloworld/tests/src/Unit/helloWorldTest.php

try the same for kernelTest

my test file starts

=====================

namespace Drupal\Tests\helloworld\Unit;

use Drupal\Tests\UnitTestCase; use Drupal\helloworld\Helloworld;
> -1 votes

---
Tags: 8, testing
---


# Question
Title: Taxonomy Term Hierarchy(not programmatically nor content related)
I know there are zillion topics about this, but I just couldn't apply it to my View Block in Drupal 8. On the other hand all these Taxonomy Term Tree creation is based on content related.

Here is what I would like to do, I would like to display my "Collections" taxonomy term hierarchy without content relationship, as it is(just parent-child terms). This is how my taxonomy term hierarchy looks like:

And this is how far I could get:

This is my result(which is completely wrong):

\**FYI: I am using Views Tree and I follow this Taxonomy display children with Taxonomy View Depth not working \**

Thank you for help and time in advanced.

# Answer
> 0 votes
you can use the *Views Tree* module for this: https://www.drupal.org/project/views\_tree

It works pretty well, you just need to use the Tree (list) views **FORMAT**, add the parent taxonomy term in **RELATIONSHIPS**, add the parent term's *Name* field to the **FIELDS** list, and then use it as the *Parent field* on the Tree settings:

The module will link the terms hierarchically and output a nested list, and you can always hide the parent term's name field to show just the children terms names.

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


# Question
Title: Drupal recommended-project missing Drush
I am looking to transform from `drupal-project` to `recommended-project` and seeing some difference in the folder structure.

`drupal-project` contains a drush folder outside'web' folder and 'composer.json' contains line "drush/drush": "^9.0.0".

However, `recommended-project` does not have this setup although I could still install drush using `composer require drush/drush`. Still drush isn't installed outside 'web' folder.

Can I please know why the setup has changed and a way to have drush folder outside 'web'?

# Answer
> 5 votes
It is important to understand the distinction between the Drupal core project templates and the drupal-composer project template.

* The Recommended and Legacy project templates are maintained by Drupal core. As a result, it only includes those components validated by the core maintainers to be very stable and needed by most Drupal users. The bar for this is very high, and the complexity of the component plays into the decision. For example, Drush is very stable and used by most Drupal users, but it is a fairly large and complex project, and therefore has not been added to a core project template. Use the Recommended project if you'd like your web root inside a "web" directory, or the Legacy project if you would like your web root at the project root.
* The drupal-composer/drupal-project template is maintained by the community. It contains more components that are likely to be useful to a wide range of users. If a bug or configuration problem is found with this project, then it must be reported and fixed through the community repository on GitHub.

The latest version of drupal-composer/drupal-project uses the same core scaffold components as the drupal/recommended-project Composer template provided by Drupal core. It is safe to start with the drupal-composer/drupal/project template for your site.

If you add Drush to your site, either by starting with drupal-composer/drupal-project, or by adding it manually to the drupal/recommended-project, then the Drush binary will always be installed inside the vendor directory. This will be inside the web root for the Legacy project, or outside the webroot for the Recommended project, and for drupal-composer/drupal-project.

If you decide to start with the Recommended project and add Drush, you should also look at the composer.json for drupal-composer/drupal-project and see if there is any configuration in the "extra" section that you might want to copy over for your site.

---
Tags: drush, installation
---


# Question
Title: Composer keeps overwriting .htaccess (and other files) every time I do anything
Every time I try to update anything using Composer, it overwrites a load of files. One of the files it overwrites is .htaccess, which I have customised, so I have to keep patching it all the time. Here's an example (below) of it doing this even when package I asked to update didn't need updating. I'm guessing it's because I used the "drupal/core-composer-scaffold" package to create the site. I did that because I was following these instructions: https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies#composer-from-scratch.

What am I doing wrong, to make it keep scaffolding (if that's the word for it) repeatedly? Thanks.

```
~/sites/default$ composer update drupal/security_review
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package academicpuma/citeproc-php is abandoned, you should avoid using it. Use seboettg/citeproc-php instead.
Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.
Package technosophos/LibRIS is abandoned, you should avoid using it. No replacement was suggested.
Package zendframework/zend-diactoros is abandoned, you should avoid using it. Use laminas/laminas-diactoros instead.
Package zendframework/zend-escaper is abandoned, you should avoid using it. Use laminas/laminas-escaper instead.
Package zendframework/zend-feed is abandoned, you should avoid using it. Use laminas/laminas-feed instead.
Package zendframework/zend-stdlib is abandoned, you should avoid using it. Use laminas/laminas-stdlib instead.
Writing lock file
Generating autoload files
Scaffolding files for drupal/core:
  - Copy [project-root]/.editorconfig from assets/scaffold/files/editorconfig
  - Copy [project-root]/.gitattributes from assets/scaffold/files/gitattributes
  - Copy [web-root]/.csslintrc from assets/scaffold/files/csslintrc
  - Copy [web-root]/.eslintignore from assets/scaffold/files/eslintignore
  - Copy [web-root]/.eslintrc.json from assets/scaffold/files/eslintrc.json
  - Copy [web-root]/.ht.router.php from assets/scaffold/files/ht.router.php
  - Copy [web-root]/.htaccess from assets/scaffold/files/htaccess
  - Copy [web-root]/example.gitignore from assets/scaffold/files/example.gitignore
  - Copy [web-root]/index.php from assets/scaffold/files/index.php
  - Copy [web-root]/INSTALL.txt from assets/scaffold/files/drupal.INSTALL.txt
  - Copy [web-root]/README.txt from assets/scaffold/files/drupal.README.txt
  - Copy [web-root]/robots.txt from assets/scaffold/files/robots.txt
  - Copy [web-root]/update.php from assets/scaffold/files/update.php
  - Copy [web-root]/web.config from assets/scaffold/files/web.config
  - Copy [web-root]/sites/README.txt from assets/scaffold/files/sites.README.txt
  - Copy [web-root]/sites/development.services.yml from assets/scaffold/files/development.services.yml
  - Copy [web-root]/sites/example.settings.local.php from assets/scaffold/files/example.settings.local.php
  - Copy [web-root]/sites/example.sites.php from assets/scaffold/files/example.sites.php

```

# Answer
That's Drupal's Composer Scaffold. Listed as `"drupal/core-composer-scaffold": "^8.8.0"` or a different version in your project's `composer.json` file.

To prevent certain scaffold files from being overwritten every time you run a Composer command you need to specify them one by one in the `"extra"` section of your project's `composer.json`. See the docs on Excluding scaffold files.

The following snippet prevents the `.htaccess` and the `development.services.yml` from being overwritten.

```
"drupal-scaffold": {
    "locations": {
        "web-root": "web/"
    },
    "file-mapping": {
        "[web-root]/.htaccess": false,
        "[web-root]/sites/development.services.yml": false
    }
},

```

---

But maybe you want to ensure you always get Drupal's latest `.htaccess` for security updates for example. For that you don't exclude this file from Drupal Scaffold but you patch it instead. See the docs on Altering scaffold files.

Create a patch of the `.htaccess` and maybe put it in a folder called "patches" in your project root. Then configure a `"post-drupal-scaffold-cmd"` in the `"scripts"` section of your `composer.json` file to have this patch applied to Drupal's core `.htaccess` every time Drupal scaffolding is triggered.

```
"scripts": {
    ...
    "post-drupal-scaffold-cmd": [
        "cd web && patch -p1 < ../patches/htaccess-ssl.patch"
    ]
}

```
> 30 votes

---
Tags: 8, composer
---


# Question
Title: What do I do with the list of blocked IP addresses
I have a growing list of blocked IP addresses on my Drupal 7 site. I've installed the following modules: Honeypot, Captcha questions, Captcha, reCaptcha, and Hidden Captcha. They all work fine and there are no more bogus users or posts created but there are still a lot of bots that try to intrude with scripts. Is there something I can do with the collected IP addresses from this path: admin/config/people/ip-blocking to help perhaps others or the community as well?

# Answer
> 1 votes
We've all been there and felt that.

This is time consuming. You could report the abuse to the abuse@domain.xyz email by looking up the Whois record for each IP. This email address and investigation are required by ...

> The 2013 Registrar Accreditation Agreement (RAA) requires ICANN-Accredited registrars to provide abuse contact information and take steps to investigate reports of abuse. This includes:
>
> Maintaining an abuse contact to receive abuse reports involving domain names sponsored by the registrar, including reports of illegal activity, and publishing an email address to receive reports on the home page of the registrar's website;
>
> Taking reasonable and prompt steps to investigate and respond appropriately to any reports of abuse;
>
> Establishing and maintaining a dedicated abuse point of contact to receive reports of illegal activity filed by law enforcement or other similar authorities designated by the government of the jurisdiction in which the Registrar is established or maintains a physical office. The registrar should review such reports within 24 hours of submission. This includes a dedicated email address and telephone number that is monitored 24 hours a day, seven days a week;
>
> Publishing on the registrar's website a description of its procedures for the receipt, handling, and tracking of abuse reports; and
>
> Providing an abuse email address and telephone number in Whois results.
>
> The full abuse contact requirements are provided in Section 3.18 the 2013 RAA.

CleanTalk.org and abuseipdb.com will accept the IPs and emails you find as spam. One at a time though so start with the biggest offenders.

> When you sent a report, the IP or Email address with malicious activity will be added in our blacklist database with status "Suspicious". If we will receive other abuse reports so the status will be changed to BlackListed.

Spamcop.net will take spam emails you find then sends "warning information to the internet service provider responsible for hosting the services used by the spammer (web sites and email sending sites)."

Rather than "a growing list of blocked IP addresses", have you considered blocking by country or region or IP range? You can do that through the .htaccess file or Drupal modules.

I hope this gets you started in your crusade for a better world.

---
Tags: 7
---


# Question
Title: How do I get the submitted moderation state of a custom block?
I am a bit new for Drupal and currently working on Drupal8. I need to implement custom restrictions for workflow. Basically i want to get the submitted value of `moderation_state` filed in `mymodule_form_alte`

Here are the things that i have tried but all returns `Null`. The strange thing is that the below method works for **node** but do not work for **block\_content**

```
 function mymodule_form_alter($form, &$form_state, $form_id) {
   $formSate = $form_state->getValue('moderation_state')[0]['valye'];
   var_dump($formState); // Output : Null

   $formSate = $form['moderation_state']['widget']['#default_value'];
   var_dump($formState); // Output : return the default value of dropdown not the one that i have selected
}

```

Here is the moderation\_state field

# Answer
all most there try the following

```
// Get the current  entity.
$entity = $form_state->getFormObject()->getEntity();
$moderation_state = $entity->get('moderation_state')->getString();
// Do the things.

```

or in a submit or validation thing try to

```
// use dump() as it is way better
dump($form_state->getValues()) // <-- and find in the array

```
> 2 votes

---
Tags: hooks, workflows
---


# Question
Title: How can I programmatically add webform elements to an existing webform?
I have a webform that is very simple, it's a questionnaire. It is attached to a content type called "event". e.g.

```
discussion_1:
  '#type': likert
  '#title': 'Discussion 1'
  '#questions':
    'Question 1': 'Question 1'
    'Question 2': 'Question 2'
    'Question 3': 'Question 3'
  '#answers': likert_five_scale

```

Is it possible to alter this webform when the webform is rendered by populating the questions from another source such as a view?

i.e. there will be a variable number of discussions with variable numbers of questions.

I am trying to dynamically build a webform based on data that is coming from the node to which the webform is attached

# Answer
> 3 votes
You need to use hook\_webform\_load() and alter a webform's elements via `\Drupal\webform\Entity\Webform::setElements`. If you trying the alter webform elements based on the node (aka source entity) you might need to use hook\_webform\_submission\_load() and then alter the webform's element via `\Drupal\webform\Entity\WebformSubmission::getWebform`

# Answer
> 5 votes
So I spent a full day investigating on something similar. Kudos to @jrockowitz for providing the right direction. Below is something I wrote to work.

```
$webforms = \Drupal::entityTypeManager()
  ->getStorage('webform')
  ->loadByProperties([]);

$new_field = [
   'new_field'=>[ '#type' => 'textfield',
     '#title' => 'Question one',]];

foreach ($webforms as $webform) {
     // Applying to all forms.
      if (!in_array('new_field', $webform->getElementsDecoded())) {
        // $webform->getElementsDecoded() will get all the previous elements of the webform.
        $new_element_arrangment = array_merge($webform->getElementsDecoded(), $new_field);
        $webform->setElements($new_element_arrangment)->save();
    }
}

```

# Answer
> 0 votes
Create a custom module and use hook\_form\_alter to add new fields and set default values.

```
function YOURMODULENAME_form_alter($form_id, &$form) {
  if ($form_id == 'YOUR_FORM_ID') {
        $form['yourmodule'] = array(
        '#type' => 'checkbox',
        '#options' => t('Test'),
        '#title' => t('Title),
        '#description' => t('Description.'),
        '#weight' => 100,
    );
  }
}

```

---
Tags: 8, webforms
---


# Question
Title: Should a splash page linking to other multisite instances also be a multisite instance or a bare HTML page?
**This is the situation:**

1. Global domain: www.domain.com (exists of one page, with links to other 3 subdomains)
2. Sub domain 1: sub1.domain.com (full website)
3. Sub domain 2: sub2.domain.com (full website)
4. Sub domain 3: sub3.domain.com (full website)

**My question:**

Is it overkill to also create a site for the global domain? It will only have one page (frontpage). Or what is the best practice to accomplish this? **The global domain is just a landingpage where you can make a choice between the 3 subsites.**

# Answer
If you need **more flexibility** on the long run, you better **create a separate website for the global domain**. Keep in mind that it will **require extra resources** on your server.

If your **global landing page is simple** you can consider the option to only **use a HTML page**. Keep in mind that this will **give you less options on the long run**.
> 1 votes

---
Tags: 8, multi-sites
---


# Question
Title: Migrate two user fields (translation) to translation
I'm trying to migrate two user fields in Drupal 7 (name in two languajes) to a translated field in Drupal 8. I have tried several options but all failed. I have two yml templates (one for the user and another for the translation with parameter translations:true) but not working. The user is migrated correctly. The translation of the user is created correctly. The field of the user is correctly but the translated field is not translated.

These are a part of the yml files...

migrate\_D7\_user.yml

> ```
> source:
>   plugin: d7_user
> process:
>   uid:
>     -
>       plugin: get
>       source: uid
>   name:
>     -
>       plugin: get
>       source: name_english
>   langcode:
>     -
>       plugin: default_value
>       default_value: en
> destination:
>   plugin: 'entity:user'
>
> ```

migrate\_D7\_user\_translation.yml

> ```
> source:
>   plugin: d7_user
>   translations: true
> process:
>   uid:
>     -
>       plugin: migration
>       source: uid
>       migration: migrate_d7_user
>   name:
>     -
>       plugin: get
>       source: name_spanish
>   langcode:
>     -
>       plugin: default_value
>       default_value: es
>
> destination:
>   plugin: 'entity:user'
>   translations: true
>
> ```

Thank you in advance, Juanjo.

# Answer
> 0 votes
Now it works. There was a problem with the migration of the user admin (user/1). If you migrate admin user, then you can't edit translations of any user. Now I put a custom source plugin with function query() overwritten:

```
/**
   * {@inheritdoc}
   */
  public function query() {

    $query = parent::query();

   // Only migrate users not admin (1)
    $query->condition('uid', '1', '<>');
    return $query;
  }

```

---
Tags: migrations
---


# Question
Title: How do I override a view template in my theme folder properly?
I do not know if I am something missing, but I have a View in Drupal 8 and wanted to make a Template override in my theme, where I would print-out the image URL of one field and set it as "background-image" via inline CSS.

So I turned on theme debugging to see the template suggestions and picked `views-view-field.html.twig`, copied the file to my theme, renamed it to match the suggestion, cleared the cache and it looks like the template override is working.

But all the variables I am trying to print-out are blank, even after clearing the cache the field just disappeared. When I try to dump() or kint() any variable written in the file (view, field, row, output) it prints "null" or completelly nothing.

What am I doing wrong?

I am sure template override works, because when I type regular text in a file it gets printed out, but all the variables are somehow missing and I can not print anything out of them.

# Answer
> 0 votes
Copy the content of the previous template used and start from there. It is most likely that the variable you are trying to display are not available in that template. Consider adding variables using hook\_preprocess.

---
Tags: views, theming
---


# Question
Title: How can I catch an EntityStorageException exception?
I have a custom Webform Handler that submits a webform to an external SOAP api. Once a user submits the form, the data is sent to the external api, my custom webform hidden field 'error' is updated to read 'Yes' or 'No' depending on the feedback from the api and the form details are saved to the Drupal database. The contents of the custom 'error' field is then used to send a conditional email to the website admin. All works fine except when the SOAP api is offline, then there is an EntityStorageException error and the details in the form are neither saved to the database or submitted to the SOAP api. I've tried to Catch the EntityStorageException, but it's not working.

My code is as follows:

```
namespace Drupal\mycustom_handler\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\Core\Entity\EntityStorageException;
/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "sentinelapplication",
 *   label = @Translation("Sentinel Application"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers application via SOAP"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class mycustom_handler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }
  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $values = $webform_submission->getData();
    $endpoint = 'www.soapapi.com';

    // Add the SOAP Call
    try {
      global $base_url;
      $wsdlurl = $base_url ."/modules/custom/mycustom_handler/src/Plugin/WebformHandler/mycustom.wsdl";
      $client = new \SoapClient($wsdlurl, array('location'=>$endpoint, 'exceptions'=>true, 'trace'=>true));
      // upload webform detail to SOAP
      $webform_submission->setElementData('error', 'No');
    }
    catch (SoapFault $ex) {
      $webform_submission->setElementData('error', 'Yes');
    }
    catch (Exception $ex) {
      $webform_submission->setElementData('error', 'Yes');
    }
    catch (EntityStorageException $ex) {
      $webform_submission->setElementData('error', 'Yes');
    }
  }
}

```

I have also tried but had no luck with:

```
catch (\EntityStorageException $ex)

catch (Drupal\Core\Entity\EntityStorageException $ex)

catch (\Drupal\Core\Entity\EntityStorageException $ex)

```

Not sure if it is an issue with the `preSave function` (and `postSave function` as I tried that too) because if I use the `submitForm function`, the error does not display and the data is saved to the Drupal database. However, while using the submitForm function solves my error problem, I can't seem to figure out how to update the custom 'error' field in the submitForm function.

So has anyone got any idea how to Catch the EntityStorageException error or alternatively, if that is not possible, how can I update the webform submission within the submitForm function?

# Answer
> 0 votes
Thanks to Hudri, the answer to this problem was to add a backslash before SoapFault in the catch because my try/catch code is made within a local namespace and the Soap call is made in the global namespace. So my code should have been `catch (\SoapFault $ex)`. All working now - thanks.

---
Tags: webforms
---


# Question
Title: How to change password via REST when validating email address (first login link)
Is there a `REST api` way to allow the user to set a new password on email confirmation / first time login?

I tried the same code as for changing the password when you're already logged in and adding the `pass-reset-token` as a GET param but without any luck. Server always returns the following message:

`{"message":"Users can only update their own account, unless they have the \u0027administer users\u0027 permission."}`

Does anyone have any idea? If not, I will write some custom code inspired from the core module but I hoped that the rest api should handle such things.

# Answer
To avoid all security implications I just displayed the actual Drupal form when the user changes the password for the first time, styled it to look like the js app and added a redirect on form submission to the actual js app page. Works fine so far.
> 2 votes

# Answer
I'm not sure there is a pure Drupal core way of doing this, but there are contrib modules which can help. These modules involve resetting the password when it has been forgotten but may help with understanding the process.

Password reset REST allows resetting the password via REST.

> Small module to help with resetting password through rest.
>
> This attempts to provide the same logic present with a pass-reset-token as you'd do with the normal interface.

REST Password Request provides an alternative method which involves generating a temporary password so the user can change their password via rest, and then log in as normal.

REST Register User with Email Verification supports email validation, but may not be exactly what you're after.

It is also worth reviewing this issue regarding anonymous REST and user entities: A REST resource's "auth" configuration MUST be non-empty, which prevents configuring it for anon access only
> 3 votes

---
Tags: 8
---


title: Display custom profile field in twig

text:
# Question
Title: Display custom profile field in twig
In drupal7 I used this code in my template file (node--article.tpl.php) to display the author bio. This is a custom profile field named field\_author\_bio.

```
<?php print user_load($uid)->field_author_bio['und'][0]['value']; ?>

```

In drupal8 I have the same setup.But I'm stuck how to do this with a twig template?

Any advise? Thanks.

# Answer
> 0 votes
I have found a pretty simple solution. I was thinking way to difficult. It was pretty simple to make the author\_bio field visible on my article pages.

All I had to do is go to: Configuration, Account settings, Manage display and select the "Compact" display (admin/config/people/accounts/display/compact). And then add author\_bio. And Save. Thats all.

This way I don't need any code.

Now the author\_bio field is displayed on the article page.

Thanks

# Answer
> 0 votes
This is a user template from Drupal 8. Check detail here or below code.

```
{#
/**
 * @file
 * Theme override to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 */
#}

<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>

```

Please see the comment code. If you want to render your custom field in template, just `content.<your_custom_field>`. With your example is `content.field_author_bio`.

In case your field's content when rendering is not your expectation, you maybe need to use `template_preprocess_user()` for preprocessing content before rendering in the template (Search more about this function if you need).

---
Tags: theming
---


title: Import CSV with Single Quoted data

text:
# Question
Title: Import CSV with Single Quoted data
I need to use feeds importer to import csv file. But there's single quote in the values like `doesn't`. Is there anyway to escape the single quote?

Thanks

# Answer
Part of the problem here is that there's no standard specification for CSV.

Added to that, Microsoft does not have much incentive to ensure interoperability between their version of CSV and Drupal's version, and so it is not surprising that they do not offer any (direct) way to encapsulate the contents of cells with single quotes within double quotes, so you've got to do something a bit more complicated if you want Excel to output Drupal-friendly CSV files.

Or, since Drupal is telling you where the problem is, you can do it manually. If you only have a few rows with apostrophes, then that may not be a big deal. If you have a lot of rows in your CSV with apostrophes or single quotes, then you've got a bit of pain.

Alternately, if you've got Python on your machine, or are willing to install it, this python script to add double-quotes to CSVs may work for you, and may be much easier than dealing with Excel macros. It all depends on the languages and language environments you're comfortable with, however.

One might argue that Drupal (or more specifically the Feeds module) should support Microsoft's CSV, and thus handle apostrophes gracefully when not wrapped in double quotes. If you are of this opinion, you may want to file a request with the Feeds project. Since there is no (standard) CSV spec, this can't be considered a bug (AFAIK), but it does seem like a useful feature that they might want to add.
> 3 votes

# Answer
Just Ensure the CSV value separators are double quotes
> 1 votes

# Answer
When I have Microsoft Access, I import Excel files into it. Then I export them from Access to a csv file by using an advanced feature to save in UTF-8 format. At the moment I don't have Access so I can't give a better description, but it does work. This takes care of apostrophes and quotes.
> 0 votes

# Answer
If using Excel to edit a csv, then you'll want to Save As-\>Tools beside the Save button. Choose "Web Options" and select "Encoding" tab, Save this document as Unicode(UTF-8). This solved my error.
> 0 votes

---
Tags: feeds, importing-exporting
---


# Question
Title: how to be the last hook_page_alter called?
If you implement hook\_page\_alter in your own module, your hook will be called somewhere between all the other modules.

I am trying to undo something another module is doing in hook\_page\_alter. Somehow my hook is called before the other one.

How can I become the last hook to get called ? Or, what is the first hook after hook\_page\_alter that still uses $page ?

# Answer
> 0 votes
To make your hook last called you can make use of `hook_module_implements_alter` like the following:

```
function MODULENAME_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'page_alter') {
    // Move MODULENAME_page_alter() to the end of the list. module_implements()
    $group = $implementations['MODULENAME'];
    unset($implementations['MODULENAME']);
    $implementations['MODULENAME'] = $group;
  }
}

```

---
Tags: 7, hooks
---


# Question
Title: What is the best way to redirect node to node
I am trying to figure out what is the best way to create a redirect from one node to another. For example, say we have two nodes:

```
node/1 | path-one
node/2 | path-two

```

I created the following redirect:

But when visiting `path-one` it still shows `node/1` instead of redirecting to `node/2`.

The only way I can do it is to remove the path alias for `node/1` and then it works.

# Answer
> 0 votes
Try the redirect when logged out of your admin account as I believe when logged in as an admin any redirects from a page that exists won't get triggered. This is to allow you to be able to still access that page as an administrator

---
Tags: 8, redirection
---


# Question
Title: Append current query string to private file urls?
If I use template\_preprocess\_file\_link, can I add the current url query string and append it to the link per user? Will this link be cached for all users?

Update:

This appends it, but does seem to get cached:

```
  if (preg_match('/private:\/\//i', $file_entity->getFileUri())) {
    $query = \Drupal::requestStack()->getCurrentRequest()->query->all();

    if (!empty($query)) {
      $options['query'] = $query;
    }
  }

  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));

```

# Answer
> 1 votes
Adding this cache context seemed to do it (although I do not know if this is bulletproof):

```
  if (preg_match('/private:\/\//i', $file_entity->getFileUri())) {
    $query = \Drupal::requestStack()->getCurrentRequest()->query->all();

    if (!empty($query)) {
      $options['query'] = $query;
    }

    $variables['#cache']['contexts'][] = 'url.query_args';
  }

```

---
Tags: 8, files
---