# Question
Title: Proper way to define weight / country wise shipping rates
I need to configure country wise shipping rates by weight. So each country has different shipping rates for different weights. So I have divided countries in different zones. The countries in each zone have same shipping rates. So what I have done is created several flat rates services like following.

```
Zone 1 - 0.5KG, Zone 1 - 1.0KG, Zone 1 - 1.5KG, Zone 1 - 1.5KG, Zone 1 - 2.0KG and so on ...
Similarly Set for each Zone
Zone 2 - 0.5KG, Zone 2 - 1.0KG, Zone 2 - 1.5KG, Zone 2 - 1.5KG, Zone 2 - 2.0KG

```

Defined respective rates for each flat rate service. And configured like following.

```
Order total weight comparison
Parameter: Order: [commerce_order], Operator: <=, Value: 0.5

AND

Order address component comparison
Parameter: Order: [commerce_order], Address: Address, Address component: Country, Operator: is one of, Value: AL ...

```

This works for me well, but I have to configure 91 flat rate service and define the conditions manually again and again.

Though at the end I am getting my desired result, I feel there must be a better way to achieve this task, but I am not aware of that.

Please guide me to do it properly.

# Answer
> 0 votes
Have you looked at these two modules?

1. Commerce Shipping Postal Code Weight
2. Commerce Shipping Weight Tariff

# Answer
> 0 votes
Shamelessly taken from here drupal.org/node/2352837

Be sure that the "Shipping", "Shipping UI", and "Commerce Shipping Postal Code Weight" modules are enabled.

Be sure to configure all the countries you support for shipping in the address field of the customer's shipping profile under Store \> Customer profiles \> Profile types \> "manage fields" next to "Shipping information" (admin/commerce/customer-profiles/types/shipping/fields/commerce\_customer\_address). You must select at least one country under the "Available countries" section of that page.

Visit the shipping method edit screen under Store \> Configuration \> Shipping \> Shipping Methods \> "edit" next to "Postcode weight shipping method" (admin/commerce/config/shipping/methods/postal-code-weight-shipping-method/edit).

You will see one fieldset with shipping options for each country you selected.

For each country, specify all the weight ranges you support in the "weights" field and indicate the units of measurement you're using.

For each country, specify the groupings of postal codes for which you need to specify rates using commas to separate postal codes in the same category and semicolons to separate categories. For example, let's say I want the following: 14586 and 14623 (West Henrietta, NY and Rochester, NY, respectively) have all of the same rates 06468 (Monroe, CT) has a different set of rates

Then I'd enter "14586,14623;06468" into the "Postal Codes" box.

Click the "Save" button at the bottom of the page to rebuild all of the postal tables based on the new weights and postal codes.

For each country, click the "Edit" link below each rate table to edit the table of values.

Each range of weights is specified as "Min weight" exclusive to "Max weight" inclusive, so 0-5 would mean "greater than 0 and 5 or less" and 5-10 would mean "greater than 5 and 10 or less".

After you've specified the rates, the customer will see them appear during the Shipping step of checkout. It's calculated based on the total order weight and the country and postal code that the customer enters for his or her shipping address.

---
Tags: rules, commerce
---


# Question
Title: How to override the ['search_distance'] in Location: Distance / Proximity Views in a custom module
After looking at the location module. I couldn't find any way to override the 'search\_distance' parameter by creating a custom Form.

dose anyone know how to override this variable by using a custom module? .

I do have a map that is already searching proximity by zip code. it uses php code to determine the latitude, longitude.

I want to add the 'distance' selectbox next to the zipcode and filter it by (25 miles, 50 miles, 100 miles) like that.

Please note: the below Form for filtering is written in a custom module. so I'm looking for php code.

# Answer
Found a solution for this. you need to override the query() method in 'location\_views\_handler\_filter\_proximity' handler class for your view. This link will help you to understand to override the view handler. you can extend the old class with the custom class that you want to override.

I can see the variable get updated with what i wanted now. below is a sample code that you would use for this kind of a override.

```
    class Yourcustom_class extend location_views_handler_filter_proximity{
    public function query() {

 if(!empty(filter_xss($_REQUEST['dist'])))
            {
                $distquery=  filter_xss($_REQUEST['dist']);
                $this->value['search_distance'] = $distquery;
            }

      }

}

```
> 0 votes

# Answer
I haven't had much experience with Location module. This feature is supported out of the box with Openlayers module. I would recommend checking out that module.

I have done a similar sort of thing for one of my clients. I had to hide the distance fields as they didn't want that. If you view source you can see those fields in HTML.

http://biopetonline.com.au/stores
> 0 votes

---
Tags: 7, location, google-maps
---


title: How to force image URLs as HTTPS?

text:
# Question
Title: How to force image URLs as HTTPS?
There are a few places where I am calling `ImageStyle::load('style')->buildUrl($uri)` to get a physical file path of an image.

After enabling HTTPS and forcing all traffic to use HTTPS, I noticed that this will only return `http://` at the start of the url, and not `https://` causing mixed mode flag in the browser.

Is there a way to do this and get the correct protocol? Can I not just obtain the relative path to the file instead? I notice that this method has hardcoded `'absolute' => TRUE` when building the url to return.

Edit: fields using the normal rendering method i.e. `{{ content.field_image }}` have the correct protocol and do not cause an issue.

Here is the code I am using to generate the variable:

```
/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle =='homepage' && $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node->get('field_hero_image')->getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('homepage_hero')->buildUrl($entity->field_image->entity->getFileUri());
    }
  }
}

```

In the node view mode twig template:

```
  {% if node.field_hero_image is not empty %}
    <div class="hero__graphic" style="background-image: url({{ hero_image }});"></div>
  {% endif %}

```

# Answer
> 14 votes
You can use `file_url_transform_relative()`:

```
/**
 * Transforms an absolute URL of a local file to a relative URL.
 *
 * May be useful to prevent problems on multisite set-ups and prevent mixed
 * content errors when using HTTPS + HTTP.
 *
 * @param string $file_url
 *   A file URL of a local file as generated by file_create_url().
 *
 * @return string
 *   If the file URL indeed pointed to a local file and was indeed absolute,
 *   then the transformed, relative URL to the local file. Otherwise: the
 *   original value of $file_url.
 *
 * @see file_create_url()
 */
function file_url_transform_relative($file_url) {

```

# Answer
> 2 votes
You could try altering your base\_url by un-commenting the following line in settings.php and changing the http to https.

```
/**
 * Public file base URL:
 *
 * An alternative base URL to be used for serving public files. This must
 * include any leading directory path.
 *
 * A different value from the domain used by Drupal to be used for accessing
 * public files. This can be used for a simple CDN integration, or to improve
 * security by serving user-uploaded files from a different domain or subdomain
 * pointing to the same server. Do not include a trailing slash.
 */
# $settings['file_public_base_url'] = 'http://downloads.example.com/files';

```

---
Tags: 8, ssl
---


title: Downloading a Feature

text:
# Question
Title: Downloading a Feature
I may be thinking about this the wrong way, but I would like to download a feature that is already created. I know how to create a feature and download it, but how do you download a feature that already exists so you can use it on another site? Preferably in Drush.

I'm using Drupal 7.50. Thanks!

Edit: I figured out that in the UI, if you create "recreate", you can download it from there. How can this be done in drush though?

# Answer
> 4 votes
You can use my very favorite drush command:

`drush fu your_feature`

This is the same as using "recreate" in the UI except that it will update your feature directly where it resides in your code base (usually at /sites/all/modules/your\_feature).

Now you can copy that folder (or zip it up if you like) and use it on any site you'd like.

---
Tags: drush, features
---


# Question
Title: How do you change the order of uploaded videos?
How can we change this page so new content added goes to the top, not the bottom?

http://www.liveops.com/resources/videos

When it's added to this page, it goes to the top: http://www.liveops.com/resources

# Answer
The listed videos are created using a view. It looks like the view is called Resources (or something similiar). Edit that view, and there should be a tab called 'block', where you can edit the block view. In there, under 'sort', choose 'nid' and set it to sort descending.
> 0 votes

---
Tags: entities
---


title: Post a node in two sites

text:
# Question
Title: Post a node in two sites
I have two sites.I want,when posting a node to one site,this node to be automatically posted in also to the other site and vice versa.How can I do that?Does this need web services? thanks

# Answer
> 1 votes
You can do that with web services but that will require a fair bit of work. You can easily achieve this functionality by using a domain access module.

This will allow you to publish a node to multiple domains.

---
Tags: nodes
---


# Question
Title: How can I enforce maintenance_mode at all times in a specific environment?
In Drupal 7, we could override the `$conf` variables in settings.php to force a site (e.g. development) in maintenance mode. In Drupal 8, this has changed to `$config`, but the maintenance mode variable is not part of the configuration anymore. How can I force system.maintenance\_mode in a specific environment's configuration?

# Answer
> 2 votes
I think you might want to take a different approach.

The maintenance mode is now a *state* in Drupal 8, not a *configuration*. The difference is a state is a *ephemeral state* that's specific to the current environment (see the state API docs for more info).

As such, you might want to replace the `State` service with your own service class that uses the `StateInterface` interface if you're looking to fundamentally alter the way state behavior (which could lead to unforeseen problems).

Another tact might involve some sort one-time toggling of state (e.g. programmatically as shown above, a `drush state-set` / `drupal state:override`) based on some event (e.g. deployment of site).

---
Tags: 8, configuration
---


title: Redirect after create or update node

text:
# Question
Title: Redirect after create or update node
How to redirect to certain Path after create/update specific Content type node ?

# Answer
You can achieve this by

1. Make sure the ?destination parameter in your url is filled out. This will redirect you to the page defined in the destination parameter.
2. Use the node save redirect module. This module allows you to configure the redirect path per node type after saving a node.

Node Save redirect module.

This module provides a method of specifying a location to take the user after saving a piece of content.

A set of radios buttons are added to the submission vertical tab on the content type edit form.

The available options are.

> Default - Default behaviour
> Return to Edit page after saving
> Return to content overview page (assuming the user has access permissions
> Re-redirect to another location. (any valid drupal path)
> 3 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Drupalgap: Hello World sample - where is app folder?
I have a Drupal 7 website and wish to develop a mobile app for it. I have successfully installed Drupalgap. I am trying to run the Hello World sample app described in the Drupalgap 7 docs. The instructions say to create a custom module and place it in the `app/modules/custom/my_module` folder. The problem is that I don't have an "app" folder anywhere. What am I missing? Thanks for any insights.

# Answer
> 2 votes
The app folder is in the folder mobile-application

1. Root folder drupal
    * mobile-application
    * + app
    * + - modules
    * + - * custom
    * + - * + my\_module

# Answer
> 1 votes
1. Go to the admin/config/services/drupalgap. In this mobile-application is the folder where your app is running.

2. Go to the drupal project folder. "var/www/html/drupal/mobile-application" In this directory app folder is exist

# Answer
> 0 votes
If you have not change anything and go to the DrupalGap module configuration and installed the SDK then you will get the app folder in root inside mobile-application folder.

---
Tags: 7, javascript
---


# Question
Title: Twitter Card Preview is failing with twitter:image
I'm trying to add Twitter Cards to my site so that tweets referencing my blog posts will be expandable and show extra info. I've installed the metatag module, enabled the Metatag: Twitter Cards sub-module as well as patched the Twitter Cards sub-module to fix a problem with it generating `<link />` tags instead of `<meta />` tags.

When I include a twitter:image tag, the Twitter Card fails, but when I remove it, it works just fine. What am I doing wrong?

```
<meta property="twitter:url" content="http://liberalgeek.com/content/why-do-atheists-celebrate-christmas" />
<meta property="twitter:card" content="summary" />
<meta property="twitter:description" content="I can't speak for all atheists, I can only speak for myself, so please leave a comment below and explain why you celebrate Christmas! When I hear someone ask, "Why do atheists celebrate Christmas?" my first thought often is: Better Question: Why do Christians celebrate Christmas?" />
<meta property="twitter:creator" content="@kennywyland" />
<meta property="twitter:title" content="Why do Atheists celebrate Christmas?" />

<!-- the following line causes the problem -->
<meta property="twitter:image" content="http://liberalgeek.com/sites/default/files/styles/large/public/Christmas%20Tree.jpg" />

```

I have tried `<meta property=` as well as `<meta name=` and they behave the same way.

The image is publicly visible, it's large enough without being too large... what is wrong?

To be clearer, by "failing" I mean that Twitter refuses to acknowledge there is a Twitter Card for that URL, so the preview is not shown along with the tweet. When I test this on the twitter card preview page, this is the result I get:

However, when I remove the `twitter:image` tag and generate the preview again it works just fine and looks like this:

During further testing I found the STRANGEST thing. If I change the domain from liberalgeek.com to www.liberalgeek.com, the Twitter Card successfully generates, although the thumbnail image is a broken image. (That may just be due to high twitter volume, but I'm not sure.)

I want the Twitter card to work, even if they don't include the unnecessary www.

Notice that:

* The .htaccess file is the standard one installed with Drupal
* I don't think I'm using gzip compression
* Apache isn't sending back the wrong headers
* The error log doesn't shown any error
* The access log shows entries with a return code equal to 200, and a correct content length value, when Twitter tries to access the image

I found a site on my server which twitter handles just fine:

```
<meta property="twitter:image" content="http://www.geekqi.com/images/StylizedYinYangRedLucida.png" />

```

But I'm not sure what the difference is between this and all of my other sites.

# Answer
> 3 votes
I made a test with this values

```
<meta name="twitter:url" content="http://liberalgeek.com/content/why-do-atheists-celebrate-christmas" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:creator" content="@kennywyland" />
<meta property="twitter:description" content="I can't speak for all atheists, I can only speak for myself, so please leave a comment below and explain why you celebrate Christmas! When I hear someone ask, "Why do atheists celebrate Christmas?" my first thought often is: Better Question: Why do Christians celebrate Christmas?" />

<meta name="twitter:title" content="Why do Atheists celebrate Christmas?" />

<!-- the following line causes the problem -->
<meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg">

```

Changing the image, the card works normally in the preview tool.
I would try to check if you have some restriction on the file.
Have a look at the crawling section of the API docs

> Twitter's crawler will respect robots.txt when scanning URLs. If a page with card markup is blocked, no card will be shown. If an image URL is blocked, no thumbnail or photo will be shown.

**UPDATE** As suggested by the author of the question, changing robot.txt could not be enough. Since Twitter could have cached your file, you need to wait at least 24 hours to let it expires.
I add that the same problem could be found not just on robot.txt file, but also on images. Indeed, wrong Twitter cache could lead to a 404 error and a broken preview image.

# Answer
> 1 votes
To fix this issue do the following: **For twitter** go to https://cards-dev.twitter.com/validator and insert the webpage URL and then hit Preview card, this will clear twitter cache.

**For facebook** go to https://developers.facebook.com/tools/debug/sharing/ and insert the webpage URL (make sure Sharing Debuger tab is active)and hit Debug, this will clear your cache. If you still see the old image Scarp the URL by pressing **Scrap Again** button.

# Answer
> 0 votes
I wonder if the Twitter API balks on the %20 space in the image filename.

To eliminate that possibility, it's worth testing with an image URL that has no space in the filename,

i.e:

```
<meta property="twitter:image" content="http://liberalgeek.com/sites/default/files/styles/large/public/Christmas-Tree.jpg" />

```

vs the current:

```
<meta property="twitter:image" content="http://liberalgeek.com/sites/default/files/styles/large/public/Christmas%20Tree.jpg" />

```

# Answer
> -1 votes
Try this: `<meta name="twitter:image:src" content="http://liberalgeek.com/sites/default/files/styles/large/public/Christmas%20Tree.jpg" />`

---
Tags: 7, meta-tags, social-network
---


# Question
Title: Create a view with a list of webform without any submission by current user
I am currently stuck trying to build a view wich contains a simple list of webform's name not submitted yet by the current user so that the current user can only see a list of webforms to be filled. How can this be accomplished?

I experimented a lot of settings but i couldn't get the expected result. Any help would be much appreciated

# Answer
> 0 votes
I'm not sure if there is a solution to create such kind of view using the Views module. But the Forena module (disclosure: I'm a co-maintainer) can be used for this type of reporting. More specifically by using its facility to create a Display of a table in ***crosstab*** format.

A ***crosstab*** table is a table with a special layout. It is formatted as a grid, with:

* the **rows** representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), etc.
* the **columns** representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
* the **intersections of rows and columns** containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) **include a hyperlink to a drill-down report**.

Below is a sample of such ***crosstab*** report (including drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the Forena issue queue for more details about the above screenshot. And/or have a look at the video about How to generate crosstab reports with graphs (Forena also supports charting of those data, a typical related requirement ...).

Specific to your question here, I'd create such table in **crosstab** format with rows/columns like so:

* The rows should represent your users (1 row for each user).
* The columns should represent your webforms (1 column for each webform).

With such setup, the answer to your question is then contained in the intersections of all rows and columns that are shown as "blank" (= zero submissions of the specific webform by the specific user).

PS: I'm assuming you're using D7 ...

---
Tags: 7, views, webforms
---


# Question
Title: Views get total row count in views-view.html.twig
I need to get the total rows count in **views-view.html.twig** file. So that I can loop through it and create the indicators required for my bootstrap carousel view block.

I tried the solution provided in this thread Drupal 8 Views get total row count in views-view-fields.html.twig but nothing seems to be working.

Can any one please guide me how its possible.

# Answer
This can be achieved as follows. NB this outlines a simple approach which works. It can be finessed and improved upon by stripping our unnecessary divs, applying classes more elegantly, etc, but this will work:

* Adding a views attachment display and attaching it to your main display of the slides (display: after);
* Set this attachment with an ordered list display format with List class = carousel-indicators;
* Add one custom text field (it will not be displayed so it does not really matter what this is);
* Set it to evaluate the same conditions as your main display (eg content filtered by a boolean "display in slider" = TRUE ... or whatever). This way number of bullets definitely = number of slides;
* Copy the core views-view-list.html.twig to your theme and override with your display name (see api.drupal.org/api/drupal/core!modules!views!views.theme.inc/group/views\_templates/8.3.x for general suggestions);
* Return the rows as follows:

`{% for row in rows %}
 {% if loop.first %}

{{ row.content }}

 {% else %}

{{ row.content }}

 {% endif %}
 {% endfor %}`

This gets the active class on the first item and includes the index number, thus matching the requirements at: getbootstrap.com/javascript/#carousel

Controls and required wrappers can be set simply in the views-view.html.twig:

```
 {% if rows %}

```

`<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">`

```
 {{ rows }}

```

`<!-- Controls -->`\` (...etc..)

Slide wrapper and active class can be set in views-view--unformatted.html.twig for the slides themselves:

```
 `<!-- Wrapper for slides -->`

```

`<div class="carousel-inner" role="listbox">`

`{% for row in rows %}
 {% if loop.first %}

 {{ row.content }}

`

`{% else %}

 {{ row.content }}

`

`{% endif %}
 {% endfor %}`

`</div><!-- end slider wrapper -->`

Working example: http://wri.netuxosandbox.co.uk/en
> 1 votes

---
Tags: views
---


# Question
Title: How to create a Gmap view that can be filtered?
I have a taxonomy vocabulary that has a multiple terms.

I can create a view that shows the location of all terms in a map, but I want to filter these locations by term. I mean the user first chooses which term and then the map only shows the location of this specific term.

I don't know how to set up filter criteria correctly to achieve this, any suggestions?

# Answer
> 0 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.

Specific to the "filter" part of your question, here is a quote (also from the project page):

> For those using the Commerce module a ready-to-use Order Locations map is provided (3rd screenshot). For each order placed at your store it outputs a marker on the map with its location details retrieved by IPGV&M. The view comes with filters to zoom in on country, time frame and order status. Each order location marker, when clicked, reveals in a text balloon details of the order, e.g number, date placed and order status as well as street address.

**Note**: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.

PS: I'm assuming this question is about D7 ...

---
Tags: input-formats, google-maps
---


# Question
Title: Some of my site's pages are retrieving the .css files from a different directory
I've been working on theming a Pages page on my local machine. This has been going fine, but now I have pushed the changes to a remote server and see that the site is trying to retrieve the .css file from the wrong directory.

On my local machine, this is fine. On the remote machine, it seems drupal is trying to retrieve the .css file from sites all:

```
@import url("http:/mysite.com/sites/all/themes/custom/mytheme/css/main.css");

```

Where as my local version has:

```
@import url("http://localdev.mysite.com/sites/mysite.com/themes/custom/mytheme/css/main.css");

```

Would anyone know why this is and how I could correct it?

# Answer
> 0 votes
May I know where you have added CSS? on theme.info file or template.php

This issue occurring because of your theme has contained an absolute path, You need to replace absolute path the relative path.

First, you need to check that, On which file this CSS has called.

Remove from there and add CSS on theme.info file or template.php file.

On theme.info you need to add like `stylesheets[all][] = custom/mytheme/css/main.css`

On template.php you need to add css using `drupal_add_css` on `template_preprocess_html(&$variables)`.

---
Tags: 7, theming
---


# Question
Title: Predefined webform configuration for specific content type
I'm new to Drupal, I need to create a job list page with an application form for each of the job listings presented in it.

I've created a "Job" content type, and installed the webform module

When I create a new Job, I'm able to create a form and present it in the content of the job. The problem is that it has to be done for each specific job listing manually

Is there a way to set the configuration of the webform attached to a specific node by its content type? A code based solution is preferred - but one that is based on action in admin UI is also blessed

Thank you very much!!

# Answer
> 0 votes
Yes, You can able to do it using admin UI.

Follow below instruction.

**Add new field (boolean type) at webform content type.**

Make this field as a checkbox.

**Add "Entityreference" module**

enable it

**Create entityreference view using views UI for webform content type and add above created boolean field in FILTER CRITERIA select operator \> is one of "yes"**

I have attached snapshot for views UI

**Now edit manage field on job content type**

**Add new field on job content type give the name and select "Entity Reference" in data type.**

**Now select "select list" option for widget click on next button.**

**Next page will be shown Entityreference option at there you need to section "view" for the first drop down "Views: Filter by an entity reference view" and second "View used to select the entities" pick you entity reference view which you have created prviously and save it.**

Snapshot for above description

Now you will able to select created webform on job node.

---
Tags: 7, webforms
---


# Question
Title: List organic group members from the current user group on his profile page
I am new to organic groups, I ran into a problem, I am a member of some organic group, I need to list other members of same group on my profile page, Trying to display it using views but no luck :(, I am working on drupal 7 with Organic group 7.x-2.9

# Answer
> 0 votes
I forgot to answer you last time.! Sorry. You said your were happy with some code so here it is.

Step 1: The custom module.

```
function CUSTOM_MODULE_views_pre_view(&$view, &$display_id, &$args){
// Select our view
    if($view->name == 'VIEW_NAME' and $display_id == 'DISPLAY_NAME') {
    // Get User ID from url
        $view_user = user_load(arg(1));
        $user_groups = array();
        // Get Group IDs
            $items = field_get_items('user', $view_user, 'og_user_node');
                foreach($items as $item) {
                    $user_groups[] = $item['target_id'];
                 }
    // Join like 4+78+345 for Views
        $user_groups_args = implode("+", $user_groups);
    // Send IDs to view
        $args[0] = $user_groups_args;
    }
}

```

Create a module and change what's in caps. Be aware that that module doesn't do any checking.. Only use it for user/\* or node/\* etc. where the second argument is an integer.

Step 2: The View

1. In your View, add the `OG membership: Group ID` contextual filter (make sure it's first in the list).
2. Under its settings under More, check `Allow multiple values`.
3. Because some users may be in more than one group, go to `Query settings` under `Other` and check `Distinct`.

That should be it.

---
Tags: views, organic-groups
---


# Question
Title: User login block doesn't appear for authenticated user
Well, I go to structure/blocks/User Login/configuration and I tried select all checkboxes in "Show block for specific roles" but login form doesn't appear when user has status "authenticated".

How I can solve this issue?

# Answer
> 2 votes
The user login block will never appear for any user other than anonymous users, as users are already logged in, so it makes no sense to have a login block when they are already logged in.

# Answer
> 0 votes
Maybe your talking about the menu with current user informations("my account","log out"). If that is the case the block you'r looking for is called "USER MENU".

---
Tags: 7, blocks
---


# Question
Title: How to render node content according to site theme after hook_node_insert/update?
How can I get the actual HTML of the node when i am in hook\_node\_insert/update? I would like to get the rendered HTML as it should appear in the site and save it somewhere else ... I am working in drupal 7.

# Answer
> 0 votes
So first as the hook\_node\_update doc says:

> Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. The transaction is not finalized until the save operation is entirely completed and node\_save() goes out of scope. You should not rely on data in the database at this time as it is not updated yet. You should also note that any write/update database queries executed from this hook are also not committed immediately. Check node\_save() and db\_transaction() for more info.

**Solutions:**

There's a module for that: hook\_post\_action

There's also a short article about drupal\_register\_shutdown\_function

---
Tags: theming, hooks
---


title: Print search field in template file

text:
# Question
Title: Print search field in template file
I need a search field to "pop down" under a search icon *({# Search icon #} in sample code)* in my template file.

But how do i print the search block directly into a template file?

I want it to be in my menu--main--site-main-menu.html.twig

```
    {% import _self as menus %}

          {#
            We call a macro which calls itself to render the full tree.
            @see http://twig.sensiolabs.org/doc/tags/macro.html
          #}
          {{ menus.menu_links(items, attributes, 0) }}

          {% macro menu_links(items, attributes, menu_level) %}
          {% import _self as menus %}

          {% if items %}

          {# List #}
          {% if menu_level == 0 %}
<ul{{ attributes.addClass('layout-navigation layout-navigation layout-navigation--full-width layout--large-screen-only') }}>
    {% else %}
    <ul{{ attributes.addClass('layout-navigation__dropdown-menu') }}>
        {% endif %}

        {% for item in items %}
            {% set item_classes = [
            item.in_active_trail ? 'active',
            ] %}

            {# List item #}
            {% if item.below and item.is_expanded %}
            <li{{ item.attributes.addClass('layout-navigation__dropdown', item_classes) }}>
            {% else %}
                <li{{ item.attributes.addClass('layout-navigation__link', item_classes) }}>
            {% endif %}

            {# Link #}
            {{ link(item.title, item.url) }}

            {# Submenu #}
            {% if item.below %}
                {{ menus.menu_links(item.below, attributes.removeClass('layout-navigation layout--large-screen-only'), menu_level + 1) }}
            {% endif %}

            </li>
        {% endfor %}

        {# Search icon #}
        <li class="layout-navigation__link layout-navigation__link__icon"><a href="search/node"><span class="icon fa fa-search"></span></a></li>

    </ul>
    {% endif %}

    {% endmacro %}

```

# Answer
> 0 votes
One way is to preprocess the menu and inject it as a variable, then print the variable:

```
use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_menu().
 */
function mytheme_preprocess_menu(&$variables) {
  $block = Block::load('myblock');
  $variables['myblock'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
}

```

Then in your template:

```
{{ myblock }}

```

---
Tags: theming, 8, search
---


title: Entity Query not returning all results

text:
# Question
Title: Entity Query not returning all results
For some reason, my EntityQuery is returning 60 articles. There are actually 63 of them. I am certain about this.

Here are some questions I have:

1. I don't think revisions are enabled for my content types, but how do I check? And, how do I do this programmatically? I'm not sure if my EntityQuery is returning nids or vids...
2. Why would EntityQuery be unable to find an article? It seems like it can't find it, even if I just search for nodes containing part of its title. It returns 0 results.

Here's what I've tried:

I did a loop and loaded the nodes from the nids, printed out the titles, and I copy pasted the node titles (filtered on articles) from the content list, did a diff with the alphabetized results to find the three articles which EntityQuery doesn't believe to exist. They are all normal seeming articles, which can be viewed/edited.

I started debugging into the core EntityQuery files, but I'm afraid at this rate it's going to take me a while before I understand what's going on. Does anyone know why an EntityQuery might not find certain nodes, or even have an idea where I should be looking in the core files, or what I might be expecting to look for in the DB tables?

I'm using MySQL 5.7, in case that's relevant at all.

EDIT: Someone asked for the code, I am doing an EntityQuery for all articles, yet I don't get all of them:

```
$query = \Drupal::entityQuery('node')
  ->condition('type', 'article');
$entity_ids = $query->execute();

foreach($entity_ids as $id){
  echo $id->getTitle() . "\n";
  // Do I do Drupal entity node load, or do I load via revision ID?
  // Here I would like to load the node and then do stuff with it...
}

```

# Answer
I added metadata to the query, running it as user 1, which allowed it to get all of the nodes:

```
$query = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->addMetaData('account', \Drupal\user\Entity\User::load(1)); // Run the query as user 1.
$nids = $query->execute();

echo "count: " . $query->count()->execute() . "\n";

foreach ($storage->loadMultiple($nids) as $node){
  //do stuff
}

```

Also, since revisions are allowed for nodes, it was returning $nids as revision\_id =\> entity\_id as Berdir said in his comment.
> 8 votes

---
Tags: 8, database
---


# Question
Title: How to properly use contextual filter on group content fields
On my homepage, I created a view for group contents with relationship on "Group content" and "Group". I want to create a contextual filter that when I search on the exposed filter, results will be displayed on new page.

I have an exposed filter of "Category" and "Region" and without contextual filter the result displays on the same page.

I tried filtering with field "Name" as "Display a summary", and I get this:

But when I manually click on any item and check its URL, i'm getting this:

```
http://localhost:8888/drupal-8.2.3/home/Mozilla%20123?field_trade_type_job_target_id=All&field_region_business_target_id=All

```

And I can't search to other items anymore since I am on a filter specific path, in the example above, `/Mozilla%20123?`

I tried another field name, "Category" and I get this, since the 3 given examples are in the same category:

`18` is a taxonomy path. When I manually click the content, I am directed to:

```
http://localhost:8888/drupal-8.2.3/home/18?field_trade_type_job_target_id=All&field_region_business_target_id=All

```

with this content:

This image supposed to be what I want to achieve in the first place when I click search on the exposed filter in the homepage.

Any help is greatly appreciated. Thanks!

# Answer
> 0 votes
Alright, I found the solution to my issue.

These are the steps I come up and followed.

1. Add taxonomy term relationship to the view.
2. On the Contextual filter, search "Name" with taxonomy as description
3. Under "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED", tick "Specify validation criteria"
4. Choose the desired vocabulary.
5. Save and test in the Preview section.

---
Tags: views
---


title: Add a custom handler method to a view?

text:
# Question
Title: Add a custom handler method to a view?
How can I add a custom handler method to a view ?

For example, i add a custom handler in hook\_views\_query\_alter like this:

```
$this->view->addHandler('page_2', 'filter', 'node__field_subsidiary', 'field_subsidiary_type_value', [], 'custom_handler_subsidiary_type');

```

how I manage the handler logic?

# Answer
Can you provide a little more information about what you are trying to do?

Regardless, you would need to create a subclass that extends views\_handler\_field (more info on that here https://api.drupal.org/api/views/handlers%21views\_handler\_field.inc/class/views\_handler\_field/7.x-3.x)

If you're trying to modify the output of an existing field, you would need to use a hook\_views\_data\_alter (https://api.drupal.org/api/views/views.api.php/function/hook\_views\_data\_alter/7.x-3.x) and change the handler specified in the `$data` array. Like so:

```
$data['table_name']['field_name']['field']['handler'] = 'hook_my_custom_handler_class_name';

```

This function hook should live in your module's hook.views.inc file within the 'views' folder in your module's root directory.

Your new handler class should be in a new file named the same as the class with .inc as the file type. That file should be added to your .info file using `files[] = path_to_.inc_file`

In your .module file, you would need to specify the views API:

```
function hook_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'hook') . '/views',
  );
}

```

If you're still struggling, I found this video tutorial very useful https://www.youtube.com/watch?v=biKxw5iEzsY

I got caught out with spelling mistakes when doing this so check all your code!
> 0 votes

---
Tags: views, 8
---


# Question
Title: Getting child term's Tid not the parent's
I created a form via Drupal 8 API, and I am creating a dropdown of a taxonomy terms which has a parent-child hierarchy. But when i select the taxonomy term, it displays term's parent's tid. This is how i try to display the dropdown:

```
$option = [];
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('collections', $parent = 0, $max_depth = 3, $load_entities = FALSE);

foreach ($terms as $term) {
  if($term->depth == 0){
    $term = $term->name;
  }
  elseif ($term->depth == 1) {
    $term = '-'.$term->name;
  }
  elseif ($term->depth == 2){
   $term = '--'.$term->name;
  }
  elseif ($term->depth == 3){
    $term = '---'.$term->name;
  }
  elseif ($term->depth == 4){
    $term = '----'.$term->name;
  }
  $option[] = $term;
}

$form['collection'] = array(
  '#type' => 'select',
  '#title' => t('In Collection:'),
  '#empty_option' => t(' '),
  '#options' => $option,
);

```

I have been trying to get the term's tid not the parent's tid, can anyone point out what am doing wrong? Note:I am not super experienced with drupal 8

# Answer
For the further references: I changed my code to this:

```
$option = [];
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('collections', $parent = 0, $max_depth = 3, $load_entities = FALSE);

foreach ($terms as $term) {
$key = $term->id;

if($term->depth == 0){
  $term = $term->name;
}
elseif ($term->depth == 1) {
  $term = '-'.$term->name;
}
elseif ($term->depth == 2){
 $term = '--'.$term->name;
}
elseif ($term->depth == 3){
  $term = '---'.$term->name;
}
elseif ($term->depth == 4){
  $term = '----'.$term->name;
}
 $option[$key] = $term;
}

$form['collection'] = array(
  '#type' => 'select',
  '#title' => t('In Collection:'),
  '#empty_option' => t(' '),
  '#options' => $option,
);

```

Sorry if I wasted your time.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Change the URL of a node based on parent path
So let's say I have a basic page node.

I want to have this as an entity reference inside another content type - let's say an event content type.

So let's say that the event content has a url like `baseurl.com/eventblahblahblah`

When a user clicks over to the basic page that is the reference on node `eventblahblahblah`, I want them to go to `baseurl.com/eventblahblahblah/basicpagenodehere` \- this needs to be the URL in the browser.

In addition, `basicpagenodehere` can be in multiple references - so if `basicpagenodehere` is also referenced by `event2blah`, then I want it to also be located at the url `baseurl.com/event2blah/basicpagenodehere`

I'm looking at possibly doing this with alterRoute -

```
class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
  }
}

```

But I'm not sure if this is the correct place to do it.

This link suggests maybe PathProcessor, but I don't think that would change the actual URL on the node at the end of processing:

How to alter and rewritte current path programmatically in Drupal 8?

**So how do I set a dynamic URL based on referring node?**

# Answer
The routing system is probably not the right place for this, you would need to rebuild the routing table whenever the content is changed, which is very slow.

PathProcessor is the right tool. By the way, path aliases are also implemented in a PathProcessor, the aliases are coming from a lookup table. You can change the path in and outbound dynamically or with your own lookup table if you need it for performance reasons.

Better for SEO would be a redirect to avoid duplicate content, but this changes the url in the browser, what you don't want.

---

Example for the symmetrical inbound/outbound (asked in the comments):

```
  public function processInbound($path, Request $request) {
    if (strpos($path, '/foo/') === 0) {
      $path = preg_replace('#^/foo#', '', $path);
    }
    return $path;
  }

  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    $path = '/foo' . $path;
    return $path;
  }

```

This will add `/foo` to all paths.

**One way to approach this** could be, you get the child node `node/x` in the outbound processor as input, the parent node id from the current route. Then you get the title from each of both nodes and put the path together.

For inbound I suggest a third fix path parameter, so that you can identify this kind of path right away and scrap all but the title from the child node, query the node id and you are back where you started at `/node/x`.
> 6 votes

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


# Question
Title: Does the sitemap.xml file does from the xmlsitemap module actually get generated?
I see that there is a 1.xml file generated in the sites/default/files/xmlsitemap folder, but I do not see a file in the Drupal root. However, when I call http://www.example.com/sitemap.xml I do get the info. Is this the normal behaviour?

# Answer
Yes, that's normal behaviour.

xmlsitemap\_menu() includes a route for /sitemap.xml specifically.
> 2 votes

# Answer
This is utterly normal behavior: the module caches the sitemap in the files directory, then delivers it via `http://www.example.com/?q=sitemap.xml` which gets mapped to `http://www.example.com/sitemap.xml` with clean URLs.
> 1 votes

---
Tags: 7, xml-sitemap
---


# Question
Title: Functional test not displaying context aware block
I have a context aware block I've created.

```
/**
 * Provide a context aware block.
 *
 * @Block(
 *   id = "my_context_aware_block",
 *   admin_label = @Translation("My context aware block"),
 *   category = @Translation("Display some node information"),
 *   context = {
 *     "node" = @ContextDefinition(
 *       "entity:node",
 *       label = @Translation("Current Node")
 *     )
 *   }
 * )
 */

```

It references the current node in the build method.

```
$node = $this->getContextValue('node');

```

Everything works as expected in my "live" environment. The issue I am encountering is that my functional test is NOT displaying the block when it IS in a context in which it should show. (I haven't bothered testing a context in which the block is not supposed to show.)

```
  public function testSomeStuff() {
    // Create a piece of content
    $node = $this->drupalCreateNode(array(
      'title' => t('My sample node'),
      'type' => 'a_valid_node_type',
    ));
    $node->save();

    // Place the block in the sidebar
    $this->drupalPlaceBlock('my_context_aware_block');

    $this->drupalGet('node/' . $node->id());

    // Note: Whether I check the page content or the response, I don't see
    //       the block there. I am showing examples of both just for the
    //       sake of providing detail in this question.
    $this->assertContains('force phpunit to fail so that I can manually look at the text content', $this->getTextContent());
    $this->assertSession()->responseContains('some valid markup that appears in the block');
  }

```

I have even tested setting

```
protected $profile = 'standard';

```

and the block still doesn't appear when I'm viewing the node I created \[$this-\>drupalGet('node/' . $node-\>id());\].

This is on Drupal 8.2.5.

I am inside of /drupal/root/directory/core running PHPUnit from the command line as such

```
sudo -u www-data ../vendor/bin/phpunit ../modules/custom/my_module/tests/src/Functional/MyFunctionalTest.php

```

Have I discovered a bug or is there something I am missing and doing wrong?

Edit: Here are more details of the complete solution.

First off, you will need to create a user that has administrative rights and log that user in to the site.

```
$adminUser = $this->drupalCreateUser(array(
  'administer blocks',
  'access administration pages',
));
$this->drupalLogin($adminUser);

```

Then, instead of using $this-\>drupalPlaceBlock('my\_context\_aware\_block');, do the following:

```
// Place the block in the content area
$block_url = 'admin/structure/block/add/my_context_aware_block/classy';
$edit = [
  'region' => 'content',
];
$this->drupalPostForm($block_url, $edit, 'Save block');

```

Note: My block didn't need any context configuration. If it did, I could have included that with the $edit array.

# Answer
As discussed in IRC, pretty sure your problem is `$this->drupalPlaceBlock('my_context_aware_block');` which doesn't configure the necessary context mapping. That's not visible in the UI if you only have a single context, but it's still there and then stored in the settings.

See \Drupal\block\Tests\BlockUiTest::testContextAwareBlocks(), go to a URL like admin/structure/block/add/test\_context\_aware/classy, and save the block. ,
> 0 votes

---
Tags: 8, blocks, testing, plugins
---


# Question
Title: How can I custom sort a views display containing multiple content types to list the newest item from each content type sequentially?
I have a Views block display where I've collected content items from 3 different content types, filtered by a shared Taxonomy term. My sort criteria currently is "Post date (desc)" and "Type (asc)". I have the Pager displayed and a limit of 6 items to a page.

The current results are:

Page 1
First Newest item from content type 1
Second Newest item from content type 1
Third Newest item from content type 1
Fourth Newest item from content type 1
First Newest item from content type 2
Second Newest item from content type 2

Page 2
First Newest item from content type 3
Second Newest item from content type 3
Third Newest item from content type 3
Fourth Newest item from content type 3
Fifth Newest item from content type 3
Sixth Newest item from content type 3

Page 3
Etc.

The desired results are:

Page 1
First Newest item from content type 1
First Newest item from content type 2
First Newest item from content type 3
Second Newest item from content type 1
Second Newest item from content type 2
Second Newest item from content type 3

Page 2
Third Newest item from content type 1
Third Newest item from content type 2
Third Newest item from content type 3
Fourth Newest item from content type 1
Fourth Newest item from content type 2
Fourth Newest item from content type 3

Page 3
Etc.

Is this something that requires a custom module with hook\_views\_query\_alter? If so could someone help me out with how I should build the expression in my module?

# Answer
You just need to set a correct order in your 'sort criteria', post date first, then content type.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Public and Private file system path is the same
My company inherited a Drupal 7 site that may not have been properly set up. For example I recently noticed that under Configuration, File System, the "Public file system path" and the "Private file system path" have the same path:

sites/default/files

I'm just wondering what the repercussions might be if I suddenly changed the private files to

sites/default/files/private

Is it too late for this, since there might be sensitive private files already there that can't just be moved because they're registered in the database? I haven't looked too closely at the files yet.

Thanks

# Answer
> 2 votes
The private files path should always be outside the webroot directory since users can directly access all those files through just adding /sites/default/files/private/.. to your URL. Private files means that they are delivered through Drupal to add some access permissions.

What you should do now:

1. Backup your databse and put your site into maintenance.
2. Go to your files\_managed table and find all files stored as private files.
3. Move those files to a new directory outside your webroot.
4. Change your private files path to the new path and test if everything is working.

---
Tags: files
---


title: Accessing term's tid

text:
# Question
Title: Accessing term's tid
I am trying to loop through a taxonomy term's tid, but somehow all the array elements are protected. It was very easy peasy in Drupal 7 with:

```
 $term_id_1 = $node->field_term['und'][0]['tid'];

```

I am not sure how I could access tid(here is the kint() screenshot):

and here I how I get this and my broken foreach():

```
public function setCollection($collection) {
$collection_array = [];
$collection_ids =  \Drupal\taxonomy\Entity\Term::load($collection);
kint($collection_ids);
foreach ($collection_ids as $collection_id) {
  $keys = $collection_id->values;
  foreach ($keys as $key){
    $collection_array[] = $key->tid;
  }
}

$this->collection = $collection_array;

```

}

Question 1-\> Is taxonomy terms are node?

Question 2-\> Is this line correct to get the fields?

```
  $collection_ids =  \Drupal\taxonomy\Entity\Term::load($collection);

```

Question 3-\> Can anyone lead me to get access 'tid' from this protected 'values' array?

Warm regards.

# Answer
Yes you can do `$term->id()` which should return the term id if `$term` is a Term object. See id().
> 3 votes

# Answer
Answer 1 - Taxonomy Terms are an Entity in Drupal 8 (`Drupal\taxonomy\Entity\Term`), not a node.

Answer 2 - Is your parameter `$collection` a single ID or an array ID's? If it's a single ID, then yes. If it's an array of ID's then you should be using `Term::loadMultiple()`.

Answer 3 - You can call `Term::id()` on the object, so in your case it would be `$collecion_id->id()`.
> 1 votes

---
Tags: 8, entities
---


title: Content change on hook

text:
# Question
Title: Content change on hook
I am working on a new content type. I created a hook that loops through a .csv file on its load, and makes a table from it.

What I want to do now is including this new table automatically in the CKEditor field, in the same form.

How can I do this? You don't have to tell me exactly what to do. Just some hints on which function to use would be appreciated.

# Answer
> 0 votes
In the hook YOUR\_MODULE\_form\_CONTENT\_TYPE\_node\_form\_alter() fill the field (that outputs in the ckeditor) with your HTML, like:

```
$form['field_body'][LANGUAGE_NONE][0]['value'] = $your_html;

```

You also need to make sure, that the tags get saved, by adding these tags to allowed ones for your ckeditor!

---
Tags: 7, hooks, wysiwyg
---


# Question
Title: Rules: How to modify an existing condition programmatically
I've been able to add a condition to an existing rule, but I can't find any documentation on how to modify an existing condition on a rule. The following code works for adding but I need to modify the one that already exists. Any ideas?:

```
$hk_delivery_rule = rules_config_load('commerce_shipping_service_hong_kong_delivery');

$hk_delivery_settings = array(
    'first_price:select' => 'commerce-order:commerce-order-total',
    'operator' => '<',
    'second_price' => array(
      'amount' => $hk_threshold,
      'currency_code' => 'HKD'
    )

  );

$hk_delivery_rule->condition(rules_condition('commerce_price_compare_price', $hk_delivery_settings));
$hk_delivery_rule->save();

```

# Answer
So turned out it was quite easy:

```
  $hk_delivery_rule = rules_config_load('commerce_shipping_service_hong_kong_delivery');

  foreach ($hk_delivery_rule->conditions() as $condition) {

    if (isset($condition->settings['second_price'])) {

      $condition->settings['second_price']['amount'] = $hk_threshold;

    }

  }

  $hk_delivery_rule->save();

```
> 3 votes

---
Tags: 7, rules
---


title: #states visible

text:
# Question
Title: #states visible
The states visible seems to work correct in D7. In D8 I want to test make a field visable if one OR another field have a value. And also when two fields have a value. What I have below works if both fields have a value.

```
use Drupal\Core\Form\FormStateInterface;
use \Drupal\Core\State\StateInterface;

function mymodule_form_alter(&$form, FormStateInterface     &$form_state, $form_id) {
  if ($form_id == 'node_page_form') {
    $form['field_format']['#states'] = array(
      'visible' => array(
          ':input[name="field_item_type"]' => array('value' => 'tv_show'),
          'or',
          ':input[name="field_extra"]' => array('value' => 'bike'),
      ),
    );
  }
}

```

# Answer
Try the below code .It works .

```
$form['field_item_type'] = [
  '#type' => 'select',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#options' => ['tv_show'=> 'Tv show','serials' => 'Serials']
];
$form['field_extra'] = [
  '#type' => 'select',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#options' => ['movie' => 'movie','chair'=>'Chair'],
];
$form['field_format'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#required' => TRUE,
];
$form['field_format']['#states'] = [
  'visible' => [
    [
      [':input[name="field_item_type"]' => ['value' => 'tv_show']],
      'or',
      [':input[name="field_extra"]' => ['value' => 'movie']],
    ],
  ],
];

```
> 12 votes

---
Tags: 8, javascript
---


title: Implementing Custom Cache Tags

text:
# Question
Title: Implementing Custom Cache Tags
I would like to use the new Cache Tagging in D8 to help keep related content of different types (entities, nodes, blocks, etc) in sync. But from reading the currently available documentation of this feature I do not understand how to add my own cache tag to the items of content when creating/updating said items.

For example when creating a new node of an type Store I would like to add the cache tag location:new\_york\_123 and the same for a a block. Then if I changed the display name of the New York 123 location to SoHo, I could invalidate the cache tag and have all related content update.

# Answer
Here is how to use cache tags in the context of custom blocks which I have tried and works but I think it applies to other contexts

### Use default drupal tags

In the build array you can specify `cache > tags > node_list` and this block content would get invalidated (refreshed) when ANY NODE is changed with nothing else to do on your part

```
public function build() {
    return array(
        '#markup' => MY_MODULE_awesome_dynamic_node_content(),
        '#cache' => [
            'tags' => ['node_list'], //invalidate when any node updates
            //'tags' => ['node:1','term:2'], //invalidate when node 1 or term 2 updates
        ],
    );
}

```

**Alternatively** you can put in one or more node/term/user IDs to invalidate the array on specific nodes or terms as shown in the code comment above. Note: you can mix and match nodes, terms, users and custom tags as you see fit.

### Use your own tags

if you want to have your own way of clearing your build array add your custom unique tag in the build array (any unique string will do)

```
public function build() {
    return array(
        '#markup' => MY_MODULE_awesome_dynamic_node_content(),
        '#cache' => [
            'tags' => ['MY_CUSTOM_UNIQUE_TAG'],
        ],
    );
}

```

and in your custom code logic call `invalidateTags` with your own tag

```
function MY_MODULE_custom_clear_cache_logic(){
    ...
    \Drupal\Core\Cache\Cache::invalidateTags(array('MY_CUSTOM_UNIQUE_TAG'));

```

if you want to read more about drupal 8 cache internals
> 19 votes

---
Tags: 8, caching
---


# Question
Title: How could I change webform submission tags to common html email tags?
I have a webform submission style to display the submission ,like this

but when I send Html Email to others, it didn't show the way we want,it seems to didn't support fieldset and some css elements in some Email client. Now I am here for help that is there some ways or some modules to change the tags to common html email tags like and add some css to it? I'll appreciate anyone who help me solve this problem.

# Answer
I think you want HTML format template option to send an email with HTML format.

For this, you can use htmlmail and mailsystem module and enable it and select "HTMLMailSystem" option at admin/config/system/mailsystem.

Now check step 3 at admin/config/system/htmlmail and select "Full HTML".

Now you can config you webform mail setting and select custom mail template and add your HTML tags and inline CSS in div.
> 0 votes

---
Tags: webforms, emails
---


# Question
Title: How can I force a view page not to be cached?
I created a few views which I use as JSON endpoints for a client application. However, they are not *refreshed* along with the content they serve.

**What I have tried with no success:**

* Setting Caching to none (within the View page).
* Disabled Views cache, (in Views' advanced settings).
* Running `drush cache-rebuild` as a cronjob every 12h.

I know I can use a workaround like `/api/my-endpoint?time=1234`, but this is not an option for me, since I have no access to the consuming client's code anymore. Neither I plan to recreate all these endpoints in custom code.

How can I force a JSON view page not to be cached?

# Answer
> 1 votes
This is probably not related to caching inside of views, more likely on page level. You can disable page caching with the route option `no_cache`. Use a RouteSubscriber to alter the routes of views:

**/src/Routing/RouteSubscriber.php**

```
<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {

    // no_cache for a specific view
    if ($route = $collection->get('view.testview.page_1')) {
      $route->setOption('no_cache', TRUE);
    }

    // or for all view displays of a specific type
    foreach ($collection->all() as $route) {
      if ($route->getOption('_view_display_plugin_id') == 'rest_export') {
        $route->setOption('no_cache', TRUE);
      }
    }

  }
}

```

**mymodule.services.yml**

```
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

---

This would not be necessary, if the view set the correct cache tags for the content it serves, so that the render cache could be invalidated if the content is changed.

---
Tags: views, 8, caching
---


title: Multilingual Breadcrumb

text:
# Question
Title: Multilingual Breadcrumb
I need to show a breadcrumb on my client website but it is required to be in two languages I have tried several approaches and modules but all of it show the breadcrumb in one language only.

Please, If anyone have an idea about this I appreciate your help.

Besides, Could you please explain more about using default drupal breadcrumb what should I have been installed to use breadcrumb correctly? Do I need breadcrumb + another module ???

Regards,

# Answer
Assuming you want your breadcrumbs like this:

```
  Home/La Casa >> Node/Nodo >> Friends/Amigos

```

You could override template\_preprocess\_breadcrumb like so:

```
  function MY_THEME_preprocess_breadcrumb(&$variables)
  {
     $breadcrumbs = &$variables['breadcrumb'];
     foreach($breadcrumbs as &$breadcrumb)
     {
         $breadcrumb .= '/' . locale($breadcrumb, null, 'SP');
     }
   }

```

Don't quote me on the langcodes, and this would require that you have the locale module installed and enabled, but it should output the above example breadcrumb.
> 1 votes

# Answer
I used Custom Breadcrumbs Module it has the ability to add breadcrumb for each language... For breadcrumbs which are automatically generated translation can be done in String Translation Table. I think multilingual breadcrumb can also be created using Path Breadcrumbs
> 1 votes

# Answer
Drupal has some mainstream contributed modules that can handle this in most cases. Using built-in interface translation and i18n\_string, you can add translations for many of the main breadcrumbs in Configuration -\> Regional & Language -\> Translate Interface -\> Translate.

Several modules can help you get these strings to begin with. You can use the potx module to pull all built-in interface strings from your other installed modules, which puts the strings into the locales\_source table. Then you can use the l10n\_update module to search for community-contributed translations for these strings.

For the last part of a breadcrumb that comes from a node, for example, Drupal will display the translated title of the node if it finds it. For Content Translation (node-based), the node displays its title in the breadcrumb, and for Entity Translation (field-based), you can enable the title module to convert the title property to a field, which can then be translated and displayed in the breadcrumb.
> 0 votes

# Answer
Hope this helps:

```
<?php
    //breadcrumb fix
        function THEME_NAME_menu_breadcrumb_alter(&$active_trail, $item) {
            global $language ;
            $lang_name = $language->language;
            $i = 0;
            foreach (array_keys($active_trail) as $key) {
                if($i!=0){
                    $translatedValue = i18n_string_translate(array('menu', 'item', $active_trail[$key]['mlid'], 'title'), $active_trail[$key]['title'], array('langcode' => $lang_name, 'sanitize' => FALSE));
                    $active_trail[$key]['title'] = $translatedValue;
                }
               $i++;
            }
        }
    ?>

```
> 0 votes

# Answer
Assuming you are using the `i18n` module, including submodule `i18n_menu`, then the most reliable way of translating your breadcrumbs would be implementing `hook_menu_breadcrumb_alter` and run `_i18n_menu_link_title` function on each item.

This should work:

```
/**
 *   Implements hook_menu_breadcrumb_alter()
 */
function YOURMODULE_menu_breadcrumb_alter(&$active_trail, $item) {
  foreach ($active_trail as $index => $breadcrumb_item) {
    if (isset($breadcrumb_item['mlid'])) {
      $active_trail[$index]['title'] = _i18n_menu_link_title($breadcrumb_item);
    }
  }
}

```
> 0 votes

---
Tags: 7, breadcrumbs
---


title: sort the content based on click count

text:
# Question
Title: sort the content based on click count
I'm using Link Click Count module.I want to sort the view content based count.how to list sort the content based on link click count.now It displayed the node 4 times if the count is 4.

# Answer
1. Configure the link click count module
2. Add new field in content type and set 'count the click happened on the link' in manage display
3. Use the default link click count stats view
4. In sort criteria, add the link node id and chooose the you wanted order.

##

5. whenever you click the field in the node, It will be get counted
6. The sorted result based on the click of the link will be shown in the view's result
> 0 votes

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


# Question
Title: How to change the day and month language?
Working on multilingual site, I want to change the language of the month in dutch language. For that I have created a module.

```
<?php
function mymodule_format_date($timestamp, $type = 'custom', $format = 'd M', $timezone = NULL) {
  return format_date($timestamp, $type, $format, $timezone, 'nl');
}

```

and on the node file put the date format in t() function

```
<?php print t(format_date($created, 'custom', 'd M')); ?>

```

but no luck. Please help.

# Answer
> 0 votes
For multilingual you need to import .po file in your setup. Download .po file from this link just add language prefix at here **language\_prefix (/en, /hi, /de etc..)**.

https://localize.drupal.org/translate/languages/language\_prefix

Now, add `<?php print date('j F Y', $created) ?>` simple php data function and add your data formate here.

After you will able to see day and month in your language.

If you wish to make a different format for both language just add this.

`<?php if($language->language == "language_prefix") {
 print date('j F Y', $created);
}
else {
 print date('F j Y', $created);
}` Thank you.

---
Tags: 7, datetime
---


# Question
Title: How to invalidate cache when a config entity is added/deleted?
In a MenuLinkContent entity I've a list\_string field populated with a `$key => $value` array of a custom config entity. When I add or delete a config entity the values in my field are not updated until I rebuild the cache.

I think I should set a cache tag, but I can not figure out where I should add the tag and which tag should I use.

**Edit:** The array is created in a static method on my entity class.

```
public static function getConfigList() {

  $entities = SvgIcon::loadMultiple();
  $config_list = array();

  /** @var SvgIconInterface $entity */
  foreach ($entities as $entity) {
    $config_list[$entity->get('id')] = $entity->get('label');
  }

  return $config_list;
}

```

The field is defined via hook\_entity\_base\_field\_info().

```
function svg_icon_menu_link_entity_base_field_info(EntityTypeInterface $entity_type) {

  $fields = array();

  if ( $entity_type->get('id') !== 'menu_link_content' ) {
    return $fields;
  }

  $fields['svg'] = BaseFieldDefinition::create('list_string')
    ->setLabel('SVG sprite')
    ->setDescription('Select the SVG sprite file.')
    ->setSettings(array(
      'allowed_values' => SvgIcon::getConfigList()
    ))
    ->setDisplayOptions('form', array(
      'type' => 'select',
      'weight' => 0,
      'settings' => array(
        'display_label' => TRUE
      )
    ));

  return $fields;
}

```

# Answer
> 1 votes
List fields support an allowed\_values\_callback setting, if you use that, then you don't need to worry about cache invalidation.

See https://api.drupal.org/api/drupal/core!modules!options!options.api.php/function/callback\_allowed\_values\_function/8.2.x and

---
Tags: 8, caching
---


# Question
Title: How do I export webform data input to CSV / XLS?
I have a simple one-page form (name, address, etc). I would like to export the data of the submitted webform by the user into CSV / XLS files.

How do I do that?

# Answer
If you are using the webform module you can download submission's results in csv/xls files. if you want to do that go to:

content =\> select the webform you need to export =\> click on the result tab =\> finaly click on the download button.

If you need more flexibility like exporting multiple webforms Which fulfill certain conditions.

Take a look at the Forena Reports module and this post in which a detailed exemple is given by a co-maintainer of the forena module.
> 4 votes

# Answer
Just to add information to HusterFrancis posts. People who who feel limited by the core contact functionality in Drupal 8. There is a beta version webform 8.x.

Works very well. It does everything from scratch. (Export of data input, conditional rules, e-mail handling, etc)
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Is it possible to combine several template files togather and make single integrated template instead?
For example to render a simple form like *search block* should be invoked 8 different templates like below and each of this template only has one or few line of code, see below:

```
region.html.twig
└─ block.html.twig
   └─ form.html.twig
      ├─ form-element.html.twig
      |  ├─ form-element-label.html.twig
      |  └─ input.html.twig
      └─ container.html.twig
          └─ input.html.twig

```

As you can see in below some of this files Just have a few line of code:
**region.html.twig**

```
{% if content %}
  <div{{ attributes }}>
    {{ content }}
  </div>
{% endif %}

```

**form.html.twig**

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

```

**form-element.html.twig**

```
{% if title is not empty or required -%}
  <label{{ attributes.addClass(classes) }}>{{ title }}</label>
{%- endif %}

```

**input.html.twig**

```
<input{{ attributes }} />{{ children }}

```

**container.html.twig**

```
<div{{ attributes.addClass(classes) }}>{{ children }}</div>

```
* Some of this templates files are common with other parts of page and editing each of them can affect to other parts and cause unwanted changes . for example in this case drupal theme system for: "input.html.twig", suggest only `input--submit.html.twig` and this suggestion also common between `search block` and `search form`.
* Editing and managing this template files is tedious and difficult and make my theme folder busy.
* Most of these templates have ambiguity and unclear content code

For this reason I'm looking for a method to combine this template files and make one template file like "`form--search-block.html.twig`" to I can edit all element needs for rendering a form in one special place and with more flexibility and confidently.

# Answer
> 2 votes
In drupal 8 there's this rule called theme inheritance and backward compatibility, what you have to do to accomplish what you want is to make sure that your subtheme does not inherit any core theme's `HOOKS`

You might want to play around in your subtheme and set your base theme to `null` I haven't checked it myself but it might work.

And then of course you have to define new preprocess templating rules in your `themename.theme` file using `theme_suggestions_page_alter` function, you can read more here

Then based on what you defined in your `.theme` file you may proceed with creating a unified template file

Also you might want to read this suggestion that somewhat explains a similar use case

---
Tags: theming, 8, forms, blocks
---


# Question
Title: How to exclude specific css file from aggregation
Is it possible to exclude a specific css or js from drupal'l css and js aggregation ?

For ex: Exclude custom-style.css from being aggragated ?

# Answer
> 15 votes
Similar to Drupal 7, the setting `preprocess` key to `FALSE` will prevent a JS or CSS library from being aggregated.

```
mylibraryname:
  css:
    theme:
      css/custom-style.css: {preprocess: false}

```

Same works for JavaScript

```
cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

As documented on Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

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


# Question
Title: Fixing bad node that makes search not index, but completes cron
Upon updating to the latest version of Drupal 7, the following errors presented themselves in the site:

* Warning: Creating default object from empty value in node\_build\_content() (line 1398 of /var/www/html/modules/node/node.module).
* EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7881 of /var/www/html/includes/common.inc).

These errors don't seem to interfere with much on my site, however, they do seem to stop cron from indexing the website. I've been sitting at 0% of 456 pages with a 500 page max for a week or two now since my first noticing.

I've done a lot of digging trying to resolve this issue and the following link is the closest thing I can find in resolving this issue: http://tappetyclick.com/blog/2013/01/14/how-find-bad-node-makes-search-indexing-cause-drupal-cron-fail#.Vuw1KhIrJTY

The difference between the link above and my issue is that my cron successfully submits, even though right before the success message in the report log, it produces the EntityMalformedException: Missing bundle property listed in the bullets above. Outside of that, its relatively the same story. I've gone through the step-by-step in that link and many others like it without any resolution.

I've also additionally run this through devel\_debug and a few other options to better troubleshoot but no other errors produce. Devel\_debug actually doesn't list any errors at all in its log.

At this point I'm up for suggestions as I'm running low on ideas of how to remedy what seems to be a relatively multi-possible bug. Any thoughts the community may have or links to previously helpful posts would be appreciated.

Thank you in advanced!

# Answer
> 1 votes
After some additional alterations I was able to isolate 3 nodes that were not presenting as broken, but once I accessed them with PHPmyadmin I was able to delete them from the list. Once I found them and removed them Cron began indexing once again.

# Answer
> 1 votes
I had a similiar problem with the same errors in the search cron log.

I have 100 000+ nodes and did'nt want to delete the faulty/orphan nodes.

But with this Select I was able to see where the indexing stopped.

```
SELECT n.nid, title, n.type, status FROM node n LEFT JOIN search_dataset d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL  OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC LIMIT 0,1"

```

However I found that the problem was because of uid's \> 0 in the comment table for uid's that does not exist in the users table (non existing users). So former users that had been deleted. But for some reason they still existed in the comment table with a uid \> 0 (their old uid when they where active users).

Solution was to located these "Orhan-users" in and set their uid in the comment table to zero "0".

After that the indexing continued and the node was intact, but with some comment to the nodes from active and non-active (not existing) users. *I don't delete comments even if the user is deleted from the site.*

I used this to update the comment table after I located the "missing" user.

```
UPDATE comment SET uid=0 WHERE uid="the old uid from a deleted user (not existing in users-table)";

```

**Heres the process:**

1. Locate where the indexing stops with the first SELECT.
2. Find if the node has comments (same nid)
3. Find out if all users (uid) in the comment table still exists (in the users table)
4. For those users that don't exist but have made a comment, make sure the uid in the comment-table is zero "0". With the UPDATE-script above.

This made the node displaying and the indexing continued.

---
Tags: search, debugging
---


title: Add taxonomy terms to files

text:
# Question
Title: Add taxonomy terms to files
Is it possible to add a taxonomy term to a file that it is uploaded to the site? If not I imagine that I would need to create a content type to encapsulate the file and tag that.

# Answer
> 1 votes
Your file would need to be fieldable. i.e. - using something like the File Entity module.

More complete media solutions exists also, like Media, Scald, or Asset exist which would provide this and more.

---
Tags: 6, taxonomy-terms, files
---


# Question
Title: Incorrect branch when adding modules with composer
**Edit: Gist of my complete composer.json**

I'm seeing some confusing behaviour with Drupal branch names when adding modules using composer - specifically I seem to be getting the 7.x version of the module rather than 8.x.

This is a composer based setup, **running 8.3.0-rc1** \- composer.json includes:

```
"drupal/core": "8.3.0-rc1"

```

My understanding has always been that for modules, whenever you specify the branch in composer, you remove the 7.x- or 8.x from the start.

e.g. I wanted the tagclouds module 8.x-1.x branch, so I did:

```
composer require drupal/tagclouds:1.x

```

Yet what it actually installs is **7.x-1.9+30-dev**

Composer output:

```
 - Installing drupal/tagclouds (dev-1.x 54086ae) Cloning 54086ae717

```

I also ran `drush ups` and got:

> Project was not packaged by drupal.org but obtained from git. You need to enable git\_deploy module

So I add and enable git\_deploy the same way.

composer.json:

```
"drupal/git_deploy": "2.x"

```

again it installs a 7.x release (7.x-2.2+10-dev)

Any obvious mistakes?

**Other things I've tried:**

* Explicility listing the stability in the version constraints, e.g. `2.x-dev` instead of `2.x`, and `1.x-dev` not \`1.x'. (The documentation suggests composer adds this by default though.)
* Using `composer update nothing` to regenerate the composer.lock file

# Answer
Make sure you are using the correct repository endpoint for Composer. For Drupal 8, it is `https://packages.drupal.org/8`.

Your composer.json file should contain a repository key like so:

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

```
> 1 votes

---
Tags: 8, drush, version-control, composer
---


# Question
Title: Can we write php conditions in view field templates?
My view fields are as like shown in screenshot, for each row I need to add comment link,revision link ,edit link, voting icons and topic terms etc And I have large number of views which will share all these fields.

So I thought to remove all the fields and have nid field in all my views. Then create common template file of nid. And in that template file I am planing to use node\_laod and fetch all required fields and add them with some common required html structure.

Please suggest if this will be right way to achieve such kind of workflow and reducing work load to add fields in each view, make them easy to edit or make change in fields from template files.

Is this will be good idea to write php code in template file or I am supposed to use some pre process functions etc

Please suggest ! Thanks.

# Answer
> 2 votes
No. Do not make a view that pulls a nid, then do `node_load` in the template. This will be a performance killer.

You should create a `view mode` using Entity View Mode module, add the fields to the display, and theme it with `node--node-type--view-mode.tpl.php`. Then the configured View only has to show 'Rendered Content' - and pick the view mode. Then you're done.

See: https://www.youtube.com/watch?v=wcskTtvR6Mo

# Answer
> 1 votes
It is not a good practice to put php processing in template files. Try to have only variables with the necessary information there and if-then blocks to decide what you need to print in the html. You can preprocess your data in template.php or a module.

But I would go for the "fetch as much as possible in the view" approach. You will actually gain a bit of performance and, as I understand your requirements, you will have all you need, just have to style it. On that point you can go either for different templates for every view, a more common template for multiple views (see the theming information), or even group some of the views creating different displays and providing common/separate templates as needed.

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


# Question
Title: Solution for preventing indexing of content types?
I have a custom content type that I simply want to not be indexed by the Drupal search engine. Yes, I can hide it from the search results, but there are hundreds of thousands of these nodes and rebuilding the index takes days. After much searching and trial/error, I came across this solution from ChrisPliakus.

You can see my query below in the update\_index hook, where I exclude MY\_CONTENT\_TYPE from the query. I've tested the query manually and it seems to show nodes other than the one I want to ignore, which I think is the goal there.

However, when I run drush cron --verbose, I still see those nodes getting indexed :(

---

```
/**
 * Implements hook_module_implements_alter().
 */
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ('update_index' == $hook) {
    unset($implementations['node']);
  }
}

/**
 * Implements hook_update_index().
 *
 * @see node_update_index().
 */
function MYMODULE_update_index() {
  $limit = (int) variable_get('search_cron_limit', 100);

  $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE (d.sid IS NULL OR d.reindex <> 0) AND n.type != 'MY_CONTENT_TYPE' ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

  foreach ($result as $node) {
    _node_index_node($node);
  }
}

```

---

Any ideas? Thanks in advance!

# Answer
Rather than coding a custom solution, I would use a supported module. The answer I believe will help you: Restrict Drupal Search to few content types

So for Drupal 7 you can use Custom Search, Search Config or Search API Exclude if you are using Search API. For Drupal 8 you can use Search Exclude.
> 1 votes

---
Tags: nodes, search
---


# Question
Title: Is it possible to get rid of content duplicates?
I've got a site, mysite.com. Now I'm trying to add blog on it at sub-domain, blog.mysite.com, using the Domain Access module.

When I create an article in blog, with alias blog.mysite.com/article-alias, it is available from main site, by URL mysite.com/article-alias. At the same time, main site articles, like mysite.com/about are available from blog by URL blog.mysite.com/about. No matter which affiliate I'm sending this article to, or which source site I choose, it still happens. Today, I've found that some of such pages were indexed by Google as duplicates, despite having canonical tag.

Is it possible to get rid of such pages with this module settings, or with the help of some additional modules? Still, I can't find no solution.

# Answer
You can manage your Robots.txt file through Drupal using RobotsTxt module. This way you can exclude whatever content you want from Google, etc.
> 0 votes

---
Tags: domain-access
---


# Question
Title: How to get field mapping information in custom module?
I am trying to call `field_info_field_map()` in my DefaultForm.php . What is the right way? I am getting the following error:

> Error: Class 'Drupal\module\_name\Form\Field' not found in Drupal\module\_name\Form\DefaultForm-\>module\_name\_settings\_get\_field\_options()

The code I am using is as follow:

```
$fields = Field::fieldInfo()->getFieldMap();

```

the code i am trying to convert to d8

```
function mn_settings_get_field_options() {
  static $options = null;
  if (is_array($options)) {
    return $options;
  }
  $options = array();
  $fields = field_info_field_map();
  foreach ($fields as $field_name => $field_data) {
    if (isset($field_data['bundles']['node'])) {
      $node_types = $field_data['bundles']['node'];
      $options[$field_name] = $field_name . ' (In content types: ' . implode(', ', $node_types) . ')';
    }
  }
  asort($options);
  return $options;
}

```

# Answer
Looks one potential solution is to use is EntityFieldManager::getFieldMap. See the change log for this change.

Also, FYI:

> When working directly with an $entity, the field definitions (which include base and configurable fields) can be directly requested from the object with $entity-\>getFieldDefinitions() or $entity-\>getFieldDefinition($field\_name)
> 2 votes

# Answer
The following DB query will give me list of all fields attached to node: `select name from config where name like 'field.field.node%';`
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Add entity reference field to content type
I have 2 content type 1.Employee performance 2.Task

Task content type has a field that assign users to the task (Assigned To Users).Each employee has a node in Employee performance content type and he is the author of the node. How I can add a select list field in Employee performance that display all the tasks that assign to the employee(author) by using entity reference field in view?

# Answer
> 1 votes
You would need to use the "Views: Reference by entity reference view" Mode.

You then need to have created an Entity reference view display to correspond to this. In this view you need to pass the current node author as an argument / contextual filter and show all the nodes you want to display there.

Select this view in the entity reference field's settings as attached, an that should do it.

---
Tags: views
---


# Question
Title: Help with SQL-query finding and updating uid's from non-existing users in comment table
I need help to make a SELECT from the drupal database.

Two or three tables

* comment
* users
* node (maybe)

I want to find all uid's in the comment table from former users but where the uid\>0 in the comment table. uid's for former users but whom don't exist in the users table.

I also would like to make an UPDATE-script that can set all uid's from non-existing users in the comment table to zero "0".

This will solve some of the search indexing problem, where it stopps at certain nodes.

Please help me.

# Answer
> 0 votes
I think this should do it. Make sure you take a backup before running this:

```
UPDATE {comments} SET uid = 0
WHERE uid > 0
AND cid IN
(
  SELECT cid FROM {comments} AS comment
  LEFT JOIN {users} AS user
  ON user.uid = comment.uid
  WHERE user.uid IS NULL
)

```

---
Tags: 7, database, search
---


# Question
Title: How used function drupal_render_children in file twig?
I want use function `drupal_render_children` in file \*.html.twig Drupal 8. What solution for do ?

# Answer
Well, for one, it is deprecated. Two, you cannot use PHP functions directly within the Twig template.

You can implement the appropriate preprocess hook to do this, to pass to Twig as a variable.
> 1 votes

---
Tags: theming, 8
---


title: Login to drupal with just a number

text:
# Question
Title: Login to drupal with just a number
Is it possible to login to Drupal with just a number?

Use case is a kiosk where users have a nfc tag. So my idea was to hide the input field an use the number retrieved from the nfc tag to identify the users.

The kiosk is only used internally and there would be no keyboard just a touchscreen.

Thanks

# Answer
You should definitely have a look at the Identification module. Some details (from its project page):

> ... allows users to login with a custom identification number (or string). To configure this module, the site builder creates a (or specifies a pre-existing) field on the user entity. The value stored in this field for a particular user can then be used as the identification login credential.
>
> ### Use Case
>
> An organization that wants users to be able to login using a custom identification number and password. This means each user account will have three unique identifiers:
>
> * core user name
> * core user e-mail address
> * custom user identification number (or string)

**Credits** (and kudos) to tyler frankenstein!

**Note**: This answer applies to both D7 and D8.
> 1 votes

# Answer
So basically, you mean just a number and no password? The simplest way to do this would be to use the number as the username (when adding a user), and then a predefined password that's the same for all users.

This approach has some major security caveats, but would work. In JS on the login page, or in whatever approach you use for the kiosk, have the number fill in the username field, and fill in the hidden password field with the default password.

Modifying the look and feel of the login form/page can be done through hook\_form\_alter() and CSS.
> 0 votes

---
Tags: users, authentication-authorization
---


title: How to modify the search index?

text:
# Question
Title: How to modify the search index?
There's a search index for the Apache Solr module. However, I don't see any way to change this index. It seems that various fields and items are added to the index without rhyme or reason.

If I wanted to index a field called "keywords" how would I go about this? Do I have to use the method described in Adding Customized Fields to the Apache Solr index in Drupal?

Basically, there's a keyword field, which will have comma separated values of keywords, and I want to index this for Apache Solr search.

# Answer
You should use hook\_apachesolr\_index\_document\_build in your custom module. This hook helps to extend basic SOLR Document object and adds custom fields for indexing.

If 'Keywords' field has machine name 'field\_keywords' hook implementation may be as below

```
/**
 * Implements hook_apachesolr_index_document_build().
 */
function MY_MODULE_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
  if ($entity_type == 'node') {
    // Adds 'Keywords' field as a separate field to Solr index.
    $document->keywords = isset($entity->field_keywords[LANGUAGE_NONE][0]['safe_value']) ?
      $entity->field_keywords[LANGUAGE_NONE][0]['safe_value'] : '';
  }
}

```
> 0 votes

# Answer
I'm not sure if the *keywords* field is a reference field (term or node entity). Please update the array key from the example, I used term reference as example

```
$term->field_keywords[LANGUAGE_NONE][0][tid]

```

Please try this, in your *mymodule.module*:

```
function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type) {
  // I think you should do a foreach here, since you are using multi-valued field.
  foreach ($entity->field_keywords[LANGUAGE_NONE] as $key => $val) {
    $tid = $val['tid'];
    // The 1st letter indicates the data type and the last letter is
    // 'm' for multi-valued.
    $document->addField('im_field_keywords', $tid);
  }
}

function mymodule_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->addParam('fl', 'im_field_keywords');
}

```

Then, prepare the variable.

```
/**
 * Implements hook_apachesolr_process_results().
 */
function mymodule_apachesolr_process_results(&$results) {
  foreach ($results as $key => &$result) {
    $result['foo'] = $result['node']->im_field_keywords;
  }
}

```

Call this variable in you search-result.tpl.php e.g.

```
<?php print $result['foo']; ?>

```

I hope it helps.
> 0 votes

# Answer
Do you have the search\_api module installed?

If the keyword field is already a part of your content-type bundle, you should be able to see it at */admin/config/search/search\_api/index/default\_node\_index/fields*

This page allows you to pick and choose which fields to index, and to boost the fields importance in the index.
> 0 votes

---
Tags: search
---


title: tableselect form doesn't work

text:
# Question
Title: tableselect form doesn't work
I can't get form-table of '#type' =\> 'tableselect' to work. I've lifted the example from 8.3.x core/lib/Drupal/Core/Render/Element/Tableselect.php Tableselect. The table works and there are no log messages.

What happens is the page reports that there are no users found (ie. the table is empty) even though the $form array has the row data in it.

If I change the type to '#type' =\> 'table' the table is populated as expected.

This is the code I am using.

```
namespace Drupal\simpleForm\Controller;
use Drupal\Core\Controller\ControllerBase;

class DisplayTable_1 extends ControllerBase
{

    public function description_one()
    {
        $header = [
            'first_name' => $this->t('First Name'),
            'last_name' => $this->t('Last Name'),
        ];

        $options = [
            1 => ['first_name' => 'Indy', 'last_name' => 'Jones'],
            2 => ['first_name' => 'Darth', 'last_name' => 'Vader'],
            3 => ['first_name' => 'Super', 'last_name' => 'Man'],
        ];

        $form['table'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $options,
            '#empty' => $this->t('No users found!!!'),
        );

        return $form;
    }

}

```

Any help would be appreciated.

# Answer
> 2 votes
Found the issue: the **#type' =\> 'tableselect** has to be built inside a class that extends **FormBase**.

This Works:

```
  class DisplayTable_1 extends FormBase {
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $options = [
            1 => ['first_name' => 'Indy', 'last_name' => 'Jones'],
            2 => ['first_name' => 'Darth', 'last_name' => 'Vader'],
            3 => ['first_name' => 'Super', 'last_name' => 'Man'],
        ];

        $header = [
            'first_name' => t('First Name'),
            'last_name' => t('Last Name'),
        ];

        $form['table'] = [
            '#type' => 'tableselect',
            '#title' => $this->t('Users'),
            '#header' => $header,
            '#options' => $options,
            '#empty' => t('No users found'),
        ];

        // Add a submit button that handles the submission of the form.
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
            '#description' => $this->t('Submit, #type = submit'),
        ];
        return $form;
    }

    public function getFormId() {
        return 'fapi_example_input_demo_form';
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Find out what was submitted.
        $values = $form_state->getValues();
        foreach ($values as $key => $value) {
            $label = isset($form[$key]['#title']) ? $form[$key]['#title'] : $key;

            // Many arrays return 0 for unselected values so lets filter that out.
            if (is_array($value)) {
                $value = array_filter($value);
            }

            // Only display for controls that have titles and values.
            if ($value && $label) {
                $display_value = is_array($value) ? preg_replace('/[\n\r\s]+/', ' ', print_r($value, 1)) : $value;
                $message = $this->t('Value for %title: %value', array('%title' => $label, '%value' => $display_value));
                drupal_set_message($message);
            }
        }
    }
}

```

# Answer
> 0 votes
try

```
$header = [
  'first_name' => ['data' => $this->t('First Name')],
  'last_name' => ['data' => $this->t('Last Name')],
   ...
 ];

$options = [
    1 => ['first_name' => ['data' => ['#title' => 'Indy']], 'last_name' => ['data' => ['#title' => 'Jones']],
    ...
];

```

I checked the code over here.

---
Tags: 8, forms
---