# Question
Title: Entity References Auto create between Nodes
I have node 1 has a reference to node 2 & node 3 how can I make node 2 & node 3 have a reference automatically (because they have the same reference with node1)?

# Answer
> 1 votes
You can implement hook\_entity\_insert()

> Act on entities when inserted.
>
> Parameters
>
> **$entity:** The entity object.
>
> **$type:** The type of entity being inserted (i.e. node, user, comment).

and inside the hook check if you have more than one node in the reference field, in this case you will edit all the nodes and add the reference to the others.

# Answer
> 0 votes
You can find a solution that works for me on the following pages: https://www.drupal.org/project/prepopulate/issues/2668010 it is using the module prepopulate and you can find the documentation on this module page.

An other solution is proposed by using the business rule module.

---
Tags: nodes
---


# Question
Title: Field contains list and values of it are shown in one symbol
I'm developing a drupal module and there's a problem. I need to make a content type with some fields and one of them should have list with string values. But when I try to create content and choose new content type I created, I see list and there are values contains first symbol of the string that I need.

coursebook.info.yml

```
name: Course Book
description: Course book
type: module
core: 8.x
package: Course book module

```

field.storage.node.field\_disciplines.yml

```
langcode: en
dependencies:
  enforced:
    module:
    - coursebook
  module:
  - node
id: node.field_disciplines
field_name: field_disciplines
entity_type: node
type: list_string
settings:
  allowed_values: { "1":'A', "2":'Bb', "3":'Cccc'}
  max_length: 1000
module: core
locked: false
cardinality: 100

```

field.field.node.coursebook.field\_disciplines.yml

```
langcode: en
dependencies:
  config:
  - field.storage.node.field_disciplines
  - node.type.coursebook
id: node.coursebook.field_disciplines
field_name: field_disciplines
entity_type: node
bundle: coursebook
label: 'disciplines'
description: 'Type disciplines here'
required: false
default_value: 'example'
settings: { }
field_type: list_string

```

core.entity\_view\_display.node.coursebook.default.yml

```
langcode: en
status: true
dependencies:
  config:
  - field.field.node.coursebook.field_year
  - field.field.node.coursebook.field_semester
  - node.type.coursebook
id: node.coursebook.default
targetEntityType: node
bundle: coursebook
mode: default
content:
  field_year:
    label: hidden
    type: string
    weight: 0
    settings: {  }
    third_party_settings: {  }
  field_semester:
    label: hidden
    type: string
    weight: 1
    settings: {  }
    third_party_settings: {  }
  field_disciplines:
    label: hidden
    type: string
    weight: 2
    settings: {  }
    third_party_settings: {  }

```

core.entity\_form\_display.node.coursebook.default.yml

```
langcode: en
status: true
dependencies:
  config:
  - field.field.node.coursebook.field_year
  - field.field.node.coursebook.field_semester
  - node.type.coursebook
id: node.coursebook.default
targetEntityType: node
bundle: coursebook
mode: default
content:
  field_year:
    type: string_textfield
    weight: 0
    settings:
      size: 30
      placeholder: 'example'
    third_party_settings: {  }
  field_semester:
    type: string_textfield
    weight: 1
    settings:
      size: 30
      placeholder: 'example'
    third_party_settings: {  }
  field_disciplines:
    type: string_textfield
    weight: 2
    settings:
      size: 30
      placeholder: 'example'
    third_party_settings: {  }
hidden: { }

```

And what I see -  But i shuold see this list:

```
allowed_values: { "1":'A', "2":'Bb', "3":'Cccc'}

```

There are only files that describe problem field. I hope you understand my problem. I develop my module using this manual: https://medium.com/touch4it/custom-content-type-with-custom-fields-for-your-drupal-8-module-9478fd018f76

# Answer
> 1 votes
You need to have the allowed values settings in the following format:

```
allowed_values:
  -
    value: '1'
    label: A
  -
    value: '2'
    label: 'Bb'
  -
    value: '3'
    label: Ccccc

```

The quotes don't matter for single word strings. I hope this helps.

---
Tags: 8, nodes, hooks, .info
---


title: Auto-submit exposed form

text:
# Question
Title: Auto-submit exposed form
I'm currently working on a views exposed form block. I want the form to auto-submit using AJAX, whenever an exposed filter is changed.

I have searched for this, but I couldn't find any tutorial or guide. I cannot see any setting in the view, so I guess I have to implement `hook_form_alter`. Is that correct, or am I missing something?

# Answer
> 2 votes
I actually found the answer myself. Using the Better Exposed Filters module did the trick.

From the module's description:

> Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed.

---
Tags: views, 8, ajax
---


# Question
Title: Drush can not connect to mysql when run a Drupal in a Docker/Azure
I have a website that it's running ok in Docker/Azure.

I have this configuration in my settings.php

```
$databases ['default'] ['default'] = array (
    'database' => getenv ( 'MYSQL_DATABASE' ),
    'username' => getenv ( 'MYSQL_USER' ),
    'password' => getenv ( 'MYSQL_PASSWORD' ),
    'prefix' => '',
    'host' => getenv ( 'MYSQL_HOSTNAME' ),
    'port' => getenv ( 'MYSQL_PORT' ),
    'driver' => 'mysql'
);

```

When I make drush status

I get this.

```
 Drupal version   : 8.7.3
 Site URI         : http://default
 DB driver        :
 DB hostname      :
 DB port          :
 DB username      :
 DB name          :

```

Any idea how to make that Drush get the mysql configuration options?

Thanks

# Answer
It looks like the environment variables are defined only for HTTP requests. In other words, they seem to be set in FPM, NGINX, or Apache, but not in your shell.

Try typing `echo $MYSQL_DATABASE` in your shell. If that outputs nothing, you'll have to export the environment variables first, so Drush can see them.
> 1 votes

---
Tags: drush
---


# Question
Title: How to make an nid replacement in a Text area inside Footer?
I want to generate an nid of the current page in the Text area inside the footer of a view. I cannot add the ID (node id) in the Footer. What is the proper way for doing this? Any hint?

Thank you.

# Answer
For the current node ID try this token:

```
[current-page:url:unaliased:args:value:1]

```

See http://www.drupal.org/node/1360922
> 5 votes

# Answer
Besides tokens you can do it with Views features.

You can use `Replacement patterns` of the Fields you have added to your Views, and also of Contextual filters arguments (which is what you'll probably need).

To use them you have to use the **Use replacement tokens from the first row** option:

If you want to display a Block Views on your node pages that only shows information about the current page you'll have to add the `ID` Contextual filter to your Views and configure it with the usual `Provide default value > Content ID from URL` (set other options as per your needs). This is how you can get those argument patterns you see in the screenshot.
> 2 votes

---
Tags: views
---


# Question
Title: Exposed filter or facet for a vocabulary listing select list
I have to create a form with a fulltext search field and a dropdown listing every terms of a certain vocabulary. On submission the form is redirecting the user with the value of both the fields as parameters in path. I don't know which should be better to use between a facet or a simple list listing every terms of the needed vocabulary?

# Answer
Facets are usually used for a lot more complex examples with many properties to narrow down your search by.

Both facets and the usual Views with Exposed filters form create paths that hold search parameters entered by users.

The simplest case would probably be to add the textual filter for the Body field, and the Filter for the Taxonomy reference field, and Expose them (so that the users can choose values for them and narrow down the search results). You can use Exposed form settings to change the way the form fields display, drop-downs sometimes aren't the most usable options.

You can use Better Exposed Filters module if you need more options for the exposed form display.
> 0 votes

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


# Question
Title: How to align views pager url with real page number?
When creating pager in views (D7) you get urls with query parameter like `page=X` by default. But this X does not match actual page number.

`page=1` is generated for `2` link in the paginator and so on.

Is there any way to make them the same without too much of code kung-fu or did I miss some checkbox?

# Answer
As 4k4 mentioned in the comment there is an issue for this you should check out.

In the meantime you might implement a workaround (outside of Views)

* with the help of the Query Parameters To URL,
* or outside of Drupal through your server configuration and redirects.
> 2 votes

---
Tags: 7, views, paging
---


# Question
Title: Display selected fields from referenced node rather than just referenced node title
I've searched for an answer to this, I can't find it for the life of me.

I want to in a node display additional selected fields from referenced nodes, not just the title field of the referenced node.

Like follows:

```
CONTENT TYPE A, NODE A1
Title: Employee 134
First Name: John
Last Name: Smith
Content Type B Reference: Job 3

CONTENT TYPE B, NODE B1
Title: Job 3
Job: Carpenter
Description: Constructs tables and chairs.
Image: carpenter.jpg

```

I can currently only display for A1:

```
Employee 134
John
Smith
Job 3

```

I want it to display:

```
John Smith
Carpenter
[carpenter.jpg]

```

# Answer
Using display suite, create a new display mode for Content Type B, and show only the Job and Image fields.

Modify display for Content Type A to use the new display mode.
> 0 votes

# Answer
You can do this through Views module, it's usually referred to as displaying "Parent" info on "Child" nodes through the reference field.

1. Create Views of type Content displaying Content type A nodes, you'll probably want to create the Block display
2. Under Advanced (third column in Views) add the Relationship for your Reference field. You can require it if you only want to show A nodes that have a reference to B nodes.
3. Under Fields add the `Job` and `Image` fields. They will now be available since the Relationship has been added. These fields will use that Relationship to show information from type B nodes. Without that Relationship the fields will show information from type A nodes.
4. Now add the `ID` Contextual Filter (Content Category) and configure it to `Provide default value` from `Content ID from URL` (set other contextual filter options as needed). This limits Views to only show information related to the node that is currently being viewed and is showing this Views display.
5. Save the Views and under Blocks place the newly created block into a region in your theme, and configure the Block settings for the contextual filter. Set Block Visibility to only show on node type A nodes.

This will show the referenced node information on the node that references it.
> 0 votes

---
Tags: nodes
---


# Question
Title: Allow some products to be sold only in bundles (groups) with some other products
I'm making a commerce site with Drupal 8 and Drupal commerce and I have a not so common request. Some of the products should be available to buy only in groups (bundles) with some other products. E.g. if you want to buy product A in quantity 100 you must also buy product B, product C and/or product D and sum of them (B+C+D) must also be 100. Other way it shouldn't be possible to buy any of them separately.

I saw that there are some Bundle modules (not even sure if they could fulfill this request), but they exist only for Drupal 7.

So is there some module for D8 which will allow grouping products like this. If not what would be the best way to achieve this feature?

# Answer
> 1 votes
As far as I know, there are no **supported** modules to acheive what you want.

So if you want a sustainable and future proof solution, you should probably code it yourself.

I would go for solution, where I create a custom entity type, **Product Validation**.

Here are some fields, that I think it should contain:

1. **Product ID** (The product it's active on).
2. **Applies above (quantity)** (A minimum quantity that must be purchased, before the validation is applyed).
3. **Depending products** (Products that be must purchased too).
4. **Min SUM** (The minimum sum of all the depending products).

Those are just fields that should probably be there, you can always add more fields like, if only one of depending products must be purchased, or all of them, maybe also support for multiple product ID's to avoid creating duplicates, etc.

Then add a custom validate handler, when the user clicks the `place order` button on the cart page.

**EDIT:** To alter the cart form you could use hook\_form\_alter, and check if `(strpos($form_id, 'views_form_commerce_cart_form_default') === 0`. The cart form has a unique ID per order so that's why you want to do like that. Then you can add `$form['#validate'][] = 'MY_MODULE_product_validation'`, where the logic will then be.

Your logic will look similar to this:

```
$product_validation = $entityTypeManager->getStorage('product_validation')->loadByProperties([
  'product_id' => $product->id(),
]);

if (isset($product_validation)) {
  if ($product_validation->getAppliesAbove() > $product->quantity) {
    $total_quantity = 0;
    foreach ($product_validation->getDependingProducts() as $dep_product) {
      // Check if $dep_product has been added to cart.
      // If yes $total_quantity += $cart->getItem('something')->quantity.
    }
    if ($product_validation->getMinSum() >= $total_quantity) {
      return TRUE;
    }
    return $form_state->setError($form, 'something');
  }
}

```

**OBS:** This code is using dummy variables and is intended to help you understand the logic, not as a "ready to implement" solution.

I hope it all makes sense.

# Answer
> 0 votes
Drupal Commerce doesn't currently have a STABLE bundle module ported to 8, but if you like living on the edge, commerce\_product\_bundles which is under development MIGHT be able to get the job done. You can assign multiple bundle items (a product wrapped in a bundle item) to a bundle group (a group of bundle items sold together), and can specify the minimum and maximum quantities for each of those bundle items, as well as a new selling price if you like.

You might be limited setting the minimum and maximum quantities of Products B, C, D to reach 100 the way you mentioned, in that you would need to give a fixed quantity range to B,C and D. (like 34, 33, 33 etc) But you certainly can require/allow the 100 of A, and predetermine a satisfactory combo of B,C,D equaling 100. You can also require products B,C,D, and not require A... etc. You'd have to test it with your use case to see if it's sufficient.

The docs don't explain the full function of the D8 development version, but you can read their brainstorming session here: https://www.drupal.org/project/commerce\_product\_bundle/issues/2799643

Just beware, when I tested the module personally, it broke my cart path when I tried uninstalling it, so test it locally first. You might be able to sponsor some tweaks and a stable release on it, or this may give you some ideas as to how to accomplish it yourself with your own custom code.

Here are some photos of the UI to help you wrap your mind around the function: Hope this helps!

---
Tags: 8, commerce
---


title: Add a condition on dropdown selection

text:
# Question
Title: Add a condition on dropdown selection
I have a dropdown in a node and the id of the dropdown is "field\_b\_status". I want to add condition in a rule if the drop down value is equals to one of the value "Complete" then send email.

When i try to add that, i see the error. **Data selector field\_b\_status.value for context Data to compare is invalid. Unable to get variable field\_b\_status, it is not defined.** Please see the screenshot:

Can you please help me how to add dropdown "field\_b\_status" in the condition?

# Answer
> 0 votes
Rules in Drupal 8 doesn't have much flexibility. So in your case, you will do the following to achieve it.

Under Data selector, you will type: **{{node.field\_b\_status.value}}** and choose Direct mode instead.

And rest will be similar to your screenshot.

# Answer
> 0 votes
The problem is that `field_b_status.value` is not a valid value in the data selector. I guarantee that it does NOT show up in the autocomplete for the data selector. Why? Because it is not fully qualified. If you want a field value, you need to also specify the entity that the field belongs to.

The solution is, when using the data selector, choose one of the values listed in the autocomplete for the data selector - DO NOT type in your own value. What you want to select is probably something like `node.field_b_status`, or `node.field_b_status.value`, depending on what type of field `field_b_status` is, whether it's a single-valued or multiple-valued field, and depending on how the event provides the entity context (I assume it's something like "node", but it doesn't have to be ...).

---
Tags: 8, rules
---


title: 404 on index.php?q=admin

text:
# Question
Title: 404 on index.php?q=admin
I restored my Drupal 7 site from backup and now can't get to the admin page.

Getting a Drupal 404 page on `example.com/index.php?q=admin` as well as `example.com/?q=admin`.

Needless to say `admin/` also gives a 404.

Same file system and database were working yesterday.

# Answer
> 1 votes
I encountered this problem on a *localhost* install of *Drupal 8* on *Ubuntu18.04*. I could see the base url page but every link into my site was 404 (e.g. any link from the admin bar).

**Clean URLs**

I started with the Drupal.org page, "Page Not Found" Errors on every page except homepage where I found this:

> To configure mod\_rewrite from .htaccess, the Apache config needs to allow at minimum "FileInfo" overrides. In order to make the simple DirectoryIndex test work, apache needs to allow "Index" overrides.

Then I found a solution which translated this for me into practical steps. I enabled "Clean URLS", following a hint on Install Drupal on Ubuntu 18.04 Bionic Beaver Linux.

1. edit Apache's default site configuration /etc/apache2/sites-enabled/000-default.conf

```
$ sudo vim /etc/apache2/sites-enabled/000-default.conf

```
2. insert the following just after the line that has *DocumentRoot /var/www/html*

```
<Directory /var/www/html/>
           Options Indexes FollowSymLinks
           AllowOverride All
</Directory>

```
3. restart Apache

```
$ sudo systemctl restart apache2

```

# Answer
> 0 votes
The answer appears to be that the `/admin` or `?q=admin` path only exists when you are logged in to Drupal as an administrator.

The login page is reached at `example.com/user/login`.

---
Tags: .htaccess
---


# Question
Title: Can I translate nodes and provide access to their translated content without the use of a site-wide language switcher?
## Intended behaviour / question

1. Writer creates /node/5001
2. Translator translates /node/5001 to french using all the niceties of the Content Translation backend system
3. Visitor goes to /node/5001 and sees a link in the sidebar to the french version
4. Visitor arrives at /fr/node/5001, reads it, and then clicks away using one of the main menu links or anything in the sidebar
5. Visitor is now browsing the website in English, since that's the main language of the website, and the language menu links are written in. The viewing of translated content behaves just like viewing any other page on the website; it doesn't change languages for good.

Things are going wrong between steps 4 and 5, since step 4 puts the website in "French mode" which means all menu links point to french versions of content. In theory, all subsequent browsing will be in French (which is not what I want), and in practice the language will switch back and forth between French and English depending on the availability of translations (which is even worse), even though the URL will include the /fr/ prefix no matter what is actually displayed.

Is there a practical solution to this?

## Background / supplemental

I've enabled Drupal 8's Content Translation and Language modules. Language detection & selection is done using the default mechanism, which recognizes language code prefixes in the first component of the website's path (for example, `/fr/node/1`, for the french version of node 1).

I'm now wondering if there's any way, without going toe to toe in a fight to the death with the Drupal final boss, to provide translations ONLY of the content on select pages, but NOT of the entire site, such that the content is made available through links on my website, with the default language being restored to English when navigating away from those same pages?

The intention is to use Drupal's built-in (though other non-core suggestions are welcome) translation management features to create and manage subordinate multilingual content on the backend, but then access these translations on a case by case basis through links in a block for example, without having these *navigation* actions trigger persistent language *selection* events (from a user perspective) which rewrite all the menu URLs to match.

Basically, I'm trying to get something to work that would be the Content Translation module equivalent of a bunch of multilingual PDFs attached to a single piece of English content. Except I don't want to link to PDFs, I want to link to ordinary web pages, with the only real difference being that they're written in another language, and linked to an English version behind the scenes.

Am I wasting my time with this, or is there a way to translate just a subset of my content, with access opened up to those translations from the english site, minus the persistence of a full-on language switch for the remainder of the browsing session?

# Answer
Drupal multilingual features are very versatile and can cover most if not all cases. It is still a fairly complex feature and it is necessary to understand some concepts before you know how to configure everything to satisfy a particular need.

The most important concept to understand in your case is the two-part nature of the multilingual system. One part is called the interface and the other is content. Interface and content are translated separately. Once you translate your interface you can add as many nodes/content as you like and you don't have to translate the parts of the interface again, you only have to translate the node content (if you wish to have that content translated at all).

Interface language and Content language don't need to match. You can have the English interface being active while watching a French node.

The **Detection and selection** configuration under Languages configuration allows for different settings when it comes to selecting which language to choose for either the interface or content.

There may be more than one combination of options that solves your particular problem, and I haven't tested this, but I'll offer the most likely solution.

You don't want the interface language to change, you always want the English menus etc. That means you shouldn't use the URL under Interface language selection at all, just use the default fallback. This means your URLs won't ever have the `/fr/` in from of them (path prefix selects the interface language, not the content).

You need to enable the separate Content detection (separate from Interface selection), and set that to `Content language`. This option adds a special parameter to your nodes links that tells Drupal which node translation to serve.

Here's the likely config:

Here is what the links might look like:

`/node/97?language_content_entity=en`

`/node/97?language_content_entity=fr`

You can use Views or simply create language-specific Menus or menu items that list those links.
> 2 votes

# Answer
A simple solution in such cases would be to remove the language switcher and provide for translated content only modal links:

```
<a class="use-ajax" data-dialog-type="modal" data-dialog-options="{"width":800}" href="/fr/node/1">French version</a>

```

You could add the links to the node, in a template or preprocess hook. Or create a block (View or custom block plugin), which lists the available translations of the current node as modal links.

How to build such links see How to open a popup form from a view link?
> 2 votes

# Answer
Just to add to prkos's excellent accepted answer, I found that once I configured my website according to his instructions, if I really wanted to let end users use `/fr/` language path prefixes, thereby making pages accessible without full-site switching at paths like `/fr/node/1`, I could do so via the following .htaccess / mod\_rewrite rule:

`RewriteRule "^fr/(.*)" "https://%{HTTP_HOST}/$1?language_content_entity=fr" [P,QSA]`

That assumes that mod\_proxy and SSLProxyEngine are both enabled / on.

One issue with the above is that pages will be suddenly be accessible at two different URLs, without a visible redirect, which may or may not interfere with analytics. Also, the canonical URL in the site's meta will differ from the URL shown, even if the Redirect module is enforcing canonical URLs.

Anyhow, I just thought I'd throw that "solution" out to the wind, in case someone reading this in the future REALLY has their heart set on parameterless URLs. As for me, I'll probably just stick to the default of `node/1?language_content_entity=fr`.
> 1 votes

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


# Question
Title: Does Acquia Dev Desktop allow 2 or more local sites using different core versions?
The goal was to assemble a local version of a live Drupal 7 site, plus a new installation of Drupal 8 which would become the upgraded version of the Drupal 7 site. But whether I create the Drupal 7 or the Drupal 8 version first in Dev Desktop 2 ("DD"), it seems not to allow the 2nd version in a different Drupal version. Despite different database names clearly defined in DD, a second site added is always being confused as associated with the 1st site's database. What needs to be done differently, if indeed it should be possible to have these 2 versions coexisting in the DD sites list?

# Answer
> 1 votes
Yes Aqcuia Dev Desktop 2 allows you to work on Drupal 7 and Drupal 8 sites together. I have multiple 7 and 8 sites built on Dev Desktop 2. **I do however keep the codebases for them in different directories.** My D7 production copy sites are not kept in the Sites/devdesktop folder. Also, they are all imported to Acquia, not generated by Acquia. The only "crossing of wires" I ever got was in cloning composer built 8 sites, and those were actually Acquia generated sites.

My D8 composer sites, though they are in Sites/devdesktop are also imported, not generated by Aquia, as I am using this composer based Drupal 8 project: https://github.com/drupal-composer/drupal-project

Drupal has docs on it here: https://www.drupal.org/docs/develop/using-composer/using-composer-template-for-drupal-projects

There is also a short YouTube video on how to install it with composer here: https://m.youtube.com/watch?v=IhWAegz8glk

To import a site rather than letting Acquia build it, do the following:

* click the + button on the DD UI panel and select "import local Drupal site".
* Select the directory of the codebase
* name the site,
* choose php version.
* create a new database.
* Click OK.

You can then use backup and migrate to restore your D7 data in your case.

I'm honestly not sure if it's the importing feature itself, or the separate directories that is doing the trick, but it has been working great for me!

Let us know!

---
Tags: acquia-dev-desktop
---


# Question
Title: Is there a way to get the max size of a varchar textfield?
I have an entity with a textfield created using the core **Fields** feature that looks like this when I inspect the type of the field table in the database `varchar(40)`.

I want to be able to determine max size of the string that can go into this field programmatically. I.e. I want do know if there is a function I can call with suitable parameters, and it would return 40.

A Drupal API function would be the preferred answer, but a could live with a PHP function if this is not available in the Drupal API.

I was reminded in a comment (now deleted) that I previously had answered a very similar question.

However, that answer relies on the field in question being part of a schema.

This *new* question is about fields that has been created using the core **Fields** feature. (I.e. using `drupal_get_schema()` will not fly.

# Answer
> 3 votes
There's no single function that will extract the value for you, but `field_info_field()` will get you an array that contains the data:

```
$info = field_info_field('field_foo');
if (isset($info['columns']['value']['length'])) {
  // Do something with $info['columns']['value']['length']
}

```

It it's a core text field, `value` will always be the name of the column you need to check. For other field types it may differ.

---
Tags: 7, entities, database
---


# Question
Title: How to add theme from github with composer
I have a Drupal 8 installation and I like to install a theme from github.com using composer.

It is this theme https://github.com/forumone/gesso

Can anybody help me what I have to add to the composer.json and where?

# Answer
If you still want download theme from github, you can edit file **composer.json** by add more repository:

Add this code

```
 {
    "type": "package",
    "package": {
        "name": "forumone/gesso",
        "version": "2.0",
        "type":"drupal-theme",
        "source": {
            "url": "https://github.com/forumone/gesso.git",
            "type": "git",
            "reference": "8.x-2.x"
        }
    }
}

```

after

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

```

and run `composer require "forumone/gesso"` to download theme and update composer.lock.
> 5 votes

# Answer
Adding this answer for more clarification for future readers:

The theme in question as of this comment date has a stable release from April 2018. But the development branch is active and updated.

In such a case, you would do this to fetch it instead of the latest stable:

`composer require drupal/gesso:2.x-dev`

To go even further, you can tack a commit sha on the end of the version to 'pin\` the code at that commit - unless you want rolling updates from HEAD. This is a versatile option that you can opt for in Composer that is not so known in the Drupal circles.

You don't need to pull from GitHub in this instance. The only time you would want to do this is when a package does not live on drupal.org at all, 99% of the time they are on Packagist (third party packages, like Prophecy etc).

The rare case is when you have a private repo on GitHub/GitLab or elsewhere, then this is the approach you would want to take to fetch it.
> 4 votes

# Answer
You shouldn't use the Github repository, unless you're getting involved in the theme's development - it doesn't contain a composer.json file, so isn't supposed to be installed this way.

You could mess about trying to set it up as a custom repository, but given that this is a theme hosted on (and packaged by) drupal.org, it would be easier to just install it the standard way:

```
composer require drupal/gesso

```
> 2 votes

# Answer
In your theme root add `composer.json` as follow

```
 {
  "name": "my/theme",
  "description": "Theme.",
  "type": "drupal-theme",
 }

```

And in your main composer.json(Drupal) under "Repository" section add

```
{
  "type": "vcs",
  "url": "git@github.com:my/theme.git",
  "no-api": true
}

```

And then run `composer update`
> 0 votes

---
Tags: 8, installation, composer
---


# Question
Title: Why isn't my custom Form API #states applied in my webform yaml editor working?
I have the need to set visibility state of a checkbox option in one question (**Table checkbox select**) based on the value of another checkbox in the ***same table***. I also have other scenarios where I would need same functionality but across different questions in the same webform.

I know I can easily do it between two different questions ( 2 different elements) with the built-in conditional logic UI in webform but no such UI option for my case now (afaik) so I'm trying to set it via the custom one and this is my first time with form states and custom condition in webform so I appreciate your kind help so greatly.

I went through trials and errors and the code wasn't being saved till I, thanks to @jrockowitz 's tip, learnt that I was using php code where I need to use yaml code since I'm using the yaml source editor (shown in the screenshot below). When I fixed that, my custom code would save and it reflects as entered in the webform source yaml. However, the custom condition is still not working as expected and I'm still not sure why.

I'm adding the code in the Edit source box accessible via clicking its link on the form "Conditions" tab.

I got the selectors for the involved question options from the "Available selectors" list by clicking on the "Help" link under "Learn more about Drupal's Form API #states." on the "Conditional Logic" for the element editing tab in my webform.

This is a sample full yaml code for the form with a sample question and what I want to achieve but not yet working:

```
some_question:
  '#type': tableselect
  '#title': 'some question'
  '#options':
    q1: 'q1 (hide if q2 is checked)'
    q2: 'q2 (hide if q1 is checked)'
    q3: q3
    q4: q4
    q5: q5
    q6: q6
    q7: q7
  '#states':
    ':input[name="some_question[q2]"]':
      invisible:
        ':input[name="some_question[q1]"]':
          checked: true
    ':input[name="some_question[q1]"]':
      invisible:
        ':input[name="some_question[q2]"]':
          checked: true

```

What am I missing here ?!

* For those who maybe aren't familiar with the UI edit source, this is a link with info and screenshots : https://www.drupal.org/node/3012686
* **Note:** As per @leymannx 's kind advice, I re-wrote the whole question to rid it of my dump of updates with my trials and errors. I hope it's now cleaner, clearer and more worthy of up-votes :)

# Answer
For the simple case where Question 2 is shown only if Question 1 is left unchecked, your YAML doesn't look right to me. If you're editing YAML in the conditions tab for the Question 2 checkbox, then just the last 3 lines should suffice:

```
invisible:
  ':input[name="some_question[q1]"]':
    checked: true

```

I don't think you want the `"#states"` key to be in there anywhere, nor do you want to include any selector information for Question 2.

That's if the YAML is part of Question 2's Condition source. If on the other hand the YAML you're showing is part of the *form's* source, then it should probably look something like this:

```
q2:
  '#type': checkbox
  '#title': 'Question 2'
  '#states':
    invisible:
      ':input[name="some_question[q1]"]':
        checked: true

```

Note that the `#states` key is shown here, but only once - we're omitting 2 out of 3 of the same lines as above.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Can't render node view mode pro-grammatically
I try to render an HTML data from my node view mode but unfortunately, I have some small progress. I did some searching and modification on the others code Here. I have this now.

```
$nid = 145;
$entity_type = 'node';
$view_mode = 'pdf';

$view_builder = \Drupal::service('entity.manager')->getViewBuilder($entity_type);
$storage = \Drupal::service('entity.manager')->getStorage($entity_type);
$node = $storage->load($nid);
$build = $view_builder->view($node, $view_mode);
var_dump($build);
die();

```

But when I run it I got this error

> TypeError: Argument 1 passed to Drupal\Core\Routing\CurrentRouteMatch::getRouteMatch() must be an instance of Symfony\Component\HttpFoundation\Request, null given, called in C:\wamp64\www\executive-coatings\docroot\core\lib\Drupal\Core\Routing\CurrentRouteMatch.php on line 127 in Drupal\Core\Routing\CurrentRouteMatch-\>getRouteMatch() (line 99 of core\lib\Drupal\Core\Routing\CurrentRouteMatch.php).

As I did step by step checking I got that just issue is with `$build = $view_builder->view($node, $view_mode);`

What is wrong with this code? Am I in the right way to render HTML data from a view mode?

**MORE INFO**

The Idea behind this is to get node data according to a specific view mode, then render the data to HTML format and use that HTML data in a PDF function to generate the related PDF file.

I simply use this code in one of my custom modules, that is ecc\_pdf module. as you can see I simply set a valid ID to load valid data for the test process. My node type name is `safety_report` this is my full view mode list

I use Drupal 8

PHP 7.2

**For checking that I have any issue with other codes or not, I create a new basic site and apply this part of code inside a custom module but I get the same error again.**

This is my new custom test module code, This is my full module code for test.mudole file.

```
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
use Drupal\Core\Render;
$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';
$builder = \Drupal::service('entity_type.manager')->getViewBuilder($entity_type);
$storage = \Drupal::service('entity.manager')->getStorage($entity_type);
$node = $storage->load($nid);
$build = $builder->view($node, $view_mode);
$output = \Drupal::service('renderer')->render($node);
var_dump($node);

```

This my info file

```
name: ECC TEST
description: For creating the custom TEST
package: Custom
type: module
version: 1.0
core: 8.x

```

As I said I create just a new site, and I don't have any other file in my module, I just have .mudole and .info.yml file that I mention above. And the Article node that I test just is Drupal default.

This is the full error that logged for me

# Answer
> 3 votes
Your problem is here:

```
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
use Drupal\Core\Render;
$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';
$builder = \Drupal::service('entity_type.manager')->getViewBuilder($entity_type);
$storage = \Drupal::service('entity.manager')->getStorage($entity_type);
$node = $storage->load($nid);
$build = $builder->view($node, $view_mode);
$output = \Drupal::service('renderer')->render($node);
var_dump($node);

```

You have dumped your code raw into a file. You cannot do that - your code is being called before Drupal has bootstrapped. You need to put your code into a function some hook that is called after Drupal has bootstrapped. I don't know what you're trying to accomplish, so I can't give any more info than that.

---
Tags: 8, entities
---


# Question
Title: Webform detect sender country automatically
We use Drupal 7 webform module. We want to detect the sender's Country automatically from the IP Address. Then based on the Country, the form is sent to another e-mail address. We do not want an extra location checkbox, as not to harm the conversion rate.

So for example: If the person is located in the US then send form submission to `us@company.eu`.

Is this possible?

# Answer
You could take a look at the ip2country module, which saves the country on the $user object based on the user's current IP address.

From the description of the module:

> This module uses a visitor's IP address to identify the geographical location (country) of the user. The module makes this determination and stores the result as an ISO 3166 2-character country code in the Drupal $user object, but otherwise has no effect on the operation of your site.
> 0 votes

---
Tags: webforms
---


# Question
Title: Scoping an admin link to only show for certain node bundles
I have 2 node content types / bundles, A and B. each A has a relationship with multiple Bs. When on the edit page, node/%/edit, for A, I want to show a link to the list of related B so that an editor can easily see a prefiltered list of B for A.

I have created a route:

in `my_module.routing.yml`

```
my_module.related_B:
  path: '/node/{node}/related_b'
  base_route: entity.node.canonical
  options:
    _admin_route: TRUE

```

and have configured a view page at the same url `node/%/related_b` that contextually filters porperly. no issues there.

The link is added to the menu via the `my_module.links.task.yml`

```
my_module.related_B:
  route_name: my_module.related_B
  title: 'Related B'
  base_route: entity.node.canonical
  weight: 100

```

Everything shows up and looks/works the way I want it to.

The problem is that I cannot seem to figure out how to limit that link/view to only show and work when on the edit page for an instance of content A. It shows on EVERY node edit page.

I've tried the following and did not seem to get anywhere:

* trying to hook into `hook_local_tasks_alter` in `my_module.module`
* custom `RouteSubscriber` Plugin

In D7 I was abel to accomplish this with a hook and access callback:

```
function my_module_menu()
{
    $items = array();

    // Single sync functionality
    $items['node/%node/related_B'] = array(
        'title' => 'Related B',
        'page callback' => '_B_page_callback',
        'page arguments' => array(1),
        'access callback' => '_B_access_callback',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK,
    );

    return $items;
}

function _A_access_callback($node)
{
    if($node->type == 'A' && user_access('administer nodes'))
    {
        return TRUE;
    }

    return FALSE;
}

```

# Answer
I solved this. I mentioned that I had tried `hook_local_tasks_alter` when I should have been using `hook_menu_local_tasks_alter`

```
/**
 * Implements hook_menu_local_tasks_alter().
 * @param $local_tasks
 * @param $route_name
 * @param RefinableCacheableDependencyInterface $cacheability
 */
function mymodule_menu_local_tasks_alter(&$local_tasks, $route_name, RefinableCacheableDependencyInterface &$cacheability)
{
  if ($route_name == 'entity.node.edit_form') {
    $route_match = \Drupal::routeMatch();
    $node = $route_match->getParameter('node');

    if ('A' != $node->bundle()) {
      unset($local_tasks['tabs'][0]['my_module.related_B']);
    }
  }
}

```
> 0 votes

---
Tags: 8, nodes, routes
---


# Question
Title: Fivestar appears on content type, but can't vote
I have problem with Fivestars module, (Drupal7).

It is configured in field and appears on content type page, but cannot vote (like voting is disabled - when inspecting with firebug, i see no Javascript activity over stars, and no any possible javascript conflict.)

Permissions are set correctly.

What in the world could cause this ? (it seems more-less like plug-and-play module :D )

# Answer
When adding the FiveStar field,

* If you choose "Rated while viewing" , that means all users can rate the node (with permissions) can rate the node. This is ideal to allow users to rate how well the article was writtem etc).
* If you choose "rated while editing", it will make the rating field disabled (static field) for other users than the node author. This is ideal for review nodes to allow the reviewer to leave their ratings while making the node or any other entity.
> 1 votes

# Answer
If you have checked the `permission` and chose "`rated while viewing`" correctly you must check the "`Allow users to vote on their own content.`" option in the edit section of your field as well. it lets you vote for your own content.
> 1 votes

# Answer
You should enable "users can vote for their own materials" (sorry, if translation is somewhat inaccurate).

That would be in /admin/structure/types/manage/YOUR\_CONTENT\_TYPE/fields/field\_vote

My fivestar field is called "vote", thus "field\_vote" at the end.
> 0 votes

# Answer
Make sure the "Allow voting on the entity" is enabled in the Field: Rating displays field within the View.
> 0 votes

---
Tags: rating
---


title: Twig D8 Field Format

text:
# Question
Title: Twig D8 Field Format
Is it possible via Twig to output a field's value, that uses the fields formatter. I would like to display a file field two different ways in the same twig file. The first will be a link to the file with a label to the left. The second will be the SOLR Extract text from the file, with a label on the left.

Here are the formatters I am talking about.

As shown in the second image, there are multiple options for how to display the field. Is there a way in Twig to do something like the following.

```
{{ content.field_name.FORMATTER_NAME_HERE }} or
{{ content.field_name[0].value | FORMATTER_NAME_HERE }}

```

I would like to use the `URL to file` and `Text extracted from attachment` formatters.

# Answer
> 4 votes
There's no out of the box way to display a field in twig with two different formatters. But it can be done with a hook in a custom module.

You can repurpose a field in hook\_entity\_view or hook\_ENTITY\_TYPE\_view().

Here's an example:

```
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article' && $view_mode == 'teaser') {
    $settings = [
      'type' => 'pdf_special_formatter',
      'settings' => $build['field_pdf']['#items']->getSettings(),
    ];
    $build['pdf_alternate_display'] = $build['field_pdf']['#items']->view($settings);

  }
}

```

Note that the settings may need to be altered before sending to another field formatter. You'll have to look at that field formatter for the required settings.

# Answer
> 2 votes
Technically it is possible. Field items have a public `view` method that accepts either view mode or field formatter. Unfortunately that method is not allowed by default Twig sandbox policy in Drupal. You need to override it in your settings.php file as described here.

```
{{ node.field_image.view({type: 'image', settings: {image_style: 'large'}}) }}

```

An alternative approach could be using Twig Tweak module which provides a wrapper around this method.

```
{{ node.field_image|view({type: 'image', settings: {image_style: 'large'}}) }}

```

---
Tags: theming, 8
---


# Question
Title: Display long text fields as type text input not as textarea on node forms
I have some fields which are configured as long text fields, which I need to display as `<input type="text />` instead of `<textarea></textarea>`.

I'm trying to find the correct naming convention so that I can have some theme overrides in my templates folder.

Is that the correct approach? Is there documentation about overriding specific field outputs on edit screens?

# Answer
> 2 votes
Drupal textfield widget can only be applied to string fields. https://git.drupalcode.org/project/drupal/blob/8.7.4/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/StringTextfieldWidget.php#L9

However it's not a big deal to alter its definition and make it support long strings.

```
/**
 * Implements hook_field_widget_info_alter().
 */
function HOOK_field_widget_info_alter(array &$info) {
  $info['string_textfield']['field_types'][] = 'string_long';
}

```

After having this done it should be possible to assign textfield widget to long text fields on "Manage form display" page.

---
Tags: 8, theming
---


# Question
Title: How to un-cache a specific node field (also for anonymous)
My goal is to replace (by a custom markup) the render array of `field_product` when some conditions are met. (in a ecommerce site)

**Ex:** If this is the weekend or if it is after 12pm the `field_product` must not be rendered (but a markup like "the webshop is closed")

In `mymodule_preprocess_node(&$vars)` I have tried without success:

```
$vars['content']['field_product']['#cache']['max-age']=0;

```

or

```
$vars['content']['field_product']['#cache']['contexts'][] = 'session';

```

Unfortunately, it is not working for anonymous users

The only solution I found is:

```
$vars['#cache']['max-age']=0;

```

But as you can see, all the node is un-cached... not the `field_product`

What is wrong with my code?

Again: this should be uncached for anonymous users

# Answer
You have to make sure you add `#cache` data inside of a render array only to render elements (containing `#type`, `#theme` or `#markup`). In other places of a render array it doesn't work.

Where you add cache max-age or contexts inside of an entity doesn't make a difference though, because there is no field level, only entity level caching.

Another problem is page caching for anonymous users. See How do I disable Twig and block cache for a specific module?
> 0 votes

---
Tags: 8, nodes, caching
---


# Question
Title: What is required for a view menu item to show up as a link in the admin page?
I'm creating several views that are to be used as reports. Since they all have a common topic, I'm grouping the views under a sub-path of `admin/reports` (e.g. `admin/reports/data/needs_correction` and `admin/reports/data/status`).

With most admin sections in Drupal, there's usually a landing page that lists all of the sub-content for the section. So, to provide that, I've implemented `hook_menu()` in the feature that contains the exported report views, as follows:

```
/**
 * Implements hook_menu().
 */
function MY_menu() {
  $items = array();

  $items['admin/reports/data'] = array(
    'title'             => 'Data reports',
    'description'       => 'Various reports on the status of data in the system.',
    'position'          => 'left',
    'page callback'     => 'system_admin_menu_block_page',
    'access arguments'  => array('access administration pages'),
    'file'              => 'system.admin.inc',
    'file path'         => drupal_get_path('module', 'system'),
  );

  return $items;
}

```

The only problem is that, after a cache clear, when I navigate to `admin/reports/data`, all I get is the message "You do not have any administrative items."

# Answer
In addition to the report views needing to have "Page" displays with URLs nested under `admin/reports/data`, I also had to make sure the following settings were enabled under "Page: Menu item entry" settings within the Views:

* **Type:** Normal menu entry
* **Menu:** Management

Without both of these settings, the menu links will *not* show up under the new custom reports page.
> 0 votes

---
Tags: views
---


title: Obtaining SUM('field') in PHP code

text:
# Question
Title: Obtaining SUM('field') in PHP code
Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:

```
$count = Drupal::entityQuery('node')
  ->condition('type', 'artefacts')
  ->condition('status', '1')
  ->condition('default_langcode', 1)
  ->condition('field_city', $id)
  ->count()
  ->execute();

```

but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8.

```
$sum = Drupal::entityQuery('node')
  ->condition('type', 'cities')
  ->condition('status', '1')
  ->condition('default_langcode', 1)
  ->condition('field_country', $id)
  ->aggregate('sum(field_artefact_count)', 'total')
  ->execute();

```

seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?

# Answer
> 4 votes
Use QueryAggregateInterface::execute:

```
$result = \Drupal::entityQueryAggregate('node')
  ->aggregate('nid', 'sum')
  ->condition('status', NodeInterface::PUBLISHED)
  ->execute();

```

The result returned is keyed by fieldname and aggregate function:

```
$sum = $result['0']['nid_sum'];

```

---
Tags: 8
---


title: Create module that create Content Type

text:
# Question
Title: Create module that create Content Type
I'm developing module that creates a content type. I saw the same question and there was a solution. I had tried it but it didn't work.

job\_post.info.yml

```
name: Job Post
description: A job posting content type
type: module
package: Pro Drupal Development
core: 8.x

```

job\_post.module

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

$content_type = \Drupal\node\Entity\NodeType::create([
    'type' => 'new_content_type',
    'label' => 'new content type',
  ]);
  $content_type->save();

```

# Answer
The code from your question should work in a hook\_install(). But you need a lot more configuration for a content type, which you can create the easiest way in UI. See the comment of @Hudri.

Then export the configuration to the config folder of your module, see Organizing config for use with a module
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: How do I generate PDF of HTML in a custom module?
I want to generate PDF in my custom module. Using print module we can print node. But I have made html in my custom module and that I wanted to make pdf and save it in files.

I have tried custom **dompfg** library but its working. i wanted to do something like this:

```
$html = "<h1>Header</h1><P>Pdf generated.</p>";

include ("mpdf.php"); /// This will be something to include for mpdf
$mpdf=new mPDF('win-1252','A4','','',20,15,48,25,10,10);
$mpdf->WriteHTML($html);
$mpdf->Output('../default/files/users/filename.pdf','F');
exit;

```

Any suggestions?

# Answer
There is quite a bit more involved in integrating Drupal with the mPDF library than the code snippet you show.

As often with Drupal, there is a module for that. It is named PDF using mPDF, and this is what it will do:

> This module is used for Conversion of HTML pages to PDF documents using mPDF PHP Library. It allows you to generate a pdf document of any node.

Make sure you follow the instructions in the README.txt files carefully. You need to place the mPDF library in the right directory, and install the Libraries API, for it to work correctly.
> 3 votes

# Answer
You can generate PDF Using Html using dompdf

In my case I need to create a pdf from a custom menu callback. So to achieve this

Step 1 : Download dompdf library

Step 2 : Place the library in sites/all/libraries/dompdf

Step3 : Create a function like the following for download pdf for your custom html

```
<?php

require_once("sites/all/libraries/dompdf/autoload.inc.php");
use Dompdf\Dompdf;

function generate_custom_pdf(){

  $html = '<put your html content here>'; // you may add your content here

  $dompdf = new Dompdf();
  $dompdf->load_html($html);
  $dompdf->render();
  // This does not save the pdf field and instead it opens a dialog box asking whether you have to save the pdf or not
  $dompdf->stream("ckl-sample.pdf");
  drupal_exit();
}

?>

```
> 1 votes

---
Tags: files
---


# Question
Title: Display content based on taxonomy with view
I have a hierarchical taxonomy like the following:

* Bachelor of Degree
    + Year1 (child term of Bachelor of Degree)
        - Term1 (child term of Year1)
    + Year2
        - Term2

The body text of content1, content2, … of a content type will go under the terms term1, term2, ….

Can you kindly help me in getting the view with the following structure?

* Bachelor of Degree
    + Year1 (child term of Bachelor of Degree)
        - Term1 (child term of Year1)
            * content1
            * content3
    + Year2
        - Term2
            * content2
            * content4

# Answer
> 0 votes
You would use /taxonomy/term/% - which is a default view, you don't have to create it. The view should show Fields of body content or whatever other fields you you have associated with the node that you wish to display. Your content types also need to have fields where the correct taxonomy categories can be selected when creating the node. Your view "Sort" and "Filter" criteria will determine how these nodes are ordered.

To preview your view, use /numerical term ID of your taxonomy term

To get your nodes to display, create a menu with the same parent-child structure as your taxonomy terms and set the menu paths as the taxonomy term ID. You would then display this menu as a block either on a page or in a sidebar.

# Answer
> 0 votes
**A simplistic one page approach:**

The instructions will be slightly different terminology for Drupal 8 and Drupal 7. Below is one way to get it done in Drupal 8

Create a new view of content, set to the "type" that you mentioned above. Select page, and set the page display setting to your desired format, **of: fields**. Add the content body to "fields" , as you mentioned you wanted to display the body. Also add **"Bachelor Degree" Content** field to grab the Bachelor degree vocabulary. Click **exclude from display**, as this field is only there to grab the fields for grouping. You can also deselect **link label to the referenced entity** if you like.

Under the **Advanced tab** \- **add relationships**, add **Taxonomy term referenced from field\_bachelor\_degree** so that you can add that relationship to what will be your term parent field.

You can now go back to fields and add the **parent term** taxonomy field, and use the relationship you just created. Click **exclude from display**, as this field is only there to grab the fields for grouping. You can also deselect **link label to the referenced entity** if you like.

Then under **format settings** use **grouping fields** to display the content under the term headers in your (content) view. In your case, **grouping field nr. 1** should be the taxonomy term name related to parent term, and **grouping field nr. 2** should be the first content taxonomy term. See second photo. Note: The second grouping field will only become available after saving the first one. You can then use Sort criteria how you want it (probably ascending).

Also, if your content type contains content not related to this view, you can add/change your filter criteria to only show the "Bachelor degree" vocabulary.

This method should do the trick for Drupal 8. I have provided a screen shot of the Drupal 8 view, the grouping fields, and the result of this below.

If you were asking for a complex paging solution, I have that too, but I removed it from this answer to make this answer more concise.

---
Tags: views
---


# Question
Title: How can I use 'xx time ago' as date format?
How can I use 'xx time ago' for date format in Drupal 8 nodes ?

I want to replace "xx time ago" with {{ date }} in node.

In Drupal 7 it worked with this code :

```
<?php
 print format_interval(time()-$node->created);
?>

```

# Answer
There are two ways to tackle this.

One is to just use the field formatters. If you have a DateTime field, just goto **Manage Display**, and change the **Format** to **Time ago**. Then click the gear, and pick some options. These are cache aware that will bubble up through the page, but you may end up with short cache lifetimes in some situations.

The other is to use a `template_preprocess_node()`. This is preferable when you have a timestamp that isn't a field. Then you use the date formatter service to render out the timestamp in timeago format. It is preferable to use the formatDiff() versions rather than formatInterval() (while not formally deprecated, it is discouraged).

```
function MYTHEME_preprocess_node(&$variables) {
  /** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
  $date_formatter = \Drupal::service('date.formatter');
  $request_time = \Drupal::time()->getRequestTime();
  $variables['foo'] = $date_formatter->formatDiff($request_time - 12345, $request_time, [
    'granularity' => 3,
    'return_as_object' => TRUE,
  ])->toRenderable();
}

```

When you specify `'return_as_object' => TRUE` with the formatDiff() functions, a `FormattedDateDiff` object gets returned, which contains the formatted string as well as a mostly accurate `[#cache]['max-age']` entry in a render array to make this work with Drupal 8's new caching system. Then you can just use `{{ foo }}` in your Twig template; the render engine will do the right thing with the render array instead of a plain string.

Also read the docs on `DateFormatterInterface` for the `formatTimeDiffSince()` and `formatTimeDiffUntil()` variants, and for the `$options you can pass in`.
> 16 votes

# Answer
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Datetime%21DateFormatter.php/function/DateFormatter%3A%3AformatTimeDiffSince/8.2.x

$this-\>date-\>formatTimeDiffSince($time\_stamp);

or

\Drupal::service('date.formatter')-\>formatTimeDiffSince($time\_stamp);
> 3 votes

# Answer
The easiest approach is to prepare it in ỳourtheme\_preprocess\_node() and then just print it in the twig template.

However, with D8's render caching, trying to do a time ago output on the server side can not work, unless you disable caching. It will be calculated on the first request and then never change again.

Instead, you want to send the time in an easy to parse markup, and then use JS to display it as a time ago format. See how d.o does that for comment dates: https://www.drupal.org/node/2704717 (it also includes functionality to switch between relative and absolute dates with a double click).
> 2 votes

# Answer
**Twig has a native Date extension that provides a "Time Ago" filter**

See http://twig.sensiolabs.org/doc/extensions/date.html

**|time\_diff** is the one you want. The problem is Drupal doesn't include this extension by default.

So to get this in your twig templates do the following

* Install Twig Extensions Drupal Module (Be sure to follow the instructions) - https://www.drupal.org/project
* In Terminal in your Drupal Site
    + $ composer require twig/extensions
    + (be patient ... it took a while)
* Enable Module
* Use the Filter in your Twig templates

{{ field\_my\_date|time\_diff }}

Renders like "10 MONTHS AGO"
> 2 votes

# Answer
Here is Answer,

in your .theme file add below code

```
function themename_preprocess_comment(&$variables) {

  $date = $variables['comment']->getCreatedTime();
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@author', array('@author' => $variables['author'], '!datetime' => '<span class="comments-ago ">' . $variables['created'] . ' ago </span>'));

}

```

and render in your `comment.html.twig` file below code

```
{{ created }} {{ 'ago'|t }}

```

hope it will helpfull thank you...
> 0 votes

---
Tags: nodes, 8, datetime
---


title: File upload via REST returns 403

text:
# Question
Title: File upload via REST returns 403
I've been attempting to get a file to upload using REST services and have been having a heck of a time getting it to work. All attempts come back as 403 (Forbidden).

Here's the code:

```
export const postImage = async file => {
  const url = "http://XXXXXX.com/entity/file?_format=json";

  const reader = new FileReader();

  reader.readAsDataURL(file);

  reader.onload = async e => {
    const body = {
      filename: [{ value: file.name }],
      filemime: [{ value: file.type }],
      filesize: [{ value: file.size }],
      type: [{ target_id: "image" }],
      data: [{ value: Base64.encode(e.target.result) }]
    };

const requestObject = {
  body: JSON.stringify(body),
  method: "POST",
  mode: "cors",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: "Basic XXXXXXXXX",
    "X-CSRF-Token": "XXXXXXXX"
  }
};

const response = await fetch(url, requestObject);

const data = await response.json();

return data

```

I have been able to properly POST with content just fine using the same authentication. Setup for File in REST is just like with Content (JSON, basic auth). The account I'm posting from has full admin privileges. Any help would be greatly appreciated.

# Answer
I was missing the File Entity module. Installed it and was good to go.

Also, was having trouble when using normal json format. Switched to hal\_json and that got it.

It's also worth noting that using Base64.encode is unnecessary because FileReader does that for you. Also, you need to split off the file type from the returned data string, otherwise the file will be corrupted when you go to upload it.
> 1 votes

---
Tags: javascript, files
---


# Question
Title: How to get formatted date string from a DateTimeItem object
I have a standard Drupal date field 'My date' (field\_my\_date). I can get its value:

```
$node->field_my_date->value  // returns: "2017-12-14T08:00:00"

```

But I want to get a formatted date string, which should look like: "14.12.2017".

If I analyse the field in the interactive shell (drush core-cli), then I see, that I can get the DateTimeFieldItemList object or DateTimeItem object:

```
>>> $node->field_my_date
=> Drupal\datetime\Plugin\Field\FieldType\DateTimeFieldItemList {#8836
 0: Drupal\datetime\Plugin\Field\FieldType\DateTimeItem {#8841},
}

>>> $node->field_my_date[0]
=> Drupal\datetime\Plugin\Field\FieldType\DateTimeItem {#8841
 value: [
   "value" => "2017-12-14T08:00:00",
 ],
}

```

But I have not found any method to reformat the date string. Is there some possibility to define the format of the output date string? Or do I have to reformat the output string e.g. like this:

```
date("j.n.Y", strtotime($node->field_my_date->value));

```

# Answer
> 48 votes
A date field has two properties, `value` to store the date in UTC and `date`, a computed field returning a DrupalDateTime object, on which you can use the methods getTimestamp() or format():

```
// get unix timestamp
$timestamp = $node->field_date->date->getTimestamp();
// get a formatted date
$date_formatted = $node->field_date->date->format('Y-m-d H:i:s');

```

For a date range field:

```
// formatted start date
$start_date_formatted = $node->field_date->start_date->format('Y-m-d H:i:s');
// formatted end date
$end_date_formatted = $node->field_date->end_date->format('Y-m-d H:i:s');

```

# Answer
> 6 votes
The Accepted answer is good, but for anybody that would like to use the New **DrupalDateTime** here are few examples.

I. If you have a date and want format it, just pass it to the static method of the class (DrupalDateTime) as follows. You can replace the string with your date variables. Below shows both using the static version and non static version of **DrupalDateTime**

```
 $date = DrupalDateTime::createFromFormat('j-M-Y', '20-Jul-2019');
// Using the static method prints out: 20-Jul-2019:11:am

$date = new DrupalDateTime('now');  // grab current dateTime using NON static
$date->format('l, F j, Y - H:i'); // format it
// prints out nicely formatted version: Tue, Jul 16, 2019 - 11:34:am
// you can remove H:i and what's after it if you don't want hours or am pm

$date = new DrupalDateTime('now');  // grab current dateTime
// Or print $date->format('d-m-Y: H:i A');
// prints out: 16-07-2019: 11:43 AM

```

More examples:

```
$date = new DrupalDateTime();
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// The above prints current time for given Timezone
// prints : 07/16/2019 10:59 am

// Another variations of the above except it takes specific date and UTC zone
$date = new DrupalDateTime('2019-07-31 11:30:00', 'UTC');
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// prints 07/31/2019 6:30 am

```

To use these in your module/code you need to include the following at the top of your file;

```
 use Drupal\Core\Datetime\DrupalDateTime;

```

**How to test it with Drush** Save the above code in a php script let drush run the srcipt after it bootstraps drupal like:

```
drush -r /path-to-your-drupal-documentRoot -l example.com scr ~/path-to your-script

```

For multisites make sure you use http://example.com with the drush -l version

# Answer
> 1 votes
To avoid the next Y2K type problem (Unix timestamp fields running out of byte ), the dates are stored in SQL's date fields. The entity object is going to have the same value as is returned from the storage media (SQL).

When you display this using the standard render code, the display widget will handle the formatting. You can set this in the Entity Display form.

If you are doing this in your code, you will need to provide the formatting code yourself. It's not hard using the DateTime object with code similar to.

```
$new_datetime = DateTime::createFromFormat ( "Y-m-d\TH:i:sT", $row["timestamp"] );
$formatted_date $new_datetime->format('j.n.Y');

```

There's probably a way to do this in twig, but it would be much easier in a template preprocess hook.

---
Tags: 8, datetime
---


# Question
Title: Display summary + read more links if body content is long, otherwise display body alone
We have a content type which has a customized template. In general, the body content of these nodes is short -- one to two sentences at most.

In some cases, however, the body content is a paragraph or more.

If the body content is shorter than 200 words, we would like to display the body field as-is.

If the body content is longer than 200 words, we would like to display the summary with a customized "read more" link.

Besides digging into the content array and counting words in the template, is there a graceful way to do this with view modes or field templates?

At the moment our clunky solution is to render both display types and swap between them with javascript, but this displays the "read more" link even when the body content is short enough to be displayed without the need for a summary.

## node--custom.tpl.php

```
<?php
// Other fields above..

$summary = field_view_field('node', $node, 'body', [
    'label' => 'hidden',
    'type' => 'text_summary_or_trimmed',
]);

// Render summary of body, which is visible by default
print render($summary);

// Render full body as hidden with 'element-invisible' class (see field--body--timeline.tpl.php)
print render($content['body']);

?>

```

## field--body--custom.php

```
<?php if($element['#view_mode'] !== 'full'): // Display trimmed version ?>
    <div class="<?= $classes; ?>">
    <!-- this is the summary field -->
        <?php foreach($items as $delta => $item):
            print render($item);
        endforeach; ?>
        <a class="fullTextButtonOn">Read More…</a>
    </div>
<?php else:
    // Display full body text with the element-invisible class and hidden by default ?>
    <div class="element-invisible <?= $classes; ?>">
    <!-- this is the full body field -->
        <?php foreach($items as $delta => $item):
            print render($item);
        endforeach; ?>
        <a class="fullTextButtonOff">…Read Less</a>
    </div>
<?php endif; ?>

```

## Resulting HTML on render

```
<div class="field field-name-body field-type-text-with-summary field-label-hidden">
    <!-- this is the summary field -->
    <p>Leverage agile frameworks to provide a robust synopsis for high level overviews. Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition. Organically grow the holistic world view of disruptive innovation via workplace diversity and empowerment.</p>
    <a class="fullTextButtonOn">Read More…</a>
</div>

<div class="element-invisible field field-name-body field-type-text-with-summary field-label-hidden">
    <!-- this is the full body field -->
    <p>Leverage agile frameworks to provide a robust synopsis for high level overviews. Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition. Organically grow the holistic world view of disruptive innovation via workplace diversity and empowerment.</p>
    <p>Bring to the table win-win survival strategies to ensure proactive domination. At the end of the day, going forward, a new normal that has evolved from generation X is on the runway heading towards a streamlined cloud solution. User generated content in real-time will have multiple touchpoints for offshoring.</p>
    <a class="fullTextButtonOff">…Read Less</a>
</div>

```

# Answer
> 0 votes
Have you seen the Smart Trim module, that allows you to trim text fields to a given length, in words or characters, you can also add a read more link.

From the module description:

> After installing and enabling Smart Trim, you should see a "Smart trimmed" option in the format dropdown for your text fields. This is located in the "Manage Display" section of "Structure-\>Content types. With smart trim, you have control over:
>
> * The trim length
> * Whether the trim length is measured in characters or words
> * Appending an optional suffix at the trim point
> * Displaying an optional "More" link immediately after the trimmed text
> * Stripping out HTML tags from the field

---
Tags: 7, theming
---


title: How can I load a Store by user ID?

text:
# Question
Title: How can I load a Store by user ID?
I am building a multi-seller commerce site, where a user can register and sell their product. I need to display a menu link if the user is anonymous to "become a seller", where they are directed to log in and a create store form.

If the user is logged in, I want to display a menu link that displays "My Store" if they previously created a store. To determine if they have a store, how can I load a store via their user ID?

I have been unable to find an example where someone can load a user's store.

# Answer
The user ID is saved on the store when it's created. Therefore you can load it with code similar to the following one.

```
$store = \Drupal::entityTypeManager()->getStorage('commerce_store')->loadByProperties(['uid' => \Drupal::currentUser()->id()]);

```

That will load the store based on the currently logged-in user.
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: Set parameter for internal or external traffic based on IP
We want to block external traffic in Google Tag Manager and I am trying to do something like shown here.

I created this:

```
/**
 * Implements hook_init().
 */
function myfunction_init() {

  $internal_ips = [
    'x.x.x.x',
    'x.x.x.x',
  ];

  $internal_traffic = 'no';
  if (in_array(ip_address(), $internal_ips)) {
    $internal_traffic = 'yes';
  }

  $data_layer = [
    '#type' => 'markup',
    '#tag' => 'script',
    '#markup' => "<script>
                    var dataLayer = [];
                    dataLayer.push({ 'internalTraffic': '$internal_traffic'});
                  </script>",
    '#weight' => 100 ,
  ];

  drupal_add_html_head($data_layer, 'data-layer');
}

```

It would work but the problem is I have cached pages so this will not be correct. I did try `hook_boot` but that did not work because `drupal_add_html_head()` is not a valid function (I'm assuming it wasn't initialized yet).

# Answer
> 1 votes
To request the uncached client IP I recommend providing a JSON endpoint that has `drupal_page_is_cacheable(FALSE)` set. Then get the IP from there with an Ajax request and do whatever you need to do now with JavaScript.

First, provide a route.

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['myip'] = [
    'page callback'   => '_MYMODULE_myip_callback',
    'access callback' => TRUE,
  ];

  return $items;
}

```

Second, provide the endpoint that returns the result of the IP comparison. (Bonus points for getting the internal IPs from an admin settings form. More bonus points for checking the user role as well.)

```
/**
 * Callback to provide an uncached JSON response.
 */
function _MYMODULE_myip_callback() {

  $internal_ips = [
    'x.x.x.x',
    'x.x.x.x',
  ];

  $data = [
    'internal_ip' => in_array(ip_address(), $internal_ips) ? TRUE : FALSE,
  ];

  // Mark this page as being uncacheable.
  drupal_page_is_cacheable(FALSE);

  drupal_json_output($data);
}

```

Third, add the JS.

```
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/js/scripts.js', ['scope' => 'footer']);
}

```

Fourth, the Ajax request and DOM manipulation in the JS file.

```
(function ($, Drupal) {
  'use strict';
  Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {

      $.getJSON('/myip', function (result) {

        if (result.internal_ip) {
          function_to_call_if_internal_ip();
        }
      });

      var function_to_call_if_internal_ip = function () {

        // Do whatever you need to do.
        // ...

      };

    }
  };
})(jQuery, Drupal);

```

---

### Note

One thing to mention. I adjusted the sample to follow your sample flow "do something if internal IP". In the original snippet I do the opposite "**only add Google Tag Manager if external IP**" to never have the tag manager script added at all if the request comes from an internal IP and it works just fine.

```
$.getJSON('/myip', function (result) {

  if (result.add_scripts_by_client_ip && result.add_scripts_by_user && result.add_scripts_by_host) {
    _add_google_tag_manager('GTM-XXXXX');
  }
});

var _add_google_tag_manager = function (gtmid) {

  if (!!gtmid && gtmid !== null && gtmid !== '') {

    $('html').once('myBehavior').each(function () {
      $('body').prepend('<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=' + gtmid + '" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>');
      $('head').append("<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer', '" + gtmid + "');</script>");
    });
  }
};

```

---

If you use Varnish, Memchached or some other server-side caching strategy, don't forget to exclude `/myip` from them.

---
Tags: 7, caching
---


# Question
Title: Access fields of node content type from event "rules_entity_insert:comment"
In Rules 8, I know how to make custom fields of a content type accessible in an event "After updating a content item (rules\_entity\_update:node)", that is:

```
Condition: Entity is of bundle
Entity: node
Type: node
Bundle: my_content_type

```

So that I can use something like {{node.my\_custom\_field.value}}.

But, when I'm in an event "After saving a new comment (rules\_entity\_insert:comment)", the above solution does not work. How should I do to access custom fields of the node the comment is attached to?

# Answer
Couldn't find an answer using Rules, and ended up adding some code:

```
function my-module_comment_insert(Drupal\Core\Entity\EntityInterface $entity)
{
   // Get NID and load Node
   $nid = $entity->get('entity_id')->target_id;
   $node = \Drupal\node\Entity\Node::load($nid);
}

```

From there I can use $node-\>get('field\_something'). Of course if it's an entity reference field (as per my case), there's some work to do.
> 0 votes

---
Tags: 8, rules
---


# Question
Title: How do I make a profile select option on user registration?
I thought this was easy but normal fields and media don't seem to do what I want. I can use normal fields, because it is Drupal 8 and the user is an entity. So all I want to be able to do is:

a) show the user a "profile picture" upload option upon registration b) also allow them to choose one of the 5 pre-existing images I have uploaded c) easily allow myself as admin to upload more images

Right now I'm thinking of doing a bit of a hack where I simply add an image field, but add another field with custom logic (somehow) that allows the user to choose an image.

But I was hoping someone can suggest something better? Or alternatively, advise perhaps on a way to re-use the image field and add a "choose image" feature to it?

P.s. I am trying to simply allow the user to choose an avatar when signing up. They must just be able to click on the one they like, out of a set of predefined options. If they don't like one, they must be able to upload their own.

# Answer
I ended up doing this:

1. Created a new content type called "profile picture"
2. Gave this content type an image field
3. Loaded a bunch of profile pictures
4. Added a node reference field to my user so i can select one of the profile picture nodes.
5. And then finally installed and used this: https://www.drupal.org/project/entity\_reference\_views\_select
> 1 votes

# Answer
Many problems in Drupal can be solved in more than one way. This is also one of them.

One way might be to use the Avatar Kit module.

Another might be to create a Select field with options linking to some images you uploaded to the files folder or similar. You'd probably have to do some custom formatting if you wanted to display the options as images, and not just links or text.

The complication comes in with your request to allow users to upload their own images if they don't like the present choices. Selecting one image from a set is simple enough, and allowing to upload their preferred one is simple enough, but the combination of these options isn't as simple, it's not so common, and requires more logic than is present in the core out-of-box.

A solution that is flexible and extensible is to create a separate Media Type for these user pictures, and use Entity Browser module to build a great user experience when filling their profile forms where they can choose from a set of images you chose, or are allowed to upload a new one. This solution isn't the easiest to implement though, or at least isn't to someone who expects these features should come out-of-box.

You have to think about the images uploaded by users, are they available to all users to use or are they limited to the person who uploaded the image? This affects how you structure your Media type, different access treatment usually means you need a separate structure for it.
> 1 votes

---
Tags: 8
---


# Question
Title: How can alter the select options provided by Simple hierarchical select?
Simple hierarchical select is used to display Taxonomy as a select field in my existing content type. So I'm trying to alter the value of it. Even tried using `hook_form_alter` but didn't work. So is there any way or hook using which I can alter the value of the select list?

# Answer
> 3 votes
Finally, I was able to resolve it by using the module handler "shs\_term\_data\_response". Like below

```
function YourModuleName_shs_term_data_response_alter(&$content, $context) {
  $termList = json_decode($content);
  $filteredList = array();
  /..your logic to modify $termList and push it to new array.../
  $content = json_encode($filteredList);
}

```

Hope it may help someone :)

---
Tags: 8, forms
---


# Question
Title: How do I add a css class to body from a page callback function?
I have a module that produces a lot of pages. A set of these are handled by a particular part of my application, and I would like all these to have a class added to either `html` or `body`. I'd settle for `#block-system-main`.

The existing answers point to a template preprocess hooks e.g. `hook_preprocess_html()` but this feels wrong.

I'd have to create that hook and then tell it to go somewhere else to determine which page call back was used and which class to apply - it's all backwards. Drupal's already selected the right callback, so a 2nd lookup is another thing to maintain and an inefficiency.

I could of course do something like set a `global $extra_page_classes` variable and then implement the hook to add these classes to the page, which is more efficient but it's still messy. Or I could add (yet another) wrapping `<div>` to my callback output, but that's not going to give a themer chance to adapt the rest of the page elements outside of the main content.

Seems odd that a page callback, responsible for the substantial content of the page, can't set page-level attributes. A page callback can, for example, choose to call `drupal_add_css()`, but it (apparently) can't do something as simple as add a class to the page.

As it seems odd and Drupal usually has some (often hidden) elegance, I thought I'd ask specifically if there was a better way.

# Answer
> 0 votes
Well, I think your confusion comes from the D7/D6 fact that a "page" has little clue whats going on around it. As you've said the page callback function tells drupal "what goes in the `$content`" but not what adornments happen on the page HTML DOM around `$content`.

To my knowledge unless your using Panels, Context or something else to share "page state" through components of your site -- this is simply how D7 simply works.

Without using context, panels, etc. I usually end up looking for url paths or NIDs or custom content array attributes `#project-add-body-classes` in hook functions to fire off my logic.

For what you describe I would use `hook_html_alter()` and look for a page path to alter the `body_classes` array as needed.

# Answer
> 0 votes
You could simply do it from within a page callback with inline JS.

```
drupal_add_js('jQuery(document).ready(function () {
  jQuery("body").addClass("foobar");
});', 'inline');

```

---

Alternatively use `template_preprocess_html` to add a body classes depending on the current path.

```
/**
 * Implements hook_menu().
 */
function MYMOUDLE_menu() {

  $items = [];

  $items['foo/bar'] = [
    'title'            => 'Foobar',
    'description'      => 'Lorem ipsum.',
    'access arguments' => ['access content'],
    'page callback'    => '_MYMODULE_mycallback',
    'type'             => MENU_CALLBACK,
  ];

  return $items;
}

```

Now add the body class dynamically by comparing the URL arguments from above.

```
/**
 * Implements template_preprocess_html().
 */
function MYMODULE_preprocess_html(&$variables) {

  // Add HTML <body> class.
  if (arg(0) === 'foo' && arg(1) === 'bar') {
    $variables['classes_array'][] = 'foobar';
  }
}

```

---
Tags: 7, theming
---


title: Webform issue with captcha

text:
# Question
Title: Webform issue with captcha
I have created about 11 webforms in my website. Now I want to add recaptcha challenge in all of them.

I have installed the captcha module and recaptcha module. recaptcha is coming in all these forms. The problem is form gets submitted even if challenge is not taken. Below is yml file of a sample webform I have created

```
test_field:
  '#type': textfield
  '#title': 'Test field'
  '#required': true
captcha:
  '#type': captcha
  '#captcha_type': recaptcha/reCAPTCHA

```

# Answer
> 2 votes
I don't think reCAPTCHA module provides front-end validation. Have you tried performing front-end validation using reCAPTCHA API? You could try something like this:

```
 $('form').submit(function () {
   if (!grecaptcha.getResponse()) {
     event.preventDefault();
     $('<span class="red recaptcha">reCAPTCHA is invalid</span>').insertAfter('.g-recaptcha');}
  });

```

# Answer
> 0 votes
If you have already created a webform then you can follow thi step

1. Open this url /admin/structure/webform (Structure -\> Webform)
2. Click on "Build" in OPERATIONS column
3. Click on "+Add element" button, there will be seen a list form element, you can select captcha from available element

---
Tags: 8, webforms, captcha
---


# Question
Title: Get node ID or URL in Twig on field level
I have a field value, which I would like to link to the content (to the node itself, using it in a teaser).

How can I get the URL or at least the ID on field level, to create that link?

# Answer
The node in a field template is the parent entity you find in element\['#object'\], which you can use to build the path:

```
{{ path('entity.node.canonical', {'node':  element['#object'].id}) }}

```
> 8 votes

# Answer
Without preprocessing, directly in Twig:

```
{# get owner entity #}
{% set owner_entity = element['#object'] %}
{# render id #}
id = {{ element['#object'].id }}
{# render raw field value #}
field foo = {{ element['#object'].field_foo.0.value }}

```
> 3 votes

# Answer
You should maybe preprocess you the URL in place. Via `template_preprocess_field` get the node ID, build the path alias, send it to Twig.

```
/**
 * Implements template_preprocess_field__FIELD_NAME().
 */
function MYTHEME_preprocess_field__MYFIELD(&$variables) {

  if ($variables['element']['#entity_type'] === 'node') {
    $node = $variables['element']['#object'];
    $nid = $node->id();
    $variables['myurl'] = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid);
  }
}

```

In `field.html.twig` then do:

```
{% if myurl %}
   <a href="{{ myurl }}">Kool Keith</a>
{% endif %}

```
> 2 votes

---
Tags: theming
---


# Question
Title: hook_field_widget_form_alter - modify specified field only
I'd like to use a hook to modify a widget, but only for a named field.

**Use case:** a form has an entity reference to another content type, using an options\_buttons widget (a list of available courses the user can apply for). Rather than just the title alongside each checkbox, I'd like to display some extra fields from the content type such as date, a URL etc.

The documentation suggests `$context['widget']` ("The widget plugin instance.") is the place to look, however a var\_dump of that just seems to give me lots of protected properties and no clear way of getting the field name.

Essentially I'm after a D8 version similar to this old example I found:

```
if ($context['field']['field_name'] != 'field_bannerimage') return;

```

# Answer
> 3 votes
So it's actually to be found in **$context\['items'\]**

```
if (($context['items']->getName() != 'field_myfield')) {
  return;
}

// if still here, our field matches. do something

```

Also note you can be more efficient by using the WIDGET\_TYPE hook, e.g. for my "Check boxes/radio buttons" widget:

```
function hook_field_widget_options_buttons_form_alter(...)

```

# Answer
> 0 votes
Refer below sample code

```
function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_name = $context['items']->getName();
  $field = FieldConfig::loadByName('node', 'page', $field_name);

  if ($field) {
    $element['#prefix'] = 'hello world';
  }
}

```

---
Tags: 8, forms
---


title: Email misses fields from form

text:
# Question
Title: Email misses fields from form
This is regarding a Drupal 8 site, specifically Drupal 8.7.1 and the "Contact" module (with Contact Emails, Contact Storage enabled).

The issue that I'm running into is some of the fields are not included in the email that's sent out when the form is submitted. No Swiftmailer or other HTML email packages involved here, my ultimate goal is just to include all fields that were filled out.

I narrowed the situation down to this - when logged in, the resultant email sent out after form submission always contains all of the correct fields. If **not**, or in other words an **anonymous** user fills out the form, some fields are missing from the email entirely.

The aforementioned missing fields are actually paragraphs, or entity revisions, that I made use of to get access to the add / remove paragraph functionality on the front end. They work great, with a bit of preprocessing, but absolutely refuse to be included in email messages when the submitter is an anonymous user.

**Sanity check** \- The fields are all there and filled out as part of the Contact Storage module, so that's not the issue. Anonymous users obviously do not have any kind of access to administer paragraph types, but this is not needed when the paragraphs are fields in a contact form(?).

I've checked around the various stack exchanges and other sites, but I can only find vaguely relevant issues, such as Theme contact emails. Using paragraphs in Contact does not appear to be a popular thing to do. They are embedded as subforms, but I can't find anyone else who has asked this question.

The site is hosted on Acquia Cloud, PHP 7.2, if that helps. Short of digging through the module's entire codebase or setting up HTML mail with something like Swiftmailer, I'm stumped.

Any help is much appreciated, please let me know if you need any more detail on something - I know this is a lot to read without code or screenshots.

# Answer
> 1 votes
After working with JDev518 on this we discovered this was a permissions issue with paragraphs. Although this should have worked as is, we ended up installing Paragraph Type Permissions" and assigning specific permissions to create/edit/view the paragraph fields in question for anonymous. This "forced" the permission check to work and started including the submitted values in the email. However the contact module is determining the view permissions on those paragraph fields when it's building the email seems to be the cause of this issue.

---
Tags: 8, forms, emails, paragraphs
---


# Question
Title: Select all nodes, where date is greater then current date and repeat event option is empty
I have content type "event". In this content type I have a date field, provided by the Date Recur module. At the result I have range of the dates: Event start and end date. Also Date Recur provides an option to repeat event. I need to select all event nodes where date field is greater then current date and repeat event option is empty or select all nodes, where repeat event option is not empty.

My code:

```
$current_time = \Drupal::service('date.formatter')->format(time(), 'custom', 'Y-m-d\TH:i:s');

$query = $this->db_connection->select('node__field_type', 'n_f_type');
$query->join('node_field_data', 'n_f_data',
  'n_f_data.nid = n_f_type.entity_id AND n_f_data.type = n_f_type.bundle');

$query->join('node__field_event_dates', 'n_event_dates',
  'n_event_dates.bundle = n_f_type.bundle AND n_event_dates.entity_id = n_f_type.entity_id');
$query->fields('n_f_data', ['nid']);
$query->condition('n_f_type.bundle', 'event');
$query->condition('n_f_data.status', 1);
$group_and = $query->andConditionGroup();
$group_and->condition('n_event_dates.field_event_dates_value', $current_time, '>=');
$group_and->condition('n_event_dates.field_event_dates_rrule', '', '<>');
$query->condition($group_and);
$group_or = $query->orConditionGroup();
$group_or->condition('n_event_dates.field_event_dates_rrule', '%RRULE%', 'LIKE');
$query->condition($group_or);
$query->range(0, 500);
$events = $query->execute()->fetchAll();

```

Please, can anybody help me to build the correct query, because current query returns empty array.

```
SELECT * FROM table_name.node__field_event_dates where
((field_event_dates_value >= '2019-07-17T10:00:00') and
(field_event_dates_rrule is null or field_event_dates_rrule not like
'%RRULE%')) or (field_event_dates_rrule like '%RRULE%');

```

Last query works fine;

I need some help to transform the last query via using Drupal and/or conditions.

# Answer
> 0 votes
Right now your rrule condition is a singleton of its "OR" group. You need to add all the other conditions to an "AND" group and place that group as a sibling to the rrule condition in the "OR" group.

---
Tags: 8, nodes
---


title: Facet Block : only 10 items are shown

text:
# Question
Title: Facet Block : only 10 items are shown
Using Search\_api, search\_api\_db and facet\_api.

Ive created a view display using 'Facet Block'.

Ive set the facet field to the one I want to use. The facet configuration of this field has no listing limits.

ive set the view setting's 'pagination' to display all items.

When I look at the rendered block, it only shows 10 items.

Does anyone ever face this kind of problem ?

Is there an hard-coded limit ?

# Answer
> 0 votes
You can manually edit this limit in the search\_api\_views module source file.

You find this here in the commerce kickstart bundle:

/profiles/commerce\_kickstart/modules/contrib/search\_api/contrib/search\_api\_views/includes/display\_facet\_block.inc

Then you correct the limit of 10 on line 167 of **display\_facet\_block.inc**

`$limit = empty($this->view->query->pager->options['items_per_page']) ? 100`

---
Tags: search
---


title: Using search api programatically

text:
# Question
Title: Using search api programatically
I have read and tried https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

I am using drupal 8 and using the default content index for testing. I am able to run the following code and I get a result count, but not result items.

```
$index = \Drupal\search_api\Entity\Index::load('default_index');
$query = $index->query();

// Change the parse mode for the search.
$parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
  ->createInstance('direct');
$parse_mode->setConjunction('OR');
$query->setParseMode($parse_mode);

// Set fulltext search keywords and fields.
$query->keys('');
$query->setFulltextFields(['title', 'name', 'body']);

// Do paging.
$query->range(20, 10);

// Set one or more tags for the query.
// @see hook_search_api_query_TAG_alter()
// @see hook_search_api_results_TAG_alter()
$query->addTag('custom_search');

// Execute the search.
$results = $query->execute();

echo "Result count: {$results->getResultCount()}\n";
$ids = implode(', ', array_keys($results->getResultItems()));
echo "Returned IDs: $ids.\n";

```

Count shows a value but I can't get any result items. I tried with $query-\>keys(''); $query-\>keys('\*'); and some value $query-\>keys('some value'); In all cases the count seems to be correct. The search therefore seems to be executed correctly, but how can I retrieve the items?

# Answer
```
    //first just run this line
    kint($results);
    //and then you can uncomment the next lines, in my case I needed the response key 'elasticsearch_response'
    $response = $results->getExtraData('elasticsearch_response', []);
    $hits = $response['hits']['hits'];
    foreach($hits as $hit){
      kint($hit);
    }

```
> 1 votes

# Answer
Just found this old post while debugging the same issue. Adding my fix in case other hit it too..

The problem I ran into using the sample code was this line:

```
// Do paging.
$query->range(20, 10);

```

I since I only had a few records in my database, there wasn't 20+ records, the total count was correct, but couldn't page that far.

Updating to:

```
// Do paging.
$query->range(0, 10);

```

Fixed my issue.
> 1 votes

# Answer
You need to iterate and get them. Here is one way I did it:

```
$results = $query->execute();
$output = '';

foreach ($results as $result) {
  $value = $result->getField('fieldname')->getValues();
  $output .= $value[0];
}

```
> 0 votes

---
Tags: 8, search
---