# Question
Title: How do I prevent the user autocomplete page from listing all the account names?
I am building a site where users have access to all the user profiles. When users access (for example) site.com/user/autocomplete/a or site.com/user/autocomplete/b, the site returns all the usernames starting with those letters.

Is there a way to limit the number of returned usernames? When I access https://drupal.org/user/autocomplete/a as logged-in user, I don't get the complete list of usernames starting with *a*.

Note: I DO want both the autocomplete function and give access to user profiles BUT, I also want to prevent URLS like 'user/autocomplete/a', 'user/autocomplete/b' …etc from listing all account names. Drupal.org has achieved this, and I am trying to find a way to do it on my website.

# Answer
> 1 votes
The callback function used by default on Drupal for the user autocomplete page (`user_autocomplete()`) always return a maximum of 10 usernames starting with the string it receives as argument.

```
function user_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_select('users')->fields('users', array('name'))
      ->condition('name', db_like($string) . '%', 'LIKE')
      ->range(0, 10)
      ->execute();
    foreach ($result as $user) {
      $matches[$user->name] = check_plain($user->name);
    }
  }
  drupal_json_output($matches);
}

```

This is even true for Drupal 4.7.

```
function user_autocomplete($string) {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $string, 0, 10);
    while ($user = db_fetch_object($result)) {
      $matches[$user->name] = check_plain($user->name);
    }
  }
  print drupal_to_js($matches);
  exit;
}

```

If the user autocomplete page returns more than 10 usernames, it's probable the callback function has been changed by a third-party module to return more results or even all the usernames starting with the given string.

---
Tags: users
---


title: Code for unziping file

text:
# Question
Title: Code for unziping file
I am creating a module for Drupal 8, in which I want to upload and extract zip file to a root directory. Inside `moduleSettingsForm.php` file, I have a `function submitForm(array &$form, FormStateInterface $form_state)`. I am getting all the values of uploaded file but I am unable to extract the content of file.

So is there any way to do this in Drupal 8?

# Answer
There are a Drupal 8 Way how to unzip a ZIP archive:

```
use Drupal\Core\Archiver\Zip;
use Drupal\Core\Archiver\ArchiverException;

try {
  $zip = new Zip('/path/to/archive/file.zip');
  $zip->extract('/path/to/archive');
  // Remove the source zip file if necessary.
  // $zip->remove($file);
  // Shows list (array) of those unzipped files regarding the zip file folder.
  var_dump($zip->listContents());
}
catch (ArchiverException $exception) {
  watchdog_exception('custom_module_name', $exception);
  // Some code if the error of unzip will happen.
}

```
> 4 votes

# Answer
Once you have the file uri of the uploaded file, this stops being a Drupal problem and starts being a PHP problem.

You should take a look at SO for a full description.

What you are looking for is this snippet.

> ```
> $zip = new ZipArchive;
> $res = $zip->open('file.zip');
> if ($res === TRUE) {
>   $zip->extractTo('/myzips/extract_path/');
>   $zip->close();
> }
>
> ```
> 3 votes

---
Tags: 8
---


# Question
Title: Failed to import Bootstrap Paragraph sub module configuration
I tried to implement the Hero with Xeno Hero in the Bootstrap Paragraphs in Drupal 8. I encountered an error when I tried to import the config of the sub module. I am not sure if I do it the right way but I ended up getting this error.

> The configuration cannot be imported because it failed validation for the following reasons: Configuration paragraphs.paragraphs\_type.paragraph.xeno\_hero.default depends on configuration (field.field.paragraph.xeno\_hero.xeno\_content, field.field.paragraph.xeno\_hero.xeno\_invert, field.field.paragraph.xeno\_hero.xeno\_offset, field.field.paragraph.xeno\_hero.xeno\_overlay, field.field.paragraph.xeno\_hero.xeno\_parallax, paragraphs.paragraphs\_type.xeno\_hero) that will not exist after import.

What I did is importing a single item, but I don't know which configuration type to go for, so I tried *Entity Form Display* and *Entity View Display* as well as *Fields*.

Could anyone just point me to the right direction or show me hints that I could follow to get this right?

# Answer
> 0 votes
To use that module, you should upload it to the site, usually in the /modules/custom/ folder since it is not an official Drupal.org module, and then enable it. The configuration should get installed when you enable it. You should not have to do that manually.

After the module is enabled, you need to edit the Paragraph reference fields that you want to make this bundle available in.

Hope that helps.

---
Tags: configuration, paragraphs
---


title: restrict page callback url?

text:
# Question
Title: restrict page callback url?
With this callback code - is it possible to restrict url just to be example/page1 (2 arg) but not example/page1/321 or example/page1/abc/efg...?

```
// hook_menu example
function example_menu() {
 $items['example/page1'] = array(
'page callback'     => 'example_page1_callback',
'access callback'   => TRUE,
'type'              => MENU_CALLBACK,
 );
 return $items;
  }

 // hook_meny callback function
function example_page1_callback() {
 // please provide code within this function to turn these next three
  // variables into separate output variables for the template.
  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  $variable_to_print3 = array('bing', 'bang', 'bong');
  return;
 }

```

# Answer
> 1 votes
The easiest way would be within your code.

You could change your `'access callback' => TRUE,` to a function e.g. `'access callback' => my_access_check,`

And within that function you can have an if statement to detect if a 2nd arg existing and if it does return false which would provide an access denied

If you wanted to do a "page not found" or a redirect or something else then you could put this logic into your `'example_page1_callback'` function

---
Tags: 7
---


title: Detect browser in preprocess function

text:
# Question
Title: Detect browser in preprocess function
My goal is to render a warning message to IE 11 users, prompting them to use a modern browser.

I'm a bit of a noob, but from what I understand, it's possible to detect a user's browser using a preprocess function. I found this function online, which looks like it does what I need it to do, but I'm getting a "The website encountered an unexpected error. Please try again later." error when I add it to my THEMENAME.theme file.

```
function THEMENAME_preprocess(&$variables, $hook){
  if (get_browser_name(htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8')) == 'Internet Explorer'){
       $variables['browserIs'] = 'IE';
   }
   else{
       $variables['browserIs'] = 'OTHERS';
   }
 }

```

Any ideas on how I can accomplish what I need?

# Answer
Use the Browser detect module , it will add browser class to html tag as well.

> This project allows you to identify the browser and the device used.
>
> A class is inserted in the HTML tag so you can use as you need.

Also, you can detect it by calling this function after install this module

```
 Drupal.behaviors.browser_detect.browserVersion();

```
> 1 votes

# Answer
The function would be get\_browser. But you should be using Javascript to detect this instead of PHP.

There are a variety of ways it would fail/be incorrect from the PHP layer, caching, spoofing, etc. Once it gets cached, it would show up for the next person regardless of what browser they are using.

Plenty of JS libs out there can detect it as close as possible, but there is also a module ready to roll here as well that will just solve this for you more than likely, one such module being Browser Detect. There are a few modules for this actually, try them out and see what one suits you best.
> 2 votes

---
Tags: 8, theming
---


title: .htaccess rewrite doesn't work

text:
# Question
Title: .htaccess rewrite doesn't work
I have custom module with page at `/page` wich expects `$_GET['id']` to do it's job.

Here's `.htaccess` rewrite rule that works on empty website

```
RewriteRule category+/(.*)$ page.php?id=$1 [L]

```

On Drupal 8 I suppose that line should be

```
RewriteRule category+/(.*)$ page?id=$1 [L]

```

but it gives me 404 Error when i visit `/category/5`

# Answer
> 2 votes
The rewrite rule will not work because page is not a valid path on the server. By default Drupal rewrites all requests into index.php. When you rewrite to page apache will expect a path page on the server.

This is not quite the right way to accomplish what you are trying to do in Drupal. However you can achieve what you are trying to do with the following

```
RewriteRule category+/(.*)$ page?id=$1 [R=301,L]

```

That will redirect category/5 to page?id=5 and you will get 5 in $\_GET\['id'\]

Check these out as well

https://www.drupal.org/docs/user\_guide/en/content-paths.html

How do I retrieve the query parameters from a path?

---
Tags: 8, .htaccess
---


# Question
Title: Does hook menu accept a wildcard as argument 0?
In a custom module I have implemented `hook_menu()` using the following code.

```
function MYMODULE_menu() {
  $items = [];

  $items['%/review'] = [
    'page callback' => 'review',
    'page arguments' => [0],
    'access arguments' => ['access content'],
    'type' => MENU_CALLBACK,
  ];

  return $items;
}

```

Wildcard should be existing node. I am trying to access mydomain.com/product1/reviews (where product1 is node/1) and then print some related product data on reviews page.

I'm getting a 404 error. If I change `$items['%/review']` to `$items['abc/%']` everything works. What can be the problem?

Note: I don't want to change node route. I want to access this path mydomain.com/product1/reviews where product1 is an existing node.

# Answer
> 0 votes
Since your products are nodes, this is what you need to do

```
  $items['node/%node/review'] = [
    'page callback' => 'my_module_review',
    'page arguments' => [1],
    'access arguments' => ['access content'],
    'type' => MENU_CALLBACK,
  ];

```

In your callback

```
function my_module_review($node) {
  // since you used %node you have access directly to the $node object here as param
}

```

So basically right now you can only access it via `/node/{nid}/review` similarly how you can access the edit form via `/node/{nid}/edit`

Now, install & enable **Sub-pathauto**

> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview)

So it converts it to `/{node-alias}/review` and also you'll now be able to access the node edit form via `/{node-alias}/edit`

# Answer
> 1 votes
Wildcards may not be used as the first component of a route path in `hook_menu`. https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7.x

what can you do if you want this feature, the solution is kind of tricky solution like

```
function MYMODULE_menu() {
  $items = [];
 $myItems =  // load what do you have
foreach($myItems as $myItem){
  $items[$myItem.'/review'] = [
    'page callback' => 'review',
    'page arguments' => [0],
    'access arguments' => ['access content'],
    'type' => MENU_CALLBACK,
  ];
}

  return $items;
}

```

---
Tags: 7
---


# Question
Title: How to alter breadcrumbs from my controller in my module?
The breadcrumb code seems to gather everything from the URL, as it should. But in my module, the other entries used in the URL path do not represent somewhere where the user can go. They instead pass information from my form to a controller object.

Is there a way to remove these entries in the breadcrumb from my modules' controller object?

# Answer
To customize your Breadcrumbs you need to take full control of the Breadcrumb for that particular route with your own Breadcrumb Builder service.

To do this, you need to create an entry in your module/profile services file:

e.g., `mymodule/mymodule.services.yml`

```
services:
  mymodule.breadcrumb:
    class: Drupal\mymodule\MyModuleBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 100 }

```

You then need to create your Breadcrumb Builder class

e.g. `mymodule/src/MyModuleBreadcrumbBuilder.php`

```
<?php

/**
 * @file
 * Contains Drupal\mymodule\MyModuleBreadcrumbBuilder.
 */

namespace Drupal\mymodule;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Class MyModuleBreadcrumbBuilder.
 *
 * @package Drupal\mymodule
 */
class MyModuleBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    $route = $route_match->getCurrentRouteMatch();

    // Add conditionals that return TRUE when the current route should have it's
    // breadcrumb handled here.
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);

    // Add logic here that builds up the breadcrumbs based on desired behaviour.
    $links[] = Link::createFromRoute(t('Home'), '<front>');

    $breadcrumb->setLinks($links);

    return $breadcrumb;
  }

}

```

The `applies` method is where you register this Breadcrumb Builder to be used for the particular route, so build a conditional there that matches your route(s) and returns `TRUE`.

The `build` method is where you build your Breadcrumb for any routes that `applies` returns `TRUE`, so if you are dealing with multiple routes you will need to build the appropriate logic here to build said Breadcrumbs.

I recommend reading through Palantir's blog post for more background and details: https://www.palantir.net/blog/d8ftw-breadcrumbs-work
> 10 votes

# Answer
This was a very interesting problem. I ran into this today while trying to set up custom controller to display a user dashboard. All the posts I saw was about overriding the BreadCrumbBuild system. I wanted to see what the breadcrumb builder was doing in the first place.

The default breadcrumb processing happens through this logic in the

```
core/modules/system/src/PathBasedBreadcrumbBuilder.php

```

file. This is the logic used for creating the breadcrumb.

```
public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $links = [];

    // Add the url.path.parent cache context. This code ignores the last path
    // part so the result only depends on the path parents.
    $breadcrumb->addCacheContexts(['url.path.parent', 'url.path.is_front']);

    // Do not display a breadcrumb on the frontpage.
    if ($this->pathMatcher->isFrontPage()) {
      return $breadcrumb;
    }

    // General path-based breadcrumbs. Use the actual request path, prior to
    // resolving path aliases, so the breadcrumb can be defined by simply
    // creating a hierarchy of path aliases.
    $path = trim($this->context->getPathInfo(), '/');
    $path_elements = explode('/', $path);
    $exclude = [];
    // Don't show a link to the front-page path.
    $front = $this->config->get('page.front');
    $exclude[$front] = TRUE;
    // /user is just a redirect, so skip it.
    // @todo Find a better way to deal with /user.
    $exclude['/user'] = TRUE;
    while (count($path_elements) > 1) {
      array_pop($path_elements);
      // Copy the path elements for up-casting.
      $route_request = $this->getRequestForPath('/' . implode('/', $path_elements), $exclude);
      if ($route_request) {
        $route_match = RouteMatch::createFromRequest($route_request);
        $access = $this->accessManager->check($route_match, $this->currentUser, NULL, TRUE);
        // The set of breadcrumb links depends on the access result, so merge
        // the access result's cacheability metadata.
        $breadcrumb = $breadcrumb->addCacheableDependency($access);
        if ($access->isAllowed()) {
          $title = $this->titleResolver->getTitle($route_request, $route_match->getRouteObject());
          #kint($title);
          #kint($route_match);
          #exit;
          if (!isset($title)) {
            // Fallback to using the raw path component as the title if the
            // route is missing a _title or _title_callback attribute.
            $title = str_replace(['-', '_'], ' ', Unicode::ucfirst(end($path_elements)));
          }
          $url = Url::fromRouteMatch($route_match);
          $links[] = new Link($title, $url);
        }
      }
    }

    // Add the Home link.
    $links[] = Link::createFromRoute($this->t('Home'), '<front>');

    return $breadcrumb->setLinks(array_reverse($links));
  }

```

So what it does is it trims the full URL by removing substrings after each of the path separators (/) and then checking if the url created corresponds to a valid route and if the route is accessible to the user and then creates the breadcrumb. So if the subsequently generated trimmed versions of the URL is not to be accessed by the user then there is a permissions issue for that route. If they are not meaningful routes they wouldn't be shown.

I ran into the issue while using a custom title callback for the controller. I had used the same callback for multiple routes from the same controller. However I was using the path of the current request to create the title. So the breadcrumbs were all created with the current page's title. I fixed the issue by adding the RouteMatchInterface as an argument to the \_title\_callback. This was available as a typehinted argument for the Controller and the title\_callback

See: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes#s-typehinted-parameters

Hope this helps.
> 1 votes

---
Tags: 8, breadcrumbs, page-controller
---


# Question
Title: How should I perform a redirect in hook_form_alter()?
When users log in, I want to redirect them to another page, when they have a certain role. In Drupal 7, I'd use `drupal_goto()` in `hook_user_login()` to do the redirect, and `hook_module_implements_alter()` to make sure that my module is last in the list, so that everything else gets a chance to run.

In Drupal 8, it seems that performing a redirect outside of a controller is not a supported use case.

On that page, gngn has the same problem, and manually generates a RedirectResponse and sends it.

The problem is that, as I see it, `send()` doesn't terminate the request and the page will have two HTML documents: a 'redirecting to...' page, followed by whatever page would have been there in the first place. Which could be a security issue.

johnvb notes this, and inserts a call to `exit()` after `send()`.

Presumably something useful is being done in the `$kernel->terminate()` call in index.php, which is being bypassed by calling `exit()`.

In Drupal 7, `drupal_goto()` called `drupal_exit()` to handle this problem.

`drupal_goto()` was removed says that modules needing to interrupt the request flow should throw an HTTP exception, but there are no 'redirect' exceptions.

As the user login also does a redirect, another approach would be to alter the redirection URL, as suggested on the `drupal_goto()` change record link above. However, that approach will result in my method being called on every single request, which for what I'm doing seems insanely wasteful.

So, how should I perform a redirect from `hook_form_alter()` in Drupal 8?

# Answer
> 10 votes
```
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function [MODULENAME]_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Alter login form and add own custom submit handler.
  $form['#submit'][] = '_[MODULENAME]_user_login_form_submit';

  // Not all forms pay attention to $form['#submit'][]. For these
  // try adding your submit hook to the #submit for the specific
  // button.  e.g.,
  $form['actions']['submit']['#submit'][] = '_[MODULENAME]_user_login_form_submit';
}

/**
 * Custom submit handler for login form.
 */
function _[MODULENAME]_user_login_form_submit($form, FormStateInterface $form_state) {
  // Set redirect to login form.
  $form_state->setRedirect('custom.redirect_callback');
}

```

# Answer
> 0 votes
You have several ways to redirect user after login. As in the previous answers you can do it by implementing hook\_form\_FORM\_ID\_alter() and adding additional submit function, but you can still use hook\_user\_login function too:

To redirect to some route with parameters generating some url (using Symfony\Component\Validator\Constraints\Url class reference):

```
$form_state->setRedirectUrl(new Url('route_name', ['route' => 'parameters']));

```

To redirect to some route:

```
$form_state->setRedirect('route_name', ['route' => 'parameters']);

```

Also you can use `Symfony\Component\HttpFoundation\RedirectResponse`, for example if you want to redirect a user to some custom user page:

```
function your_module_user_login($account) {
    global $base_url;
    $redirect = new RedirectResponse($base_url .'/your-url/'.$account->uid->value);
    $redirect->send();

}

```

# Answer
> 0 votes
The correct way to set a redirection after a form is submitted, in Drupal 8, is following these steps.

The alternative would be using the *redirect.destination* service. In this case, also with Drupal 8 it would be possible to use `hook_user_login()`.

```
function mymodule_user_login(UserInterface $account) {
  \Drupal::destination()->set($url_destination_as_string);
}

```

The documentation for `RedirectDestination::set()` says, though:

> This method should be used really rarely, for example views uses it, in order to override all destination calls in all of its rendering.

As side note, the correct method to redirect users after they log in, in Drupal 7, is using code similar to the following one.

```
function mymodule_user_login(&$edit, $account) {
  $edit['redirect'] = $path_to_redirect_users_to;
}

```

It works because the `&$edit` parameter the hook receives is the `$form_state` parameter passed to the login form submission handler.

```
function user_login_submit($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;
  user_login_finalize($form_state);
}

function user_login_finalize(&$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array(
    '%name' => $user->name,
  ));

  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array(
    'login' => $user->login,
  ))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();
  user_module_invoke('login', $edit, $user);
}

```

---
Tags: 8, forms, redirection
---


# Question
Title: How to create a pager to display next article in particular taxonomy?
How to create a pager to display next article in particular taxonomy? I can not find any module.

I tried to do this with a view. I created a view that display all content from article and add a pager, but then i've got another problem (cant related this with another view from home page that display image and title from all articles and navigate to chosen article)

Sorry for my english.

I have view that displays fields (image and title) from articles with taxonomy term (e.g. Shapes) like this:

When i click on image i go to this article:

but I dont know how to do pager like on this picture that could navigate me to next article:

# Answer
You can accomplish this with the contrib module Flippy. It will allow you to add pagers for specific content types. Hope it helps.

> Flippy is an ultra-simple module that generates previous/next pagers for content types. On the Node type administration screen, you can turn Flippy on or off for each content type. It'll generate a unique pager for each content type, so you can page through Articles or page through Blog posts, but you can't page through all nodes on the site.
> 1 votes

# Answer
There is often more than one way of solving a problem in Drupal, and this question is the same. It depends on your particular needs which approach you might want to implement.

One option is to make a new View where users would read the articles, they wouldn't be taken to the actual article node page.

You create a new Views Page Display, with a different path. Override the Pager options to only show one article.

Adjust your original Views to link to the newly created Views page, and not the article node paths. You'll need to construct the links of the "articles" in your original views to point to the new Views page with the correct option for the pager page that leads to the specific item. You'll probably be able to do that with the Views Counter field, since it will follow Pager pages predictably.

The Pager in the second Views will be responsible for flicking between individual items.

You have to think about which path/link users see when reading an article. Do you want those to be the node pages or are you happy with one page where only the pager option changes? It affects the SEO of the project so you have to think about it from that standpoint.

---

A different solution could possibly be created with the use of Views Header and Footer options where you insert the links to previous/next article based on some criteria, possibly with Offset option. I'm not sure about the performance though. If you have a long list and it takes a while to collect all the data from the database it may end up being slow to navigate.
> 0 votes

---
Tags: views, paging
---


# Question
Title: Serve aggregate CSS/JS files from S3 instead of local storage
I have enabled aggregate CSS/JS from the backend. It stores the aggregated files in the local system. How do I make them accessible through the S3 bucket? I have already installed the S3fs module.

The point is when my server is down it automatically creates another instance. And that newly created instance does not have the previous aggregated CSS/JS files. Therefore, it breaks my website.

# Answer
> 1 votes
It's all explained in the module's README.txt

> * This will configure your site to store new uploaded files in S3. Files which your site creates automatically (such as aggregated CSS) will still be stored in the server's local filesystem, because Drupal is hard-coded to use the `public:// filesystem` for such files.
> * However, s3fs can be configured to handle these files as well. In **settings.php** you can enable the `s3fs.use_s3_for_public` and `s3fs.use_s3_for_private` settings to make s3fs take over the job of the public and/or private file systems. This will cause your site to store newly uploaded/generated files from the public/private file system in S3 instead of the local file system. However, it will make any existing files in those file systems become invisible to Drupal. To remedy this, you'll need to copy those files into your S3 bucket.
>
> Example: `$settings['s3fs.use_s3_for_public'] = TRUE;`
> * If you use s3fs for public, you should change your php twig storage folder to a local directory, php twig files in S3 produce latency and security issues (these files would be public). Please change the `php_storage settings` in your **setting.php** and choose a directory, out of docroot recommended.
>
> Example: `$settings['php_storage']['twig']['directory'] = '../storage/php';`
>
> If you have a multiple backends you may use a NAS to store it or other shared storage system with your others backends.

---

Related Question: Serve compressed JS and CSS with S3 as filesystem

---
Tags: css-js-aggregation, 8
---


# Question
Title: Exposed filter autocomplete has TID with taxonomy term
I created a view from taxonomy terms of different country names. I added an exposed filter to allow the user to enter the country, but when the user selects the country, it automatically adds the taxonomy ID after the name.

I've tried various things, from hooks to jQuery, I can't seem to figure out how to remove the TID. Please advise.

# Answer
> 0 votes
One solution can be custom javascript to remove the number from the result: like

```
(function($, Drupal, drupalSettings){
'use strict';

 Drupal.behaviors.my_module = {
   attach: function(context) {

  // Remove TID's onload.
  Drupal.my_module.remove_tid();

  // Remove TID's onchange.
  jQuery('body').find('#YOUR_FILTER_EXPOSED_ID').find('.form-autocomplete').on('autocompleteclose', function() {
    Drupal.my_module.remove_tid();
  });
}
};

Drupal.my_module = {
  remove_tid: function () {
    let field_autocomplete = jQuery('body').find('.form-autocomplete');
    let autocomplete_tid_stripped = field_autocomplete.val().split(' ')[0];
    field_autocomplete.val(autocomplete_tid_stripped);
  },
};

})(jQuery, Drupal, drupalSettings);

```

Another solution could be using views\_autocomplete\_filter module, add a relation to your taxonomy term and instead of entity filter and a filter on terms name, so there will not id there. a little slower but works.

---
Tags: views, 8
---


# Question
Title: Database Abstraction to Fetch published content of specific content type throwing error
I'm attempting to grab all published content of type 'homepage\_slide', as currently my slider loads all content unpublished or otherwise.

Here is my current Abstraction query.

```
  if ($variables['is_front']) {

    // Create data for slider
    // Get from DB nids of content type homepage_slide
    $query = \Drupal::database()->select('node', 'n');
      $query->fields('n', ['nid']);
      $query->condition('n.type', 'homepage_slide');
      $query->condition('n.status', 1);
      $nids = $query->execute()->fetchAll();

    $variables['home_page']['slides'] = array();

    // get and set values from content type to variable
    foreach ($nids as $val) {
      $node = Drupal\node\Entity\Node::load($val->nid);

      $text = $node->get('body')->getValue();
      $img = $node->get('field_image')->getValue();
      $link_url = $node->get('field_button_link')->first()->getUrl();
      $link_title = $node->get('field_button_link')->first()->title;

      $file = \Drupal\file\Entity\File::load($img[0]['target_id']);
      $img_src = $file->url();

      $variables['home_page']['slides'][] = array(
        'text' => ['#markup' => $text[0]['value']],
        'img_src' => $file->url(),
        'link_url' => $link_url,
        'link_title' => $link_title
      );
    }

  }

```

When I remove the line `$query->condition('n.status', 1);` it works. However throws the below error when I leave it in.

```
The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Drupal\Core\Database\DatabaseExceptionWrapper</em>: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'status' in 'where clause': SELECT n.nid AS nid
FROM
{node} n
WHERE (n.type = :db_condition_placeholder_0) AND (status = :db_condition_placeholder_1); Array
(
    [:db_condition_placeholder_0] => homepage_slide
    [:db_condition_placeholder_1] => 1
)
 in <em class="placeholder">themename_preprocess_page()</em> (line <em class="placeholder">126</em> of <em class="placeholder">themes/themename/themename.theme</em>). <pre class="backtrace">Drupal\Core\Database\Statement->execute(Array, Array) (Line: 631)
Drupal\Core\Database\Connection->query('SELECT n.nid AS nid
FROM
{node} n
WHERE (n.type = :db_condition_placeholder_0) AND (status = :db_condition_placeholder_1)', Array, Array) (Line: 358)
Drupal\Core\Database\Driver\mysql\Connection->query('SELECT n.nid AS nid
FROM
{node} n
WHERE (n.type = :db_condition_placeholder_0) AND (status = :db_condition_placeholder_1)', Array, Array) (Line: 510)
Drupal\Core\Database\Query\Select->execute() (Line: 126)
themename_preprocess_page(Array, 'page', Array) (Line: 287)
Drupal\Core\Theme\ThemeManager->render('page', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 501)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 176)
__TwigTemplate_e559a627712398e644a3084e1d00b70842705a0f1b596808c95e6be526e73217->doDisplay(Array, Array) (Line: 455)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 422)
Twig\Template->display(Array) (Line: 434)
Twig\Template->render(Array) (Line: 64)
twig_render_template('themes/themename/templates/html.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('html', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 147)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 148)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
</pre>

```

Thanks in advance!

# Answer
> 1 votes
Use an `Drupal::entityQuery`. The node table doesn't contain the status.

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

$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

// Loop through all nodes.
foreach ($nodes as $node) {

  // ...
}

```

---
Tags: database
---


# Question
Title: How can trusted host patterns be set dynamically?
I'm working on a site which uses the Groups module that will allow users to create groups on the site. The site will then allow for users to point custom domain names at the site, with the content for their group being available at that domain.

I've got this set up, except for the trusted host patterns. At the moment I have to manually add the domains to `$settings['trusted_host_patterns']` in `settings.php`. I do not want to have to handle this manually however and would like to set these trusted host patterns dynamically based on domain names stored in a field in the database.

I've been looking at `DrupalKernel::initializeSettings()`, and I've found that it does not appear any method exists to override the settings:

```
// Initialize our list of trusted HTTP Host headers to protect against
// header attacks.
$host_patterns = Settings::get('trusted_host_patterns', []);
if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
  if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
    throw new BadRequestHttpException('The provided host name is not valid for this server.');
  }
}

```

So I'm thinking maybe I could use a kernel event, adding trusted host patterns to the settings before the trusted host patterns are called, but I'm starting to think I may be out of luck, due to trusted hosts being set before the database connection is initialized, meaning I won't be able to set trusted host patterns from DB variables.

Does anyone have an ideas of how to get around this?

# Answer
> 5 votes
By design you can't access the database from a non trusted host within Drupal. The kernel checks the trusted host patterns when the settings are read from file, but without the settings you don't have the credentials to open the database connection.

There are a lot of ways to work around this. As mentioned in the comment by @NoSssweat you can write the trusted hosts to a file and include the file in settings.php. Or you can access the database from outside of Drupal and invoke this PHP script in settings.php. Or use a wildcard trusted host pattern matching all possible domains and then enhance security by adding a second check against the custom domain names in a kernel event subscriber when the database is available.

---
Tags: 8, event-subscribers
---


# Question
Title: Disable translations update on module enable
I have large site with 15 languages, when working locally If I enable some module over UI (or reinstall it) auto update of translations kicks off and this last for some time. I really don't need that while developing things, how could I disable this feature?

# Answer
you can configure the translation.import\_enabled key in locale.settings config a way to do that is with drush :

```
drush cset locale.settings translation.import_enabled 0

```

hope this helps
> 1 votes

# Answer
I was able to disable update by:

```
<?php

/**
 * Implements hook_module_implements_alter().
 */
function MY_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'modules_installed') {
    $moduleHandler = \Drupal::service('module_handler');
    if ($moduleHandler->moduleExists('locale')) {
      unset($implementations['locale']);
    }
  }
}

/**
 * Implements hook_modules_installed().
 */
function MY_MODULE_modules_installed() {
  $moduleHandler = \Drupal::service('module_handler');
  if ($moduleHandler->moduleExists('locale')) {
    locale_system_set_config_langcodes();
  }
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: Set a Document File in a webform submission programmatically
I have writen a PHP class that saves a pdf file programmatically. The class contains a function that returns the Drupal path private://documentA.pdf

I would like to attach the file to a webform submission:

```
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load(ID);
$data = $webform_submission->getData();
$data['file_attachment'] = //retrieve the file
$webform_submission->setData($data);
$webform_submission->save();

```

Webform element type of file\_attachment is Document file.

# Answer
> 3 votes
To attach the file to a webform submission, you should get the file id first, and then set the `file_attachment` to file id.
Try this out.

```
  $webform_submission = \Drupal\webform\Entity\WebformSubmission::load(1);
  $data = $webform_submission->getData();
  // Get the document file object from uri.
  $document = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => 'private://documentA.pdf']);
  // Get the file Id.
  $doc_id = reset($document)->id();
  // Set the file_attachment to fid.
  $data['file_attachment'] = $doc_id;
  $webform_submission->setData($data);
  $webform_submission->save();

```

---
Tags: webforms
---


# Question
Title: Show teasers from both content type and Users together in a view
I would like to be able to create a page to show teasers from content created with a certain content type, say "Company" together with teasers from Users content.

Until now, I just managed to create either a view to show the teasers of the Company content type, OR the teasers of the Users. But not both. When I add a relation, I can use fields of both in the same block, but I would like to show a page with separate blocks of both companies and users together.

How should I do such a thing, if even possible?

# Answer
> 1 votes
Since you say that you would like to show a page with *separate blocks* of companies and users, there's no need to do this all in the same View.

Create two different Views with Block displays. One for the teasers of Company content type, one for the teasers of the Users. (You have done this much already.)

Then, place both of those Blocks in theme regions on the same page, and they should both appear ... together, but separately.

---
Tags: views, 8
---


# Question
Title: Any chance for alter system settings form via hook_form_alter?
I would like to create module based on other custom module. One thing that will be nice to able to do is to alter module settings form fields. Is this possible?

# Answer
> 3 votes
You can alter any forms using `hook_form_alter()`. `$form`, `$form_states`, and `$form_id` are the parameters it gets.

Do not forget to add the following line, at the end of your `hook_form_alter()` or `hook_form_FORM_ID_alter()`.

```
    $form = system_settings_form($form);

```

If you don't want to add the "Save configuration" button, you have to add your custom callback submit with `$form['#submit'][] = '_my_callback_form_submit';` and use code similar to the following one.

```
function _my_callback_form_submit($form, &$form_state) {
  variable_set('my_variable_name', $form_state['values']['my_variable_name']);
}

```

---
Tags: 7, forms
---


title: Display a view in search results

text:
# Question
Title: Display a view in search results
I have Search API SOLR running on my **Drupal 8** site and I'd like to know if there is a way to have view pages display in my search results.

As an example, I have a database content type that allows users to put in the name of the database, the custom URL to link to the external database and a short description of it. The way I display this content on my site is with a view that can be filtered with certain criteria.

The actual node of these databases is never linked to and I never want users to end up on these node pages. However, if I search for the name of a database, it won't show up because I've disallowed that content type in my search settings but I still want that view page to be found when searching for the name of a database.

Can anyone help me figure out how to get **view pages** or pages with **view block result** to show up in my search results so that certain content type nodes that are never meant to be seen don't end up in the results?

# Answer
> 0 votes
The Search API supports views out of the box. You just need to create a new view and select the "Index" you want to search. E.g. Index Full Site or Index Resources. These match the indices you have created in the Search API setup.

This will let you get any 'fields' in the index and use some Search API specific filters (e.g. Fulltext search which looks across all index fields.).

There are some options that refer to Datasource information. This is the way you can take information from the index and related it to the full node. Depending on your needs, you may need to use Relationships to get to other items, e.g files or images.

There are a fair number of tutorials on this, just search for them.

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


# Question
Title: How do I remove the text "webform content" at the top of a block?
I have several Drupal 8 webforms, some of which are embedded as blocks. At the top of each webform, I'm getting the "webform content" text.

How do I safely remove that text?

# Answer
> 2 votes
It looks like you are including the field label in the display. If you created the block using a custom block type do the following:

* Go to Admin-\>Structure-\>Block Layout-\>Types
* Then select your WebForm block type
* There will be a tab labeled "Manage Display"
* On this page, mark the field label as hidden.

Not sure what to do if you are using the built in Webform blocks

---
Tags: 8, webforms
---


# Question
Title: How do I remove the appended string from image and Javascript URLs?
I have a Drupal 8 website. I have installed the Advagg module. The URL for the JavaScript file has a string appended.

The same happens for the URLs of the uploaded images. Sometimes, the browser doesn't display the image, when its URL has that string. If I remove the string, the image is displayed. Google search console reports such files as malware.

How do I remove those strings from the end of the URL?

# Answer
The strings are to ensure that the files are not cached by proxies or intermediary caches when Drupal rebuilds its own caches. Whenever Drupal's cache is cleared and regenerated these strings will change. These are 'cache buster' strings.

Check this for an explanation of what is cache busting - https://www.adopsinsider.com/ad-ops-basics/what-is-a-cache-buster-and-how-does-it-work/
> 6 votes

# Answer
There are 2 questions here.

# Why is google identifying files as malware?

This is hard to debug on a site using file aggregation, including both the core aggregation and advanced aggregation. I suggest disabling those temporarily and seeing which specific file Google identifies as malware.

# Why are there strings at the end of the files?

As @anoopjohn has answered this is a "cache busting" technique used by a lot of different pieces of software.
> 2 votes

---
Tags: 8, files
---


# Question
Title: Search Solr View with exposed filter fullsearch return no results
I setup a Solr search index (Solr 7.7.1 and Search API Solr 3.2) with custom entities. I have several fields indexed and 2 of them are fulltext. Additionally :

* I setup the view with an exposed filter in a block (page view)
* No Ajax option is set
* I have a filter Search enabled : Fulltext Search with following options :
    + Expose this filter to visitors
    + Signle filter
    + Contains any of these words
    + Allow multiple selections
    + Parse mode : direct query
    + All Fulltextfields selected
* Exposed form settings
    + Exposed form in block : YES
    + Exposed for style : basic
* I also setup some facets on other fields

When I come to the page, all results are displayed by default. When searching for any term(s) via the Full-text textfield, I am getting blank results. Instead if I select some facet options, results do show up accordingly to the facets.

How can I get the Fulltext search to work?

# Answer
After several hours, I discovered that search\_api\_solr 8.x-3.7 was the issue. I downgraded using composer to the latest v2.7 and it works fine.
> 0 votes

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


# Question
Title: Rules Redirect User at Login by Role to URL not working
I am trying to redirect any user with a particular Role at login to a URL. I am using Backdrop (Drupal 7). I have looked at most of the posts relating to this problem, and tried many of the examples but the redirect fails. There are no messages in the Logs, I have debugging on in Rules. I have tried this which is from a post I found, and modified for my page redirection which works:

```
    { "rules_after_login_redirect_to_host_registration" : {
    "LABEL" : "After login redirect to Host Registration.",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "^user\/reset\/",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "webform\/host-registration" } },
      { "backdrop_message" : { "message" : "Redirecting to Host Registration" } }  ]
  }
}

```

However my Rule to Redirect a user at login with a Role of Host does not work:

```
{ "rules_redirect_role_host_to_selected_page" : {
    "LABEL" : "Redirect role Host to selected page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "host" : "host" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "webform\/host-registration" } } ]
  }
}

```

I am baffled. Why is the Role Condition not picked up?

# Answer
Here is a working rule to redirect users to different URL's depending on user role, you will need Rules conditional module to acomplish task, enjoy.

```
{ "rules_user_has_logged_in" : {
"LABEL" : "user has logged in, redirect based on role",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "redirect" ],
"REQUIRES" : [ "rules_conditional", "rules" ],
"ON" : { "user_login" : [] },
"DO" : [
  { "CONDITIONAL" : [
      {
        "IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "6" : "6" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } },
        "DO" : [ { "redirect" : { "url" : "pagos" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "7" : "7" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "12" : "12" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas", "destination" : "1" } } ]
      }
    ]
  }
]

```

} }

and an img to see how my rule looks.
> 0 votes

# Answer
Your problem is here: `"roles" : { "value" : { "host" : "host" } }`

Instead of "host", which is is role *name* it should be a number, which is the corresponding role *ID* (or rid). You need to change this in both places where "host" appears. Apparently you edited that by hand?

To be clear, the Rules Conditional module is NOT needed unless you want the "else if" functionality.
> 0 votes

---
Tags: users, rules
---


# Question
Title: Why are JavaScript files read from an external URL?
Drupal adds the following markup to pages.

```
<html class="js" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:sioct="http://rdfs.org/sioc/types#" xmlns:sioc="http://rdfs.org/sioc/ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:og="http://ogp.me/ns#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dc="http://purl.org/dc/terms/" xmlns:content="http://purl.org/rss/1.0/modules/content/" dir="rtl" version="XHTML+RDFa 1.0" xml:lang="fa" xmlns="http://www.w3.org/1999/xhtml">

```

I need to remove it and force my site not to read from an external URL.

How can I achieve this? Is it really bad, or doesn't it need to be changed?

# Answer
> 3 votes
You're confusing the attributes on that tag.

* `class="js"` is a class name, it has nothing to do with loading javascript from external sources. It's simply added to the tag by javascript when the page loads so that any process (css usually) that needs to know about it can easily tell whether javascript is enabled or not.
* The `xml:*` attributes are required to identify the document as XHTML. They're not related to javascript in any way.

There's no need to change anything, unless you want to get a bit more up-to-date and install a theme that produces an HTML5 document.

# Answer
> 0 votes
That line isn't loading any Javascript file from an external URL. It simply defines the document type as XHTML+RDFa (an extended version of the XHTML markup language that supports RDF), the XML namespaces used in the document, and a CSS class used for the `<html>` tag.
Actually, nothing is loaded from those URLs, which are simply used as namespace names.

To answer the question, nothing needs to be removed. Quite the opposite, the attributes of the `<html>` tag are necessary for the browsers to correctly identify the document type as XHTML, which the document type used from Drupal 7 for the HTML pages it outputs.

---
Tags: theming, javascript, files
---


# Question
Title: Unable to use drush dl. No such file or directory filesystem.inc:267
I'm trying to download Drupal 7 using Drush 8.1.2, without success. It was working perfectly for months; now, I am getting the following error message on all modules and core downloads when I'm running:

```
drush dl drupal-7

```

> copy(/tmp/drush\_tmp\_1468772300\_578bafccc15f2/tar: Failed to set default locale): failed to open stream: No such file or directory filesystem.inc:267
> Project drupal (7.50) could not be downloaded to /Applications/MAMP/htdocs/drupal-7.50

I haven't changed any tmp permissions. What can I do?

I am using PHP 5.6.10 and Drush temporary directory is `/tmp`.

# Answer
> 3 votes
The error:

> Failed to set default locale

sounds like `tar` command invoked by Drush has some problem detecting your system locale.

Try setting it to UTF-8 by the following command:

```
defaults write org.R-project.R force.LANG en_US.UTF-8

```

Source: How to fix 'tar: Failed to set default locale' error?

# Answer
> 1 votes
On MacOS I found a solution!

I has this problem only in the PHPStorm terminal, not in my default MacOS terminal.

Solution: use gnu-tar instead of the default one. https://medium.com/@fullsour/installing-gnu-tar-on-mac-827a494b1c1

First how to debug:

1. Not working yet:

`$ drush dl devel-7.x --destination=modules/ -vvv`

Outputs a line with "Failed to set default locale"
2. Install gnu-tar and add the path to ~/.bash\_profile or ~/.profile like this:

`export PATH="/usr/local/opt/gnu-tar/libexec/gnubin:$PATH"`
3. Re-open the terminal in PHPStorm and it should work:

`$ drush dl devel-7.x --destination=modules/ -vvv`

Outputs a line with "\[success\]"

---
Tags: drush
---


# Question
Title: Updating core modules independently of core?
We have a vendor that is asking us to assist them in updating a core module independently of core. Is there such a thing? For example, could you update Views without updating core? My understanding is that's not doable.

# Answer
> For example, could you update Views without updating core?

First of all, you should check if you could get away with implementing those changes via a hook, event subscriber, or altering/overriding a service.

---

If not, download *Lastest\_Drupal\_8.zip* and unzip only /core/modules/views folder onto your projects /core/modules/views folder.

If you like, you could create a patch for that particular core module using `git diff` between latest and current version.

Although, **I wouldn't recommend to do this to begin with**, this is bad practice!, but if there is a really, really, and I mean, really good reason sure.

Caveats:

* You'll have to test the core module to make sure all is good.
* You won't be able to use `composer update` unless you find a way to make it run the patch.
> 1 votes

# Answer
While you could copy a core module from a newer Drupal version, that is probably going to create issues, as the module code could be changed because of changes in Drupal core code.
For example, a new class could replace an old one. Using the newer version of the module would cause its code to try to instantiate a class that doesn't exist in the old Drupal core code, or use a service it didn't exist before.

As @4k4 said, if you need the changes that have been implemented in a patch included in an issue, you could apply that patch to the Drupal code you have, possibly on a development server.
Doing so, you could be altering more than one module, which means (technically) that more than one module is updated, not just one. This is inevitable, as in many cases, the changes are not limited to a single module/file.
> 0 votes

---
Tags: 8, updating
---


# Question
Title: Querying the user list from the database
There is a need from a different team in our organization to provide a periodic export of users, roles, and users-roles relationship data in a certain Aveksa-specific format.

Where (which table(s)) are the list of Drupal 8 users and roles stored in Drupal database? I've looked at all the tables listed in the schema and examined their records, and could not find anything that resembled user/roles data.

I figure querying the database is the way to go rather than looking at the /admin/people section of Drupal and scraping the data from there.

# Answer
If you're set on scraping this out of the database, you could try looking at the `user__roles` table that Kevin mentioned in his comment above:

```
mysql> SELECT * FROM user__roles;
+--------+---------+-----------+-------------+----------+-------+-----------------+
| bundle | deleted | entity_id | revision_id | langcode | delta | roles_target_id |
+--------+---------+-----------+-------------+----------+-------+-----------------+
| user   |       0 |         1 |           1 | en       |     0 | administrator   |
+--------+---------+-----------+-------------+----------+-------+-----------------+
1 row in set (0.00 sec)

```

But since this is Drupal, you have other methods at your disposal.

For example, you could create a View of users and roles, and then use Views Data Export to export.

This module also exposes a drush command that can execute the view (interactively, or via scheduled jobs from the system crontab) and save its results to a file.

`drush views-data-export [view-name] [display-id] [output-file]`
> 3 votes

---
Tags: users
---


title: Custom Twitter Field without template?

text:
# Question
Title: Custom Twitter Field without template?
What are my options for displaying a field from a custom content type, in the form of a tweet embed. Preferably, the field would be a URL to the tweet. I know it can be be done with a custom field template but I was hoping to leverage Display.

# Answer
use twitter embed module

> Simple embed of Twitter widgets, without OAuth.
>
> Features Expose Twitter widgets with Block and FieldFormatter. Covered widgets: Timeline, Button.
> 0 votes

---
Tags: 8
---


# Question
Title: How do I add validation in the node processor before creating a node?
I'm using Feeds import module, after importing CSV file, if a row doesn't match content type validation the feeds import saves that node with empty space in that field.

Question: Now i want FeedsNodeProcessor to validate the node, and if there is a empty space it should throw error for that node or should not create node for that row.

Example: If i have 40 rows in an excel and 39 rows satisfies the conditions of content type and only 1 row doesn't then it has to like this, 39 nodes created.

Updated: i have added hook\_feeds\_prevalidate() in my hook\_form\_alter module.

```
 function tracker_custom_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'orientation_node_form'){
      $form['#validate'][] = 'validate_orientation';
}
}
function validate_orientation($form,&$form_state)
{
....
}
function tracker_custom_feeds_prevalidate($source, &$entity, &$item, $entity_id) {
//      dpm($entity->feeds_item->id); - its not printing anything.
//      dpm($item); - its not printing anything.
  if ($entity->feeds_item->id == 'bulk_upload') {
     if (empty($item['Billing Type'])) {
         $entity->feeds_item->skip = TRUE;
         drupal_set_message('ksdhbf');
   }
 }
}

```

# Answer
You can add this functionality in a custom module. But you'll have to add the logic that you have in your node's validation here.

```
/*
 * Implements hook_feeds_prevalidate()
 */
function mymodule_feeds_prevalidate($source, &$entity, &$item, $entity_id) {
  // the $item contains your csv files column values
  if ($entity->feeds_item->id == 'import_name') { // check the feed import ID
    if ($item['some column'] != 'something') { // validate column value
      $entity->feeds_item->skip = TRUE; // skips this row from importing
    }
  }
}

```

**Important:** I think you'll need 7.x-2.x-dev in order for this hook to work, I'm using it. This is a new hook and I think it has not been added to 7.x-2.0-beta4 yet.
> 1 votes

---
Tags: feeds
---


title: how to a link in Admin black toolbar

text:
# Question
Title: how to a link in Admin black toolbar
I created a custom module and how to add a link along with icon. Basically, I want to add notification icon

```
backlinks_notifications.index:
  title: 'Notifications'
  parent: system.admin_config_ui (whats the name of that blad navigation bar on top.)
  description: 'Notificationsx'
  url: internal:/home

```

FYI : Its Admin theme.

# Answer
> 2 votes
```
   /**
    * Implements hook_toolbar().
    */
    function backlinks_notifications_toolbar() {
        $items = [];
        $items['toolbar_menu_backlinks_notifications'] = [
            '#type' => 'toolbar_item',
            'tab' => [
                '#type' => 'link',
                '#title' => 'Notifications',
                '#url' =>  Url::fromRoute('<front>'),
                '#options' => [
                    'attributes' => array(
                        'title' => t('Backlinks Notification'),
                        'class' => array(
                        'toolbar-item',
                        'toolbar-icon',
                        'toolbar-icon-backlinks-notifications',
                        ),
                    ),
                ],
            ],
            '#weight' => 999,
            '#attached' => array(
                'library' => array(
                    'backlinks_notifications/backlinks_notifications',
                ),
            ),
        ];
        return $items;
    }

```

Hook available at https://api.drupal.org/api/drupal/core%21modules%21toolbar%21toolbar.api.php/function/hook\_toolbar/8.2.x

---
Tags: 8, navigation
---


# Question
Title: Is there a way to import Paragraphs with Feeds module (no code)?
Given a Content Type (a Node), which has a Paragraph field, which in turn has some fields on it, is there a way to import the Paragraph fields into the Content Type using Feeds (or some other method, but not involving coding)?

Example: The Content type Photograph includes a Paragraph field called 'Inscription' that has these fields:

field\_inscription (text)
field\_inscription\_type (term reference)
field\_inscription\_location (term reference)

How do I import these three fields into the Paragraph field of a Photograph Content Type?

Note: There will be multiple instances of the Inscription field on some photographs.

I'm currently in Drupal 7, but would consider working in Drupal 8, if there's a solution that works in Drupal 8.

# Answer
> 1 votes
The Drupal 8 version of Paragraphs does support some basic Feeds integration with a "Target" (see the source code)

Alternatively you could write a Processor plugin that manually creates and associates the paragraphs contained within a node.

# Answer
> 0 votes
Otherwise, in D7, you can have a try at feeds\_para\_mapper

---
Tags: feeds, paragraphs
---


title: What's the use of vendor folder?

text:
# Question
Title: What's the use of vendor folder?
Whats the use of vendor folder in drupal 8, what it actually do ?

# Answer
> 3 votes
"vendor" is the folder where a Drupal - composer Installation stores it's libraries. If you look at the file web/autoload.php you'll find how that works.

Don't care. It's what's called the "External Libraries" in a java project.

---
Tags: 8
---


# Question
Title: How do I programmatically attach a file to a file field in a node?
I have a custom content type with a file field. I am trying to attach a file uploaded through a custom form to the custom content type. I am able to load the node and update all the other values of the node except the file field.

I found Realityloop: Programmatically attach files to a node in Drupal 8, but it doesn't seem to work.

This was what was suggested in the above link

```
$node = Node::create([
  'type' => 'article',
  'title' => 'Druplicon test',
  'field_image' => [
  'target_id' => $file->id(),
  ],
]);
$node->save();

```

This is what I have tried inside `submitForm`

```
$fid = $form_state->getValue('file_field_name')[0];
$file = File::load($fid);
$file->setPermanent();
$file->save();
$node = Node::load($nid);
$node->set('file_field_in_node', $file->id);
$node->save();

```

That was setting the file as permanent in the files table but the node did not have the file.

I also tried to save with

```
$node->set('file_field_in_node', $file);

```

That did not help either. I am also curious as to which is the file/function that handles the set function for the file field.

**UPDATE:**

\[SOLVED\] Not sure what was wrong earlier. Both the approaches seems to be working correctly now. So setting the file\_id or the file object into the file field for the node seem to be saving the node correctly with the file attached to it.

# Answer
If you use media core module to manage files, you have already uploaded your file, and you want to attached it to filed eg `field_file`

```
    $node = Node::load(NID);
    $node->set('field_file' , ['target_id' => FID]);
    $node->save();

```

Note: `FID` is your file id.
> 2 votes

# Answer
In your custom form use code like this:

```
$form['imagefile'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Imagefile'),
      '#default_value' => $this->configuration['imagefile'],
      '#weight' => '0',
      '#upload_location' => 'public://images/redaktion/',
    ];

```

And here's a piece of code how it works low level:

```
// check if the folder exists
$folder = date('Y-m', time());
$data = file_get_contents($imagefilepath);
if (!is_dir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}")) {
      mkdir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}");
}
// create the file entity
$photo = file_save_data($data, "public://images/pics/{$folder}/".$filename, FILE_EXISTS_REPLACE);

// later in your entity::create:
'myimage' => ['target_id' => $photo->id()],

```

The trick is to create the file entity beforehand and then link the custom entity to it.
> 1 votes

---
Tags: 8, forms, files
---


# Question
Title: How can I use a media field in a custom form?
I tried something below, which is not working in drupal 8.

```
$form['upload_documents'] = [
  '#type'          => 'media',
  '#tree'          => TRUE,
  '#title'         => t('Upload your documents'),
  '#default_value' => ['fid' => $default_value],
  '#media_options' => [
    'global' => [
      'file_extensions' => 'pdf doc docx',
      'types'           => ['document'],
    ],
  ],
  '#attached'      => [],
  '#extended'      => TRUE,
  '#required'      => TRUE,
];

```

# Answer
I found the answer to create the media autocomplete field like below.

```
// $id is your media ID.
$media = \Drupal\media_entity\Entity\Media::load($id);

$form['upload_doc'] = [
  '#type'          => 'entity_autocomplete',
  '#target_type'   => 'media',
  '#default_value' => $media,
];

```
> 4 votes

# Answer
There is also module (Media Library Form API Element) that supports this kind of implementation:

```
$form['image'] = [
  '#type' => 'media_library',
  '#allowed_bundles' => ['image'],
  '#title' => t('Upload your image'),
  '#default_value' => NULL|1,
  '#description' => t('Upload or select your profile image.'),
];

```
> 4 votes

# Answer
In Drupal 8, you can use the entity browser.

A simple example of available options:

```
$form['upload_documents'] = array(
  '#type' => 'entity_browser',
  '#entity_browser' => $entity_browser_id, // e.g. 'document_browser'
  '#cardinality' => $cardinality, // e.g. 1
  '#selection_mode' => $selection_mode, //e.g. 'selection_append'
  '#default_value' => $entities,
  '#custom_hidden_id' => $hidden_id,

);

```

In the form submit, it leaves the entity IDs of the selected entities in a hidden field.
> 1 votes

---
Tags: 8, forms, media
---


title: How to render views link field in twig?

text:
# Question
Title: How to render views link field in twig?
I have created a view that has many fields including a link field. I am using a twig template. my view twig name is `views-view-fields--dashboard--block_3.html.twig` It works nicely but I need to render a path in an anchor tag. here is my code.

```
<a href="{{ fields.view_node.content}}">
    <div class="mail-contnet">
        <h5>{{ fields.title.content }}</h5>
        <span class="mail-desc">{{ fields.body.content }}</span>
        <span class="time">{{ fields.created.content }}</span>
    </div>
</a>

```

In the anchor tag, I am getting the link but it has twig debugging wrappers. The result is bellow

```
<a href="
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->
/vanss/ques-curabitur-arcu-erat-accumsan-id-imperdiet-et-0
<!-- END OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->
">

```

and I need only the path. I have already tried the **twig\_field\_value** module. but when I `{{ fields.view_node.content|field_value}}`

> Error: Cannot use object of type Drupal\Core\Render\Markup as array in Drupal\twig\_field\_value\Twig\Extension\FieldValueExtension-\>isFieldRenderArray() (line 171 of modules\contrib\twig\_field\_value\src\Twig\Extension\FieldValueExtension.php).

Now I am looking for how to render the value of an anchor tag without any wrapper.

# Answer
If you want to remove twig debug comments you can use striptags filter

Like the following:

```
{{ fields.view_node.content|striptags}}

```
> 1 votes

---
Tags: views, theming
---


# Question
Title: Entity reference view display is not displaying fields as expected
I have a number of registered users on my drupal 8 website who some of them are "active" and the others are "blocked".

I want to add a **select list field** inside the article content type displaying only user with the status= active (Easy job!)

**Note:** I have added a field to the user page (field\_full\_name) and I want to display the users using their "Full Name" and not their "Usernames". (Still an easy Job!)

**So I did the below:**

* Create a new view to show "users"
* Create an "entity reference" display for the view.
* Delete the "username" field created by default
* Add the Full name field to the view (field\_full\_name)
* Add the filter field "User: User status (= Yes)"
* Inside the Settings of the "Entity Reference" View, check the "User: Full Name" as the search field.
* Save the view.
* Add the view as a user reference field to the article content type by selecting the Reference method: **Views: Filter by a entity reference view** and for the View used to select the entities: **Select the created view above**.

Now, when you add a new article **/node/add/article**, if you try to select a **user** from the dropdown select list, you will notice that all users are displayed using their **usernames** and not their **Full Names**.

In other words, I like to have something like this in the select list:

* Full Name 1.
* Full Name 2.
* Full Name 3.
* Full Name 4.

but actually I am receiving this:

* Username 1.
* Username 2.
* Username 3.
* Username 4.

Also I noticed the same behaviour when I tried to create an "entity reference" view displaying all the groups that the current logged in user is a member of, by doing the below steps:

* Create a new view and set the view to show: "Group content" of type: "All".
* Add relationship: "The group containing the entity".
* Add relationship: "Relates to the user entity that the group content represents".
* Add a contextual filter: "User ID" and when the filter value is not available select: "User ID from logged in user"
* Delete any available field created by default.
* Add the field: "Title" (to show the title of the group)
* Create an "entity reference" display for the view.
* Inside the Settings of the "Entity Reference" View, check the "Group: Title" as the search field.

Now, add this view as an "entity reference" field to any content type for example "Article" and when you will add a new article **/node/add/article**, if you try to select a **Group** from the dropdown select list, you will notice also that all **Groups** are displayed using the **username of the current logged in user** and not by their **Group titles**.

In other words, lets say the current looged in username "Admin1" is a member of 3 groups titled: (Group Title 1, Group Title 2 and Group Title 3)

you will see that the **entity reference select list field** is displaying:

* Admin1
* Admin1
* Admin1

Instead of:

* Group Title 1
* Group Title 2
* Group Title 3

What am i doing wrong ?!

Is there something wrong with the "entity reference view" display ?!

any help ?

It is worth mentioning that if you just duplicate the "Entity reference" display to a "page" display and you visit that page, you will indeed see a list of **users** displayed using their **Full Name** or list of **Groups** displayed using their **group titles**

Thank you in advance,

# Answer
You could use the realname module (which now has a D8 release). Or, you could alter the user name as displayed in Drupal:

`function HOOK_user_format_name_alter(&$name, $account) {
 // Load the full user account.
 $account = \Drupal\user\Entity\User::load($account->id());
 // Get the full name from field_name.
 $full_name = $account->get('field_name')->value;
 // If there's a value, set it as the new $name.
 if (!empty($full_name)) {
 $name = $full_name;
 }
}`
> 1 votes

---
Tags: views, 8
---


# Question
Title: Change in view hooks file name/location in core 8.3.x?
I have a custom module that uses a couple of view hooks, and in 8.2.x I had them in my\_module.views\_execution.inc, in my module root directory. However, with the update to 8.3, my hooks are not being found. I'm looking at the 8.3 docs, but the incredibly verbose hooks overview page doesn't mention it, and neither does the page with the list of hooks.

So where do my view hooks need to be placed in 8.3 so they can be found?

# Answer
I was finally able to get the hooks working again by putting them in the `my_module.module` file. I thought I read about that when I was first implementing these hooks when the site was still in 8.2, but it worked in the `views_exection.inc`file and not `.module` then. I haven't been able to find any documentation on this change so far, so if anyone could shed some light on it, I'd appreciate it.
> 3 votes

# Answer
I just used query\_alter in `module.views_execution.inc` in a Drupal 8.7 installation and it ran fine. So there shouldn't be any change for the behavior of module.views\_execution.inc location.

The API documentation seems to show the same as well

https://api.drupal.org/api/drupal/core%21modules%21user%21user.views\_execution.inc/8.8.x
> 0 votes

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


# Question
Title: How do I handle an incoming POST request in a module?
I am really new to Drupal but I have to do a project using it and I was just wondering how to handle an incoming POST request in a module:

I am creating a module that will get incoming data from a Webform, process the data by running an R script on it, and then return the result of the R function on the data to the url path specified in the module, but I am not sure at all how to begin handling POST requests - can someone give me some insight? In Webform settings you can specify a URL to send a POST request with the form data upon submission, but if I can figure out how to handle that data I will be golden!

# Answer
If posting to external URLs is allowed, and given that you are not familiar with Drupal, you can post that data to an external URL where you can write a script using the language / framework you are familiar with and process the data. Especially since you are only looking to process the data with R.

If you want to manage your processing within Drupal itself that is also doable. You will have to write a custom controller in your module, add the route in the module.routing.yml file and then handle the POST data in your controller.

Here are couple of places you can start

https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

How to get $\_POST and $\_GET parameters
> 2 votes

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


# Question
Title: Adding a taxonomy term translation changes the original language value!
I have an issue when I try to add a translation of a taxonomy term using the site UI. The original language value changes to the translation value that I added.

How can I prevent that from happening?

# Answer
You need to make sure it is translatable in the language settings.

Go to:

/admin/config/regional/content-language

Make sure that taxonomy term is checked in the custom language settings. If not, check and save.

Then find the Taxonomy section in the form. In this section, make sure that your vocabulary and fields you want translatable are checked. Include the show language on edit option as well

Once you have done that, go to:

http://www.solarwindsmsp.test/admin/structure/taxonomy

And create translations for the vocabulary for each language you want.

Also edit the vocabulary settings and make sure there is a default language specified for new terms.

Next, if you have existing terms, you need to edit the term and set a default language in the dropdown. E.g. english instead of not specified.

Once you do this, you will get a translate option on the edit / delete dropdown in the list. Select translate to add additional languages.
> 2 votes

# Answer
If you are using **Entity Translation** the path for this is a bit different.

/en/admin/config/regional/entity\_translation

This is what worked for me:

1. Select Taxonomy as Translatable Entity
2. Find your Taxonomy in the display below
3. Pick Default language
4. Uncheck "Hide language selector"
5. Check "Exclude Language neutral from the available languages" Important for a variety of other reasons... SOLR and view queries for example
6. Uncheck "Prevent language from being changed once the entity has been created"
7. You could check/uncheck "Hide shared elements on translation forms" depending on your situation.

And then YES ... You will need to edit every term so it has a defined language (Default is English in my case)

Once All terms have been assigned a language they can be translated.
> 1 votes

# Answer
You have to enable Content Translation module, and select taxonomy vocabularies you want to be translated, and you will see translation buttons in every single fields/terms
> 0 votes

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


# Question
Title: The directory tmp does not exist and could not be created
I keep getting this error since updating to Drupal 7.5.8 and cannot get rid of it regardless of trying all I know. Even adding it / copying-pasting the previous tmp dir or changing the tmp file name (eg tmp3) doesn't solve it. Any files placed in the directory are writable unless I need to add a new Drupal 'group' in security.

Any one know how to solve this update issue?

# Answer
> 2 votes
You didn't mention the actual (complete) value for the path of the "Temporary directory" you want to use. But something that should work, pretty sure, is like so:

* Navigate (in your web browser) to relative path `admin/config/media/file-system`.
* Copy the value you have entered for "*Public file system path*", assume it's `some/path/files`.
* Paste the copied value (like `some/path/files`) in the field "*Temporary directory*", and append to that value something like `/temp`, so that it becomes something like `some/path/files/temp`/
* Hit the `Save configuration` button and you should be good to go (Drupal will, automagically, take care of the rest).

# Answer
> 1 votes
Please update the file size first in `php.ini` file. Then check again.

```
upload_max_filesize = 1024M

post_max_size = 1024M

```

---
Tags: files, updating
---


# Question
Title: How to make autocomplete search by an entity field instead of by name?
Let's say we have 3 custom entities:

When creating a new operator, I need to autocomplete the license:

By default we can use the autocomplete to find by name. So, we need to type the name to display the related results.

But here I'd like to autocomplete by authority name instead (since a license has no name).

Is it possible? If so, how to do it?

# Answer
> 1 votes
1. Create a new view with the display type "Entity Reference"
2. Add "Fields", "Filter criteria" and "Sort criteria" like in any other normal view
3. Under "Format \> Settings", select the fields you want to be searchable
4. Under "Show \> Settings", select the fields you want to show as search result
5. Save the view
6. Now visit "Structure \> Content type \> NODETYPE \> Manage fields"
7. Edit your entity reference field, set the "Reference Method" to "Views: filter by an entity reference view"
8. Select your previously created view

---
Tags: 8
---


# Question
Title: Why am I failing to programmatically create a webform in hook_entity_insert?
I need to create a webform programmatically when a node is created. I refer and follow https://www.drupal.org/project/webform/issues/3038697

Here are the steps to reproduce:

1. Create new module via console, and install module.
2. In module.module add:

```
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\webform\Entity\Webform;

```

Add hook with webform create function:

```
function module_entity_insert(EntityInterface $entity){
  // Build a render array of elements.
  $elements = [
    'name' => [
      '#type' => 'textfield',
      '#title' => t('Name'),
    ],
  ];

  $settings = [
    // Define settings.
  ];

  // Append default settings.
  $settings += Webform::getDefaultSettings();

  // Create a webform.
  $webform = Webform::create([
    'id' => 'custom_id',
    'title' => 'Title',
    'elements' => Yaml::encode($elements),
    'settings' => $settings,
  ]);

  $webform->save();
}

```
3. Now, after save and cache clear, go to add new content (any type will do).

Suppose I have new sample webform created along the new node creation, but here is the error message:

> The website encountered an unexpected error. Please try again later.Drupal\Core\Entity\EntityStorageException: Object support when dumping a YAML file has been disabled. in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save() (line 847 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Drupal version is latest, fresh install. What am I doing wrong? Or what's missing?

# Answer
> 1 votes
The problem was at line:

```
'elements' => Yaml::encode($elements)

```

The solution is to replace the `Yaml` in the `use` statement:

from:

```
use Drupal\Component\Serialization\Yaml;

```

to:

```
use Symfony\Component\Yaml\Yaml;

```

I don't know the exact explanation, it just works on my code.

# Answer
> 1 votes
I just ran into this error...just change t('Name') to 'Name' and it should work.

Apparently the translate function expands out to an object (instead of what you might expect...'Name' or 'Nombre'...etc): and dumping objects to yaml is apparently no longer "allowed".

Ex:

```
Drupal\Core\StringTranslation\TranslatableMarkup Object
(
    [translatedMarkup:protected] =>
    [options:protected] => Array
        (
        )

    [stringTranslation:protected] =>
    [string:protected] => Name
    [arguments:protected] => Array
        (
        )

)

```

---
Tags: 8, webforms
---


# Question
Title: How do I make my site with pre-loaded content and pre-loaded config available to others without creating a distribution?
I want to be able to provide a simple way for users to install a Drupal website that contains a certain set of content, contributed modules and custom content types. I also want to keep the process of developing this scenario as simple as possible for the developer.

I know that the standard way to do this would be to create a Distribution such as those that are listed at https://www.drupal.org/project/project\_distribution. Another example is the Umami content available in a standard Drupal distribution. However, building a distribution seems to be quite a bit of work and should require a commitment to maintain that distribution if it is listed on the Drupal website. So, my question is whether there is a simpler way to allow users to install a website with some given content without my having to make the effort of building a distribution, since whatever I build will not be listed on the Drupal website.

The thought that there may be an easier way was prompted by my experience with some theme vendors. With some theme vendors, the process of installation involves only creating a database from an included SQL script and then starting the installation wizard and only having to input the database credentials. No other answers need to be answered in the installation wizard. It is almost as easy for the user as installing a distribution, and I am wondering if it may be easier for me as a developer to implement.

When I examine some of these theme installations that use this approach (e.g., News+ lite at https://www.drupal.org/project/newsplus\_lite) there is no code in the docroot/profile sub-directory, so this approach cannot be using a standard install profile or distribution because that is where extra content or code would be stored for an install profile or distribution. From my investigations so far about creating Distributions or Installation Profiles, I have not yet read how such an approach would work or be implemented. So, I am asking if anyone knows how such an approach (as utilized in the News+ Lite and other similar installations) works and how I might duplicate it.

# Answer
One of the support staff at MoreThanThemes was kind enough to provide some direction on how they do this. You can see the result in the structure of their free or paid themes. In short, the steps are pretty simple for what might be termed a `cloned installation`. The steps are basically the following.

1. Create a clone of the site that you want to install (https://www.youtube.com/watch?v=9NMRwkTzrCM describes that pretty well)
2. In the clone, overwrite/replace the `/docroot/default/settings.php` file with the `docroot/default/default.settings.php` file
3. Make a clone of the original database (e.g., using `MySQLDump`, `PhpMyAdmin` copy or `drush sql-dump`) and install it in a new database instance that you will use for the cloned site.

If you also have removed the Umami distribution and the minimal distribution from core, then the installation wizard will automatically bypass the choice for which install profile to use. In that case, the installation wizard only asks for the database information, where you will use the information for the cloned database. That will be all you need, and you will have a installed clone of your original website.

From my testing, it looks like the UUID of both sites are the same, just as if you had cloned the original site. So, the main use case from what I can see for this scenario would be if you wanted to share a copy of your site with other people, including the content (like the theme companies do). The only difference from a regular distribution like Umami or OpenAtrium from the user's standpoint is that they have to load the database file on their own before they do the installation. But from a developer's standpoint, this seems to be a much easier approach to sharing a website with the content and should be adequate for many users who want to test out your site.

I am surprised that this is not more widely documented and perhaps I have missed something here. But in my tests so far, this seems to be all that is needed. Hopefully this will help someone else who may need this simpler approach.
> -1 votes

---
Tags: 8, installation
---


# Question
Title: Pass field value of original node in webform
I'm using Drupal 8.7.8 and Webform 5.4.0. I have multiple section nodes that are displayed on course nodes. These are 2 different content types.

I'm adding webforms to sections, via the twig file conditionally (not all sections) with `{{ drupal_entity('webform', 'my_form_id') }}` and I need to pass the value of `field_code` of the section into a hidden field on the webform.

Once the form is rendered on the course page, the `field_code` value passed belongs to the course node rather than the section. How can I access the `field_code` value on the section?

I tried adding a hidden field with this token as the default `[webform_submission:node:field_code:value]`, which works when I test the form on the section, but when I test the form on the course (where the user will access it) I'm getting the `field_code` value of the course.

What's the best way to handle this? Is there a way to set the source entity to the content type that the form is on? Please let me know if I need to add more info.

Thanks!

# Answer
> 0 votes
I'm answering this with how I solved it in case anyone else has the same question. Maybe my question could be worded better though...

I was able to get this working with the Webform Node module.

I installed webform node. Then, I added a webform field to my content type. I selected the form I wanted as the default field settings. I selected the "Use this field's Content entity as the webform submission's source entity." checkbox.

I added my form to the display of the nodes I wanted it to be on in the content type's twig:

```
{% if node.field_name.entity.label == "My condition label" %}
  {{ content.field_name_of_webform_field }}
{% endif %}

```

Now, on my course page the same form appears for each section and I get the code for the section that the person filled-out the form on in the \[webform\_submission:source-entity:field\_code:value\] token!!

A couple of the resources that helped me: https://www.youtube.com/watch?v=B\_ZyCOVKPqA https://www.webwash.net/moving-forward-webform-drupal-8/#attaching-a-webform-to-a-node

---
Tags: 8, webforms
---


title: Contextual filter using any term ID

text:
# Question
Title: Contextual filter using any term ID
I want to set up a view with a contextual filter that will work with any term id (without selecting a specific category). I could only find some old, dated mentions of this. So I'm not sure if this is really possible currently or not.

# Answer
> 0 votes
Sorry I wasn't trying to be vague. My view was based on an entity, rather than content, like a node. So I wasn't seeing the "Has taxonomy term id" option in the list of contextual filters. I was only seeing specific taxonomy fields as options. I found that core does not offer that by default for other entities.

I did find a module that provided the functionality I was seeking: https://www.drupal.org/project/taxonomy\_entity\_index

I will also say that this module seems to expect entities to have bundles. If not there is an error. I'm going to submit a patch soon.

Hopefully that will help others. I will take my 2 downvotes and go home now.

(I'll also include this issue link for having the functionality in core: https://www.drupal.org/project/drupal/issues/1040786)

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