title: How to use sprintf in Url::fromUri?

text:
# Question
Title: How to use sprintf in Url::fromUri?
I am trying to convert this from D7 to D8:

```
l(drupal_strtoupper($field),
sprintf('http://finance.google.com/finance?q=%s',
$exchange . ':' . $field),
array('attributes' =>
array('target' => '_blank',
       'title' => (drupal_strlen($title)) ? $title : $field)
)
);

```

I am doing this and it produced error:

```
return Link::fromTextAndUrl(Unicode::strtoupper($field), Url::fromUri(sprintf('http://finance.google.com/finance?q=%s'),$exchange . ':' . $field))->toString();

```

> InvalidArgumentException: The URI '' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 281 of core/lib/Drupal/Core/Url.php)

# Answer
It doesn't really make sense to use `sprintf` (or any other string formatting/replacement functions) here - the API can already accommodate what you need in a much more structured manner:

```
$options = ['query' => ['q' => $exchange . ':' . $field]];
$url = Url::fromUri('http://finance.google.com/finance', $options);
$link = Link::fromTextAndUrl(Unicode::strtoupper($field), $url);

```
> 2 votes

---
Tags: 8
---


# Question
Title: Problems upgrading Media from 8.3 to 8.5
I have a Drupal 8.5.3 site (built from the composer project) that was previously on the 8.3 branch before the critical security updates forced me to update to 8.5. One of the things I missed in the upgrade is that the Media module has moved to core and has its own upgrade instructions. So as I look through those instructions, I have steps 1-5 covered and need to upgrade the codebase. I should also say that the site has heavy usage of the Media module with content and paragraph fields.

So after going through the process\[1\] of getting the right versions of the right modules in place, when I try to `updb`, I get this error message:

```
In order to run the Media Entity 2.x upgrade, please uninstall and remove from the codebase the contributed "Media" module.
Before continuing, please make sure all modules that provide plugins for Media Entity (or depend on it) have their code updated to their respective 2.x branches. Note that you will probably need to revert to the 1.x branch of the Media Entity module if you want to uninstall existing plugin modules. The following modules depend on media entity and need to be either upgraded or uninstalled: media.

```

If I do a `cr` or try to `pm-uninstall media`, I get a long error message\[3\].

What am I doing wrong, and how can I get updated? I feel like this is quite a mess and I wonder if it'd be better to spin up a new 8.5.3 site and migrate content over. Though I'm sure I would run into configuration problems with my existing sets of media fields.

## Update

Thanks to @sonfd's clue, I was finally able to get this upgraded. It was a pretty tedious process that I'm going to lay out in a blog post soon.

## Update 2

Wrote up a blog post to lay out how I resolved this issue. Maybe it will help others. Definitely lays out my newly-gained scar from not reading upgrade instructions and changelogs more closely.

\[1\]:

```
/usr/bin/php -d memory_limit=-1 /usr/local/bin/composer remove drupal/media
# (NOTE: If I don't remove drupal/media first, I get a composer install error[2])
/usr/bin/php -d memory_limit=-1 /usr/local/bin/composer require \
  drupal/inline_entity_form drupal/crop:2.x-dev drupal/media_entity_instagram:2.x-dev \
  drupal/media_entity:2.x-dev drupal/media_entity_slideshow:2.x-dev \
  drupal/media_entity_twitter:2.x-dev drupal/slick_media:2.x-dev \
  drupal/media_entity_actions
/usr/bin/php -d memory_limit=-1 /usr/local/bin/composer remove drupal/video_embed_field
/usr/bin/php -d memory_limit=-1 /usr/local/bin/composer update
/usr/bin/php -d memory_limit=-1 /usr/local/bin/composer require drupal/media

```

\[2\]:

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - drupal/image_widget_crop 2.1.0 requires drupal/crop 1.0 - 2.0 -> satisfiable by drupal/crop[1.x-dev].
    - drupal/image_widget_crop 2.1.0 requires drupal/crop 1.0 - 2.0 -> satisfiable by drupal/crop[1.x-dev].
    - drupal/image_widget_crop 2.1.0 requires drupal/crop 1.0 - 2.0 -> satisfiable by drupal/crop[1.x-dev].
    - Can only install one of: drupal/crop[1.x-dev, 2.x-dev].
    - Installation request for drupal/crop 2.x-dev -> satisfiable by drupal/crop[2.x-dev].
    - Installation request for drupal/image_widget_crop (locked at 2.1.0) -> satisfiable by drupal/image_widget_crop[2.1.0].

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

```

\[3\]:

```
$ ../vendor/bin/drush pm-uninstall media
Error: Call to a member function addConstraint() on null in          [error]
media_entity_type_alter() (line 72 of
/Users/jason/Sites/artobject/web/modules/contrib/media/media.module)
#0
/Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Extension/ModuleHandler.php(539):
media_entity_type_alter(Array, NULL, NULL)
#1
/Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Plugin/DefaultPluginManager.php(333):
Drupal\Core\Extension\ModuleHandler->alter('entity_type', Array)
#2
/Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Entity/EntityTypeManager.php(117):
Drupal\Core\Plugin\DefaultPluginManager->alterDefinitions(Array)
#3
/Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Plugin/DefaultPluginManager.php(175):
Drupal\Core\Entity\EntityTypeManager->findDefinitions()
#4
/Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Entity/EntityTypeRepository.php(83):
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions()
#5
/Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Entity/Entity.php(523):
Drupal\Core\Entity\EntityTypeRepository->getEntityTypeFromClass('Drupal\\user\\Ent...')
#6
/Users/jason/Sites/artobject/vendor/drush/drush/lib/Drush/User/User8.php(26):
Drupal\Core\Entity\Entity::load(0)
#7
/Users/jason/Sites/artobject/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php(558):
Drush\User\User8->load_by_uid(0)
#8
/Users/jason/Sites/artobject/vendor/drush/drush/includes/bootstrap.inc(354):
Drush\Boot\DrupalBoot->bootstrap_drupal_login()
#9
/Users/jason/Sites/artobject/vendor/drush/drush/includes/bootstrap.inc(473):
drush_bootstrap(6, 6)
#10
/Users/jason/Sites/artobject/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(59):
drush_bootstrap_to_phase(6)
#11
/Users/jason/Sites/artobject/vendor/drush/drush/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#12 /Users/jason/Sites/artobject/vendor/drush/drush/drush.php(12):
drush_main()
#13 {main}.
Error: Call to a member function addConstraint() on null in /Users/jason/Sites/artobject/web/modules/contrib/media/media.module on line 72 #0 /Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Extension/ModuleHandler.php(539): media_entity_type_alter(Array, NULL, NULL)
#1 /Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Plugin/DefaultPluginManager.php(333): Drupal\Core\Extension\ModuleHandler->alter('entity_type', Array)
#2 /Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Entity/EntityTypeManager.php(117): Drupal\Core\Plugin\DefaultPluginManager->alterDefinitions(Array)
#3 /Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Plugin/DefaultPluginManager.php(175): Drupal\Core\Entity\EntityTypeManager->findDefinitions()
#4 /Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Entity/EntityTypeRepository.php(83): Drupal\Core\Plugin\DefaultPluginManager->getDefinitions()
#5 /Users/jason/Sites/artobject/web/core/lib/Drupal/Core/Entity/Entity.php(523): Drupal\Core\Entity\EntityTypeRepository->getEntityTypeFromClass('Drupal\\user\\Ent...')
#6 /Users/jason/Sites/artobject/vendor/drush/drush/lib/Drush/User/User8.php(26): Drupal\Core\Entity\Entity::load(0)
#7 /Users/jason/Sites/artobject/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php(558): Drush\User\User8->load_by_uid(0)
#8 /Users/jason/Sites/artobject/vendor/drush/drush/includes/bootstrap.inc(354): Drush\Boot\DrupalBoot->bootstrap_drupal_login()
#9 /Users/jason/Sites/artobject/vendor/drush/drush/includes/bootstrap.inc(473): drush_bootstrap(6, 6)
#10 /Users/jason/Sites/artobject/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(59): drush_bootstrap_to_phase(6)
#11 /Users/jason/Sites/artobject/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#12 /Users/jason/Sites/artobject/vendor/drush/drush/drush.php(12): drush_main()
#13 {main}
Error: Call to a member function addConstraint() on null in media_entity_type_alter() (line 72 of /Users/jason/Sites/artobject/web/modules/contrib/media/media.module).

```

# Answer
> 1 votes
It seems that you need to uninstall and remove from the codebase the contrib media module before doing this update.

On the contrib media module's project page they state:

> Drupal core version 8.4 now includes a media module with similar functionality. In #2831274: Bring Media entity module to core as Media module core adopted media namespace to add support for full-featured media entities. In case you are using the 8.3.x contrib media on your sites you need to uninstall it and remove it from the codebase before updating to Drupal 8.4.

---
Tags: 8, media
---


title: content relationship in views

text:
# Question
Title: content relationship in views
I have a view and I need to relate contents, the problem is that you do not show me the data. Two contents: 1. productions, 2. functions (theater). the functions are related to the productions, but inversely not.

I need to create a cover of productions, which contain the dates of the functions with the link of your purchase.

example:

Manage Field: functions

products, they have no related field Thank you very much!

Add a similar problem, on the same types of content. Is list of productions:

I can not add a list with this design. Add views

thanks

# Answer
> 1 votes
You can introduce `functions` fields into your `productions` views by adding a Relationship through the Entity reference field.

1. Add a new Relationship **Content referenced from field\_production\_content**
2. Add a new Field `field_date_functions` and set it to use the Relationship `field_production_content`
3. Add a new Field `field_tiket_link_functions` and set it to use the Relationship `field_production_content`

If I understood your structure correctly you'll see functions fields on their related functions nodes in Views results.

---
Tags: 8, views
---


title: Update user when node is created

text:
# Question
Title: Update user when node is created
I'm new in Drupal 8 and I need to update the user when a node of a specific content type is created or updated. I did some searching and I find **hook\_entity\_create** but this hook Act when **creating** a new entity

# Answer
> 3 votes
```
/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function MYMODULE_node_insert(Drupal\node\NodeInterface $node) {

  if($node->bundle() == 'article') { //check for a content type, ex: article
    $user = \Drupal\user\Entity\User::load($uid); // load the user
    $user->set('field_name', $some_value); // set a value for a particular field
    $user->save();
  }

}

```

Originally I wrote:

`MYMODULE_node_create(Drupal\node\NodeInterface $node) {`

Changed it as per the comment below.

# Answer
> 0 votes
You can use *Rules* module (in alpha) to perform some actions after new content or updated content is saved.

# Answer
> 0 votes
I'm not sure that I clearly understand your needs, but the `hook_node_presave` lets you the option to take a different action if it's a new or an updated node. Of course, it is always a good idea to wrap it in a `try catch`.

```
/**
 * Implements hook_node_presave().
 *
 * Acts on an node before it is created or updated.
 *
 * This hook is invoked from $node->save() before the node is saved to the
 * database.
 *
 * @param \Drupal\Core\Entity\EntityInterface $node
 *   The node that is being inserted or updated.
 *
 */
function MYMODULE_node_presave($node) {
  // If it is the wanted content type ...
  if($node->getType() === 'my_wanted_type') {
    // ... and if what you need is the current user ...
    $user = \Drupal::currentUser();
    // ... check if it is a new or an updated node
    $operation = $node->isNew() ? 'create' : 'update';
    // ... and call the function that will handle your needs.
    updateUserOnNodeSave($user, $operation);
  }
}

function updateUserOnNodeSave($user, $operation) {
  if(null != $user) {
    if($operation === 'create') {
      // do something meaningful with $user
    }
    elseif($operation === 'update') {
      // do something meaningful with $user
    }
    $user->save();
  }
}

```

---
Tags: 8, nodes, users
---


title: views expose filter by taxonomy

text:
# Question
Title: views expose filter by taxonomy
I have this structure :

* mobile

+ Lg
        - V10
        - V20
    + Samsung
        - A7
        - J5
    + Nokia
        - 1100
        - 1110
* laptop ...
* tablet ...

How can I create that with view expose filter? (step by step filter)

# Answer
You can do this with the special type of filter `Has taxonomy terms (with depth)`.

1. Add a new Filter **Has taxonomy terms (with depth)**
2. Select your Vocabulary in the new filter settings,
Selection type: **Dropdown**
**Show hierarchy in dropdown**
Depth **2** (this will include 2 levels of children of a chosen term)
3. **Expose this filter to visitors, to allow them to change it** and **Apply**

You will get a drop-down that shows your terms with hierarchy.

If you don't want a dropdown you can use a module like Better exposed filters to use radio buttons instead.
> 0 votes

---
Tags: views
---


# Question
Title: Shopping cart contents section is empty for anonymous users
there is a problem in my eshop (build with latest D7 and commerce 1.14) in checkout page where the "Shopping cart contents" section is empty for anonymous users.

I checked the permission "View any type of products" for anonymous users but didn't fix the problem

Any ideas?

Thanks

# Answer
This is almost always due to some sort of relationship in the View's configuration linking from the cart order's line items to some other entity the user doesn't have direct access to view. Rather than try to find the right permissions, the easiest thing to do assuming you have other filters (or contextual filters) on the View to ensure the customer doesn't see other data is to disable SQL rewriting under the advanced settings for the View.

On a hunch, though, you should also make sure anonymous users have access to view their own orders. We have special code in the cart module to ensure access control works in that situation, and it could be the entire order is inaccessible and not just some related entity.
> 1 votes

---
Tags: commerce
---


title: D8 can't see module

text:
# Question
Title: D8 can't see module
Using the drupal console I created a module in a `/sites` subdirectory - because I want that module to be available only during development.

The creation process worked.

I tried to create a controller using the console and it said there was no such module. I tried enabling the module: no such module. Using:

```
drupal debug:module --type=no-core

```

listed the one other module I've created which is in `/modules`.

(Yes, I cleared caches.)

# Answer
> 0 votes
The only valid places for modules to live are:

* /modules
* /sites/foo\_site/modules/ (modules here will only be available when you list modules for that site specifically)
* /profiles/foo\_profile/modules (modules here will only be available when the site has been installed with this profile)

Anywhere else and Drupal won't find them. There's more information on the Installing Drupal 8 Modules page.

Disabling a module for a particular environment is something different, you handle it with configuration management rather than file system paths.

See How to prevent devel module to be installed on production enviroments? for the full picture.

---
Tags: 8
---


title: View button that links to current node

text:
# Question
Title: View button that links to current node
I'm trying to create this button in my views with a custom text, that needs to link to the current node.

I know you can use links and that works, but.. i need something like a variable that makes the link always go to the current node.

# Answer
The field `Content: Link` allows you to enter `Text to display`.

1. Add a new Field **Content: Link**
2. Under **Text to display** enter **Bestel nu**

Easy :)

For more complex changes you can use the "Rewrite the output of this field" option on the "Content: Link" field. It's more reliable to use this field than Path.

You can use "Global: Custom text" field to construct some output (also "Rewrite the output of this field") using the tokens for the fields listed above it, but it isn't necessary in this case.
> 0 votes

---
Tags: 7, views, nodes, navigation
---


# Question
Title: Display nodes that reference the same node than current page
I have a Drupal 8.5.3 installation. I'm struggling to fix this, I have read many threads but none is exactly what I need, or at least I'm not being able to solve it: I have 2 content types: A, and B. They both have an entity reference field that references to another content type, C. I'm trying to create a block view to embed into any node of type A a list of B nodes that reference to the same C node that the current A page.

In other words:

Content type A: Cities

Content type B: Brands

Content type C: Countries

If node Rome (A) has a field that references to Italy (C), I'd like to display on it all the brands (B) that have also a field that references to Italy (C).

I have tried using relationships, contextual filters, providing default values from URL, etc. But I'm unable to make it work. I've tried selecting my entity reference field as a relationship, and then adding a contextual filter of Content ID that uses that relationship. I have also tried some other combinations but it's not working. I would appreciate some help!

Thank you very much!

# Answer
It can be tricky to orient yourself around this, but it is a fairly common request to list sibling nodes according to whatever criteria (usually Taxonomy and Entity references).

The solution involving Entity references is to use two Relationships, one pointing to the common node (C), then another to point to the nodes that reference it (A) and then a Contextual filter that feeds the Views context on what node you're currently on (B).

1. Create Views listing your content A
2. Add a Relationship **Content referenced from field\_ref\_C**
3. Add another Relationship **Content using field\_ref\_C**, and set it to use the Relationship from the previous step **field\_ref\_C: Content**
4. Add a Contextual filter **ID** (from `Content` Category) and set it to use the second Relationship (**field\_ref\_C** the one from the previous step) with these options:
**When the filter value is NOT available:**
**Provide default value**
**Content ID from URL**
When the filter value IS available or a default is provided
Specify validation criteria (optional)
Content
\[your appropriate types - B\]
5. Add another Contextual filter **ID** but this time **Do not use a Relationship**:
**When the filter value is NOT available:**
**Provide default value**
**Content ID from URL**
**More: Exclude**

This will exclude the node you're currently viewing from the list.

If you want to check the output in Views Preview at this point enter the same node ID both times, for example to see what the block would output on node 14 enter `14/14`.

The first argument is taking the current node of type B and navigating through the connections, to the country C and back to content A you want to show, the second argument is excluding the current node from the list.
6. Place your block in a region shown only on content B, don't forget to set the option **Node from URL** on block settings.
> 13 votes

---
Tags: entities, views
---


# Question
Title: Inject service(s) into Drupal unit test?
I am writing a unit test upfront for a service that does not exist yet. Let's just say it is called `ResponseFormatter`.

I want to start adding unit tests for what I expect this service to do. How do I inject it to a UnitTestCase, or reference it?

Example, I am trying to do something like:

```
class FormatterTest extends UnitTestCase {

  /**
   * @dataProvider responses
   */
  public function testThisWorks($response, $expected) {
    // the following line I want to call a service,
    // ex. like $this->responseFormatter->format($string);
    $clean = html_entity_decode(strip_tags($response));
    $this->assertEquals($expected, $clean);
  }

  public function responses() {
    return [
      ['not-set', 'not-set'],
      ['<strong>foo</strong>', 'foo'],
      ['& #93 bar', '& #93 bar'],
    ];
  }
}

```

# Answer
> 9 votes
If your new service is sufficiently independent (it doesn't have any or many of it own dependencies), then just create it the `setUp()`. And then if you have dependencies, you set up mocks (also called doubles).

An example of a this in core is `TimeTest::setUp()` does:

```
protected function setUp() {
  parent::setUp();

  $this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
  $this->time = new Time($this->requestStack);
}

```

A mocked request stack is created, and the setup then directly instantiates the service class being tested (`Time()` in this case), passing in the mocked dependency to the constructor.

Then assertions in test methods are pretty simple

```
public function testGetRequestTime() {
  $expected = 12345678;

  $request = Request::createFromGlobals();
  $request->server->set('REQUEST_TIME', $expected);

  // Mocks a the request stack getting the current request.
  $this->requestStack->expects($this->any())
    ->method('getCurrentRequest')
    ->willReturn($request);

  $this->assertEquals($expected, $this->time->getRequestTime());
}

```

The mock simulates what the service's dependency would do, and then the service method is invoked directly.

If your service has a lot of dependencies, or mocking them is hard, then you should do a `KernelTest` instead of a `TestCase` or `UnitTest`. However, that may be an indication that your service is too complicated and needs to be broken up (I am also having a problem thinking of a core service that is kernel tested and not unit tested).

---
Tags: 8, testing
---


# Question
Title: How to include CSS from a vendor directory?
Is it possible to include CSS from a vendor directory? I need to include a CSS artifact from a Pattern Lab dependency.

Is it best to copy the artifact into the Drupal theme and just reference it that way?

# Answer
It's probably best to copy it, yes. Drupal isn't set up to serve any assets from the `vendor/` folder, and actively prevents it by default with an .htaccess file. Also, all assets are normally handled via "libraries", which are defined by a module and whose JS/CSS files must be in the module folder.

You could change the .htaccess and insert a direct style element with `/vendor/.../xyz.css` into the page, but at that point it's probably a lot cleaner and more secure to copy it.

If it changes often and you want to avoid manually copying/committing it every time, you might look at automating this with a build script (eg. with webpack).
> 4 votes

# Answer
If you are wanting to add a CSS file from an external source you can use Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

As part of our development process we use Gulp to take all the files (regardless of folder location) and aggregate them into a single minified CSS file so having a vendor/ folder where you take the minified CSS files and include them is totally doable. If the CSS file you are placing locally in your subtheme is not minified, you can Gulp to minify that as well.

Read through the different CSS properties to see what best fits your needs.
> 0 votes

# Answer
I just ran into this issue, and as I wasn't able to find a solution for it, I created the Vendor Stream Wrapper module, which creates a vendor:// stream wrapper that serves files from the vendor folder, even if it is outside the webroot. The module allows for using the vendor:// stream wrapper in \*.libraries.yml files.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How do I include a CSS library in my custom module?
I want to include the YAMM!3 CSS library in my Drupal 8 site. To that end, I wrote a custom module following the instructions in this answer. Although that answer is in regards to a php library, I thought it would also work for a CSS library.

This is the `composer.json` from my custom module:

```
{
  "name": "drupal/my_yamm3",
  "type": "drupal-module",
  "require": {
    "geedmo/yamm3": "*"
  }
}

```

In the `composer.json` in the root of my Drupal codebase, I have this:

```
"extra": {
    ...
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/custom/my_yamm3/composer.json"
        ],
    ...

```

I updated my codebase with this commands:

```
$ composer update
$ composer dumpauto

```

And I noticed this line in composer's output:

```
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Installing geedmo/yamm3 (1.1.0): Loading from cache

```

Which is confirmed by an examination of the filesystem:

```
$ ls vendor/geedmo/yamm3/
bower.json  composer.json  demo/  gulpfile.js  index.html  LICENSE.txt  package.json  README.md  yamm/

```

I've enabled the `my_yamm3` module on my site, and under `admin/config/development/performance`, I've disabled css aggregation.

However, when I load the page, I do not see the yamm libraries being loaded in the network tab in my browser.

Am I using the correct method to load a third-party css library? What am I doing wrong?

**EDIT** osman asked for some confirmation of the state of my environment. In my drupal project root, while I do have `/composer.json` and the directories `/drush/` and `/vendor/`, I don't have `/scripts/` nor `/web/`. I guess that means I am not using the `drupal-composer/drupal-project` project.

Regarding his recommended additions to `composer.json`, this is what I had:

```
"extra": {
    "installer-paths": {
        "core": ["type:drupal-core"],
        "modules/contrib/{$name}": ["type:drupal-module"],
        "profiles/contrib/{$name}": ["type:drupal-profile"],
        "themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"],
        "modules/custom/{$name}": ["type:drupal-custom-module"],
        "themes/custom/{$name}": ["type:drupal-custom-theme"]
    }
},

```

So again it looks like I don't have the composer project?

# Answer
> 3 votes
**Fundamentals**

To bind a CSS library into your Drupal installation, it should be defined and exposed via a \*.libraries.yaml file.

For example (taken from core's classy theme):

```
book-navigation:
  version: VERSION
  css:
    component:
      css/components/book-navigation.css: {}

```

defines that there is a library called `book-navigation` that when included in a page will deliver the `css/components/book-navigation.css` css file.

**Using composer with 3rd-party CSS libraries**

Composer works easily and reliably for PHP dependencies, using the `merge-plugin` in the way you started working in the OP. But, CSS and Javascript libraries, especially when some preprocessing or building step is required, are a different story. This is an open and unsolved (to my knowledge and to the date) problem, you can read this issue to get an idea of what problems arise:

The main problem is, that when you import the library as a composer dependency, as you did, the library is installed inside the `vendor` directory **wherever** that is located. So, you cannot assume much inside your \*libraries.yaml file about the file path to the CSS/JS file(s) you want to use.

**Alternative (A) without composer: using CDN / externally hosted libraries definitions**

For you case, and taken that you want to include this file:

```
https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css

```

you could define it inside your \*libraries.yaml file as an externally hosted library (see #external):

```
my_module.yamm3:
  remote:  https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css
  version: VERSION
  license:
    name: MIT
    url: https://github.com/geedmo/yamm3/blob/master/LICENSE.txt
    gpl-compatible: true
  css:
    theme:
      https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css : { type: external }

```

N.B.: This approach should always deliver the latest `yamm.css` version.

**Alternative (B) without composer: keeping a local copy in your own module's folder**

If you place the CSS file inside your module's folder, e.g. `css/yamm.css`, you will be able to use the following yaml definition in your \*.libraries.yaml file in order to be able to use it:

```
my_module.yamm3:
  version: VERSION
  css:
    theme:
      css/yamm.css : {}

```

**Attaching a library to page(s)**

Finally, after you are done defining your library, you can start using it.

This is documented extensively here (https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module) and I would recommend reading that if you haven't already.

Good luck!

# Answer
> 1 votes
More likely your `vendor` directory is off of the web root. Could you confirm that?

If you by any chance using `drupal-composer/drupal-project` project, it would have a folder structure like this:

```
/composer.json
/drush/
/scripts/
/vendor/
/web/
/web/core/
/web/libraries/
/web/modules/
/web/profiles/
/web/sites/
/web/themes/
...

```

The `libraries` folder is the folder you need your YAMM!3 CSS library placed in. So that it could be accessible via web also.

In my `composer.json` file I have Drupal specific folders defined in `extra.installer-paths`:

```
...
"extra": {
    "installer-paths": {
        "web/core": ["type:drupal-core"],
        "web/libraries/{$name}": ["type:drupal-library"],
        "web/modules/contrib/{$name}": ["type:drupal-module"],
        "web/profiles/contrib/{$name}": ["type:drupal-profile"],
        "web/themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"]
    }
}

```

With the help of `composer/installers` package and the configuration in `extra`, each package required by composer is copied to their own dedicated folders. So, yours could be copied into `libraries` folder.

Check out the code and documentation at https://github.com/drupal-composer/drupal-project

It should provide all the details for you to update your project to support what you need. Otherwise come back for more :)

# Answer
> 1 votes
Drupal 8 does not allow for an easy way to set up libraries that use files in the vendor directory. To get around this, I just created the Vendor Stream Wrapper module, which creates a vendor:// stream wrapper, allowing for linking to files in the vendor folder, even if it is outside the webroot.

---
Tags: 8, composer, theming
---


# Question
Title: Pre-populate an Entity Reference when Adding a Node : Based on URL Alias
I am trying to pre-populate an entity reference with a specific game node, when a profile node is added; based on URL of the game the add button is on.

The game node I want to reference in profile node is in the URL of the profile's add page.

By using views to contextually filter, matching the first portion of the url (the game node title), with a game node. Then to be used as the field's select list.

Only selection in drop down would make it seem pre-populated.

```
                         --

```

Two content types \- game \- profile

\*game nodes alias pattern is \[node:title\]. so just /game1/ , /game2/

I added an alias for each game node to go to the profile add page game1/add \> node/add/profile game2/add \> node/add/profile

Using Entityreference prepopulate module i use /node/add/game-profile/?field\_gmeprfl\_game\_eref=\[node:nid\] to generate id to reference; the ? (question mark) prevents the \[node:nid\] from processing to an id. it stays literaly "/node/add/game-profile/?field\_gmeprfl\_game\_eref=\[node:nid\]". if i take out the "?" it will process to the nid number.

If I use view entity reference list to contextual filter the game1 part of url against the nodes alias , there is not alias for me to add in contextual filter. (id prefer this way so my links look better than ?field\_gmeprfl\_game\_eref=14

\**i use d7 prepopulate entity reference node (?field\_gmeprfl\_game\_eref=\[node:nid\]), i cant use ? with \[node:id\] as the ? prevents the tokens from processing. if i can do this and make urls the same as OP: id consider that also.

# Answer
> 0 votes
Your latest update mentions you're having trouble constructing the link, so I'll focus on answering that.

It seems that if you construct the link manually (simply type in the addressbar) everything is working correctly (this is to test that the Entityreference prepopulate module is working correctly on your side).

The problem then seems to be how to construct the link automatically for each of your game nodes, so that by clicking on the link, a Profile creation form is shown with the relevant entity reference prepopulated.

## Add Prepopulate links to Views

1. In your Games views add a field **Content: Nid** and **Exclude from display**
2. After that field (it's important the Nid comes before this) add a new field **Global: Custom text**
3. In the `Text` textarea of that field enter:
`<a href="/node/add/game-profile?field_gmeprfl_game_eref=[nid]">Add new Profile referencing this Game</a>`

Check that the token really is \[nid\] under Replacement patterns.

Now you have a list of Games with links that when clicked open the Create profile page with the related Game pre-selected.

## Add Prepopulate links to Node pages

If you need to display the link on the actual node page, you can se the same Views as above only create a Block with a Contextual filter.

This has to be done through Views block because the module you're using (Entityreference Prepopulate) doesn't have the URL widget feature implemented so you have to work around it.

1. Create a Block display View of Games
2. Add the same Fields as above (use the same Views)—the hidden Nid and Custom text with the link code.
3. Add a Contextual filter **Content: Nid** and configure it:
**When the filter value is NOT available**
**Provide default value**
**Content ID from URL**

This will limit the list to show the Prepopulate link for the current node only, otherwise it would show links for all games, like above.

This filter isn't responsible to the link contruction! Link is being constructed using the Fields!
4. Place your block in Content region or whereever you want the link to display, restrict the Block visibility to Game pages

Visit some Game pages and click on the links, see they are prepopulated with the nodes where you clicked the link.

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


title: Reviews Content Type with Rating Field

text:
# Question
Title: Reviews Content Type with Rating Field
We are looking to create a content type that will allow users to create reviews. Each review (node) when created it will be tagged with one taxonomy term.

For example, any user can write a review for Phone \> LG \> G3

One of the fields for the reviews content type will be RATING. The rating will be five star and later will be used on a view to show an average score for the particular taxonomy term (product).

Based on the example ablove show an average score for LG G3 phone. Which will be shown in a view.

Should we use a list field (1,2,3,4,5 as options) for the RATING field? Or is better to wait until the Fivestar module is more mature? Haven't even used Fivestar but it seems that it will do what I am talking about. Or am I wrong?

# Answer
Fivestar and maybe Rate seem like the modules for your problem.

But you can also use a list field like you mention. You seem to have the need to restrict the voting to the author of the Review node, while creating it (on Node Edit, not to all visitors on Node View).

But there aren't any ETA for Drupal 8 versions of those modules. Maybe you can help with that while working on your project? Although Fivestar has much more features than you seem to need, it's a more flexible solution and may be more future-proof.

It all depends on when you need it working, and how much you can invest in getting the D8 versions up and running.

If you're a developer or can sponsor one you can work on the D8 versions to get the superb usability for your users.

If not you can use the List field and some Views magic to build the basic vote and stats structure.
> 1 votes

---
Tags: views, 8, rating
---


# Question
Title: How to get plugin configuration through plugin manager?
I have defined plugin manager and I have installed two plugins, I am getting plugins name and id by `$plugins = $this->pluginManager->getDefinitions();` but I need to access its configurations and display whether this property is enabled or not with an edit button. How to do it?

# Answer
The plugin manager is not responsible for storing the configuration, that happens somewhere else.

Typically plugin configuration is then stored in a config entity, either in a 1:1 relation (e.g. blocks) or 1:n (e.g. views, view/form displays, filter formats).

I'd suggest that you look at those modules to see how they work, block is probably one of the simpler cases in core. You can also ask more specific questions if you're stuck on implementing that
> 2 votes

---
Tags: 8
---


title: Two modules trying to extend NodeForm

text:
# Question
Title: Two modules trying to extend NodeForm
I have two modules that both extend NodeForm the usual way:

```
function MY_MODULE_entity_type_alter(array &$entity_info) {
  $entity_info['node']->setFormClass('default', 'Drupal\MY_MODULE\Form\MyModuleNodeForm');
  $entity_info['node']->setFormClass('edit', 'Drupal\MY_MODULE\Form\MyModuleNodeForm');
}

```

As far as I can tell (both from actually looking into what `setFormClass()` does and simply trying out) this is a race condition that only one of them can win. Although they both want to deal with different content types and what they do would not conflict at all, they can't coexist. With the old, 7-style alter and submit functions, this could be solved but what would be the proper 8-ish way to do it? Both modules are mine, I can combine them if necessary but that wouldn't be really elegant.

# Answer
> 3 votes
You have two options. Either go back to using \_form\_alter() hooks to handle it, or you can extend twice:

module 1 node for extends module 2 node form which extends node form. Then make sure to call the parent::validateForm and parent::submitForm from your validate and submit handlers.

---
Tags: 8, forms
---


# Question
Title: how to pull parent term from nested array?
I'm building a custom field and formatter in Drupal 8(and teaching myself how to use Drupal & PHP, so bear with me)

I'm not sure how to pull a parent term 'name' value from a nested array.

Right now, I've got this:

```
$tid = 15
$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);

```

But I'm not sure how to get the 'name' field so I can use it in my #markup.

I used var\_dump to see what was there (can't use kint at the moment. Devel caused issues with some other modules)

Here's the array that came back:

```
array(1) {
[3]=> object(Drupal\taxonomy\Entity\Term)#1187 (26) {
    ["values":protected]=> array(9) {
        ["tid"]=> array(1) {
            ["x-default"]=> string(1) "3"
        }

        ["vid"]=> array(1) {
            ["x-default"]=> string(10) "plant_part"
        }

        ["uuid"]=> array(1) {
            ["x-default"]=> string(36) "2xxxxxx6-5xxb-2xx5-8xx7-axxxxxxxxc"
        }

        ["langcode"]=> array(1) {
            ["x-default"]=> string(2) "en"
        }

        ["name"]=> array(1) {
            ["x-default"]=> string(11) "Term wanted"
        }

```

I was trying something like this, but no luck:

```
 $parent['values']['tid']['x-default']

```

# Answer
> 0 votes
If you check closely with the `var_dump()` output, you will see, that you actually load an array of entity objects with the type taxonomy term: https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.5.x

This object has a getter method `getName()` that returns the desired property:

```
$names = [];

foreach($parent as $term) {
  $names[] = $term->getName();
}

$names_list = implode(', ', $names);

```

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


# Question
Title: How to unset content or hide content from node by ID or by path alias?
1. Create content for a custom content type "Artist" (Add Content \> Artist)
2. Note the node number (/node/\[number\]).
3. Set an URL alias for the node.

`node/[number] to /details/[node:field_artist_title]`

I want to hide the content from this content type by URL. Any idea how can I remove the content from node\__content?

# Answer
> 2 votes
You could check either for a path alias fragment or the node ID in a node preprocess function and then unset the whole content like following.

Ensure to replace MYTHEME/MYMODULE with your **custom** (sub-)theme's or **custom** module's machine name.

To be placed in either your **custom** (sub-)theme's `template.php` file (D7) or `MYTHEME.theme` file (D8) or in a **custom** module's `MYMODULE.module` file (D7 & D8).

```
/**
 * Implements template_preprocess_node.
 */
function MYTHEME/MYMODULE_preprocess_node(&$variables) {

  // Check for node type.
  if ($variables['node']->getType() == 'artist') {

    $current_path  = \Drupal::service('path.current')->getPath();
    $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $alias_args    = explode('/', $current_alias);

    // 1. Unset content per path alias.
    if ((isset($alias_args[0]) && $alias_args[0] == 'details')
      && (isset($alias_args[1]) && $alias_args[1] == 'michael-jackson')) {
      unset($variables['content']);
    }

    // 2. Or unset content by node ID.
    if ($variables['node']->id() == '123') {
      unset($variables['content']);
    }
  }
}

```

---

You could also use simple CSS.

```
#node-123 .field-name-body { display: none; }

```

# Answer
> 0 votes
The body of this node has a class as `page-node-1520` you can use it in CSS to hide what you want. Or you can create your node twig template `page--node--1520.html.twig`

---
Tags: 8, theming, nodes
---


# Question
Title: How to solve error filter_mailchimp_campaign plugin does not exist?
I have a D8 website which gives a error:

```
Er is onverwacht een fout opgetreden. Probeer het later nog eens.</br></br><em class="placeholder">Drupal\Component\Plugin\Exception\PluginNotFoundException</em>: The "filter_mailchimp_campaign" plugin does not exist. in <em class="placeholder">Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition()</em> (line <em class="placeholder">52</em> of <em class="placeholder">core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php</em>). <pre class="backtrace">Drupal\Core\Plugin\DefaultPluginManager->getDefinition('filter_mailchimp_campaign') (Line: 70)
Drupal\filter\FilterPluginCollection->initializePlugin('filter_mailchimp_campaign') (Line: 80)
Drupal\Component\Plugin\LazyPluginCollection->get('filter_mailchimp_campaign') (Line: 26)
Drupal\filter\FilterPluginCollection->get('filter_mailchimp_campaign') (Line: 91)
Drupal\filter\FilterPluginCollection->sortHelper('filter_mailchimp_campaign', 'filter_align')
uasort(Array, Array) (Line: 90)
Drupal\Core\Plugin\DefaultLazyPluginCollection->sort() (Line: 84)
Drupal\filter\FilterPluginCollection->sort() (Line: 137)
Drupal\filter\Entity\FilterFormat->filters() (Line: 149)
Drupal\filter\Entity\FilterFormat->getPluginCollections() (Line: 357)
Drupal\Core\Config\Entity\ConfigEntityBase->__sleep()
serialize(Array) (Line: 240)
Drupal\Core\Cache\DatabaseBackend->doSetMultiple(Array) (Line: 193)
Drupal\Core\Cache\DatabaseBackend->setMultiple(Array) (Line: 181)
Drupal\Core\Cache\DatabaseBackend->set('filter_formats:nl', Array, -1, Array) (Line: 107)
filter_formats(Object) (Line: 131)
Drupal\filter\Element\TextFormat::processFormat(Array, Object, Array)
call_user_func_array(Array, Array) (Line: 993)
Drupal\Core\Form\FormBuilder->doBuildForm('node_page_edit_form', Array, Object) (Line: 1056)
Drupal\Core\Form\FormBuilder->doBuildForm('node_page_edit_form', Array, Object) (Line: 1056)
Drupal\Core\Form\FormBuilder->doBuildForm('node_page_edit_form', Array, Object) (Line: 1056)
Drupal\Core\Form\FormBuilder->doBuildForm('node_page_edit_form', Array, Object) (Line: 557)
Drupal\Core\Form\FormBuilder->processForm('node_page_edit_form', Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder->buildForm('node_page_edit_form', Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
</pre>

```

I tried several solutions like uninstall all , reinstall with devel but none of this is working.

Any suggestion how to proceed?

# Answer
Can be solved by:

I was able to fix this. I had to go into the database and manually delete the entry "filter.mailchimp\_campaing" from the config table.
> 1 votes

---
Tags: 8, emails
---


# Question
Title: Prevent Drupal from Caching API Responses
I am not sure this is even supposed to happen, but it looks like Drupal is caching REST API responses. I have created a module that makes certain data available through the REST API, and changing the value in the DB requires clearing the cache for it to be reflected immediately in the API response.

Is there a way to prevent Drupal from doing this? The idea behind my API responses is that they are supposed to return real-time data. Currently I'm talking about the `user.data` service (`users_data` table), but an answer for any arbitrary data would be appreciated.

A specific random example of what retrieving the data looks like:

```
$user_data = \Drupal::service('user.data')->get('my_module', $id);

```

It looks like the cache I want to avoid is stored in `cache_dynamic_page_cache`.

EDIT: The simplest API response in this case (in the `get()` method) is:

```
return new ResourceResponse($user_data);

```

# Answer
I think you need to define `#cache` settings in your controller's response. You could define it in such a way that your response isn't cached at all, but you're probably better off defining cache tags in such a way that the cache is cleared when the entity is updated. See the Cache API documentation for more info.

Based on the information you've given, *I think* you'll probably want something like below added to your response array.

```
'#cache' => [
  'keys' => [
    'MY_MODULE_WHATEVER_KEY_YOU_LIKE',
  ],
  'tags' => [
    'user:' . $id,
  ],
  'max-age' => Cache::PERMANENT,
],

```

You'll need this use statement at the top of your file for `Cache::PERMANENT`

```
use Drupal\Cache\Cache\Cache.php;

```

The above will cache your response permanently, but break the cache when the user with `$id` is updated.
> 2 votes

---
Tags: 8, caching
---


# Question
Title: Don't Associate Orders With Drupal Users - Guest Checkout Only
Drupal 8, Drupal Commerce

We desire a "guest only" checkout experience. We don't want to associate orders or customer profiles with Drupal user accounts.

An unauthenticated user can checkout as a guest and achieve this.

However, if a user is authenticated before they checkout their order and customer profile will be associated with their Drupal user. This is what I am trying to avoid.

Does anyone have pointers for how this might be accomplished?

# Answer
It sounds like you're trying to work against some basic assumptions of Drupal Commerce, namely that users who are logged in should be associated to their data. This is true of Drupal itself - for example, an authenticated user cannot create an anonymous comment.

The simplest thing to do would be to instruct these users to log out. You can likely find a way to alter how Drupal Commerce creates new shopping cart orders such that authenticated users get anonymous orders associated to their sessions similarly to anonymous users, but I can't guarantee that the module throughout won't be checking to see if the user is currently logged in and making assumptions based on this elsewhere.
> 2 votes

---
Tags: 8, commerce
---


title: REST Export View Path is empty

text:
# Question
Title: REST Export View Path is empty
I have created a REST export view of contents.

I have all default configuration. I set my path to "/api".

Now when I try to add another rest export view on it, and create a contextual filter and I want to provide the path into "api/%", I am getting "Path is empty" when I click apply.

# Answer
> 0 votes
This is outdated. Should be fix by having proper configuration.

---
Tags: 8
---


# Question
Title: How to export content from dev environment for deployment to production environment?
We have to deploy content of around 37 content types from development to production environment. Each content type is having around 10 to 12 nodes. So, we have around 360 nodes for migrating to production environment.

How can i proceed it with at drupal end ?

# Answer
I haven't done it myself but a colleague of mine had to do this last week. It's just exporting and importing the database. He used HeidiSQL with this link: https://support.appliedi.net/kb/a1034/how-to-import-and-export-a-mysql-database-using-heidisql.aspx
> -2 votes

---
Tags: 8, nodes, deployment
---


# Question
Title: Field Collection fields causes errors in array_flip functions in /includes/entity.inc
This is a follow up question from this question. I now am sure that it's the Field Collection module that causes the error message `"Can only flip string and integer values!"`. My previous question was about HOW to find which module causes the error. I have now used Xdebug and Atom to backtrace the stack like this:

When the error arises on row 175 in /includes/entity.inc I have these values in the variable $ids:

```
$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;

```

As you can see it's an array in an array, which causes the error, as array\_flip() only can flip integers and strings, not arrays.

The array in an array value comes from row 8016 in /includes/common.inc:

```
function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
  if ($reset) {
    entity_get_controller($entity_type)->resetCache();
  }
  return entity_get_controller($entity_type)->load($ids, $conditions);
}

```

Going one step further back in the stack, the value comes from these rows in sites/all/modules/entity/entity.module:

```
function entity_load_single($entity_type, $id) {
  $entities = entity_load($entity_type, array($id));
  return reset($entities);
}

```

And if you bare with me, one more step back in the stack... to sites/all/modules/field\_collection/field\_collection\_entity.inc, where I find these rows (row 265):

```
  public function hostEntity() {
    if ($this->fetchHostDetails()) {
      if (!isset($this->hostEntity) && $this->isInUse()) {
        $this->hostEntity = entity_load_single($this->hostEntityType, $this->hostEntityId);
      }
      elseif (!isset($this->hostEntity) && $this->hostEntityRevisionId) {
        $this->hostEntity = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
      }
      return $this->hostEntity;
    }
  }

```

Now to my question... what happens is that the `host entity id` (26391) is passed up the stack once for every field collection field that exists on the page. 10 field collection field instances = 10 error messages on row 175 in `/includes/entity.inc` (and equally many on row 388).

Can anyone tell me what I might be doing wrong? I suspect I have drawn this error upon myself. All other posts I have read among the issues for Field Collection suggests that this shouldn't be a problem any more. Otherwise I would have posted this in as an issue for Field Collection.

The field types I am using in these Field Collection fields are: Image, Long text and Link.

What more info can I give you to solve this problem? I am not an expert coder, so maybe there is something obvious in the stack above, that I don't see?

# Answer
In case anyone has the same problem, try to update the module to the DEV version. In the above case the php error messages mentioned disappeared.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I add the Schema.org type 'BreadcrumbList'?
I want to add the Schema.org type `BreadcrumbList` for my website.

I have installed Schema.org module, but I'm unable to find any option there.

I tried using the Easy Breadcrumbs module, but it does not have the Schema.org type `BreadcrumbList`.

I have checked on the Schema.org website and there in example given for JSON-LD.

# Answer
```
function yourtheme_breadcrumb($variables) {
  $sep = ' > ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']);
  }
  else {
    return t("Home");
  }
}

```
> 0 votes

# Answer
Schema.org module does not seem to support this.

What you would need is the Path Breadcrumbs module with this patch. It is supposed to provide Schema.org breadcrumb integration. Bear in mind that the patch is not yet committed, and it's still in reviewing process.

You can see the discussion here.

Hope this helps.
> 0 votes

# Answer
## Using Crumbs

https://drupal.org/project/crumbs, since 7.x-2.7, automatically adds a JSON-LD BreadcrumbList to the page.

Note that

* Google takes some time to pick up the changes.
* Sometimes Google rejects the breadcrumb on a page for unexplained reasons.

If you used easy breadcrumb before, you could configure Crumbs to be 100% equivalent with it. But probably it won't be necessary.

## Using Easy Breadcrumbs

If you want to continue using Easy Breadcrumbs, you can do it yourself with e.g. hook\_html\_head\_alter(). Some code inspiration: https://cgit.drupalcode.org/crumbs/tree/lib/CurrentPageInfo.php#n340 https://cgit.drupalcode.org/crumbs/tree/lib/CurrentPageInfo.php#n382 https://cgit.drupalcode.org/crumbs/tree/crumbs.module#n59

Since you won't have the same data available as with Crumbs, you might want to use drupal\_get\_breadcrumb() as a starting point.

Of course you could also post a feature request with Easy Breadcrumbs.

## Why JSON-LD?

See https://webmasters.stackexchange.com/questions/115107/seo-schema-org-breadcrumb-with-display-none

The goal was to have structured data that does not conflict with the themed html of the visible breadcrumb.

## Why the html head?

I think the JSON-LD can be anywhere in the page, it does not have to be in the head. The head just seemed a suitable place.
> 0 votes

---
Tags: breadcrumbs, 7
---


# Question
Title: Get labels from fields ordered on block plugin - Drupal 8
I'm trying to create a block with a label list using all labels of a specific field type, entity\_reference\_revisions.

I created a Block plugin and load the EntityTypeManager service. I tried:

```
    $values = array(
      'targetEntityType' => 'node',
      'bundle' => $bundle,
      'mode' => $view_mode,
      'status' => TRUE,
    );
    $entity_view_display = $this->entityType->getStorage('entity_view_display')->create($values);
    $fields = $entity_view_display->get('fieldDefinitions');
    $labels = [];
    foreach ($fields as $field) {
      if($field->getFieldStorageDefinition()->getType() == 'entity_reference_revisions') {
        $labels[] = $field->get('label');
      }
    }

```

The problem is that I get the fields in a wrong order, and I can't get the weight attribute.

# Answer
I solved it loading the field definition using entityManager, I got the weight attribute, and then ordered the labels by weight.

```
$node = $this->requestStack->getCurrentRequest()->get('node');
$bundle = $node->getType();
$view_mode = 'full';

$fields = [];
foreach($this->entityManager->getFieldDefinitions('node', $bundle)  as $field_name => $field_definition) {
  if($field_definition->getType() == 'entity_reference_revisions') {
    $field_name = $field_definition->getName();
    $element = $node->$field_name->view($view_mode);
    $fields[] = [
      'name' => $field_name,
      'label' => $field_definition->getLabel(),
      'weight' => $element['#weight'],
    ];

  }
}

usort($fields, [$this, 'sortByWeight']);

```
> 0 votes

---
Tags: views, 8, blocks, plugins
---


# Question
Title: Remove time filter in a date exposed filter in a view
I have a view with a date field exposed filter but this date field in its content type configured to be date and time. Is there any way to make this exposed filter work only by date because now when I enter a date, didn't get any result.

# Answer
> 0 votes
Here you can implement this functionality by choosing "**Is Between**" in exposed filters. It works only with **date**. Because at time of node creation, it's asking for date and time both in "Authored On" section. If still you want to implement, you will have to use any trick by using jquery and hiddem fields in background

---
Tags: views
---


title: What is this markup in node.html.twig?

text:
# Question
Title: What is this markup in node.html.twig?
In node.twig.html (Bootstrap) I am seeing the code below and I am unsure of it's purpose. It is causing a problem with a view mode that I need to theme.

Is it important? Can I get rid of it?

```
<h2{{ title_attributes }}>
  <a href="{{ url }}" rel="bookmark">{{ label }}</a>
</h2>

```

# Answer
> -2 votes
this is the node title.

the h2 should be kept on every page if you are concerned about SEO

---
Tags: theming, bootstrap-theme
---


# Question
Title: Obtain the total (count) of the contents associated with a nested taxonomy (only in the parent taxonomy)
It is possible to count the contents associated with a nested taxonomy in Drupal 8 views, but the difference of this is that the taxonomies are of two levels.

For example:

I have these taxonomies:

Now, I have three created contents in which I associated the terms of the taxonomy, I stay like this:

I need something like this:

What I need to get in the view is, the total post associated with the parent taxonomy.

For example, I would like to see something like:

Backend: 2

Frontend: 1

What I have tried so far only shows me the totals independently(using aggregation), for example:

Backend - Post One - Total: 1

Ruby- Post One - Total: 1

Backend - Post Two- Total: 1

Python- Post Two- Total: 1

Frontend- Post Other- Total: 1

Is it possible to do this in Drupal 8 views?

# Answer
> 0 votes
I tried something similar I think, here's my code but keep in mind it's not perfect.

first get alle the terms

```
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$nodes = $node_storage->loadMultiple();
$node_tags = [];
foreach ($nodes as $node) {
  if ($node->hasField('field_terms')) {
    foreach ($node->get('field_terms')->getValue() as $value) {
      array_push($node_tags, $value);
    }
  }
}

```

after that you count all the terms

```
foreach ($node_tags as $key) {
  if (isset($count[$key['target_id']])) {
    $count[$key['target_id']]++;
  }
  else {
    $count[$key['target_id']] = 1;
  }
}
arsort($count);

```

then (and this still needs a lot of work) you search for them

```
$tags = $terms_storage->loadTree('tid');
$i=0;
foreach ($count as $key => $c) {
  foreach ($tags as $tag){
    if($tag->tid == $key){
     //here you can get the $tag->tid
     //you can get $tag->name
     //time used = $c
    }
  }
  $i++;
}

```

if you want to get the other terms

```
foreach ($tags as $tag){
  if(!array_key_exists($tag->tid,$count)){
   //here you get the same info
  }
}

```

---
Tags: views, 8
---


# Question
Title: Field without Used in data in Fields Report
I had several fields on content that had an empty *Used in* in `/admin/reports/fields`. Apart from being inelegant :-), it's a real problem because Views doesn't see them properly as belonging to content (and it will probably cause other problems down the line, that's only what was apparent now).

After contemplating different ways to solve it (the field-related commands on Drush are unusable, probably not yet ported), I did it manually in the database with a combination of cloning and replacing. All are done but `body` because, obviously, the UI doesn't allow me to specify field names without the `field` prefix.

So, I know that this is probably the result of some settings gone wrong, what actually makes Drupal think a field is used in a type? I couldn't locate the exact setting .yml yet. Storage.node.body.yml and the others actually don't show anything really different for body and all the others that are already correct now.

By the way, not some stale data of cache or drush entup.

I am in `Drupal\field_ui\FieldStorageConfigListBuilder` right now with a little dump:

```
if ($field_storage->getName() == 'body' && $entity_type_id != 'block_content') {
  ksm($field_storage->getBundles());
}

```

It returns an empty array. Khm...

# Answer
OK, I'm on the right track after a bit of sleuthing. `Drupal\Core\Entity\EntityFieldManager::getFieldMap()` reveals that the final knowledge comes from `entity.definitions.bundle_field_map`. I won't write where it dwells because we're performing heart surgery here... But he who dares will find it. :-)
> 0 votes

---
Tags: 8, entities, configuration
---


# Question
Title: Migrate nodes from D7 to custom entity defined in D8
I have defined custom entity using Drupal console. the entity have extra columns defined to store field data from D7 nodes migrated instead of having entity fields.

I am using Migrate tools and Migrate plus modules and created migration group defined as below:

```
id: phases
label: Phases nodes migration
migration_group: phases
deriver: Drupal\taxonomy\Plugin\migrate\D7NodeDeriver

source:
  plugin: d7_node
  node_type: phase

destination:
  plugin: entity:phase_entity

process:
  id: nid
  type:
plugin: default_value
default_value: phase
langcode: language
name: title
user_id: uid
changed: changed
created: created

migration_dependencies: { }

```

The migration group listed under `admin/structure/migrate` But no import action execute.

I have tried to import with basic fields only but nothing happens.

I searched a lot but no results even examples, I did created destination plugin to save the entity but I don't know how to.

Do I have write some code? where to write it or where docs for that part?

Does Drupal migration not work for custom entities at all so I have to look for another solution?

Any help will be appreciated, Thanks in advance.

# Answer
I did some research and found reviews that entity:{custom entity} is not working.

There exist table destination plugin help migrate directly to DB tables.

The plugin have some issues but there exist patches here
> 1 votes

# Answer
It looks like you're very close. Is your entity called "phase" or "phase\_entity"? If it is "phase", then you should adjust that under destination. Here is what I would recommend:

```
id: phases
label: Phases nodes migration
migration_group: phases
source:
  plugin: d7_node
  node_type: phase
destination:
  plugin: entity:phase
process:
  id: nid
  type:
    plugin: default_value
    default_value: phase
    langcode: language
  name: title
  user_id: uid
  changed: changed
  created: created
migration_dependencies: { }

```
> 2 votes

# Answer
When migrating data, I usually export all of the relevant data into CSV format, and then use a Python script (you can use any script, of course) to format the data into the new Drupal site format, and then post it in using D8's REST server. The main downside is that you have the overhead of HTTP requests, but I have done this with some success for moderate-to-large projects.

If you would like, I can give you some example code. Mainly, you are looking to authenticate with the REST server, and then systematically upload one content type at a time, and ideally record the newly posted entity's info as you may need to to set up references for content uploaded later.

However, if you want to go through the normal import route, another user may post a solution. This is my own workaround to the issue, and while it works it doesn't address how to use the Migrate modules.
> 0 votes

---
Tags: 8, entities, migrations
---


# Question
Title: How to add custom css classes to views exposed filters?
I would like to add *custom css classes* to specific *views exposed filters*. Is this possible either by default or with some Drupal module?

UPDATE: Please, note that I am not referring to the views exposed filters form in general, but individual filters, eg. a class to a date filter, another class to an entity reference filter, etc.

# Answer
> 3 votes
Have you considered something like this?

```
`.view-[viewname] .views-exposed-widgets`

```

You could use:

```
theme_form_alter(&$form, &$form_state, $form_id)

```

Check for the view/form id, and then add classes:

```
$form['#attributes']['class'][] = 'test';

```

# Answer
> 0 votes
I achieved this by opening up the page with the exposed filters that i'm interested in... I found that Drupal adds a class that is without any style... For me, I added this because i wanted to put some filters on their own line:

```
.views-widget-filter-field_application_nid {
width: 100%;
}

```

Hope that helps... :)

# Answer
> 0 votes
You could use

```
function theme-name_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id=='views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'view-name') {
        $form['#attributes']['class'][] = 'class-here';
    }
  }
}

```

Here you need to use your own

```
- theme name
- view name
- class

```

Hope this helps.

Thanks

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


title: Redirect .com domain to .dk/en

text:
# Question
Title: Redirect .com domain to .dk/en
I have a site; www.example.net. If you type www.example.com it redirects to www.example.net which is okay.

On my site i have to different language prefixes /da and /en that you can switch between.

My question: is it possible to redirect all who try to visit the site via www.example.com to www.example.net/en?

# Answer
> 0 votes
In your `.htaccess`,

```
RewriteCond %{HTTP_HOST} www.example.com
RewriteRule ^ http://www.example.net/en [R,L]

```

Where `www.example.com` is your old domain and `www.example.net`is the new one.

---
Tags: i18n-l10n, redirection
---


# Question
Title: How to increase priority of my custom CSS?
I have this View:  The empty rows have a `distrib0` class that should make the background red.
For that I have a custom CSS (amap.css) with `tr.distrib0 {BACKGROUND-COLOR:#FF0000;}` in it.
I have this `amap.libraries.yml` containing

```
amap:
  version: 1.x
  css:
    theme:
      css/amap.css: {}
  js:
      js/amap.js: {}
  dependencies:
    - core/drupalSettings

```

and finally, I attach the CSS with

```
function amap_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'calendrier_des_distributions' && $view->current_display == 'page_1') {
    $view->element['#attached']['library'][] = 'amap/amap';
  }
}

```

As you can see in the screen capture, my CSS is there but after `color.css` which is part of the current theme.
And of course my background is not red!
What can I do (besides adding `tr.distrib0 in tr.distrib0` to `color.css`which I'd prefer to avoid)?

# Answer
You have added wrong CSS here. Background color will not works with tr tag because we have style of td over tr tag. Please correct with this code

```
tr.distrib0 td {
 background-color:#FF0000 !important;
}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to add multiple js files in hook_field_widget_form()?
When I load two JS files using `drupal_add_js()` as can be seen in the code marked "After", it does not show `alert()` text on page load and also when I click on the button created in the form to load fancybox (popup) it shows

```
$.fancybox is not a function

```

When I just add `taxonomy_fancybox.js` it shows alert, so my question is How can I make sure both `fancybox.js` and `taxonomy_fancybox.js` are loaded.

Before

```
/**
 * Implements hook_field_widget_form().
 */
function taxonomy_fancybox_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  drupal_add_js(drupal_get_path("module", "taxonomy_fancybox") . '/taxonomy_fancybox.js');
}

```

After

```
/**
 * Implements hook_field_widget_form().
 */
function taxonomy_fancybox_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  drupal_add_js(drupal_get_path('module', 'fancybox') . '/fancybox.js');
  drupal_add_js(drupal_get_path("module", "taxonomy_fancybox") . '/taxonomy_fancybox.js');
}

```

taxonomy\_fancybox.js has

```
(function ($) {
  Drupal.behaviors.selectterms = {
    attach: function (context, settings) {

      alert('enters');

      $('#edit-select-terms').click(function (e) {

        e.preventDefault();

        $.ajax({
          url: '/ajax/fetch-vocabularies/',
          success: function (data) {
            $.fancybox(data);
          }
        });

      });

    }
  };
}(jQuery));

```

# Answer
> 0 votes
Seems you missed step 3. from the README.

> 3. Download the fancyBox plugin and extract the entire directory into sites/all/libraries. (You may need to create this directory). The path to fancyBox should be sites/all/libraries/fancybox/source/jquery.fancybox.js. (the module uses the minified version, so actually jquery.fancybox.pack.js).

The second JS then doesn't fire anymore as the first JS virtually raised an exception already (due to the non-existent 3rd party library).

---
Tags: 7, javascript
---


title: Create an Entity (Beginner)

text:
# Question
Title: Create an Entity (Beginner)
beginner here,

I am trying to follow the typical entity example and create my own entity in Drupal 7. So I basically changed the name from typical\_entity\_example\_1 to source\_entity and the test fails (see picture below). I'm not sure what I'm doing incorrectly, any advice would be much appreciated.

install file:

```
function source_entity_schema() {
  $schema = array();
  $schema['source_entity'] = array(
    'description' => 'The base table for source_entity.',
    'fields' => array(
      'teid' => array(
        'description' => 'The primary identifier.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'title' => array(
        'description' => 'Entity title.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'description' => array(
        'description' => 'Entity description.',
        'type' => 'text',
      ),
    ),
    'primary key' => array('teid'),
  );
  return $schema;
}

```

Module file:

```
<?php

function source_entity_info() {
  $info = array(
    'source_entity' => array(
      'label' => t('Source Entity 1'),
      'base table' => 'source_entity',
      'entity keys' => array(
        'id' => 'teid',
      ),
    ),
  );
  return $info;
}

```

Test file

```
class SourceEntityUnitTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Source Entity Test 1',
      'description' => 'Check existence and possibilities of source_entity.',
      'group' => 'Source Entity',
    );
  }

  public function setUp() {
    parent::setUp('source_entity');
  }

  public function testSourceEntity1() {
    $entity_description = entity_get_info('source_entity');
    $this->assertEqual($entity_description['base table'], 'source_entity', t("Entity type 'source_entity' exists."));

    $new_entity = entity_create('source_entity', array());
    $this->assertFalse($new_entity, t("Can't create an instance of source_entity because 'source_entity' entity type has not create callback."));
  }

}

```

# Answer
**Module file:** Hook name is source\_entity\_info() insted of source\_entity\_entity\_info()

```
    <?php

    function source_entity_entity_info() {
      $info = array(
        'source_entity' => array(
          'label' => t('Source Entity 1'),
          'base table' => 'source_entity',
          'entity keys' => array(
            'id' => 'teid',
          ),
        ),
      );
      return $info;

}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to Automatically Manage a LARGE Number of Views Pages Under ONE?
I am developing a website for a school's Alumni Association that has been around since the 1800s. Every student has a Grad Class specified in the database:

e.g. /students/1947/John\_Doe (indicates graduated in 1947; all of this is ready to go).

But now I want to create a page for every year (1890, 1891, ... 1970, 1971, etc.) and have each listed on that page:

e.g. /students/1947 (would list all students who graduated in 1947)

Using Contextual Filters, this is easy!! But the problem is that creating each individual page for each individual year would be extremely cumbersome. Do each of these pages needed to be created manually (with an identical Contextual Filter) or is there a way to automatically manage all of these graduation classes under a single view? If so, how would those pages be created?

# Answer
> 3 votes
All you have to do is to add a wildcard to the URL pattern of your view like `/students/%` and then use this as argument for the contextual filter.

Similar to how the default "Taxonomy term" view does it (screenshot attached):

---
Tags: views
---


title: Security issues with v7.59

text:
# Question
Title: Security issues with v7.59
I have updated various Drupal 7 sites to version 7.59 (and included all relevant updates) because of the security update. However I've still experienced issues with sites being hacked, there were also no warnings or issues reported on the site report when the update was completed. Yesterday an attack lead to malicious phishing code being inserted into a website, Google has now flagged this site. The malicious code has now been removed.

Are there any other known security vulnerabilities or patches that are available for Drupal 7?

# Answer
> 3 votes
Most likely there are still hacked/inserted files in your code base thats leaving an opening for the attacker to rexploit. After updating to 7.59 you need to go through the files/code and remove anything that's not supposed to be there. Very hard if you're not using git. Also also includes the /sites/default/files folder and subfolders as well as all other directories

---
Tags: security
---


# Question
Title: How do I programmatically remove one breadcrumb link?
in Drupal 7 I could just use `array_pop($breadcrumb)`, but in Drupal 8 the breadcrumb is an object and I don't see a method for removing the last element.

How can this be done?

# Answer
> 9 votes
Drupal 7 and Drupal 8 are more or less the same in some aspects.

If you use `preprocess_breadcrumb` in your theme, you would do

```
function my_theme_preprocess_breadcrumb(&$variables) {
  array_pop($variables['breadcrumb']);
  ...
}

```

You could also solve this in the template file, by skipping the first item in `{{ breadcrumb }}`

If you want module only solution, you could swap the breadcrumb service with your own thing.

# Answer
> 2 votes
If you are using a BreadcrumbBuilder, and try to remove a Link already added, you can't. Unless you create a custom Breadcrumb class, to add a new method or override an existing one.

My solution was this :

```
<?php

namespace Drupal\my_module;

use Drupal\Core\Breadcrumb\Breadcrumb;

/**
 * Blablabla.
 */
class BreadcrumbCustom extends Breadcrumb {

  /**
   * Sets the breadcrumb links.
   *
   * @param \Drupal\Core\Link[] $links
   *   The breadcrumb links.
   * @param bool $force
   *   Boolean to indicate if you should force to override the existing links.
   *   Use with caution.
   *
   * @return $this
   *
   * @throws \LogicException
   *   Thrown when setting breadcrumb links after they've already been set.
   */
  public function setLinks(array $links, $force = FALSE) {
    if (!empty($this->links) && !$force) {
      throw new \LogicException('Once breadcrumb links are set, only additional breadcrumb links can be added.');
    }

    $this->links = $links;

    return $this;
  }

}

```

and inside the BreadcrumbBuilder :

```
$links = $breadcrumb->getLinks();
unset($links[1]);
$breadcrumb->setLinks($links, TRUE);

```

---
Tags: 8, breadcrumbs
---


title: Use mysql SET variables in db_query

text:
# Question
Title: Use mysql SET variables in db_query
How can I use mysql `SET` variables while using my PDO queries?

```
db_query('SET @x := 5,SET @y := 6, SELECT * from mytable')->fetchAll();

```

I have tried this and many variations of this statement with and without `':'` etc, but it doesn't work.

# Answer
> 1 votes
There are 2 points here.

```
SET @x := 5,SET @y := 6, SELECT * from mytable" should be "SET @x := 5,SET @y := 6; SELECT * from mytable

```

as

```
SET @x := 5,SET @y := 6;" and "SELECT * from mytable

```

are 2 separate MySQL statements.

You can not execute multiple statements together using `db_query()`. Since the PHP functions `mysql_query()` and `mysqli_query()` can only execute one SQL statement, the `db_query()` wrapper can also only execute one SQL statement.

What you can do here is, divide that into two part and run it.

```
db_query('SET @x := 5,SET @y := 6;')->execute();
db_query('SELECT * from mytable')->fetchAll();

```

---
Tags: database
---


# Question
Title: Taxonomy term option is missing in view category
I have several site on Drupal 8.5 where I don’t see the "taxonomy term" option in view. So I can’t create a view that lists taxonomy terms of a vocabulary.

See the first screen shot to see the problem.

Why I don’t see this option ? Is there something to install or enable ? I’ve checked a lot of things and I still don’t understand.

Below, there is a second screen shot of an other Drupal where I have this really useful field.

Finally, this is what I would like to add in `fields` and `Filter` in view.

# Answer
All you have to do is to choose "Taxonomy terms" under `VIEW SETTINGS` when you add a new view on `MYSITE/admin/structure/views/add`.
> 2 votes

---
Tags: views, 8
---


# Question
Title: Og Membership entity not created when assigning new node to Group; works when editing node
Using Organic Groups 7.x-2.9, I have two content types: \- Series (Group) \- Event (Group Content)

When creating an Event, a users has a select list of the Series they can assign this Event to (`og_group_ref`). However, upon saving this new Event there is no `og_membership` entity created (recorded in the table `og_membership`) and, therefore, the new Event is not in the Series group.

If you then edit this event and select the Series, the `og_membership` entity is created and the relationship is reflected on the Event. (Possibly related, there is *no* data in the table `field_data_og_group_ref`).

Using breakpoints - everything appears to be the same with one exception: When `OgMembership::save()` is called during the creation of a new entity the event entity object *does* have the nid; however, the node (Event) has not yet been saved in the `node` table.

What needs to be done in order to have the relationship when a new node (that is a group content) is created?

\[EDIT\] It *seems* the `og_membership` entity is being saved and then deleted. I found this issue regarding data loss. I don't think it's related (as of yet) because I don't have any active OG rules; however, it did make me check further. When creating group content and associating it with a group, the `og_membership` table auto increment **does** increase by 1, although no record was written. This tells me a record was written and deleted.

\[EDIT\] The above linked issue led me to another `hook_node_insert` that is used in this site. This hook uses `entity_metadata_wrapper` to set a field value, commenting this out stops the og\_membership entity from being deleted.

# Answer
> 0 votes
The issue turned out to be a `hook_node_insert` using `entity_metadata_wrapper`. I refactored that code to use `hook_node_presave` to set the field value (field unrelated to organic group) instead: `$node->field_short_url_code[LANGUAGE_NONE][0]['value'] = $string;` and all is well.

---
Tags: 7, organic-groups
---


# Question
Title: How to fix sorting by node title in glossary View when viewing page in non default language?
There is ton of materials how to do it in 7, but I was not able to find or adapt based on those solutions.

My View has fields:

* Content: Title
* Title first letter \[hidden\]

Filters:

* Content: Publishing status (= Yes)
* Content: Content type (= Basic page)
* Content: List page in glossary (= True)

Sort criteria: \- Content: Title (asc)

Relationships: \- Node

Rendering Language: Interface text language selected for page

When viewing page with default language (which is a source language for a nodes) sorting is working good. After switching language sorting not working well, seems like it's based on source translation content every time.

Generated SQL:

```
SELECT node_field_data.title AS node_field_data_title, node_field_data.nid AS nid, node_taxonomy_index.nid AS node_taxonomy_index_nid
FROM
{node_field_data} node_field_data
LEFT JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
LEFT JOIN {node__field_glossary_enabled} node__field_glossary_enabled ON node_field_data.nid = node__field_glossary_enabled.entity_id AND (node__field_glossary_enabled.deleted = '0' AND node__field_glossary_enabled.langcode = node_field_data.langcode)
WHERE (node_field_data.status = '1') AND (node_field_data.type IN ('page')) AND (node__field_glossary_enabled.field_glossary_enabled_value = '1')
ORDER BY node_field_data_title ASC

```

# Answer
> 1 votes
Now you get view rows for the original language and sort them still untranslated, because you translate them later when rendering.

You need to filter the rows for the current language to be able to sort the translated titles:

---
Tags: views, 8
---


# Question
Title: Cannot create user, email: invalid!! while trying to create a user
Here is the export of my rule:

```
{ "rules_create_drupal_user" : {
  "LABEL" : "Create Drupal User",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "civicrm" ],
  "ON" : { "civicrm_contact_edit" : [], "civicrm_contact_create" : [] },
  "IF" : [
    { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm_contact" ] } }
  ],
  "DO" : [
    { "civicrm_entity_action_create_user" : {
        "USING" : {
          "civicrm_contact" : [ "civicrm_contact" ],
          "is_active" : "1",
          "notify" : "0",
          "signin" : "0",
          "username_format" : "first last"
        },
        "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
      }
    }
  ]
}
}

```

An "Cannot create user, email: invalid!!" error occurs soon after submitting the webform. Drupal user has to be created soon after Civicrm contact is created. After submitting webform as I have used civicrm integration, civicrm contact is created.

Any help?

# Answer
> 0 votes
Here is a rule that fires when civicrm contact is created. It works off Tag, ie the webform adds a Tag to the Contact. Rules then runs off that event. Note this rule also auto logs the person in but you should be able to get some clues from this. You need civicrm\_entity module.

```
    { "rules_self_create_user_account_and_login" : {
    "LABEL" : "Create User Account",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules" ],
    "ON" : { "civicrm_entity_tag_create" : [] },
    "IF" : [
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-entity-tag:entity-id-contact" ] } },
      { "data_is" : {
          "data" : [ "civicrm-entity-tag:entity-table" ],
          "value" : "civicrm_contact"
        }
      },
      { "data_is" : { "data" : [ "civicrm-entity-tag:tag-id" ], "value" : "525" } }
    ],
    "DO" : [
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-entity-tag:entity-id-contact" ],
            "is_active" : "1",
            "notify" : "1",
            "signin" : "1",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      },
      { "redirect" : { "url" : "civicrm\/user?reset=1" } }
    ]
  }
}

```

---
Tags: 7, rules, civicrm
---


# Question
Title: Display referenced user's email address instead of username
I have a user reference field as a select list in my content type. When adding node I got a list of usernames. What I want is to display E-mails/ (or other user fields) instead of username. I tried to create entity reference view but it does not show the selected fields in the view either.

# Answer
You are on the good track with solving your problem using Entity Reference Views Display. Once you have that Display type ready, you can edit your Entity reference field to use that Views display.

Your question seems to have two parts, one is displaying user information in Views, and the other is making the Entity reference field use the Entity Reference Views instead of a Select list.

## Entity Reference Views in Drupal Core—Needs work

There are efforts to make using Views as Widgets on Entity reference field forms in Drupal Core: View output is not used for entityreference options. You can patch your installation using the patch from that Issue.

Or you can use the already suggested module Entity Reference Views Select until it's all sorted out in core: Similar support to be ported to core. Follow the instructions from the module about how to configure your Entity reference field.

## Showing user information in Views

Since your Entity reference field is referencing Users, it makes the most sense to create a View of type `User`.

Show **Users**, but don't create a Page or a Block. When you Save the View create a new Display of type `Entity Reference`.

Add Email and other fields you want to show on the Create node form when selecting users.

Whatever fields you see in this Display, you will see when selecting users on the create/edit node form.
> 2 votes

# Answer
I think it might be a shortcoming of the core entity reference/select list functionality. In Drupal 7 it was working as you would expect but in Drupal 8 it seems not to have the same behaviour.

You can try using entity\_reference\_views\_select which promises to do exactly this
> 1 votes

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


# Question
Title: How do you perform a Guzzle POST request with "Basic Auth" for the current user?
In my class, I have the following request:

```
    $rest_response = $client->post($endpoint, [
      'auth' => ['admin', 'admin'],
      'body' => $serialized_entity,
      'headers' => [
        'Content-Type' => 'application/hal+json',
        'X-CSRF-Token' => $token,
      ],
    ]);

```

It works because I have a user with the username/password as "admin"/"admin", but when that user's password is changed, it won't work anymore, as expected.

In the logs, I am getting an "access denied" error for the endpoint I am trying to POST to - and the user associated with that error says "Anonymous (not verified)". All other log messages printed out in my controller show the current user's username.

I am running Drupal core 8.1.9.

The question is - how do I use basic\_auth to get the current logged-in user's credentials to be passed into the request?

# Answer
You were so close main thing here is the "Authorization" Header ...

```
 $current_user = \Drupal::currentUser();
 $account = $current_user->getAccount();

 $username = $account->name;
 // pass would be hard to get as stored hashed
 //... so you would need to get a bit tricky to "catch" the users password when they log in...
 $pass = 'admin';
 $auth = 'Basic '. base64_encode ($username . ':' . $pass);
 $rest_response = $client->post($endpoint, [
   'body' => $serialized_entity,
   'headers' => [
     'Authorization' => $auth,
     'Content-Type' => 'application/hal+json',
     'X-CSRF-Token' => $token,
  ],
]);

```

And just for fun:

```
  var basicAuthCredential = username + ":" + password;
  var bace64 =  btoa(basicAuthCredential);
  var Auth =  'Basic ' + bace64;
  fetch(url,{
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': Auth,
      'X-CSRF-Token': token
    },
    body: JSON.stringify(data)
}).then(response => response.json())...

```
> 3 votes

# Answer
I was able to figure out a workaround solution that solved my question. First, I had to allow "Anonymous" users the permission to POST to my custom REST resource. This allowed my resource to be accessed by the POST request programmatically-called by my Guzzle client.
In my REST resource, I am checking for the user's permission, which restrict access for users without the permissions defined (in my case, "access content").

```
/**
 * Provides a resource to get bundles by entity.
 *
 * @RestResource(
 *   id = "distribution_content_ingestion",
 *   label = @Translation("Distribution Content Ingestion"),
 *   serialization_class = "Drupal\my_module\Normalizer\JsonDenormalizer",
 *   uri_paths = {
 *     "canonical" = "/entity/distribution_ingest/{distribution_id}",
 *     "https://www.drupal.org/link-relations/create" = "/entity/distribution_ingest/{distribution_id}"
 *   }
 * )
 */
class DistributionIngestResource extends ResourceBase {
  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to POST requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @param string $distribution_id
   *   The Distribution ID to ingest.
   * @param array $data
   *   The data from the POST.
   *
   * @return \Drupal\rest\ResourceResponse
   *   Throws exception expected.
   */
  public function post($distribution_id, $data) {
    // You must to implement the logic of your REST Resource here.
    // Use current user after pass authentication to validate access.
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }

    /**
     * Some code here.
     */
  }
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Controlling/selling node access by node reference?
I have been using Drupal for many years now (starting with Drupal 6) and only recently - in the context of a big project - made the switch to D8. So far, working with D8 has been a very pleasant experience, to say the least. I was prepared, however, that there would be a few rocks on the road. And I would like to ask for help removing a big one (for me)...

In a nutshell, the situation is this: I am creating a kind of **learning management system** (LMS), with `lessons`, `courses` and `classes`. Each lesson belongs to exactly one course, but each courses *may or may not* belong to *zero, one or more* classes. I was thinking of using simple node references to structure this:

* a field in the content type lesson that references the course that this lesson belongs to
* and an entity reference field in the content type class that references all courses in this class (so, this is referenced the other way round)

Now, I'd like to sell access to each of these content types and my problem is this: If a user buys access to one of the classes, she should also be able to access all of the courses (and lessons) that are referenced by this class. So, when checking the access permissions for a single course, the system will not only have to check, if the user has bought this course, but also, if the user has access to a class that contains this course.

I was first thinking of solving this with the module Node access node reference, but this seems to work the other way round (and doesn't have a D8 version). Same for Access by Reference. (In general, most of the access control modules I looked at, don't seem to be ready for D8 yet.) But what about rule-based access control? Or groups?

Can anybody suggest a way forword?

Any help would be much appreciated. Thanks in advance.

# Answer
Why not go custom access the main thing is relating your "Class" or Item to the product the person buys aka on the product you could create a entity reference to the node or class or whatever ...

you can do some thing like the following

```
use Drupal\Core\Access\AccessResult;
/**
* Implements hook_node_access().
*/
function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account){
// Note thes checks do not work on admin (user 1). and clear cache each time.
$type = $node->bundle();
if ($type === 'your_content_type') {
  if ($account->id() !== 0) {
    $user = $account->getAccount();
    $uid = $user->id();
    // Ok we know is trying to access and the node type.
    $storage = \Drupal::entityTypeManager()->getStorage('commerce_order');
    $orders = $storage->loadByProperties(['uid' => $uid]);
    if (count($orders) != 0) {
      $has_bought = FALSE;

      // CUSTOM FIND Your Corse .
      $corse_type = $node->field_corse_type->value;
      foreach ($orders as $order) {
        $order_items = $order->order_items->referencedEntities();
        foreach ($order_items as $item) {
          // Do better than this lol ...
          // dump($item);
          if ($item->title->value == 'SOME Course' && $corse_type == 'SOMETHING RELATED TO PRODUCT') {
            $has_bought = TRUE;
        }
      }
    }
    // final check.
    if ($has_bought === TRUE) {
      return AccessResult::isAllowed();
    }
    else{
      // Kick them. as not bought.
      return AccessResult::forbidden();
    }
  }
  else {
    // Kick them. as not paid.
    return AccessResult::forbidden();
  }

  }
  else {
  // kick them.
  return AccessResult::forbidden();
  }
 }
 else {
  return AccessResult::neutral();
  }
}

```
> 1 votes

---
Tags: nodes, users, commerce, entities
---


# Question
Title: How to hide an empty view block when using a contextual filter and NO file fields?
I'm trying to figure out how to hide a view block when it has no rows. Though this questions is similar, it's not the same. In my situation I am also using a contextual filter but have no file fields so the answer in that question doesn't apply.

I've tried **global: null** as a second contextual filter but still the block shows with just the title.

Can anyone help me solve this issue.

Many thanks for any help.

# Answer
Add another filter it's not important which field , as example if you have `Content:title` ( or any field you have in fields row) and set filter is it's not empty.

The mechanism is simple, contextual filter cause view not consider as empty even thought there is no any row, and when you add a filter on a field that not exists it cause view considered as empty. **So only add one of your view field to filter and check if it is not empty**
> 1 votes

# Answer
I tried various methods suggested in various places, including this one from @zhilevan, but the only way I could get it to work was to remove the title from the block and add it in as a header to the block.
> 0 votes

---
Tags: 7, views
---


title: D8 Commerce - Non-orderable product

text:
# Question
Title: D8 Commerce - Non-orderable product
What's the best way to configure some products so that they are not on sale .. i.e not show the price or add to cart button without creating a new product type?

# Answer
> 0 votes
Ideas...

1) create custom config entity like "products\_not\_on\_sale"

2) Alter node view to hide the fields if referenced in above ^

--- or ---

1) add new field of type bool to say item on sale or not.

2) alter node view to hide fields if value is checked.

# Answer
> 0 votes
You just need to uncheck the `active` option on each product variation. That will hide the "Add to cart" button and price without hidding the product or its information.

# Answer
> 0 votes
Thanks. I ended up achieving what I wanted in a twig template by copying it from the below path:

```
modules/contrib/commerce/modules/product/templates/commerce-product-variation.html.twig

```

to:

```
themes/custom/mytheme/templates/product/commerce-product-variation--summary.html.twig

```

"summary" is the display for the panels page I've configured.

Then used the variation active status boolean value to determine whether or not to show it:

```
{% if product_variation_entity.status.value != 0 %}
<div{{ attributes }}>
  {{- product_variation -}}
</div>
{% endif %}

```

---
Tags: commerce
---