title: How to set the default page of my site?

text:
# Question
Title: How to set the default page of my site?
I want set the default frontpage of both my local and production site site.

In my local environment I created a content it has node id (**/node/20**) and it has URL alias of **/homepage**. In the Basic site settings I set my default frontpage to **/homepage**

In the production environment I also create a content it has node id (**/node/33**) and it has URL alias of **/homepage**. In the Basic site settings I set my default frontpage to **/homepage**.

Whenever I deploy something to the production environment, I export the configuration of my local environment (in the Drupal CMS) and I will import to the production environment. But whenever I import my configuration to the production my default frontpage is setting my homepage to **/node/33**, why is drupal doing this? I specifically set the default page to **/homepage**.

I'm using drupal 8 by the way.

# Answer
> 1 votes
Drupal core expects only internal URL (node/123) in the page.front setting. See `\Drupal\Core\Path\PathMatcher::isFrontPage`.

To be able to set page alias in the front page settings, I have created a workaround. I made a replacement of the `path.matcher` using an alias fallback:

**mymodule/src/MymoduleServiceProvider.php:**

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the path matcher service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Override the path matcher for the alias fallback.
    $definition = $container->getDefinition('path.matcher');
    $definition->setClass('Drupal\mymodule\AliasFallbackPathMatcher')
      ->addArgument(new Reference('path.alias_manager'));
  }
}

```

**mymodule/src/AliasFallbackPathMatcher.php:**

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Drupal\Core\Path\PathMatcher;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * The path matcher with alias fallback implementation.
 */
class AliasFallbackPathMatcher extends PathMatcher {

  /**
   * The alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * Creates a new PathMatcher.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The alias manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, RouteMatchInterface $route_match, AliasManagerInterface $alias_manager) {
    parent::__construct($config_factory, $route_match);
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   *
   * Support path alias for the front page path.
   */
  protected function getFrontPagePath() {
    if (!isset($this->frontPage)) {
      $path = parent::getFrontPagePath();
      $this->frontPage = $this->aliasManager->getPathByAlias($path);
    }
    return $this->frontPage;
  }

}

```

# Answer
> 0 votes
Someone may correct this but I'm fairly sure that's the intended behaviour.

That setting gets stored in the database as the actual Drupal path (**/node/33**) rather then the alias. In other words, that field gets stored as a path and translated to an alias on display. Which is kind of the opposite to how you use aliases elsewhere.

There's probably many of reasons for that. But I suspect it may have something to do with the fact that aliases are fluid, they get regenerated and reassigned all the time whereas a path remains relatively constant. A change to an alias could in effect change your front page which is bad. There are also a bunch of low level classes/functions that need to know your front page but don't have access to the path module.

It probably depends on how you're importing your config but I suspect something may be messing with/regenerating your aliases on import.

---
Tags: 8
---


# Question
Title: Can use the commerce kik start with aegir hosting system like a platform!
I'm using Aegir on ubuntu 16.04 using php 7.02. My question is, can I use this commerce like a platform in the aegir hosting system? That means that I can't access the installation wizard and I have to go with the installation wizard (or skip it with default values) by drush/ drush-provisione! It gives me often generic errors about the database table system that it doesn't exist.

What to do?

# Answer
Aegir 3 comes with e-commerce for drupal 7, there is not yet a d8 platform, if you are trying the d7 platform and it is not working then you have not installed aegir properly!

The aegir install asks you whether to install platforms ot not, you will have to try the link above or re-install aegir.

For anybody wishing to install aegir properly, make sure you use the instructions here:

http://docs.aegirproject.org/en/3.x/install/

A new linux install is a must!
> 0 votes

---
Tags: commerce, aegir
---


# Question
Title: Open Id Connect SSO on cross platform sites
I have 3 sites(all were sub domain sites)

1. Server(id.test.com) - .NET
2. Client1(client1.test.com) - Drupal
3. Client2(client2.test.com) - .NET

Am using OpenId Connect for login. My login & logout using drupal site is successful. But when i login through Client2 and navigates to Client1 site automatic login was not made, when i initiates a click in "Login using Generic" button, login occurs.

Is that possible to login automatically? I have checked OpenId Connect SSO module which supports only for Drupal sites. Is there is any other way to achieve this?

# Answer
> 0 votes
The OpenID Connect module is designed only to login your users when they use the login button(s).

The SSO module will propagate the logins to your Drupal sites, if you are using Drupal as authentication provider/clients.

If you are using a cross-platform setup, you will have to create your own auto-login propagation in a custom module. Depending on your authentication provider, you may (or not) be able to define post-login actions to use. Or you may yourself utilize post-login hooks of your Drupal site to trigger logins on the remaining sites.

Unfortunately, the solution you are asking for not only depends heavily on your authentication provider, but also is far out of the scope of Drupal Answers.

---
Tags: 7, authentication-authorization
---


# Question
Title: Where are the field labels and descriptions stored?
I have been exploring Drupal 8 and it's tables lately. The config table has the storage information serialized as blob. But it doesn't store the Label or Description of a field. Where can one find these data? Is there a core function which helps in fetching all these data for a particular content type?

# Answer
You can try something like this :-

```
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
$field_label = $node->field_file->getFieldDefinition()->getLabel();
$field_desc = $node->field_file->getFieldDefinition()->getDescription();
$field_settings = $node->field_file->getFieldDefinition()->getSettings();
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Authorize.net Getting error "A valid amount is required."
In our project we have used Commerce Authorize.Net module. We have not added any discount. No coupons are applied yet still when we proceed to checkout in testing mode we are always getting error as "A valid amount is required.". Our product price is $17.95 and when we get response from Authorize.net we are getting price as $-99.05 and hence payment is declined.

We have also used PayPal for payment method and it is working fine and giving proper amount for same product.

How can we solve this issue?

# Answer
I got the solution of this issue.

When we were working in local we have removed orders from CMS before moving database to Dev site. But because of dependency some orders were not removed completely. When Authorize.net finds such orders it has treating them as pending order and was adding payment in new order as Unknown payment method.

Some how this was adding extra amounts to final payment of new orders and was creating negative amount.

To resolve this I have deleted all my dummy orders from CMS and also from Table "commerce\_payment\_transaction".

This has resolved my issue.
One of the Drupal's Stackexchange answer helped me to resolve this issue, Why would just adding a product to cart create a payment with method type "unknown" and credit card of "4111--------1111"
> 0 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: How to hide content when first displaying the view (Views contextual filter)
I am on drupal 7.56 and using **Views** to display some content based on a **filter**.

**I am trying to not display content when the user opens the page for the first time**. I want to make sure the user only displays values that will be related to the filter. My filter is on the Title and is a Search box.

I know that it is possible to reach that goal with contextual filter. I did it once, but can't do it again.

Can somebody help me make that views work like that ?

# Answer
You can do this with an exposed filter and selecting the input required option. This option will appear in the Advanced section in the view configuration. You'll want to add an exposed filter for your title field first. *I think* that's in core.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: How can I include Google Structured Data via a module?
Looking through Google's suggestions of search optimisation for a site that I control, I would like to add their "Structured Data" JSON to various pages on the site. Their suggestion is to include the data in custom script tags:

```
<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Organization",
  "url": "http://website.com",
  "logo": "http://website.com/logo.png",
  "contactPoint": [{
    "@type": "ContactPoint",
    "telephone": "+44 1234 567890",
    "contactType": "customer service"
  }]
}
</script>

```

What I can't work out is how to include this data "the Drupal way". I tried adding it as a library (thinking I'd later use DrupalSettings to customise the contents) but that includes it as a standard "type=javascript". How do I add it to the page header with the correct script type?

Google ref: https://developers.google.com/search/docs/data-types/corporate-contact

(answers giving a module that does this already are also welcome!)

# Answer
> 1 votes
There is a Drupal 8 module works tandem with the Metatag module: Schema.org Metatag

From the module description:

> This project extends Drupal's Metatag module to display structured data as JSON LD in the head of web pages. Read more about Schema.org, JSON LD, and how this module works in an article on Lullabot.com, Create SEO Juice From JSON LD Structured Data in Drupal.

# Answer
> 0 votes
You can define the type attribute this way :

```
google_search:

        version: 1.x

        js:

          js/lib/library/google-search.js: { attributes: {type: application/ld+json} }

```

---
Tags: 8, theming
---


title: Limit user registration by email domain

text:
# Question
Title: Limit user registration by email domain
I want to allow people only with an email ending with a specific format and domain such as foo.bar@mail.school.edu to register for the site that I am building. How can I do this in the Admin Tool Bar?

# Answer
> 1 votes
You can use domain\_registration to allow or dissalow emails from certain domains to register.

Setup is very simple as seen from the instructions on the project page

> 1. Install the module
> 2. visit 'admin/config/system/domain\_register'
> 3. Choose if you want to only allow, or disallow the domains from registering
> 4. Enter the domain names you wish to allow/deny (one per line) in the format of 'foo.com'. Wildcards are allowed.
> 5. Enter the error message you wish to show to the end user if the email address doesn't validate

---
Tags: users
---


# Question
Title: How to fix warning message related to Pantheon module?
When I am running update.php, I am getting warning message. I am sure this is showing because the module was deleted without uninstalling. I am unable to find the Pantheon module or the module for which this warning is related.

> User warning: The following module is missing from the file system: pantheon. For information about how to fix this, see the documentation page. in `_drupal_trigger_error_with_delayed_logging()` (line 1143 of /homepages/46/d644118784/htdocs/includes/bootstrap.inc).

# Answer
Try using module\_missing\_message\_fixer

## with drush

you just need to run the following 2 commands

```
drush en module_missing_message_fixer
drush mmmff pantheon

```

## without drush using the user interface

1. Enable the module
2. make sure you have the permission Administer Module Missing Message Fixer
3. Go to: admin/config/system/module-missing-message-fixer
> 1 votes

---
Tags: updating
---


# Question
Title: How to change background color in my Tao subtheme
We have a custom sub theme built on Tao and I tried adding

`body {
 color:#fff;
 background:#333;
 }`

to the `style.css` file, but to no avail. In Chrome dev tools I started inspecting elements and changing their backgrounds individually, but I cannot figure out how to change the background color for all divs, form elements, blocks, etc without some super complicated CSS.

I'm trying to avoid doing this, if possible:

```
#main-content {
  background: #333;
}

#page {
  background: #333;
}

#page-title {
  background: #333;
}

#branding {
  background: #666;
}

div.limiter {
  background: transparent;
}

div.region {
  background: #333;
}

span.fieldset-title {
  background: #333;
}

div.tabs {
  background: #333;
}

fieldset.collapsible {
  background: #333;
}

.collapsed .fieldset-legend a {
  background: #333;
  color: #fff;
}

```

Further, when implementing this code, I cannot get some divs to change color, for instance `<div id="page-title">`

# Answer
It depends on the structure of the theme. If your can´t see any change after apply this, there are two possible reasons:

```
body {
  color:#fff;
  background:#333;
  }

```
1. There are other elements, like divs, upon your body elemnts.
2. The change that you made is not reflected on your site. Check if you are working in the correct css file. If it is a .sass file, maybe it needs to compile. Other reason for that, is for the cache, try to delete by going to `admin/config/development/performance`

Good luck!.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Restrict a role to administer certain vocabularies and terms, and remove the access to creating vocabularies
I gave to users the *Administer vocabularies and terms* permission to let them access the page on *admin/structure/taxonomy*, but I want to restrict the access to that page to certain vocabularies.

The only issue that remains is the *Add vocabulary* permission that comes with *Administer vocabularies and terms*.

How can I restrict users from creating/editing some vocabularies and still giving the permission to maintain taxonomy terms in other vocabularies?

# Answer
> 1 votes
"***Creating a new vocabulary***" is what you do using the URL `admin/structure/taxonomy/add`, while "***Editing existing vocabularies***" (say with machine name `demotags`) is done using the URL `admin/structure/taxonomy/demotags/edit`.

A possible solution to "*restrict*" access to these URLs (which seems to be the missing piece you are looking for) is to use the Rules module for this. To do so, have a look at my answer to the question "How to make the permissions of a module more granular?". It includes a rule (in rules export format), which you should be able to use if you apply these minor tunings to it:

* Check the Rules Condition about which roles this validation should be applied for (if any, if not remove that condition).
* Adapt the Rules Condition with the URLs containing `visitors` (to match the taxonomy related URLs like in my first paragraph).
* You probably don't need the Rules Condition with the "regex" in it (you only have a few URLs to be validated). In that case, you don't need the "OR" part either.
* Review the Rules Action (the message you want to show, and the redirect you want to force).

# Answer
> 0 votes
1. Create a new permission called for example 'Add new vocabulary'

```
 /**
  * Implements hook_permission().
  */
   function YOUR-CUSTOM-MODULE-NAME_permission() {
      $permissions = array(
        'add new vocabulary' => array(
          'title' => t('Add new vocabulary'),
        ),
      );
      return $permissions;
    }

```
2. Alter menu admin/struture/taxonomy/add 'access arguments'

```

  /**
  * Implements hook_menu_alter().
  */
   function YOUR-CUSTOM-MODULE-NAME_menu_alter(&$items) {
   $items['admin/structure/taxonomy/add']['access arguments'] =
    array('add new vocabulary');
   }

```
3. From admin/people/permissions you will find your new permission 'Add new vocabulary' under your YOUR-CUSTOM-MODULE-NAME, and give it only to your desired roles.

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


# Question
Title: Add another button for UI field set in admin
I feel like I must not have the correct terms when searching on this topic. I am relatively new to Drupal. What I need to create is a field set in admin which has an Add Another Foo button so any given node could have as many Foo field sets as desired. These would be draggable to sort for the node and accessible for the public facing twig to display.

Can someone help me with the terminology for this and if there is a tutorial on implementing I would really appreciate a link!

Example gui:

# Answer
You're looking for the Paragraphs module.

You can use it to create a paragraph type with the required fields in it (reference, specification, etc), than add a multi-valued field to your node type referencing that paragraph type.

Because it's a field, you'll get the standard add another and sorting functionality.

The How to start with Paragraphs for Drupal 8 docs page should get you going pretty quickly.
> 1 votes

---
Tags: 8, nodes, forms
---


title: Content Lock on Entityform nodes?

text:
# Question
Title: Content Lock on Entityform nodes?
In Drupal 7, it appears that the Content Lock module (which prevents concurrent editing of nodes) is not able to work its magic on Entityform-based nodes. Is there a workaround? Something similar with Entityform capabilities?

# Answer
You might get it to work by implementing an "**edit-in-progress**" (= EIP) feature using the Flag module, combined with using the Rules module. Similar to what I described within "Option 1" in my answer to "Can the Flag module be used to lock content while editing to prevent concurrent edits?" (BTW, that question is a variation of yours, not a duplicate though ...).
> 1 votes

---
Tags: 7, entities
---


title: Chosen library not working

text:
# Question
Title: Chosen library not working
I installed chosen module and the library v1.8.3.

Jquery update is 1.10

Libraries is installed and enabled as well.

I get this error on the console when I try to use a select list with chosen:

```
Uncaught TypeError: this.selected_item.off is not a function

```

Does anyone know how to solve this?

# Answer
I guess the Chosen library version 1.8.3 (released Jan on 22 2018) is a little bit too far ahead of the Chosen module version 7.x-2.1 (released on Mar 23 2017).

Replace the library by an older release (preferably version 1.1.0) and it should work.

---

From the Chosen module's `README.txt`:

> ```
> -- INSTALLATION --
>
>   1. Download the Chosen jQuery plugin
>   (http://harvesthq.github.io/chosen/ version 1.1.0 is recommended)
>   and extract the file under sites/all/libraries.
>   2. ...
>
> ```
> 1 votes

---
Tags: 7, theming
---


title: Why doesn't core get updated to 8.5?

text:
# Question
Title: Why doesn't core get updated to 8.5?
I am trying to update via Composer following what reported in Update core via Composer, but when I do `composer update drupal/core --with-dependencies`, I get the following output.

> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Nothing to install or update
> Generating autoload files

I checked /admin/report/updates, and I can see that Drupal 8.5 is available. The content of composer.json is the following.

```
    "repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

```

Why isn't Composer updating core?

# Answer
If `composer update drupal/core --with-dependencies` doesn't work, verify the *composer.json* file contains these lines and remove them. (XX equals anything.)

```
"replace": {
    "drupal/core": "~8.XX"
}

```

In any case, run `composer require drupal/core:~8.5.1`, even if the *composer.json* file did not contain those lines.

If that fails, try my last ditch method.

* Remove the *core* and *vendor* folders

```
sudo rm -rf core vendor

```
* Clear the Composer cache

```
composer clearcache

```
* Run `composer require drupal/core:~8.5.1`

Don't forget to make a backup first, if you haven't already.
> 1 votes

---
Tags: updating, composer
---


title: Fontawesome speed loading problems

text:
# Question
Title: Fontawesome speed loading problems
I’m using the Bartik Theme on Drupal 8.5 as a base theme (I have the Fontawesome module: 8.x-2.0 installed and I have the fontawesome being loaded from my local files) and I doing a few changes on my custom theme. In one of the templates I took over, I used fontawesome with the tag: `<i class="far fa-comments"></i>`.

Sometimes on loading of the pages, before the icon shows, it appear a small square on his place, and only an instant after the icon loads. I still have the site on debug mode, but is this behavior normal? How can I make the loading of the icons faster?

# Answer
Summarising the contributions of BhargavSushant and Mario Steinitz, configuring the Fontawesome Module to load the Font Awesome library from the given source rather than from the local library file is slower option (unless you have a bad server) and also when we are running our site on a “dev” node we should expect delays on loading the icons. Thank you all for your help
> 1 votes

# Answer
Scripts are added to the last in the resulting HTML Page in Drupal 8, and External CSS is added in the head, but external CSS is loaded after internal CSS that is used in modules. This might be creating an unwanted delay in rendering your font awesome styles.

I suggest you minimize the delay of your font awesome script by hosting it on your own server and calling it from there.
> 2 votes

---
Tags: theming
---


# Question
Title: Earliest point in page load to issue a redirect?
I'd like to redirect all of the paths for my media entities the path of a file on the entity. What hook would allow me to do this as early in the page load process as possible?

# Answer
> 2 votes
You should create an EventSubscriber! This post gives a pretty good code example.

I'm doing exactly this and I had some issues when the media's file changes, the redirect will be cached and still point to the old file. To get around this I use the page\_cache\_kill\_switch service which you can inject into your subscriber or just call like:

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

One other note is that you'll want to make sure you only fire the redirect when the route `\Drupal::routeMatch()->getRouteName() == 'entity.media.canonical'`. This will make sure you only redirect when trying to *view* the entity vs edit or etc.

# Answer
> 0 votes
In place of the code in the post linked by @sonfd, I ended up using:

```
$baseUrl = $event->getRequest()->getBaseUrl();
$attr = $event->getRequest()->attributes;
$current_route = \Drupal::routeMatch()->getRouteName();
\Drupal::service('page_cache_kill_switch')->trigger();

if($current_route == 'entity.media.canonical' && null !== $attr && null !== $attr->get('media')) {
  switch($attr->get('media')->bundle()){
    case 'image':
      $file_field = $attr->get('media')->get('field_image')->getValue();
    break;
    case 'document':
      $file_field = $attr->get('media')->get('field_file')->getValue();
    break;
  }
  $file_field = reset($file_field);
  $fid = $file_field['target_id'];
  $file = Url::fromUri(
    File::load($fid)->url()
  );
  $url = $file->getUri();
  $event->setResponse(new RedirectResponse($url));
}

```

---
Tags: 8
---


# Question
Title: Anonymous user can view unpublished content
Is there any way anonymous users can access unpublished pages using view?

I have a REST api for a custom content type that has setting of unpublished content and I want anonymous users can access it.

# Answer
Yes, You can enable module Workflows which is currently packed in core since 8.3 and check for permission for anonymous user

> View any unpublished content

in /admin/people/permissions

Note: Not to confuse about the permission when enable only Workflows. You need to enable module Content Moderation(Core module) to make Workflows work. Once go to /admin/config/workflow/workflows you will see the the default workflow. Here is the permission after enable Content Moderation.
> 2 votes

# Answer
Found this module and solves my problem View Unpublished.

> This module allows you to grant access for **specific** user roles to view unpublished nodes of a **specific** type. Access control is quite granular in this regard.
> 1 votes

---
Tags: 8
---


# Question
Title: Can I use Rules Transform to remove text from a returned value?
I notice that Drupal Rules Data Transforms has the "trim text" action option. Is it possible to trim the returned value by a specific number of characters, or remove a specific word from the returned string?

**E.g.** I grab an entity field value with my first action, and I want to remove the word "grams" from the returned value.

# Answer
You can try applying this Rules Data Transforms replace text patch which adds the ability to replace text. Flush cache after applying patch.

So now simply replace grams with nothing (empty).
> 0 votes

---
Tags: 7, rules
---


# Question
Title: How to add registry key verification step with the key being stored in another database
I am currently learning how to use Drupal through Udemy classes; I am a complete newbie.

I am building a Drupal Website, for my personal development, and when someone wants to register to the website I want the to fill in the typical form: full name, organization, etc (stuff like what Facebook for example asks). However, I want to add one extra identifier: **registry number**. What I really need to know is how to make this secure; so that when you type in a number; if it is not correct or it is random, then it would not allow you to register (sounds like the CD keys old PC games had).

Typically, those registry numbers are within the government ministries (say for businesses registries). For example to make taxes you have a registry key, i think that is how it is called; then when you do your taxes online you add that key to verify it is you. But how does the system know that key you entered is correct? It must be connected to a database that has all this information stored.

How do can I make this happen for my drupal website? But is it also feasible? (it must be right?)

# Answer
What you want is quite doable on Drupal, however if you just started learning Drupal then I am afraid you need to find an experienced developer, who could write up a custom module using the hook\_field\_validate().
> 0 votes

---
Tags: users, database, security
---


# Question
Title: How do I get an image from an external site using RSS?
I used the Aggregation module to consume news from an external RSS, but the pictures are not showing up.

Can anyone help me?

# Answer
> 0 votes
You have provided very limited information, but I think you are looking for something that shows images in News Aggregation Block, which is not a default feature.

You have to do some tweaking like mentioned here a Solution proposed by Shamseer.ch I hope they make this a feature soon.

---
Tags: 8, feeds
---


# Question
Title: How can I allow front end users to add their own custom fields?
We have a new project that is going to allow users to add their own nodes of a content type e.g. 'cars'.

There are some existing fields that they need to complete e.g. 'colour' and 'year'. We also need to allow them to add their own custom fields, which only they can use. So one user will add 'mileage' whereas another might want to add 'number of seats'. How would I go about allowing hundreds of users to do this without bloating the content type?

We will be building it in Drupal 7.

Thanks for any help.

# Answer
> I was thinking the user would be able to define fields of all of their nodes, not on a one by one basis. in other words, they define 'colour' once in their 'settings' and then add the colours for each car - not the label and the value

I don't know any module that offers this out of the box, so you would need to write your own custom module. You could try to add a new paragraphs or field\_collection field to the user's profile and let them define what custom attribute (e.g. "colour") they want to define (at least in D8 there's also the `\Drupal\user\UserDataInterface` that can be used to store personal user preferences). Then use a `hook_form_alter` or something similar to adjust the form when adding a new car and display the name of that specific attribute as a label to another paragraphs/field collection field (which then holds the actual data ,e.g. "red").
> 1 votes

# Answer
Use Field Collection module.

Install Field Collection module

Create a field collection field to a content type and set to unlimited.

Then create a fields with two text fields - "label" (for 'colour' and 'year') and "value" for that field collection

So when the node add form loads user will have two fields, Label and value with add more button there user can click and add another set of "label" and "value" pair.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Access a 'global: custom text' field in fieldpluginbase render()
I'm trying to get more familiar with FieldPluginBase to create a new custom field for views. As an example I implemented a new field called 'dropdown list' that "wraps" other view-fields the user selects. Therefore I implemented a form in `buildOptionsForm()` that shows all currently displayed view fields and let's the user select multiple via checkboxes (kind of similar to the dropbutton behavior).

This works well and in `render()` I can see which fields the user checked via `$this->options['field_types']`.

Next I want to add the user-chosen fields to a renderarray and display them as an item list (`'#theme' => 'item_list'`) to later add some custom css classes and style them. However, I have currently no way of accessing all fields that are shown in the view, only the entity fields via `$entity->get('field_name')->getValue()`. That gives me the standard entity fields like title, body, nid ... But I do have a Global: Custom text (id='nothing\_2') that I need to access (that is excluded from display and output as a custom link). I found no way of accessing the value of such fields that do not directly belong to the entity (I tried `$this->view->field[...]` and `$this->displayHandler->getValue(...)` without success).

Any idea if what I'm trying to do is possible and what I'm missing ?

```
class DropDownList extends FieldPluginBase {

  public function query() {

  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['field_types'] = ['default' => []];
    return $options;
  }
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {

    $fields = $this->displayHandler->getFieldLabels(TRUE);
    $pos = array_search('dropdown_list', $fields);
    unset($fields[$pos]);

    $form['field_types'] = array(
      '#title' => $this->t('Which fields should be included?'),
      '#type' => 'checkboxes',
      '#options' => $fields,
      '#default_value' => $this->options['field_types'],
    );
    parent::buildOptionsForm($form, $form_state);
  }

  public function render(ResultRow $values) {
    $items = [];
    if ($entity = $this->getEntity($values)) {
      // Dummy loop to show how I wanted to approach this
      // Checkboxes results are available like this (in this output
      // the user only checked the custom text 'nothing_2'):
      // nothing_2=>nothing_2 nid=>0 title=>0 body=>0 uid=>0
      foreach($this->options['field_types'] as $key=>$value) {
        if ( $value != '0') {
          // There is no field 'nothing_2'
          $items[] = $entity->get('field_name')->getValue();
        }
      }
    }
  $build['theme_element'] = [
      '#theme' => 'item_list',
      '#title' => $this->t(''),
      '#items' => $items,
    ];
    return $build;
  }
}

```

**UPDATE**

Using `$this->view->field['nothing_2']->getValue($values)` as also suggested by 4k4 returns an empty string, although I know that `nothing_2` contains a link: `<a href=....>Edit</a>` but it does not seem to be directly contained in `getValue()`

# Answer
As indicated by @4k4 the solution is using advancedRender() inside a for loop

```
public function render(ResultRow $values) {
  $items = [];
  foreach ($this->options['field_types'] as $key => $value) {
   if ($value != '0') {
    $items[] = $this->view->field[$key]->advancedRender($values);
   }
  }
$build['theme_element'] = [
  '#theme' => 'dropdownlist-theme',
  '#title' => $this->t('Dropdown List'),
  '#items' => $items,
 ];
 return $build;
}

```
> 1 votes

---
Tags: views, 8, entities, plugins
---


# Question
Title: remove email field from registration form
From core\modules\user\src\AccountForm.php, user module developer added following comment to Email fields.

```
 // **The mail field is NOT required if account originally had no mail set**
    // and the user performing the edit has 'administer users' permission.
    // This allows users without email address to be edited and deleted.
    // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.

    $form['account']['mail'] = array(
      '#type' => 'email',
      '#title' => $this->t('Email address'),
      '#description' => $this->t('A valid email address. All emails from the system will be sent to this address. The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.'),
      '#required' => !(!$account->getEmail() && $user->hasPermission('administer users')),
      '#default_value' => (!$register ? $account->getEmail() : ''),
    );

```

I do not understand what is "**originally had no mail set**" mean. it looks like , there is a config option which can turn off Email requirement, but I am unable to find the config option.

# Answer
Mean that you can set an account without e-mail, as admin or someone that have rights, in url '/admin/people/create'. But when a visitor goes to 'user/register', he must specify a e-mail, because someday an e-mail `will only be used if you wish to receive a new password`, as description says.

There are two types of accounts, one with e-mail (like a visitor that created a new account), and another without e-mail (admin created a new user). This is why AccountForm check if user have an e-mail and check if user is admin or have 'users' permission, to set e-mail field required or not.

There is no reason to a visitor create a account without an e-mail, there is no other way to admin/system contact him for any kind of situation. In other hand if an admin create a new user, somehow he will able to contact the new user.
> 2 votes

# Answer
There's a module available in Drupal 7: Optional mail on register!

https://www.drupal.org/project/optional\_mail

In addition to using the No Request New Password module as suggested on that page; I think it'll be best to use some Captcha \[preferably reCaptcha, and hidden captcha\] to prevent bot registrations. Also, the Login Security and Flood Control modules, with their proper settings!

My personal use case is a demo site where the user can get a taste of the offerings on my main site. Hence, I'm also using the 'User Expire' module, where the 'authenticated user' role can be set to expire after some hours or days of inactivity.
> 0 votes

---
Tags: 8, forms
---


title: Hooks and routes not working at all

text:
# Question
Title: Hooks and routes not working at all
I have a module called hello\_world.

I have a hello\_world.info.yml file in drupal/web/modules/custom/hello\_world whose content is the following.

```
name: Hello World
description: Hello World module
type: module
core: 8.x
package: Custom

```

This works perfectly ; the module is in the extension list.

I tried to make a help hook so I made in the same folder a hello\_world.module file with the following code.

```
<?php

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */

function hello_world_help($route_name, RouteMatchInterface $route_match) {
    switch ($route_name) {
        case 'help.page.hello_world':
            $output = '';
            $output .= '<h3>' . t('About') . '</h3>';
            $output .= '<p>' . t('This is an example module.') . '</p>';
            return $output;
            break;
    }
}

```

This does not work at all. The help page is not shown.

I also tried to make a hello world page using this controller in drupal/web/modules/custom/hello\_world/src/HelloWOrldCOntroller.php.

```
<?php

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller for the salutation message.
 */
class HelloWorldController extends ControllerBase
{
    /**
     * Hello World.
     *
     * @return string
     */
    public function helloWorld()
    {
        return [
            '#markup' => $this->t('Hello World')
        ];
    }
}

```

I added hello\_world.routing.yml to drupal/web/modules/custom/hello\_world.

```
hello_world.hello:
path: '/hello'
defaults:
_controller:
'\Drupal\hello_world\Controller\HelloWorldController::helloWorld'
_title: 'Our first route'
requirements:
_permission: 'access content'

```

This does not work either, even after clearing the cache. As I said, the hello\_world.info.yml works perfectly fine, but the help hook and the controller/routing does not. The rest of the core modules work. I am using Vagrant if it matters.

# Answer
Creating the files is not enough: The module needs also to be installed. /admin/modules gives a list of modules and allows to install them.

After a module is installed, all its hooks are invoked from Drupal.

As side note, YAML files are required to use the correct indentation. The content of the hello\_world.routing.yml file should be the following one.

```
hello_world.hello:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloWorldController::helloWorld'
    _title: 'Our first route'
  requirements:
    _permission: 'access content'

```

See the example give in Routing API, *Registering simple routes*.
> 3 votes

---
Tags: 8, routes
---


title: Open a link in a new tab in the menu

text:
# Question
Title: Open a link in a new tab in the menu
I'm using Drupal 8 with Bootstrap theme, and I've created a sub-theme and different menus.

I've tried to edit the menu twig template but i am not really familiar with Twig.

How can I add a menu where links open in new tabs?

# Answer
In my case I utilized hook\_link\_alter() to accomplish this. Situation: in my menu links, I only need **Contact Us** to open in a new tab.

```
<?php
function MYMODULE_link_alter(&$variables) {
  if (!$variables['url']->isRouted()) {
    $uri = $variables['url']->getUri();
    // Only want the Contact Us to open in new tab.
    if ($uri == 'base:contact-us') {
      $variables['options']['attributes'] = ['target' => '_blank'];
    }
  }
}

```
> 7 votes

# Answer
This one works fine for ALL external links:

```
function MYMODULE_link_alter(&$variables) {
  if ($variables['url']->isExternal()) {
    $variables['options']['attributes'] = ['target' => '_blank'];
  }
}

```
> 4 votes

# Answer
Menu target module in dev version for D8 but you can check.

Allows privileged users to choose wether or not to open menu items in a new window. When enabled, users who have access to add or edit menu items, are provided the possibility to choose if the menu items should be opened in a new window or in the same window.
> 2 votes

# Answer
Menu Link Attributes module solves this out of the box for Drupal 8. Have to be set for each link in the menu, though.
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: Make t() function translate string on template file?
I created a custom page, with my custom module.

### Hook\_Menu

```
$items['registered-products/%'] = array(
    'title' => t('Hello World'), // TRANSLATES FINE
    'page callback' => 'mymodule_product_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'file' => 'includes/mymodule.product_page.inc',
);

```

### Template File

I created a template file (.tpl.php) for my custom page, in here I have:

```
<?php print t('hello world'); ?> <!-- DOES NOT TRANSLATE -->

```

### RESULT

The `t()` translates in hook\_menu, but on the template file it does not.

**What do I have to do so the `t()` works to on template file?**

# Answer
> 1 votes
The problem should be solved as soon as the strings are identical. In the provided code, *hello world* is not equal to *Hello World*.

> Matching strings for translation is case sensitive.

---
Tags: 7, i18n-l10n
---


# Question
Title: How to set the size attribute of a select field?
When you use a "select" field with multiple values Drupal generates this HTML:

```
<select multiple="multiple" name="..." id="..." class="...">

```

How can I inject the size="..." attribute? This will cause the box to show more values.

# Answer
You might be able to do it with the `#size` property of the Form API. I am not sure, but you might need to also set the `#multiple` property to `TRUE` in order for the `#size` to be honored.

It it also not clear from the question if you are creating your own form using the Form API, modifying an existing Form API form using a `hook_form_alter()`, or writing your own form HTML (which I imagine - and hope - you are not doing).
> 4 votes

# Answer
Try this to modify Select list Height & width drupal Way

```
// Increase Height of Select list
$form['field_example1']['und']['#size'] = 15;

// Increase Height of Select list
$form['field_example2']['#size'] = 20;

```
> -1 votes

---
Tags: 7, forms
---


# Question
Title: How do I change the uploading image file name
How do I change the image name while uploading through a file uploading field? In drupal 8 whenever I add an image to a file field, it automatically uploads the image file to my S3 bucket. I need to change the image name before uploading because I need to list my image names with a specific pattern. I searched the internet but couldn't find a hook for that auto image uploading.

# Answer
> 0 votes
If you're uploading a file I'm assuming it's within a form, right? You could add a submit handler function using `form_alter()` (or override the `submitForm()` method) and change the file's name using the `$form_state` object's `setValue()` and `getValue()` methods I'm sure.

---
Tags: 8, hooks, media
---


# Question
Title: How do I retain the query string after login?
I need the user,opening a certain page of my site (www.foo.com/page\_to\_visit), to login and then go to the requested page, so I set up an hook\_menu for this specific page and a callback. In the callback I added this code which works

```
drupal_goto('user', array('query'=>drupal_get_destination()))

```

but if the url contains query strings (www.foo.com/page\_to\_visit?id=12&od=12) they are removed. I mean that, after login, the user gets redirected to www.foo.com/page\_to\_visit instead of www.foo.com/page\_to\_visit?id=12&od=12. How do I avoid this behaviour?

UPDATE: Drupl\_goto has something supporting this. Produced this code, following documentation

```
$args = array();
$params = $_GET;
$args[] = $params['q'];
unset($params['q'], $params['destination']);
if (count($params) > 1) {
  $pippo['query'] = $params;
  $args[] = $pippo;
}
drupal_goto('user', array('query'=>$args));

$args results in --->
Array
( [0] => page_to_visit
  [1] => Array
    ( [query] => Array
            ( [id] => 12
              [od] => 12
            )
    )
)

```

The result is odd for the redirect looks like http://www.foo.com/user?0=page\_to\_visit&1\[query\]\[id\]=12&1\[query\]\[od\]=12

# Answer
> 0 votes
I think, my suggestion is :-

1. alter login form
2. add a hidden field for destination URL.
3. add submit handler like `$form['#submit'][] = 'destination_redirect_handler'`
4. use `drupal_goto('destination_redirect_url')` in this `destination_redirect_handler`

# Answer
> -1 votes
Modify your call to drupal\_goto() like this:

```
drupal_goto('user', array('query'=>drupal_http_build_query($args)));

```

drupal\_http\_build\_query() builds a formatted query string from an array.

Hope this helps.

---
Tags: 7
---


# Question
Title: Filter referenced item without losing other content
I have 2 entity types Content type A and B. Content type B has a date field and an entity reference to A.

I need a view that shows all the nodes of content type A But also shows all the referenced content, until this point I have no problem.

The only problem is that the content type B needs a filter to only show the content from this year. But when I add a filter to the date field all the nodes that don't have an entity reference also get filtered out.

Content type A are assets

Fields:

* Title
* Address
* lat/long

Content type B is the maintenance of these assets

Fields:

* Title
* Entity reference to A
* date field

Now I want to show all the assets in a view.( also the ones that don't have maintenance done) In the same view there should be a column with all the maintenance within a certain timespan.

When I have this view i can put these on a google map and show which assets need maintenance and which are already done

# Answer
As what I understand your needs its very simple.

You have to set the filter criteria in the views:

1. Add Content Type **A**
2. Add Content Type **B**
3. Add Published field **twice**
4. Add Date Field and set its criteria as **you already set**
5. The field (Entity Reference field in Type B) that reference to Type A and set its operator as **Is not empty (NOT NULL)**
6. Now, **Open** re-arrange the filter criteria fields

7. You need to **Create new filter group** under the filter criteria and drag drop your fields in required group like below

I hope this will at least give you an idea how to filter different content types with different field(s).

Thanks
> 1 votes

---
Tags: 7, entities, views
---


# Question
Title: Is there any way to redirect page to front page, if it isn't translated?
Is there any way to redirect page to homepage if its translated page not found.

Suppose my page url is `/en/node/237`, If I switch translation from English to German `/ge/node/237`, if it's translated page not found, URL should redirect to homepage of its native language like: `/ge/home`

**Here is my code:**

```
 use \Drupal\node\Entity\Node;

   $elements = [];
 $ids = \Drupal::entityQuery('node')
  ->condition('type', 'intro_2')
  ->condition('langcode', 'fr')
  ->condition('nid',1218)
  ->execute();

 $nodes = Node::loadMultiple($ids);
  $language = 'fr';

 foreach ($nodes as $node) {
 $translation = $node->getTranslation($language);
$elements[] = [
 'node' =>$translation->nid->value,
'title' => $translation->title->value,
'url' => $translation->url(),
];
  }
dpm($elements);

```

Above code working fine i have checked on /devel/php,but i am having only following issues:

1)How to get current page node type dynamically in database query

2)How to get current page language dynamically in database query

3)How to get current page node dynamically in database query

**Can anyone modify the above code?**

# Answer
Finally i solved the issue by myself :

```
use \Drupal\node\Entity\Node;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse
function hook_preprocess_node(&$variables) {
$elements = [];

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
$nid = $node->id();
 }
if($node) {
$node_type = $node->getType();

 }
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

 $ids = \Drupal::entityQuery('node')
 ->condition('type', $node_type)
 ->condition('langcode', $language)
 ->condition('nid', $nid)
 ->execute();

$nodes = Node::loadMultiple($ids);
 foreach ($nodes as $node) {
 $translation = $node->getTranslation($language);
 $elements[] = [
 'node' =>$translation->nid->value,
 'title' => $translation->title->value,
 'url' => $translation->url(),
 ];
  }

 if(empty($elements)){
$language = Drupal::languageManager()->getLanguage($language);
$url = Url::fromRoute('<front>', [], ['language' => $language]);
$response = new RedirectResponse($url->toString());
 $response->send();
  }
 }

```
> 0 votes

# Answer
To get current node:

```
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
  $node_type = $node->getType();
}

```

Current language:

```
$language = \Drupal::languageManager()->getCurrentLanguage();
$langcode = $language->getId();
$language_name = $language->getName();

```

Check if translation is not available and redirect:

```
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

$translation = $node->getTranslation($langcode);
if (!$translation) {
  $url = Url::fromRoute('<front>', [], ['language' => $language]);
  $response = new RedirectResponse($url->toString());
  $response->send();
}

```

P.S.: I believe entity query you posted is a simplified version of smth more complex in your logic. Otherwise I see no reason to pass node id to entity query condition to get it back eventually. If you always have just one node use Node::load($id) instead of Node::loadMultiple($ids), and you don't need foreach in this case.
> 1 votes

# Answer
Try using `hasTranslation()`

```
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse

function YOUR_MODULE_preprocess_node(&$variables) {
  $languageCode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  if (!$variable['node']->hasTranslation($languageCode)) {
    $url = Url::fromRoute('<front>', [], ['language' => $language]);
    $response = new RedirectResponse($url->toString());
    $response->send();
  }
}

```
> 0 votes

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


# Question
Title: Translation view path broken after upgrade to 8.5.1
After upgrading my site from Drupal 8.3.5 to Drupal 8.5.1, the token `{{ path }}` is not translated anymore in the selected language.

Does anyone have a suggestion or solution?

# Answer
> 1 votes
Because Content: Path has been removed in 8.5 version. Instead you should use Link to Content.

# Answer
> 0 votes
Yes you should use, but it won't give you the translated output and your link is stucked at the original language.

https://www.drupal.org/forum/support/post-installation/2018-04-08/doesnt-show-path-field-when-adding-fields-for-view

---
Tags: views, path-aliases
---


# Question
Title: drupal7 : db_select node with multiple values field
I have a problem with db\_select, i want to return a node per row for each value of the multiple values field :

* node\_1 : value\_1\_of\_the\_multiple\_values\_field
* node\_1 : value\_2\_of\_the\_multiple\_values\_field
* node\_1 : value\_2\_of\_the\_multiple\_values\_field
* ...

here is my code with the join it only return a node linked to the values of the field :

```
$query = db_select('node', 'n')
->extend('PagerDefault');

```

// Add join with multiple values field ( a date )

```
$query->join('field_data_field_date_programme_culturel', 'fdfdpc', 'fdfdpc.entity_id = n.nid');
$query->fields('n');

```

any idea please?

# Answer
> 0 votes
I've often struggled with the join methods in the D7 database layer. When I've needed to use a join, I've just used `db_query()` and passed it my SQL string. I know that when calling the `join()` method, you must already have the object initialised. So:

```
$query = db_select('node', 'n');
$query->join(field_data_field_date_programme_culturel', 'fdfdpc', 'fdfdpc.entity_id = n.nid');

```

and you already have it like this so I don't think that's the issue. I'd suggest using `db_query($sql)`.

---
Tags: 7, database
---


title: Stipe Checkout Barcelona vs now

text:
# Question
Title: Stipe Checkout Barcelona vs now
So I happily stumbled upon the video 'Shut up and take my money' from DrupalCon Barcelona (2015) to learn about the module 'stripe\_checkout'. Notwithstanding my undying admiration for Drupal Commerce, I fully concur with the speaker that not all sites that want people to give them money need an entire Commerce Interface.

I was able to (navigating beyond the update-esoterica) mirror the behavior from the video on my sandbox, then the client site.

I very foolishly promised the solution to my client before remembering to test as an anonymous user.

It is quite clear that the Barelona Video version prompted for Email, then CC data. However, the current stripe\_checkout gathers the email from the Logged in User, and FAILS COMPLETELY for anonymous users. Unless I am missing something (always a possibility) there is no 'config setting' for allowing/disallowing for anonymous users.

So my questions: 1) Has anyone out there already cleared this hurdle with some glueCode or some-such that could be shared here? 2) Or is there some other mechanism for clearing this hurdle short of implementing full-on Drupal Commerce?

# Answer
> 1 votes
I fully accept responsibility for my 'inappropriate' question, and thanks for those that posted helpful information about how to avoid the slings and arrows of StackExchange participation in the future. I do find myself flummoxed by all this, but I so completely find StackExchange answers of such a high quality I accept my confusion as a 'price of admission'. I do apologize in advance for additional faux pas in the future... indeed, perhaps this post.

So I solved it, with a direct code edit, not the proper glueCode that I will continue to work on. Notwithstanding, I am going to post my 'Psuedo-Diff' of the code changes I made to accomplish what I was looking for. With the caveat that I am 'breaking rules', perhaps others can find this a helpful jumping-off point for better expression of a similar solution.

I really need this for a project, so this is 'good enough' for me for this site for right now, but I fully intend to circle-back and attempt to solve this problem with proper glueCode or maybe even participation in the overall project. With that, I will say, 'So Long!' and post my Pseudo-Diff code below:

```

/**
 * @file: modules/contrib/stripe_checkout/src/Controller/StripeChargeController.php
 * @line: approx 64
 */
                        $amount = $node->$field_name->value;
                        $field_settings = $node->$field_name->getSettings();
                        $currency = $field_settings['currency'];
-                       $user = \Drupal::currentUser()->getAccount();
+                       if (!\Drupal::currentUser()->isAuthenticated()) {
+                               $user = \Drupal\user\Entity\User::load(10);
+                       /**
+                        * use whatever UID correlates to the dedicated 'anonymous payer'
+                        * you set up for this purpose, for me for this site is is User Number 10
+                        */
+                       } else {
+                               $user = \Drupal::currentUser()->getAccount();
+                       }

/**
 * @file: modules/contrib/stripe_checkout/src/Plugin/Field/FieldFormatter/StripeCheckoutFormatter.php
 * @line: approx 92
 */
                $default_settings = $this::defaultSettings();
+               if (!\Drupal::currentUser()->isAuthenticated()) {
+                        $user = \Drupal\user\Entity\User::load(10);
+                       /**
+                        * use whatever UID correlates to the dedicated 'anonymous payer'
+                        * you set up for this purpose, for me for this site is is User Number 10
+                        */
+               } else {
+                       $user = \Drupal::currentUser();
+               }

/**
 * @file: modules/contrib/stripe_checkout/src/Plugin/Field/FieldFormatter/StripeCheckoutFormatter.php
 * @line: approx 127
 */
                                        'locale' => 'auto',
                                        // @todo Make configurable.
                                        'image' => 'https://stripe.com/img/documentation/checkout/marketplace.png',
-                                       'email' => \Drupal::currentUser()->getEmail(),
                                        'label' => $link_text,
                                ],
                                '#is_free' => $is_free,
                                '#price' => $price,
                                '#entity_id' => $item->getEntity()->id(),
                                '#field_name' => $item->getFieldDefinition()->getName(),
-                               '#logged_in' => \Drupal::currentUser()->isAuthenticated(),
+                               '#logged_in' => TRUE,

/**
 * @file: modules/contrib/stripe_checkout/src/Plugin/Field/FieldFormatter/StripeCheckoutFormatter.php
 * @line: approx 151
 */

+                       if (\Drupal::currentUser()->isAuthenticated()) {
+                               $elements[$delta]['#data']['email'] = $user->getEmail();
+                       }

```

---
Tags: 8, users
---


# Question
Title: Deleting a Drupal 8 Content Type Field also Deletes all the Views linked to it... Undo?
So I deleted a Drupal 8 content type field and it also deleted the views that is associated with it. Is there an undo button?

# Answer
> 1 votes
There is no undo button. Deleted configurations are deleted configurations :-(
With Drupal 8.4: It is not deleting the view anymore - it is disabling the view so you can change your view and enable it again.
(taken from the issue Ashish mentioned above, Picture by vaplas)

# Answer
> 5 votes
Yes, that's what currently happens. Drupal informs you on the delete confirmation page what all will be deleted.

You can try one thing that to restore your backed up database.

Also, there is an issue that tries to improve it so that the view updates itself instead.

---
Tags: views, 8, entities
---


# Question
Title: Make variable available in template file
I am creating a custom template file for a views table and I need to put some links in the footer of the table, these links belong to 3 nodes. How can I make this data available in my template file which is - views-view-table--my-view-name.html.twig

Is there a pre-process of some sort that I can use?

# Answer
> 0 votes
You can override `template_preprocess_views_view_table()` in your own `THEMENAME.theme` file

```
function THEMENAME_preprocess_views_view_table(&$variables){
   $variables['node1'] = "value from node 1";
}

```

in your twig file you should have the variable available

```
{{node1}}

```

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


# Question
Title: Sticky Navigation 8.x-1.1. Funny padding-top
In in Drupal 8.5 Theme Bartik and using the Sticky Navigation 8.x-1.1. When by any chance I reload a page of my site and at that moment I’m positioned in the middle of that page and the menu is “sticky”, the module add a padding-top equal to the height of the sticky menu bar to the tag Body (as an inline styling). If you go up to the top of the page, after reloading, there is a white strip at the very top of the page (originated by the padding top). Can some tell me how to fix it?

# Answer
So far my solution was to apply CSS + jQuery to me theme:

CSS

```
body.js--padding-fix {
   padding-top:0 !important;
}

```

and JQUERY

```
jQuery(document).ready(function () {
    if (jQuery('div.primary-menu-container-global').hasClass('stickynav-active'))
    {
        jQuery('body').addClass('js--padding-fix');
    }
});

```

Note: if you apply the CSS directly to the body tag, it creates a problem with the Admin Menu, that covers the top of the site (minimized this way)

Is there a better solution?
> 0 votes

---
Tags: navigation
---


# Question
Title: Views Template for first Block being applied to all
I have a View called News which has about 10 different block displays in it serving various roles. I created a template for the first block (not block\_1 and not the master) in order to apply some unique structure.

Though the changes are seen on all the blocks in News.

Based on the template suggestions for the block I need it to apply to, it suggests the following.

**Display output: views-view.tpl.php, views-view--news.tpl.php, views-view--default.tpl.php, views-view--default.tpl.php, views-view--block.tpl.php, views-view--news--block.tpl.php**

I'm using views-view--news--block.tpl.php since its the most granular of the options.

Is there another I should use?

# Answer
> 0 votes
Simply changing the machine name setting on the display allows me to make it what I want, so I gave it the machine name block\_0 and now I can make a designated template for it.

---
Tags: 7, views, theming
---


title: control RSS feeds

text:
# Question
Title: control RSS feeds
How can I control which RSS feeds Drupal generates automatically? I would like to send out my site's content but choose which categories of posts are included in the RSS. I am using Drupal 8.

# Answer
> 1 votes
Drupal 8 comes with some default RSS feeds created using views

**frontpage feed** can be edited here `admin/structure/views/view/frontpage/edit/feed_1` which provides the feed accessed from this url `domain.test/rss.xml`

and **taxonomy feed** can be edited here `/admin/structure/views/view/taxonomy_term/edit/feed_1` which provides the feed accessed from this url `domain.test/taxonomy/term/TERMID/feed` where TERMID is the term id for each taxonomy term

You can modify those or create your own views based on those to accomplish what you need

---
Tags: 8, feeds
---


# Question
Title: How do you override custom blockAccess() methods for blocks added with Page Manager?
I've created a custom block with all its methods like `blockAccess()` etc. I would like to override one of those in another module.

In my project I have used Page Manager, means I think I can't call `hook_block_access()` because blocks added with Page Manager don't get into this hook.

# Answer
> 0 votes
Your other module can implement hook\_block\_access().

The example code in Drupal core looks like this:

```
function hook_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {

  // Example code that would prevent displaying the 'Powered by Drupal' block in
  // a region different than the footer.
  if ($operation == 'view' && $block
    ->getPluginId() == 'system_powered_by_block') {
    return AccessResult::forbiddenIf($block
      ->getRegion() != 'footer')
      ->addCacheableDependency($block);
  }

  // No opinion.
  return AccessResult::neutral();
}

```

Since it's a hook, you would have to replace the word "hook" in the function name with the machine name of your module, and place this function in the .module file.

---
Tags: 8, blocks
---


# Question
Title: How to display the description of the article with 150 characters?
My site is with Drupal 8, I have a content type "Article" with a body field.

I copied the twig node.html.twig file into my theme.

If I put the following code, the description is displayed:

```
{{ content.field_article_description }}

```

The parameter of the display of the field, allows to choose the number of characters. But he stops at the first sentence, cuts the word and does not display the elipse (...).

I want the description to be cut to 150 characters right after the word (I do not want the last nmot to be cut) and I want to add at the end an elipse (...).

I want the field to be displayed in plain text (without html tags).

Is it possible to add parameters to the description field with twig ?

Can you help me ?

# Answer
Check out Smart Trim module.

> Smart Trim implements a new field formatter for textfields (text, text\_long, and text\_with\_summary, if you want to get technical) that improves upon the "Summary or Trimmed" formatter built into Drupal 7.
> 1 votes

---
Tags: 8, nodes, entities
---


# Question
Title: How should I get the user submitted input?
On an submission handler, should I fetch the user input via `\Drupal::request()->request->get()` or is `$form_state->getValues();` the better (more saver) way?

# Answer
> 5 votes
```
$request->request->all() != $form_state->getValues()

$request->request->all() === $_POST
$request->query->all() === $_GET

```

See in `Drupal\Core\Form\FormBuilder::buildForm()`

```
$input = $form_state->isMethodType('get') ? $request->query->all() : $request->request->all();
$form_state->setUserInput($input);

```

**$form\_state-\>getValues()** is already modified data that is formed on the basis of $form\_state\['input'\] and #default\_value

See in `Drupal\Core\Form\FormBuilder::handleInputElement();`

Pay attention to `#value_callback` it forms the value of the field

# Answer
> 1 votes
Not entirely sure what you're doing, but the answer is probably $form\_state-\>getValues() or $form\_state-\>getValue(). There is also $form\_state-\>getUserInput(), but as you'll see on that page, it recommends you use one of the first 2 options unless you have a specific reason and know what you're doing.

---
Tags: 8, forms
---


# Question
Title: how can I get the result of a field after it was submitted?
I would like to extract the value entered by the user in a form to use it in a custom module. I use Drupal 8.5.1 and Webform 8.x-5.0-rc10. Thanks!

# Answer
If you are using a form alter hook you can user `$form_state->getValue('element_name')`. If you are want to get the final submission's data you could do...

```
$form_object = $form_state->getFormObject();
$webform_submission = ($form_object instanceof WebformSubmissionForm) ? $form_object->getEntity() : NULL;
$value = $webform_submission->getElementData('element_name');

```
> 2 votes

---
Tags: 8, webforms
---


title: CKEditor break quotes: Why?

text:
# Question
Title: CKEditor break quotes: Why?
On the forum I made a quote using the Quote module. It works fine for the administrator, but it doesn't work for the anonymous users.

The module defines a function, called via an ajax request, which filters the text before passing it to the editor, to prevent certain XSS attacks on content edits (that the JavaScript library might not handle). Because the function did not check a CSRF token for anonymous users, it was possible to perform reflected XSS against anonymous users via CSRF.

Quotes breaks the function module (line 229 in "ckeditor\includes\ckeditor.page.inc").

```
function ckeditor_filter_xss() {
  header('Content-Type: text/plain; charset=utf-8');
  $GLOBALS['devel_shutdown'] = FALSE;
  if (!isset(
$_POST['text']) || !is_string($_POST['text']) || !isset($_POST['input_format']) || !is_string($_POST['input_format']) || !isset($_POST['token']) || !drupal_valid_token($_POST['token'], 'ckeditorAjaxCall', false)) {
    exit;
  }

```

I need to fix it.

Can I delete `ckeditor_filter_xss()`?

# Answer
If deleting any function from a contributed module works for you without giving any issues, then it's totally ok except that the next module update will override your change and you will have to delete the offending lines again. So the best course is to report this to the contributed module's developers, so they fix and commit necessary changes.

By the way, this seems to have already been reported on https://www.drupal.org/project/ckeditor/issues/2957580.
> 0 votes

---
Tags: 7, wysiwyg
---


title: Multiple Book Versions

text:
# Question
Title: Multiple Book Versions
I imagine this has been asked before, I'm just struggling to find the right answer.

Using Books to create documentation for an open source project. We're covering 3 domains, Users, Developers, and Admins. Easy enough.

Where I am struggling is how to create versions of these books for each software release. Do I just create a new book for every version? 1.0, 1.1, 1.2, etc? Should I be using a taxonomy vocab for the releases? What is a manageable way to handle this?

# Answer
> 0 votes
Documentation can be done in many different ways using different modules. If you decided to go with Books, then it is really up to you to create new books or taxonomies for new releases. Look at how Drupal's documentations is organized on https://www.drupal.org/documentation.

---
Tags: nodes, taxonomy-terms
---


title: Remove taxonomy page navigation pages

text:
# Question
Title: Remove taxonomy page navigation pages
I've a taxonomy page of a company which should show all nodes pages with this term.

I want that this page list at least 20 or so nodes, then we will need to click 1 or 2 or 3 to go to next levels.

Currently you can see every page is listing only single node. How to change this behavior?

# Answer
> 1 votes
I think your view is setup to show 1 node per page.

> 1. Go into views `admin/build/views`
> 2. Choose the view that is used for those pages most probably `taxonomy_term` view
> 3. On `basic settings: use pager` click on the cogwheel and change the items from 1 to 20 items per page
> 4. After saving this setting the basic setting should look like the following image

---
Tags: 6
---


# Question
Title: Disable cache during development: Templates are not discovered
I have followed all steps reported on https://www.drupal.org/node/2598914. However, if I create an new template file in my theme folder, it does not get discovered until I flush the cache manually via `drush cr`.

Is rebuilding the cache a must to discover new templates, or can I optimize the developer settings to auto-discover templates during development?

# Answer
> 0 votes
try add this in .htaccess (drupal root)

```
    <IfModule mod_headers.c>
       //ADD THIS
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires 0
    </IfModule>

```

---
Tags: caching
---


title: Blank search should show all results

text:
# Question
Title: Blank search should show all results
I remember that, in previous versions of the Search API and Search API Solr, by default not entering any search term would return the entire list of items.

I have tried with new empty Drupal 8.5.1 using Search API and Search API Solr, using the default configuration, with MariaDB and Postgresql, using the default view pages /search/content and /solr-search/content, but it shows an empty list and the message *Please enter some keywords to search.* message.

Does somebody know how to change it to the previous behavior to get again the whole list of elements when no search terms are used?

# Answer
> 3 votes
After trying everything that I could figure out, I have uninstalled the module, deleting all the views and installing it again and it works. No idea about what was happening sorry, but it work.

---

Finally thanks for some help I could understand what was happening :D The Filter Criteria Fulltext search was a Required, if you remove the checkbox then you will get the full list of items by default.

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


# Question
Title: Reason for adding .value to access node id?
I was trying to access node id in twig. After debugging for a while I found that `node.nid` was holding the value I wanted. However, when I tried to render using that variable it didn't print anything. After struggling for while I found that I need to append `.value` in the end which obviously worked. But I am not sure reason behind using `.value`. Can someone tell me when and where should we use such?

# Answer
Short answer: Because `nid` is a field and you want to get the field value.

Long answer: Node is like User or Taxonomy Term an entity and provides the method `id()`. So instead of accessing the id fields by their individual field name (nid, uid, tid), it's easier and better OOP practice to use the method EntityInterface::id:

```
{{ node.id }}

```
> 4 votes

---
Tags: theming
---


# Question
Title: How will I access inner fields values in twig template
I want to access 'name' key in the given image, but when I am trying with this `author_picture['#user'].contents.name` its showing nothing.

# Answer
> 2 votes
Similar question for the node id from today Reason for adding .value to access node id?

Either add `.value` to the field name

```
{{ author_picture['#user'].name.value }}

```

or use a specific method if the entity provides one:

```
{{ author_picture['#user'].getdisplayname }}

```

It is preferable to use User:getDisplayName because it does extra processing:

> By default, the passed-in object's 'name' property is used if it exists, or else, the site-defined value for the 'anonymous' variable. However, a module may override this by implementing hook\_user\_format\_name\_alter(&$name, $account).
>
> **Return value**
>
> string|\Drupal\Component\Render\MarkupInterface Either a string that will be auto-escaped on output or a MarkupInterface object that is already HTML escaped. Either is safe to be printed within HTML fragments.

---
Tags: 8, theming
---


# Question
Title: How do I view the maintenance page without putting the site in maintenance mode?
I've just been asked by the stakeholder of a site I'm working on how he can view the maintenance page of his site so he can test links on it without putting the site in maintenance mode.

I'm going to suggest that we do this in a lower environment, since the info is the same but is there any way to do this?

# Answer
By default there is no route to access the maintenance page via url. You can create a menu item and the corresponding page callback in your module :

```
// Access maintenance page regardless of the maintenance mode.
$items['maintenance'] = array(
  'title' => 'Maintenance',
  'page callback' => 'yourmodule_maintenance_page',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK
);

yourmodule_maintenance_page () {
  // Just use the internal status code to make Drupal load the apropriate theme and template.
  return MENU_SITE_OFFLINE;
}

```

And that's all, go to /maintenance to see the page.

You may also want to override the '*maintenance\_page*' theme, have a look at :

* the base preprocess function in `includes/theme.maintenance.inc`
* base template file in `modules\system\maintenance-page.tpl.php`
> 4 votes

# Answer
Another way to do it is to add the following code to your settings.php file

```
if (isset($_GET['maintenance'])) {
   $conf['maintenance_mode'] = TRUE;
}

```

Then go-to 'your\_domain/?maintenance=1' and you'll be in maintenance mode.
> 2 votes

---
Tags: 7, maintenance-mode
---


title: Passing form value into batch process

text:
# Question
Title: Passing form value into batch process
I have a form that is used to trigger a bulk operation and add a node for each of the currently registered users on the site. This is all working well, but I'd like to pass form data from BulkAddForm.php to the batch operation in BulkAddNode.php

If is were to setup a variable called $year in BulkAddForm which contained form state. How would I then use it in a line like this...

```
'title' => 'Perf-plan-' . $year . '-' . $user->get('field_user_employeeid')->value,

```

**BulkAddForm.php**

```
<?php
 namespace Drupal\create_perf_plan_for_new_year\Form;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
/**
 * Class BulkAddForm.
 *
 * @package Drupal\create_perf_plan_for_new_year\Form
 */
class BulkAddForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bulk_add_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['perfPlanYear'] = array(
      '#type' => 'textfield',
      '#title' => 'Year Tag (1819 for instance)',
    );
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Create new Performance Plans'),
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $uids = \Drupal::entityQuery('user')
      //->condition('type', 'batch')
      ->sort('created', 'ASC')
      ->execute();
    $batch = array(
      'title' => t('Bulk Add happening within the Bulk Add Form file...'),
      'operations' => array(
        array(
          '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAdd',
          array($uids)
        ),
      ),
      'finished' => '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAddFinishedCallback',
    );
    batch_set($batch);
  }
}

```

**BulkAddNode.php**

```
<?php
namespace Drupal\create_perf_plan_for_new_year;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
use Drupal\Core\Url;

class BulkAddNode {

    public static function bulkAdd($uids, &$context){
    $message = 'Bulk add happening in functional file...';
    foreach ($uids as $uid) {
        $user = \Drupal\user\Entity\User::load($uid);
        \Drupal\node\Entity\Node::create([
            'type' => 'perf_plan',
            'title' => 'Perf-plan-' . '1718' . '-' . $user->get('field_user_employeeid')->value,
            'uid' => $user->id(),
            'field_employee_uid' => $user->id(),
            //'field_supervisor_uid' => $user->get('field_supervisor')->first()->getValue()['target_id'], //Brilliant means of getting entity reference UID from User. SM
            //'field_director_uid' => $user->get('field_director')->first()->getValue()['target_id'],
          ])->save();
    }
    $context['message'] = $message;
  }

function bulkAddFinishedCallback($success, $operations) {
    if ($success) {
      $message = 'Performance plan added.';
    }
    else {
      $message = t('Encountered an error during bulk performance plan creation.');
    }
    drupal_set_message($message);
  }
}

```

# Answer
> 1 votes
You can pass variables to the batch process by doing the following...

```
     $year = "2018";
     $batch = array(
          'title' => t('Bulk Add happening within the Bulk Add Form file...'),
          'operations' => array(
            array(
              '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAdd',
              array($uids, $year)
            ),
          ),
          'finished' => '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAddFinishedCallback',
        );

```

Year in this case can obviously be anything... a piece of $form\_state for instance also works.

You could then change

```
public static function bulkAdd($uids, $year, &$context){
    $message = 'Bulk add happening in functional file...';
    foreach ($uids as $uid) {
        $user = \Drupal\user\Entity\User::load($uid);
        \Drupal\node\Entity\Node::create([
            'type' => 'perf_plan',
            'title' => 'Perf-plan-' . $year . '-' . $user->get('field_user_employeeid')->value,
            'uid' => $user->id(),
            'field_employee_uid' => $user->id(),
            //'field_supervisor_uid' => $user->get('field_supervisor')->first()->getValue()['target_id'], //Brilliant means of getting entity reference UID from User. SM
            //'field_director_uid' => $user->get('field_director')->first()->getValue()['target_id'],
          ])->save();
    }
    $context['message'] = $message;
  }

```

Hope this helps. It took me a while to figure out where in the batch array structure this needed to be placed. I didn't find the docs particularly helpful.

---
Tags: forms, batch-operations
---


# Question
Title: How do I get total webform submission count of multiple webforms?
I am able to get the webform submission count total for single webforms, but when I filter for multiple webforms (using the OR operator) it only shows the total count for 1 of the webforms. How can I have Views add the counts for all of the webforms I filter?

# Answer
I found a solution to my problem - albeit not using Views - to accomplish what I wanted to do.

My goal was to have a counter on a page where it showed how many submissions for certain forms have been submitted. I needed to show a combined total of 2 or more webforms but could not accomplish this with Views.

I did find this code that led me to my solution:

First, need to include webform\_submissions:

```
module_load_include('inc', 'webform', 'includes/webform.submissions');

```

Then added this line:

```
webform_get_submission_count($nid, $uid = NULL)

```

I took out the $uid as I did not need to filter by user and made multiple calls for the different webforms I needed:

```
$a = webform_get_submission_count($node->nid = '6');
$b = webform_get_submission_count($node->nid = '7');

```

I then put the following line to add the 2 variables to get me the total that I can then use on my page:

```
$c = $a + $b;

```

This solutions was actually better for me because with Views I could never get the No Results Behavior to show **0** when there were no submissions.
> 0 votes

---
Tags: views, webforms
---


# Question
Title: Hide 'successfully added to cart' message
I use commerce checkout on a Drupal site but it is primarily an information site. So I effectively want to hide the cart from the user.

This means that on addition of a product to the cart, I want to remove the Drupal message *'Product' added to your cart*.

This can't just be hidden in CSS because we want other checkout messages to still be visible.

# Answer
> 7 votes
I'm pretty sure that's just set by a rule called "Display an Add to Cart message".

You should be able to delete/disable that rule in the UI and the message will disappear.

# Answer
> 0 votes
@Clives's answer is correct and for those looking for Ctrl + C and Ctrl + V

```
/**
 * Disable adding to the cart the messages.
 */
function HOOK_update_7000() {
  $rules_config = rules_config_load('commerce_cart_add_to_cart_message');
  $rules_config->active = FALSE;
  $rules_config->save();
}

```

---
Tags: 7, commerce
---


# Question
Title: How do I display file and description field when multiple files are uploaded in a view?
I am using Field Collection module to display title and files all together. When I upload multiple files, the description field for each file is enabled, but it is replacing the uploaded filename.

>

I want to display both the file and description for each file in the view, not replace the description with the filename.

How can I do this? sample format image:

# Answer
> 0 votes
This issue isn't related directly to `Field collection`, it happens with core `File` fields too.

The tricky part of this question is the "multiple field values". In fields that have multiple values (more than one file allowed to upload into one field) the `delta` counts the file position (0 for first file, 1 for second etc). File descriptions are related to `delta` so the system can know which description is related to which file.

But the problem is working with `delta` in Views, you can't do all sorts of filtering and matching relating to it. For example if you create a View of type `File` you can't seem to match the description of the file (stored in the field database table) with the file (stored in the file database table). You can display either descriptions for all files uploaded to the field a particular file is uploaded to, or limit to only one value, but then you get the same description displayed for all files, which isn't correct.

## The solution

is to create Views of type `Content` (not `File`) because there you can rely on the field option "Multiple field settings" set to **Not** "Display all values in the same row". This means that each file from the field will be displayed in its own individual views row, and file descriptions will match correctly.

Here are the steps to create a list of Files showing both the file name and file description:

* Create a View of type `Content`. Use filters and sorting applicable to your particular case.
* Add a new field `File` from the `Content` category
    + Set the `Formatter` of this field to `Generic file`
    + Make sure that this field **doesn't** have the option "Display all values in the same row" enabled under "Multiple field settings"
    + Under `Rewrite results` enable the option `Override the output of this field with custom text`,
    expand the `Replacement patterns` and copy the code for the file description, it will be something like `{{ field_file__description }}`, paste that code into the text area above
    This will give you the file description as text, not linked to anything
* Add a new Relationship `File (field_file:target_id)` (it will be named `file from field_file`)
* Add a new Field `Filename` from the `File` category, it will be automatically set to use the Relationship from the previous step
    + Set its `Formatter` to `File link`. Now you have your linked file.

### Relationship:

### Fields:

### Views Results:

---
Tags: files
---


# Question
Title: What is the difference between creating fields programmatically and by exporting settings?
We are developing a custom app with decoupling approach. There are going to be many custom entities with fields. What is your preferred way to create fields programmatically, so we have all information in the code and can build our custom logic on it? So far I have identified three ways how to do it:

1. using the `BaseFieldDefinition::create` in the entity class.
2. using `.yaml` files in the modules `config/install` directory
3. using Features

With the first option, there is a problem that Workflow modules, which would be helpful, does not support the creation of the entity fields in the code (see https://www.drupal.org/project/workflow/issues/2960185). However, we can still replace Workflow module with custom entities and logic.

With other two options I am not entirely sure **what are the pros and cons** of using them. They just seem to me quite difficult to add custom logic, and/or methods to entities or create new field types (plugins).

Any suggestions will be much appreciated.

# Answer
For modules common practice is to define base fields with the first option and bundle fields with the second option. Concerning option 3 most use cases of Features are now covered by the configuration management, which you can use to synchronize fields configured in UI to a cloned site. Not only those fields created in UI , but also base fields from option 1 in case they are overridden or bundle fields installed by option 2 if they are modified in UI.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How do I remove a node from the front page after a certain period of time?
Can I use the Rules module to remove a node from the front page after a period of time determined by the administrator user when creating the node?

# Answer
> 0 votes
Use the Rules module together with `Rules Scheduler` (a sub-module of it), as explained in the steps below. These steps are based on the assumption that your content type is `article` (adapt to whatever else fits).

### Step 1: Create a field to store the expiration date

Add a field to the article content type (to store the "expiration" date), with these specs:

* Machine name (say) `field_expiration_date`.
* Use "date" as field type, for which the date module (and data API) needs to be enabled first.
* Allow only 1 date.

### Step 2: Create a Rules Component

Here is the **Rules Component** to be created (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_unpublish_a_node" : {
    "LABEL" : "Unpublish a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_to_be_unpublished" : { "label" : "Node to be unpublished", "type" : "node" } },
    "DO" : [ { "node_unpublish" : { "node" : [ "node-to-be-unpublished" ] } } ]
  }
}

```

If you do not want the node to be unplublished, you can also replace the Rules Action by another one to just perform a "remove sticky" for the node.

### Step 3: Create a Rule using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste, then "enable" the rule also):

```
{ "rules_schedule_the_unpublish_of_a_node_as_requested_by_author" : {
    "LABEL" : "Schedule the unpublish of a node as requested by author",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_expiration_date" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_unpublish_a_node",
          "date" : [ "node:field-expiration-date" ],
          "identifier" : "Unpublish-node-[node:nid]",
          "param_node_to_be_unpublished" : [ "node" ]
        }
      }
    ]
  }
}

```

Note that the above rule refers to the *Rules Component* from the previous step. Make sure to only perform the import of this rule only **after** you completed step 1, if not the import will fail ... Should you want to use another machine name, then change `field_expiration_date` in the rule above to what you prefer, prior to importing this rule.

**Be aware**: the above rule is only triggered once, i.e. when the node (of type article) is first created (as in the question). It will right away schedule the unpublish of the node (as requested in the expiration date). If the node gets edited later on, and/or the expiration date is changed afterwards: too bad, that won't change anything to when the scheduled unpublish is going to happen.

---
Tags: rules
---


# Question
Title: Automatically create redirect for a file when the file is renamed?
When a file is renamed in the file upload widget and the other file is set to temporary, is there any mechanism in the background happening with the Redirect module to create a redirect from the old filepath to the new one that was renamed?

Example, foo.pdf in a file widget, I remove it and upload foo.pdf again. foo.pdf is now called foo\_0.pdf - but links that linked to the old filename in the site still exist, therefore is it possible to get those redirected to this one?

edit: linking to related dilemma.

# Answer
Using hook\_node\_presave get the url of the old one (foo.pdf) and the new url of the new one (foo\_0.pdf) and then create a new redirect as shown by 4k4 here.

To get the orignal value (ex: title), I know in D7 you can with `$node->original->title` not sure if this still works on D8, have not yet tried it.

Also, since your url ends with .pdf I am not sure if this will work, but hopefully it will.
> 1 votes

# Answer
This module works for me: https://www.drupal.org/project/media\_entity\_download

Media entity download seeks to solve a content management issue when dealing with files and media by linking to the media/{media\_id}/download route, none of the above really matters. Linking content to media/{media\_id}/download will always fetch and return the right file without worrying that its the incorrect one, or outdated, or a unique url (document\_0.pdf).
> 0 votes

---
Tags: 8, files, redirection
---


title: I cannot modify entity values

text:
# Question
Title: I cannot modify entity values
I have installed the Views Bulk Operations module and am looking to use it to mass edit my content. However, when I select a few nodes to edit and select Modify Entity Values and click Execute, I get taken to a page that simply says, "The website encountered an unexpected error. Please try again later."

Unfortunately, my server logs and Drupal logs come up empty as to what error may have occurred.

Additionally, it seems like when I select Modify Entity Values, I should see an option for what entity value I am looking to modify but I am never presented with that option.

As an alternative, I found a guide that demonstrates how to replicate this behavior with Rules components but I have not yet been able to figure out how to make this work with taxonomy terms.

I would prefer however, to simply get the Views Bulk Operations to work as I would expect.

# Answer
> 0 votes
I finally managed to get this working. Under show available tokens, I previously had selected -- All --.

I have since changed this to be just the fields that I'm interested in having edited and it works as expected now.

My theory is that I have a lot of content types with a lot of fields and it was hitting some sort of memory error. However, I never saw an error reported.

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


# Question
Title: Error when trying to migrate comments to a clean D8 site: What's wrong with my .yml file?
I'm trying to migrate content from my current D7 site to a Drupal 8 installation.

I've managed to import some of the nodes, and now I want to import the comments for those nodes.

Every time I click on "run" (.../admin/structure/migrate/manage/importarComentarios/migrations/importar-comentarios/process/run) I get an error:

**What am I doing wrong?**

## This is my migrate\_plus.migration.importarComentarios.yml file:

id: importar-comentarios label: Comments

migration\_tags: \- CSV

migration\_group: importarComentarios

```
source:
  plugin: csv
  path: 'public://csv/exportar-comentarios-genericos.csv'
  header_row_count: 1
  delimiter: ','
  enclosure: '"'
  keys:
    - id
  column_names:
    0:
      nid: 'nid'
    1:
      created: 'created'
    2:
      body: 'body'
    3:
      autor: 'autor'
    4:
      cid: 'cid'
    5:
      titulo: 'titulo'
    6:
      mail: 'mail'

destination:
  plugin: entity:comment

process:
  entity_id: nid
  subject: title
  'comment_body/value': body
  'comment_body/format':
    plugin: default_value
    default_value: "html"
  # Migrate our custom field
  field_mail: mail
  field_nombre: autor
  status:
    plugin: default_value
    default_value: '1'
  created: created
  nombre: autor
  email: mail
  # The comment type (aka the comment's bundle).
  comment_type:
    plugin: default_value
    default_value: 'comentario'
  # The type of entity we're attaching this comment to.
  entity_type:
    plugin: default_value
    default_value: 'node'
  # The field we should attach this comment to. This is a field on your node.
  field_name:
    plugin: default_value
    default_value: 'comentarios'

migration_dependencies: {}

```

## And this is the migration overview:

This is the overview

This is the destination

This is the process

And when clicking the source, I get:

> The website encountered an unexpected error. Please try again later.

## My configuration is:

My content type is called contenido

And these are the fields of my comments

And my contenido content type has a comentarios field for comments

# Answer
> 0 votes
```
  keys:
    - id

```

The yml is using a key 'id' that is not defined in the column\_names. Since you have a 'nid' column, I suggest changing 'id' to 'nid'.

---
Tags: 8, migrations
---


# Question
Title: How to display the user name that created the profile (the owner or author of the profile)?
I have a site with Drupal 8 and I want to customize the templates of my pages.

I use the module:

Here is my template to customize the profile page:

```
{#
/**
 * @file
 *
 * Default theme implementation for profiles.
 *
 * Available variables:
 * - content: Items for the content of the profile.
 *   Use 'content' to print them all, or print a subset such as
 *   'content.title'. Use the following code to exclude the
 *   printing of a given child element:
 *   @code
 *   {{ content|without('title') }}
 *   @endcode
 * - attributes: HTML attributes for the wrapper.
 * - profile: The profile object.
 * - url: The profile URL, if available.
 *
 * @ingroup themeable
 */
#}
<div{{ attributes.addClass('profile--personnel--teaser') }}>

  <div class="views-row">

    <h3 class="views-teaser-title">
      {{ ??? USERNAME ??? }}
    </h3>

  </div>

</div>

```

How to display the user name that created the profile (the owner of the profile) ?

# Answer
> 1 votes
You can get from `getOwner()` method

```
  {{ profile.getOwner().name.value }}
  {{ profile.getOwner().mail.value }}

```

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


title: How can I user_access()?

text:
# Question
Title: How can I user_access()?
How can I use `user_access()` in Drupal 8?

# Answer
The simple answer is, you can't. It doesn't exist in D8. The longer answer is you use a method on the current user as follows:

```
\Drupal::currentUser()->hasPermission([PERMISSION NAME]);

```

You can read the change record here: https://www.drupal.org/node/2049309
> 3 votes

---
Tags: 8
---