# Question
Title: Which hook or tpl file controls the output of a view (to manipulate the results)?
I am creating a recurring events views page, but currently the output of my view is displaying multiple references of the same date event. I am also not using Fields as an output, I am using content|teaser.

I have come up with 2 methods of resolving this issue, but wanted to clarify which is best and how to go about it.

1. Find a hook that outputs the Views rows and then write a conditional to compare each row and delete the duplicates.
2. Create a tpl file and do a preg\_replace() on the views output to delete duplicate rows of the same data.

Now the question is how do i go about finding this hook or what to name the Views tpl file as? I only want it specific to this events page.

# Answer
**Views Template Suggestion**

All views templates can be overridden with a variety of names, using the view, the display ID of the view, the display type of the view, or some combination thereof.

Below are different template suggestions you can use for overriding the defaults.

Let consider a example View, named foobar. Style: unformatted. Row style: Fields. Display: Page.

**Display output**: This controls the structure of the overall view, including the position of and code around the view administrative links, header, exposed filters, pager, "more" link, footer and feed icon. This template also controls the position of and code around the primary view content, empty content, and attached views.

```
views-view--foobar--page.tpl.php
views-view--page.tpl.php
views-view--foobar.tpl.php
views-view.tpl.php

```

**Style output**: This controls the structure of this particular view display's style, e.g. HTML List, Table, Unformatted, etc. This includes the view title and the code surrounding each row (item in your view) of the given style.

```
views-view-unformatted--foobar--page.tpl.php
views-view-unformatted--page.tpl.php
views-view-unformatted--foobar.tpl.php
views-view-unformatted.tpl.php

```

**Row style output**: This controls the internal structure of each row (item in your view), including the label and the content for each field.

```
views-view-fields--foobar--page.tpl.php
views-view-fields--page.tpl.php
views-view-fields--foobar.tpl.php
views-view-fields.tpl.php

```

**Fields**: There will be one entry for each field in your display, allowing you to control the structure and code for each. If your row style is set to "Node," there won't be any field entries, and the view will use the node's template file instead.

Lets take you have added Title field in the field list, then below are the suggestion to theme title field

```
views-view-field.tpl.php
views-view-field--title.tpl.php
views-view-field--foobar.tpl.php
views-view-field--foobar--title.tpl.php
views-view-field--page.tpl.php
views-view-field--page--title.tpl.phpfoobar
views-view-field--foobar--page.tpl.php
views-view-field--foobar--page--title.tpl.php
views-view-field--page-1.tpl.php
views-view-field--page-1--title.tpl.php
views-view-field--foobar--page-1.tpl.php
views-view-field--foobar--page-1--title.tpl.php

```

**Views Preprocessors suggestion** If you want to alter the display of any view with preprocess functions, then you can use the below suggestions to modify the display of any view.

**Altering Views result** To alter the result of the view itself(i.e modifying the results before its being rendered) you can use any of the following hook,

For using these hooks, you can refer the answer by jimajamma.

**References**
> 7 votes

# Answer
The hook you are most probably looking for is views\_pre\_render(), eg, something along the lines of...

```
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name == 'THE_VIEW_YOU_ARE_LOOKING_FOR') {

    // modify $view->result per whatever logic you require

  }

}

```

...where `$view->result` is an array of all the rows in your View. Given that you are displaying nodes instead of fields in your View, this should just be an array of objects pointing to nids, eg, something like this:

```
Array
(
  [0] => stdClass Object
    (
        [nid] => 1
    )

  [1] => stdClass Object
    (
        [nid] => 2
    )

  [2] => stdClass Object
    (
        [nid] => 3
    )

  [3] => stdClass Object
    (
        [nid] => 18
    )
)

```
> 2 votes

# Answer
To use a specialized template, name the template file "views-view-***youreventsview***.tpl.php" where ***youreventsview*** is the name of your view.
> 2 votes

# Answer
I know this is an old thread. But if anyone is struggling to theme the admin views, it will be helpful.

To theme admin view, if we simply goto `Theme: Information` and create the suggested template file in our template folder of the theme, views won't simply pick up them for the themes like `seven` or `Adminimal Theme`. And it is not a good idea to modify the contributed themes also.

So, what will be the solution?

It is so simple...!

We can implement `hook_views_api` in a `custom module`.

```
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  $path = drupal_get_path('module', 'mymodule');
  return array(
    'api' => 3,
    'template path' => $path . '/templates',
  );
}

```

Once you have cleared the drupal cache, views will start looking into the module's templates folder and will apply the defined templates.

I've written a detailed explanation here.

All done.

Enjoy the theme!.
> 2 votes

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


# Question
Title: Is there an exisiting file sharing module that allows multiple file upload?
I've been doing some module searching and have had little luck. I was wondering if any of you knew of a file sharing module that has:

* Ability to upload multiple files at once
* Ability to share files and folders with specific users or all users
* Ability to delete or archive files
* Ability to upload most types of files

I found most of this functionality in file depot but it doesn't allow multiple files to be uploaded at once.

# Answer
> 0 votes
Aside from archiving files (I'm not even sure what that means for files in-use on a Node). Media Browser Plus can do all of this:

> This is an enhancement module for the Media module. The focus is on UX improvements for Media that won't bloat the main module. Currently the additions are:
>
> * Adding tags to media when uploading
> * Pulling down title and description information from web based media sources
>
> The module is still in development and more features should be coming soon. Based on the feature requests in the issue queue and my own thoughts I would organize the features for Media Browser Plus into two categories. Functional and organizational.
>
> Functional:
>
> * Click and drag to select multiple files
> * Selecting multiple files with shift or ctrl
> * Searching media
> * Contextual links and actions
>
> Organizational:
>
> * Hierarchical taxonomy based organization e.g. “folders”
> * Uploading or importing a file structure into a taxonomy hierarchy e.g. the directory tree in a zipped upload gets converted into the “folders” taxonomy
> * Updating and applying taxonomies read from media files e.g. tags added to images
> * Personal and public “folders”
> * Shared “folders” either by user or role
>
> If you have ideas or want to help out, please feel encouraged to join in the issue queue. Feedback, requests, testing, and patches are always appreciated.

# Answer
> 0 votes
There's a multiupload module for FileDepot which integrates Plupload.

This allows for drag-and-drop multiple uploads from the browser into FileDepot.

The module is here: https://www.drupal.org/project/filedepot\_multiupload

---
Tags: users, files
---


# Question
Title: How do I render a custom form on a view page?
In my module's `routing.yml` file I set the form path to a path which also shows a view page. But on that path the form does not get displayed, only the view.

When I change the path in the `routing.yml` it works, so I guess views somehow overrides/ ignores my form.

How can I do that?

# Answer
> 0 votes
It's only possible to display one "page" on a url, so you can't both display a view and a form or any other "page" for that matter.

You have a few options:

1. Insert the form into the view (can be done with a global views handler)
2. Insert the form on the view page by exposing it as a block.
3. Insert the view on the form page by exposing it as a block.

Probably the easiest solution for you is to convert the view page to a view block and insert it on the form page. Views already has support for this, so you only need a few clicks in the interface to achieve this.

---
Tags: views, forms, 8, routes
---


title: How custom a form with twig

text:
# Question
Title: How custom a form with twig
I make a form programmatically, and I am looking how a web designer can change render.

```
 public function buildForm(array $form, FormStateInterface $form_state)
{

    $form['metier'] = array(
        '#type' => 'search',
        '#title' => $this->t('Métier'),
        '#default_value' => '',
        '#placeholder'=>'Rechercher une personne par son métier',
        '#attributes' => array('title' => $this->t('Rechercher une personne par son métier')),
    );

    $form['position'] = array(
        '#type' => 'search',
        '#title' => $this->t('Où'),
        '#placeholder'=>'Où',
        '#attributes' => array('title' => $this->t('Où')),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Search'),
    );

    return $form;

}

```

If the path of my form is `/test` the suggestion template `form--test.html.twig` doens't work.

I would like give access to a template for webdesigner can custom the render.

I can do something like that :

```
  $form['metier'] = array(
        '#type' => 'search',
        '#title' => $this->t('Métier'),
        '#default_value' => '',
        '#placeholder'=>'Rechercher une personne par son métier',
        '#attributes' => array('title' => $this->t('Rechercher une personne par son métier')),
        '#prefix'=>'<div class="form-group">',
        '#suffix'=>'</div>'
    );

```

But it's hard coded.

So I am looking for a way to return a `brut` table and let the web designer make his template.

The best way for the designer ll be :

**form--test.html.twig**

```
<div class="col-md-12">{{ form.metier }}</div>
<div class="col-md-12">{{ form.position }}</div>
<div class="col-md-12">{{ form.submit }}</div>

```

I don't know if I am right, I have try to return my variable $form to a template like that :

```
return array(
    '#theme' => 'form_test',
    '#form' => $form,
  );

```

All work I can access to my fields with

> {{ form.metier }} {{ form.position }} {{ form.submit }}

But the submit button doesn't work because the hidden fields are not display like the `form_token` and he is not in my variable $form.

# Answer
You need to implement hook\_theme() in your .module file to define a new theme implementation, set the #theme key in your form to the name of your implementation and create a twig template with this same name, but replacing hyphens with underscores:

**example.module**

```
function example_theme() {
  return [
    'my_awesome_form' => [
      'render element' => 'form',
    ],
  ];

```

**Form/MyAwesomeForm.php**

```
class MyAwesomeForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    $form['#theme'] = 'my_awesome_form';
    [...]

```

**templates/my-awesome-form.html.twig**

```
<form{{ attributes }}>
  {{ form.form_build_id }}
  {{ form.form_token }}
  {{ form.form_id }}

  <div class="row">
    <div class="col-md-6">
      {{ form.name }}
    </div>
    <div class="col-md-6">
      {{ form.type }}
    </div>
  </div>
  [...]

```

In this example `form.name` and `form.type` are your form fields, the array keys that you used to create the form, and I used bootstrap markup to show them in two columns.

Hope this helps.

Regards.

PS: This is a copy of my post at https://www.drupal.org/node/2788835#comment-11785706. I cloned it here because I'm not allowed to post comments.
> 5 votes

# Answer
you can access your filed with this code this is perfectly works

```
{{ form.metier }} {{ form.position }} {{ form.submit }}
{# Renders the rest of the form #}
{{ form|without('metier','position','submit') }}

```
> 1 votes

# Answer
You need to add:

```
{{ form.form_build_id }}
{{ form.form_id }}

```

These are the fields that make the submit work.
> 0 votes

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


# Question
Title: Get custom field of node in frontend as its type
I have a requirement in drupal. In this i have a content type 'sports' and created some custom fields of type dropdown, checkbox and file.

I want to get the custom field with its type as html in front end.

Example In dropdown i have

```
<select>
<options value="15">Cricket</options>
<options value="16">Football</options>
<options value="16">Basketball</options>
</select>

```

I want the same in frontend to display as html

# Answer
> 0 votes
Finally i found what i want actually in front end.

The below code displays the form that it has on backend.

This form is for 'sports' content type. This wil bring all fields with its widget wherever we calling.

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('sports');
print drupal_render($form);

```

---
Tags: 7
---


title: Wildcard for routes

text:
# Question
Title: Wildcard for routes
How can I pass the complete path arguments to a route defined in a mymodule.routing.yml file?

```
example_archive.content_archiv:
  path: '/examplearchiv/{myvalue}'
  defaults:
  _controller: '\Drupal\example_archiv\Controller\exampleArchiveController::content_archiv'
   _title: 'example Archive'
requirements:
    _access: 'TRUE'
    myvalue: .+

```

For example:

* /examplearchiv/testvalue gives $myvalue = 'testvalue' to the controller
* /examplearchiv/testvalue/value1 causes a "page not found" error
* /examplearchiv/testvalue/value1/value2 causes a "page not found" error

According to http://symfony.com/doc/current/routing/slash\_in\_parameter.html `myvalue: .+` should also return slashes for {myvalue}; `$myvalue` should be `'testvalue/test1'`.

# Answer
Drupal 8 doesn't support this natively. You can add a simple class in a custom module that implements the InboundPathProcessorInterface that will allow this.
> 5 votes

---
Tags: 8, routes
---


# Question
Title: Check if available values of a list-field is already used by other node of content type
i have a problem regarding fields of type **list**.

The scenario is the following. I have a content type with several fields, among them a field of type **list**. This field have 3 values ("1" to "3"). I want any of those 3 values to belong only in ONE node of this specific content type.

In other words, if a node of that content type has the value "1" in that field, i want that value to be "disabled" when creating new nodes of that content type (so, only available options to be "2" and "3").

Do you have any ideas? Is it possible at all?

Thanks in advance!

# Answer
you need to build a custom module in which you implement *hook\_form\_FORM\_ID\_alter*. since we're dealing with node create/edit forms, try *yourmodule\_form\_yourcontenttype\_node\_form\_alter()*.

(you could go for *hook\_form\_alter()*, but that would yield less performance, especially since you have a query to run.)

your implementation should include a query for that specific field, probably the table *field\_data\_field\_yourfield*. narrow it by **bundle** and if it returns any **entity\_id**, that's the one you're filtering out of your dropdown.

here's a few links to help you sort things out:

please write back if it works. good luck!

cheers, Luco
> 0 votes

---
Tags: 7, nodes, entities
---


# Question
Title: Which link field accepts an URL or a Node reference?
I am looking for a field just like Link, but that allows the user enter a URL or via an autocomplete a node/entity reference.

This is because this field might be an external link or an internal link in which case it should refer to the entity.

Any suggestions?

# Answer
Maybe one of these modules can help.
Advanced Link
Linkit
> 2 votes

# Answer
In **Drupal 8** this works with normal link fields. You simply can choose if only internal, only external or both type of links can be entered in this field. You'll then get a autocomplete field that accepts either an entity title or an external link and a title.
> 3 votes

---
Tags: entities
---


title: Execute system cron manually

text:
# Question
Title: Execute system cron manually
How to execute system cron manually via drush or drupal UI?

# Answer
> 3 votes
To execute *just* the `system_cron()` hook, the easiest way is with drush

```
$ drush php-eval 'system_cron();'

```

This will start a PHP process, boostrap Drupal, and run the input. Note that this will run everything that this hook does, in addition to the file cleanup, including garbabe collection on the various database tables with ephemeral data, like `{cache}`, `{batch}`, `{flood}`, etc. There isn't an individual function in Drupal 7 that just handles the file cleanup.

Also keep in mind that when you run drush like this, you are running as the user who you logged in as. This user may or may not have persmissions on the files and tmp directories in order to delete files.

You could copy this code into your own script and then do

```
$ drush scr cleanup-the-files.php

```

# Answer
> 2 votes
You can try `drush core-cron` it will do the trick

# Answer
> 1 votes
Go to Configuration-\>System-\>Cron Settings(admin/config/system/cron), you can see system\_cron listed here. Execute this cron by clicking on run link corresponding to the same.

---
Tags: 7, cron
---


title: Change the way nested views behave

text:
# Question
Title: Change the way nested views behave
In drupal 7 I have news posts grouped by the value of certain fields, I can filter them and display correctly the latest # news per category in a tabbed view: one tab per category. I also have another tab, which should collect the last news item from each category and I'm struggling to do it right.

I tried the nested views approach but despite creating a new template and new "helper" views with which I had hoped to strip all unnecessary tags, many tags are still created, breaking the layout (not really BREAKING, but it's not as it should). Could someone suggest a way to strip the tags or (better!) to do this in one go?

I'm not a php/drupal dev but if assisted I can understand code.

**Update:**

I have narrowed down my problem to the fact that all items are rendered in one single row by the external view. This breaks the layout because there's no `</li><li...>` between them. Instead, they are wrapped by divs. I have worked on this but I don't know how to make them appear on separate rows and it seems all the remaining wrapping is created by the last `print $row` in the chain. Can I change the behavior of the print or make the view display each field on a separate row?

# Answer
In the end the Semantic Views module helped me achieve what I wanted to do.

I specified that rows had no tag and fields instead were `<li>`, I had to modify the template too, for consistency and theming reasons to reproduce the original layout of a normal view.
> 0 votes

---
Tags: views
---


# Question
Title: Is it possible to authenticate against LDAP server without creating a drupal user account
In D7 I have a section of my site I need to limit to authenticated users, but auth needs to take place against LDAP server, not drupal user base.

My users don't have a Drupal account and I am not supposed to create one for them, I am required to just check in with the LDAP server and if TRUE, grant access to these pages, if FALSE deny access.

All the LDAP modules I have tested create a Drupal user to mirror the LDAP user, as far as I can see. And it seems to me I couldn't even really keep the user "logged in" without a Drupal account...

What options do I have here, if any?

# Answer
> 0 votes
sorry, I guess you just can't do it that way.

everything you do in Drupal is tied to your *user*, even if said user is anonymous.

Drupal establishes a basic difference between logged and anonymous users, even if you give the latter every permission from the former.

hence an LDAP solution involves creating Drupal users for everyone, or else they don't get to do what registered users do.

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


# Question
Title: What if a rule doesnt fire or is interrupted because of server down etc?
I have several rules that need to be fired after certain events.

When an event occurs and the rule starts execution, and something happens to the server, it may not finish.

Is there a way to make sure a rule will always execute?

I am asking for a method like a transaction occurs in MySQL. I need to be sure that a rule is executed to ensure data integrity.

# Answer
> 2 votes
To my knowledge there is no such thing as "*make sure a rule will always execute?*" (as in your question). However, by using the Message module, you can create your own custom "*Events logging*" (to register things that happened in a site).

A great sample of this you can find in Commerce Kickstart, which uses the Commerce Message module, to create such "*Events logging*". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).

So in your case, if you'd create an appropriate events logging of all sorts of Rules related Events that you're interested in (= are critical enough?), then at least you'd have appropriate data you can use to investigate if anything went wrong.

To actually do so, for any of your Rules, you could add these Rules Actions to them:

* create a "Start Rules Action"-message (as the very first action).
* create a "Stop Rules Action"-message (as the very last action).

With that, for any set of Rules Actions that started executing, you can check if you have 2 corresponding messages.

Here is a variation that might work also: instead of creating such "Stop Rules Action" message, you could also use the Flag module to flag the corresponding "Start Rules Action" (the Message module creates messages as entities, so you can flag them for sure). Such flagging would indicate that the set of Rules Actions completed without problems. And to list all the groups of Rules Actions that were interrupted, you'd just have to use the Views module to report about all "Start Rules Action" messages that were NOT flagged ... Piece of cake, no?

**Attention**: this covers the part related to Rules Actions, not (yet) something like "what are all Rules Events that were triggered but for which not even 1 Rules Action (= create the start-message) had started (because of some kind of interruption).

---
Tags: rules
---


title: new admin menu doesn't display on page

text:
# Question
Title: new admin menu doesn't display on page
I followed a tutorial to create an admin menu: Adding sub menu to Management menu. However I still cannot see my new menu on my page. Then I download a module named Administration menu. I found my new menu item on the navbar when I use this module. Here is the screenshot:

All the menu in pink circle are old, the only new menu item is called "Product Substitue." But I cannot find on the page.

Does anyone know how to fix this? Or any tutorial? Thank you~

# Answer
> 1 votes
You're looking at the same information rendered in different ways:

The menu along the top is quite simply reading from the database for any link in that menu.

The page is constructing itself based on the hierarchy of the hook\_menu implementation. You're going to need to implement hook\_menu for your new link to get it to show on the 'page' version of the menu.

---
Tags: 7, navigation
---


# Question
Title: is it possible to have multiple image styles for one uploaded image in drupal 8
I have my main story pages. I have one image style set on the content type display page for 880 x 495. I also want to have a image style set for thumbnails sizes of these photos. But as I see it I can only have one or the other. Is there a way to apply multiple image styles to the same uploaded photo field in drupal 8?

# Answer
You can reuse images using different image sizes - as far as I am aware there isn't a way to do this using the Drupal Field UI - but you could (for example) override the node display using views for more customisation including the ability to use the same image field using multiple image styles.
> 1 votes

---
Tags: caching, media
---


# Question
Title: Print field content as div attribute in views template
**Using Drupal 8**

I have a view:

* Unformatted List
* Two fields, Title and an Image with *Image URL* formatter via the module Image Url Formatter

I need to print out that URL such that:

The problem lies in the fact that I have TWIG DEBUGGING **enabled** , so the output of the field also includes all the debug mumbo-jumbo that I don't need. I don't want to have to be turning on/off debugging to make sure this works, I want a way to print the content without that mumbo jumbo.

I thought this post would help. It explains that `field.content` contains the rendered field, and what I am looking for is the field data from the database.

When trying this out with `views-view-fields.html.twig` , the code `row._entity.field_art_image.value` **works great** but it returns the information about the image itself (alt, title, width, height..) but not its URL.

Is there a way for me to access either the image url that points to the Image Style applied to the filed? (For example `/sites/default/files/styles/large/public/2016-11/feature-javelin-throw.jpg?itok=UJugCoqn` .

Trying `file_url(row._entity.field_art_image.entity.uri.value)` works, but it returns the URL to the uploaded image, not the one that results from the Image Style applied.

# Answer
> 1 votes
The code you linked is for normal data fields like text or number.

```
{{ row._entity.field_field_text.value }}

```

An image is a reference field, which has no value property, but a target entity. This has it's own set of fields. In case of an image the target is a file entity with the field uri, from which you can get the url with `file_url()`.

```
{{ file_url(row._entity.field_image.entity.uri.value) }}

```

Or use Twig Tweak to generate an image style url:

```
{{ row._entity.field_image.entity.uri.value | image_style('thumbnail') }}

```

# Answer
> 0 votes
In order to accomplish this it was necessary to create a **preprocess function** for the field and load the `Image Style` and acquire its URL. To do so:

**mytheme.theme**

```
function mytheme_preprocess_views_view_field__myviewname__field_myfieldname(&$vars) {
   $view = $vars['view'];
   $row = $vars['row'];
   $file_uri = $row->_entity->field_myfieldname->entity->getFileUri();
   $img_title = $row->_entity->field_myfieldname->first()->getValue()['title'];
   $image_style_large_uri = ImageStyle::load('large')->buildUrl($file_uri);
   if($image_style_large_uri)
        $vars['img_url'] = array( 'url' => $image_style_large_uri, 'title' => $img_title);
}

```

With the above I am able to acquire the URL that points to the `field image` URL after it's the *Image Style* has been applied. That URL is then made available to the TWIG template through `$vars['img_url']`

**mytheme/templates/views/views-view-field--myviewname.html.twig**

```
{% if img_url is defined %}
<div class="round-frame">
    <a title="{{ img_url.title }}" href="{{ path('entity.node.canonical', {'node': row.nid}) }}">
        <div class="frame-image" style="background-image:url('{{ img_url.url }}');"></div>
    </a>
</div>
{% else %}
   {{ output -}}
{% endif %}

```

You can see I have access to the **img\_url** variable. In addition I also get the node's link by using `{{ path('entity.node.canonical', {'node': row.nid}) }}` . The reason why I have an `if/else` is to make sure that if the field does not contain the custom variable, then to print out the field's content as per the default template does with `{{ output -}}`.

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


# Question
Title: How to grant User Points to viewing user when user has viewed content?
Can anyone provide me with a simple rule that adds 1 user point to a user when this user has viewed an entity of "Article" (for example)?

I have enabled the User Points module and the "Userpoints rules" integration module. But I can't find a way to get this to work.

# Answer
Interesting question, worth to be considered as a great question for a Drupal site building exam!

Have a look at this rule:

```
{ "grant_user_points_after_content_view" : {
    "LABEL" : "Grant user points after content view",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "1",
          "tid" : "0",
          "entity" : [ "node" ],
          "description" : "View of node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022",
          "operation" : "NodeViewed",
          "reference" : "Viewing of [node:content-type] \u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E\/node\/[node:nid]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

Some details about this rule, which you should be able to import in your own site if you have the Rules UI, and Userpoints Rules (a sub-module of Userpoints), enabled and after you enable the rule also:

* Rules Event: a Node of content "Article" is viewed (adapt the machine name of the used content type to any type that fits).
* Rules Condition: user is authenticated (to be able to grant user points).
* Rules Action: grant 1 point to the user viewing the article. And use some of the available tokens to add some more details to the actual User Points transaction (description, operation, reference) ... just for fun.

Easy, no? Sorry you had to wait for 2 years ...

PS: The previous answer is not really an answer to the question here I think.
> 1 votes

# Answer
If you are using variable module, then you can do it.

Please follow the steps:

1. Provide a new variable (**text type!**), called **Number**, with the necessary PHP code (wrapped with `<?php ... ?>`). One can then use earlier calculated results like `$mynumber`.
2. Convert **Number** to an integer, called **Points**.
3. Grant **Points** to the user.

Hope this may help. Thank you.
> 0 votes

---
Tags: rules, userpoints
---


title: Filter webform submissions by access

text:
# Question
Title: Filter webform submissions by access
I have a Drupal website which uses webforms and a custom module to manage the access in their submissions using `hook_webform_submission_access`.

While successfully restricting the access of a webform submission to a user, though, when they view the "Results" tab (or the "Table) the access filter isn't triggered as these tables are generated by Views.

How can I add a filter to the default "Webform submissions" view in order not to show the ones that the user has no access on?

PS: I know I can use `hook_views_pre_render` and unset the rows from the results, but I believe a filter would be a better and more elegant solution.

# Answer
You can use Views PHP module.

This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

Enable this module and add a filter PHP filter which you can select from views filter Global Category once you install above module.

Add php code for filter condition as per your requirement.
> 0 votes

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


# Question
Title: Save certain registration fields elsewhere in database
This is for Drupal 7. I am trying to write my first real custom module but I'm running into some difficulty and I'm just not sure how to look for my answers.

I've created a new entity for my module (with Entity API) with a corresponding table in the database. I need to add records to this table upon new user registration. I've used Form API to add a new field to the user registration form but I'm not quite sure the best way to do the next step. When the registrant submits the form, I would like all the regular Drupal registration stuff to happen, but I would like to intercept this one field and have its data go to the table I've created for my entity.

Here's what I have in the .module file of my custom module (the part concerning the registration form):

```
/**
* Implement hook_form_user_register_form_alter()
*/
function my_module_form_user_register_form_alter(&$form, &$form_state, $form_id){
    //add my module textbox to the registration form
    $form['my_module_field'] = array(
        '#type' => 'textfield',
        '#title' => t('My Module field'),
        '#required' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'New Submit Button',
        '#submit' => array('my_module_form_submit'),
    );
    unset($form['actions']);
}//end my_module_form_user_register_form_alter

/* Custom Submit handler */
function my_module_form_submit($form, $form_state){
    db_insert('my_entity_table')->fields(array(
        'my_entity_item' => $form_state['values']['my_module_field'],
    ))->execute();
    drupal_set_message('Your information has been saved.');
}//end my_module_form_submit

```

This is working fine to get my special field in my special table. But the user is not created. I suppose I could do it manually (like enter the other information into the appropriate users table and everything) but obviously I would rather not do that manually.

I feel that I must be missing something obvious here but I'm not having any luck searching for it. I am self-taught in the little I know of programming and Drupal.

Is there a way for me to just jump in to the regular submission handler and say, "hey, put my field here instead!"?

Thank you for your time.

# Answer
Wow. I puzzled on this all day and 30 minutes after asking this question, of course I find the answer.

Since the $form\['submit'\] part is an array, you can have more than one handler there! I changed the lines

```
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'New Submit Button',
    '#submit' => array('my_module_form_submit'),
);
unset($form['actions']);

```

to simply be

```
$form['#submit'][] = 'my_module_form_submit';

```

and that's it! Now it does the regular registration submission handler and also mine.

Thanks!
> 1 votes

---
Tags: 7, forms, users, entities
---


title: Change cache context of a Views

text:
# Question
Title: Change cache context of a Views
I would like to set a user cache context to a Views, but I don't know where to do this (in what hook ?). In the configuration of the View, the cache is set "Tag based"

Each user have a specific property, and I want the Views to deal with it, without totally disable the cache of the Views.

I already check this hook without success :

hook\_entity\_build\_defaults\_alter hook\_entity\_views\_data\_alter hook\_views\_pre\_views

In each hook I have changed the $view-\>element\[#cache\]\[contexts\] array.

---

I give some clarifications to my problem.

I've a "Product" content type. This content type has a reference field to a Taxonomy called "Family product" and a "Public price" number field. My goal is to display a computed price the for User called "Your price". "Your price" is not a field, because it's a computed value. To compute this value, I have another content-type called "Discount grid". With a form\_alter on this content type, I list each term of the "Family product" and associate them with a textfield who take a percent of the discount value the administrator grants to this grid.

To finish, the User entity has a reference field to a "Discount grid" content. The association between the User and the Discount grid allow me to compute the "Your price" according to the family who belongs the "Product".

I hope I didn't loose you, not easy to explain.

So, I try many things since I've open this question, without success. To display my computed value with Views, I've created a custom Views field who display the computed "Your price" value by taking the "Discount grid" of the current user (the *query()* function is empty to prevent Views to search the field value on the database). It's working like a charm.

```
/**
 * @ingroup views_field_handlers
 * @ViewsField("node_costumer_price")
 */
class NodeCostumerPrice extends FieldPluginBase {

    /**
     * @{inheritdoc}
     */
    public function query() {
        // Leave empty to avoid a query on this field.
    }

    /**
     * @{inheritdoc}
     * @param \Drupal\views\ResultRow $values
     */
    public function render(ResultRow $values) {

        //Called a custom service who return the current User Discount grid
        $grid = \Drupal::service('discount.service')->getGrid();
        $node = $values->_entity;
        $price = "";

        $family = $node->get('field_family')->getValue();
        $publicprice = $node->get('field_public_price')->getValue();
        /* doing some calculation here */
        return $this->t(number_format((float) $price, 2, ',', '') . ' €');
    }
}

```

The problem is the cache. The computed value is always displaying the same price between two User with a different Discount grid.

I've created a custom cache context "discount". This context is matched on the node ID of the Discount Grid of the current User. This context work very well on a simple render array (tested returning a render array on a custom controller).

```
#modules/custom/discount/src/Context/DiscountCacheContext.php

/**
 * Defines the DiscountCacheContext service, for "per discount grid" caching.
 * Cache context ID: 'discount'.
 */
class DiscountCacheContext implements CacheContextInterface {
    /**
     * The account object.
     *
     * @var \Drupal\Core\Session\AccountInterface
     */
    protected $user;

    /**
     * Constructs a new UserCacheContextBase class.
     *
     * @param \Drupal\Core\Session\AccountInterface $user
     *   The current user.
     */
    public function __construct(AccountInterface $user) {
        $this->user = $user;
    }

    /**
     * {@inheritdoc}
     */
    public static function getLabel() {
        return t('Discount');
    }

    /**
     * {@inheritdoc}
     */
    public function getContext() {
        $user = User::load($this->user->id());
        return empty($user->get('field_auto_part_discount_grid')->getValue()) ? 0 :
          $user->get('field_auto_part_discount_grid')->getValue()['0']['target_id'];
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheableMetadata() {
        return new CacheableMetadata();
    }
}

```

Now I'm searching how to "graft" this custom context cache on the Views. The last thing I've tried is to create a custom Views filter handler for injecting the cache context in it, without success. (by trying to reproduce the core/modules/user/src/Plugin/views/filter/Current class and adapt it with my custom cache context)

I hope be clear enough this time. I try all this week to find a solution without disable the Views caching (render time /2).

# Answer
Thank you, @oknate, I found the exact solution I needed based on your answer.

You advised me to use the user ID to alter the cache tag. This solution isn't ideal because each time that a different user refreshes the content, it invalidates the cache and it is necessary to regenerate it (which requires a lot of processing).

But the next part of your answer gave me the idea to transform the user price as a render array (didn't think about it before). To this render array, I passed my custom 'discount' cache context. The view's result now has a cache version for each discount grid. With this context, if two user share the same grid, the same cached results will hit for both of the users, witch is my very goal !

```
       $user_price = number_format((float) $price, 2, ',', '') . ' €';

        return [
          '#markup' => $user_price,
          '#cache' => ['contexts' => ['discount']]
        ];

```

By the way, I remove the t() function, completely useless here (some rests of a tutorial found on the web).
> 4 votes

# Answer
Since you want the view to be custom to each user, based on that user's field\_auto\_part\_discount\_grid, you can just add the user tag to the view's cache array, assuming it isn't already there. You could also create a custom cache tag based on the price.

```
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == 'user_price') {
    $user_id = args[0];
    $user_price = 12345; // replace with logic to get price
    $view->element['#cache']['tags']['user:' . $user_id, 'discount:' . $user_price];
  }
}

```

Also, any cache tags from within the render array of the view will bubble up to the view, so you can add the user cache tag in NodeCostumerPrice's render function:

Instead of

```
return $this->t(number_format((float) $price, 2, ',', '') . ' €');

```

do this:

```
$user_price = $this->t(number_format((float) $price, 2, ',', '') . ' €');

return [
  '#markup' => $user_price,
  '#cache' => ['tags' => ['user:'.$this->user->id(), 'discount:' . $user_price]]
];

```

This will then bubble up and be added to the views cache tags in the render cache, and will invalidate the cache when the user is updated.

You can add a custom cache tag instead of the user, if you want use a custom tag, based on your custom price.

Then in hook\_entity\_update, you can invalidate the cache tag based on whatever logic you like. For example, if a user is being saved, you could invalidate your custom cache tag 'discount':

```
/**
 * Implements hook_entity_update().
 */
function mymodule_entity_update($entity) {
  if ($entity instanceof User && $entity->field_public_price->isEmpty() === FALSE) {
    $user_price = 12345; // replace with logic to get price.
    Cache::invalidateTags(array('discount:' . $user_price));
  }
}

```
> 12 votes

# Answer
You can't configure which cache contexts or cache tags views is going to use. It gets this by calculated the cache tags and contexts of all, fields, filters, displays, contexts, relationships etc used in the view.

If you enabled tag caching and used current user as context somewhere, (so you actually print something that varies per user) you should get this automatically. Otherwise you should create a handler to output the *per user* data, which should define the proper cache context using `::getCacheContexts`, then the view using this will automatically get the user context.

The clever thing behind Drupal's caching, is that it merges items, to parts the are general could use a common cache. Drupal 8 also has some clever ideas, with using placeholders in caches, so it can cache rendered html of a page with placeholder for username and simply swap username based on logged in user. It might be worth looking into this feature.
> 6 votes

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


# Question
Title: How to add missing data selector in "Create new entity" rules action?
I have created an activity log using the Message module. It is about Statuses module (for which I'm using the DEV version). When someone comments on a status update, the activity is logged, but it should be logged for the status update owner and not the current user.

Currently, when I create the rules action "Create new entity" in the rules setup, the only replacement pattern available in the data selector for "User for which to log" is 'site:current-user'. Here I want 'status:status-sender' and not 'site:current-user'. The owner of the status update must receive the notification and not the user who commented.

Message export

```
{
  "name" : "status_comments",
  "description" : "Status comments",
  "argument_keys" : [ "@status_comments_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@status_comments_user commented on your status",
        "format" : "plain_text",
        "safe_value" : "@status_comments_user commented on your status"
      }
    ]
  },
  "rdf_mapping" : []
}

```

Rules export

```
{ "rules_posted_statuses_comment" : {
    "LABEL" : "Posted a statuses comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "statuses" ],
    "REQUIRES" : [ "fbss_comments_rules", "rules" ],
    "ON" : { "fbss_comments_save" : [] },
    "IF" : [ { "NOT fbss_comments_rules_on_own" : { "comment" : [ "comment" ] } } ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "status_comments",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:status-comments-user" ],
          "value" : "[comment:commenter]"
        }
      }
    ]
  }
}

```

**Note: This is strange because I have another message type with the event "user saves a status" and in its rules action, it shows all replacement patterns for statuses in data selectors**

# Answer
Looks like you're starting to hit the limits of the most recent (beta2) release of the Statuses module. Have a look at this variation of a custom rule, which is included in Comment nr 13 of issue nr 1693620:

```
{ "rules_user_commented_on_status" : {
    "LABEL" : "User commented on a status",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Statuses" ],
    "REQUIRES" : [ "fbss_rules", "rules", "fbss_comments_rules" ],
    "ON" : [ "fbss_comments_save" ],
    "DO" : [
      { "fbss_rules_load_action" : {
          "USING" : { "sid" : [ "comment:sid" ] },
          "PROVIDE" : { "status_loaded" : { "status_loaded" : "Loaded status" } }
        }
      },
      { "mail" : {
          "to" : "[status-loaded:sender:mail]",
          "subject" : "[comment:commenter:name] commented on your status",
          "message" : "Hi [status-loaded:sender:name],\r\n\r\n[comment:commenter:name] commented on your status [status-loaded:message-formatted]\r\n\r\n\r\nRegards,\r\n[site:name]"
        }
      }
    ]
  }
}

```

Even though this is not really the rule you're looking for, pay attention to the "to" field in the eMail being constructed. That to-field uses token `...sender:mail`, which is close to the uid (I believe) of the "sender".

That very same comment in that issue also includes a patch (which I believe is committed to the current DEV version), clearly an improvement (not a bug fix ...) because it makes extra data available for subsequent Rules processing. This patch appears to be a prereq for the above rule to work: I tried to import that rule in a site using the beta2 version, but that import failed (and "I" do not want to use a DEV version, even using beta-versions is exceptional to me).

I suggest you either try to apply that patch in your current setup, or switch to the DEV version of that module. After you do so, continue with these extra steps:

* Try to import that same eMail example, so that you have a sample rule that is close to what you'll need.
* Expand your own rule, to also add such "load action" and then check if you have a similar token like that `[status-loaded:sender:mail]`, which in your case should become something like `[status-loaded:sender:name]` or `[status-loaded:sender:uid]`.

If you get that import of the eMail sample to work, then I would assume (have not tested it myself and leave that to you) that this comination of your rule with part of the eMail sample here is what you're looking for:

```
{ "rules_posted_statuses_comment" : {
"LABEL" : "Posted a statuses comment",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "statuses" ],
"REQUIRES" : [ "fbss_comments_rules", "fbss_rules", "rules" ],
"ON" : { "fbss_comments_save" : [] },
"IF" : [ { "NOT fbss_comments_rules_on_own" : { "comment" : [ "comment" ] } } ],
"DO" : [
  { "fbss_rules_load_action" : {
      "USING" : { "sid" : [ "comment:sid" ] },
      "PROVIDE" : { "status_loaded" : { "status_loaded" : "Loaded status" } }
    }
  },
  { "entity_query" : {
      "USING" : {
        "type" : "user",
        "property" : "uid",
        "value" : [ "status-loaded:sender" ],
        "limit" : "1"
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "message",
        "param_type" : "status_comments",
        "param_user" : [ "entity-fetched:0" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:arguments:status-comments-user" ],
      "value" : "[comment:commenter]"
    }
  }
]

```

} }

Note the `status-loaded:sender` in the above rule! Which should be a token you can use because of the very first Rules Action added now.

**Disclaimer**: I have NOT (repeat NOT) tested this last rule (since I never use DEV versions of a module). Though chances are that by copy/pasting relevant parts of your original (exported) rule and the (exported) eMail rule it does work as it should.

**Note**: I'm about sure that the integrity check you got (when trying to import my updated rule, as you wrote in a comment to this answer) is because "status-loaded:sender" is not returned as a "User entity". While the Message module wants/expects the "param\_user" to be a "User entity".

You might be able to "convert" that "status-loaded:sender", by adding a Rules Action "Fetch entity by property", whereas you would use "status-loaded:sender" as the property to do so. The entity type to be fetched should be, for sure, a "user" entity (not a "message"!). This Rules Action should be inserted after the first "`fbss_rules_load_action`".

The result of performing that extra Rules Action is then an actual "user entity" (a real entity), and that is what you might then use for that "param\_user" (which should avoid the integrity check error).
> 1 votes

---
Tags: 7, rules, notifications, message-subscribe
---


title: Force Logout for Specific Users

text:
# Question
Title: Force Logout for Specific Users
Our Drupal 7.5 website is having an issue where users click logout but they are sent to the front page still logged in. I believe it's related to a bakery module, however, the question I am asking here is this: how do I force logout for specific users (not all users) via command line?

I tried:

```
drush uinf <username>

```

(To get user ID)

```
drush sql-query "DELETE FROM sessions WHERE uid = <uid>;"

```

The end result was a sql deadlock that crashed the site momentarily, and when it came back up, the user was still logged in. Should the sql command have worked? If so, then I may need to troubleshoot other issues.

Update: I disabled the bakery module and the problem went away, so the command was correct, but something about the module was wrong. I don't know why.

# Answer
I disabled the Bakery module and am now able to clear the flood tables using the command without getting the deadlock.
> 2 votes

# Answer
One solution could be to install the masquerade, masquerade as that user and in the url: `user/logout`. It also works and like this: `user/login`

Other options:

Drush login, Drush logout

and this related post: How to logout all active users? suggestes to empty the sessions table, well while you only want for one selected user, do a join if needed and specify the `$uid`
> 0 votes

---
Tags: users, database
---


# Question
Title: How to retrieve a shipping service settings field in Views
My client needs a very specifically formatted file that displays order details. I'm using Views Data Export for this, and everything seems to be going well except for when it comes to the shipping information. I'm trying to show the Shipping Service name field for the shipping method that was used, but there's one catch: The client needs to use their company's codes for this field, not the default ones that come with the shipping module.

For example, if a customer used FedEx Ground, the field would need to display "FDXGRDCOL" instead of the default "FedEx Ground" name listed on the commerce/config/shipping page. One solution I had hoped would work was by renaming the Shipping Service's rules name in the Settings fieldset (admin/config/workflow/rules/components/manage/commerce\_shipping\_service\_fedex\_ground), but it seems that because shipping methods are not entities, I can't access stuff like this. I have attached a photo of this:

Any ideas?

# Answer
Try configuring the shipping field with rewrite results, checking the "rewrite the output of this field and using a either a custom token or the machine name for the shipping type, and make the machine name the same as the client's code.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to create dynamic select option field in webform module
I have created a web form in drupal 7, i have one select option with two values and one input text box. When i click on one value input text box should appear nothing so that anybody can write some text but when i click on 2'nd value, input text box should appear 6 drop-down values

How i can achieve this?

# Answer
> 2 votes
Go to Modules \> Webform and see what version it is. If it is version 4+, as RoloDMonkey has mentioned, than conditionals are built in. If your Webform module isn't 4.x then I suggest updating it so that you can use this feature.

1. Go to Content and find your webform and open it.
2. Click "Webform" tab
3. Click "Conditionals" link
4. Click the (+) button
5. Implement the logic:

* If "\[select question that has the conditional answers\]" is "\[select name of answer that opens the textbox\]" then "\[name of textbox\]" is shown
    * If "\[select question that has the conditional answers\]" is "\[select name of answer that opens the selection menu\]" then "\[name of selection box\]" is shown.

Make sure you have all possible options set up already in the webform before applying the conditionals.

Here is a demo someone built using Webform Conditionals: http://www.sixmiletech.com/node/15

# Answer
> 1 votes
Look into the Webform Conditional module. There's a demo here https://www.youtube.com/watch?v=7uxfqJr6K6U.

---
Tags: webforms
---


title: Add a page to nodes with comment form

text:
# Question
Title: Add a page to nodes with comment form
I'm using Drupal 7.

I would want to add a page to my nodes, with the comment form (only), and a link in the tab menu to reach it :

I tried with views but I did not arrive there.

Do you know the simplest way to reach there?

# Answer
> -1 votes
I believe Display Suite module will do the trick.

---
Tags: 7, theming
---


# Question
Title: Why do I get a Drupal\Core\DependencyInjection\ContainerNotInitializedException exception error?
I am using Drupal 8.1.3, Drush 8.1.7, and PHP 5.6.2 on a Mac OS X.

I've installed a fresh Drupal 8 site demo from Zircon on a local MAMP stack. When I try to run watchdog show, and some other commands, I get the following error:

> Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /Applications/MAMP/htdocs/example/docroot/core/lib/Drupal.php).

I was able to run the following commands successfully:

```
drush cr
drush version
drush status

```

I've just updated to latest version of drush, but this is my first time seeing this error.

Also, `drush pm-update` returns:

> Command pm-update needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

Edit/Update:

Here is the output of drush status:

```
Drupal version         :  8.1.3
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  ******
 Database name          :  ******
 PHP configuration      :  /Applications/MAMP/bin/php/php5.6.2/conf/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.7
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/example/docroot
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_pHswhbzOqqMuWn7c6kYMbap6DKcyXxItrvbtsCQeJYoQ04xTi19pOZywbF8KZ8Wrx43VrLsVMw/sync

```

The user interface does work.

Update: I checked some of my other projects (Drupal 7 and 8 sites), for which drush worked perfectly fine on, and they are throwing errors with the same Drush command, which tells me it's probably not a Drupal 8 problem but probably due to changes I made on my dev platform. I had installed Composer and upgraded Drush, and other related changes.

# Answer
I had the same problem with Drush throwing an exception for a test site on localhost. I was able to access the site from the browser, from where I didn't get any error message, not even a message from a exception handler. This puzzled me, since the site was clearly working.

It started to work again when I changed the file permissions for the Drupal files. The user account I was using to execute the command line was missing the permission to write in some directories.
> 3 votes

---
Tags: 8, drush, log-messages
---


# Question
Title: How do I create a local menu action to node/add/page?
Here is the code in mymodule.links.action.yml to add a local action in a custom page (generated by the Views module).

```
amidori_utils.add_content:
  route_name: 'node.add_page'
  title: 'Add Content'
  appears_on:
    - view.admin_blogs.page_1

```

The above page will create a local action menu, which will take you to node/add page which will again list links to various content that you can create.

What I want is to create a link to node/add/blog as a local action. How can I do it?

After watching to the content of the node.routing.yml file, I understand I need to use node.add as route, but I can't figure out how to pass *blog* as parameter to the end of the route.

# Answer
> 7 votes
Basing on this comment found on Local action links now provided by plugins using YAML discovery and implementing LocalActionInterface, this is the action declaration you should use.

```
amidori_utils.add_content:
  route_name: 'node.add'
  title: 'Add content'
  route_parameters:
    node_type: 'blog'
  appears_on:
      - view.admin_blogs.page_1

```

I take that, in your case, *node\_type* should be simply *blog*, if that is the machine name for the content type you want to let users create.

# Answer
> 0 votes
```
 route_name: node.add
 route_parameters:
   node_type: 'blog'

```

This will show node/add/blog.

---
Tags: 8, navigation
---


# Question
Title: How to correct my Rules Component to perform VBO operations for the Group module?
I followed the instructions included in the answer to the question "How to implement the mass operations on the Group's members page using Views?". The 2 Rules Components in it (to either block or unblock a member), work fine (and my VBO view shows the mass operations that use those 2 Rules Components).

Now I want to create a similar Rules Component for one of the other typical mass update operations (as used in the context of the Group module).

Below is the Rules Components (in Rules export format) I created for this so far, to "Delete selected members":

```
{ "rules_remove_a_group_membership" : {
    "LABEL" : "Remove a group membership",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : []
  }
}

```

This Rules Component should implement the equivalent of the *Update option* "***Remove selected members***" (as shown on `group/gid/member`, with `gid`=group id).

### My question:

Something seems wrong in the Rule Component shown above, since I can't get it to do the equivalent of the Update option of the Group module (using VBO, similar to the answer in the question I mentioned above).

So how to correct this Rules Component to perform the equivalent operation using a custom VBO action created using a Rules Component, so that with the addition of this component, my custom VBO page should be equivalent to the default page of the Group module?

# Answer
> 0 votes
## Part 1: Create a Rules Component

Have a look at this **Rules Component** (in Rules export format):

```
{ "rules_remove_selected_group_members" : {
    "LABEL" : "Remove selected group members",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : [ { "entity_delete" : { "data" : [ "group-mbrship" ] } } ]
  }
}

```

Some more details to further explain the above Rules Component:

* It uses a "Group membership" (which is an entity, remember!) as a parameter.
* All it does is to perform an Action "*Delete entity*", for the entity specified as parameter.

By deleting such entity, you do the same as what happens when using the "Remove selected members" (for 1 specific Group membership, entered as parameter).

If you want, just copy the exported Rules Component above, and import it in your own environment. Then navigate to `admin/config/workflow/rules/components` in your own site and use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***Group membership identifier*** and hit the ***`Execute`*** button. The Group membership for the id you specified will be deleted then.

***Tip***: (temporary) improve your Group Membership view to also include the field "Group Membership Id" (=`mid`). This makes it easy to know which ID to use when testing this Rules Component.

After you're confident this Rules Component works perfect for all variations of your nodes, it's time to move on to Part 2 below.

## Part 2: Extend your VBO view

The typical next step when creating custom VBO oprations, is to edit the VBO field in your view, and enable the additional VBO operation that corresponds to the Rules Component as in Part 1.

In my case, with the VBO view I'm using, I ran into some AJAX error which I could not resolve right away. I was pretty sure it is NOT a bug, but rather something I'm doing wrong. Head over to Part 4 for more details on that.

However while further investigating this error, I realized that there is no need at all for a Rules Component to implement that VBO action "*Remove selected members*". Head over to Part 3 for more details on that (sometimes the solution to a problem, is to prevent the problem from happening ...).

## Part 3: Enable a standard VBO action

Head back to your VBO field in your view, and enable "Delete item" (within *Selected Bulk Operations*). I suggest to use the "Override label"-option for it, and give that VBO action a label like "Remove selected members".

QA-test this VBO action to confirm it does exactly the same as:

* what **you** try to achieve with the custom Rules Component in bullet 1 of your question.
* what **I** try to achieve with my Rules Component in Part 1 of this answer.

## Part 4: Heading for the golden cradle (= Solve the AJAX error)

The AJAX error as in Part 2 is resolved by using this variation of the Rules Component from Part 1:

```
{ "rules_remove_selected_group_members" : {
    "LABEL" : "Remove selected group members",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : [
      { "entity_delete" : { "data" : [ "group-mbrship" ] } },
      { "drupal_message" : { "message" : "Membership of group [group-mbrship:group:title] removed for user [group-mbrship:user]." } }
    ]
  }
}

```

Note the `"ACCESS_EXPOSED" : "1"` added here now (apart from the extra "drupal\_message" Action, which has nothing to do with the AJAX error). That turns out to be the ***clue*** to solve the AJAX error. For (way) more details on this, refer to Comment nr 13 in Support issue # 2530000. My understanding about that comment is that something in Entity API or Rules is what causes the AJAX error, and by using this access setting you prevent the issue.

With that, you now have 2 solutions/answers to solve your question ... i.e. to ***Remove selected members***. My preference is using the Rules Component from Part 4, because:

* The messages you get after executing it are more detailed as compared to Part 3.
* If you want, you can add any additional Rules Action or Rules Condition in the Rules Component.

Voilà!

---
Tags: 7, rules, views, group
---


# Question
Title: Simple views handler to compute math expression.
In Views, I would like to expose a fake field that is just an elementary mathematical expression of other fields of the table (let's say, for example, field1+field2).

I expose the field in hook\_vies\_data via some

```
  $data['my_table']['fake_field'] = array(
   'field' => array(
     'handler' => 'views_handler_my_handler',
  );

```

Which function of the handler shall I define? And how do I get in the handler the two values of field1 and field2?

Alternatively, where do I found the documentation of what I am looking for?

# Answer
> 1 votes
Instead of creating own handler you should use already existent `Global: math expression` that allows you using of tokens to calculate everything you want.

# Answer
> 0 votes
I've found this post that shows you how to create your custom views field handler for SQL expressions:

http://tech-tamer.com/drupal-7-using-sql-expressions-in-views-3/

For my needs it's enough, but if you need complex data maipulation in PHP I think it's also a good point to start to work with.

But you need to create your custom filter and sort handlers to allow it working with expressions:

```
[...]
'filter' => array(
  'handler' => 'NumericExpressionFilterHandler',
  'allow empty' => TRUE,
),
'sort' => array(
  'handler' => 'NumericExpressionSortHandler',
),
[...]

```

NumericExpressionFilterHandler.php:

```
class NumericExpressionFilterHandler extends views_handler_filter_numeric {
  function op_simple($field) {
    $placeholder = $this->placeholder();

    $this->query->add_having_expression($this->options['group'],
      str_replace('.', '_', $field) . " $this->operator $placeholder",
      array($placeholder => $this->value['value']));
  }

  /**
   * For simplicity limited to simple operations.
   * @return array
   */
  public function operators() {
    $op = parent::operators();

    foreach ($op as $i => $operation) {
      if ($operation['method'] != 'op_simple') {
        unset($op[$i]);
      }
    }

    return $op;
  }

}

```

NumericExpressionSortHandler.php

```
class NumericExpressionSortHandler extends views_handler_sort {
  /**
   * Called to add the sort to a query.
   */
  function query() {
    $this->ensure_my_table();
    // Add the field.
    $this->query->add_orderby(NULL, NULL, $this->options['order'], $this->table_alias . '_' . $this->real_field);
  }

}

```

Regards.

---
Tags: views
---


# Question
Title: Display main menu expanded in footer, drop down in header
I'm trying to show the Main menu in two places, once as a dropdown menu at the top, then again in the footer as a fully expanded (non-collapsible) set of links. I'm using the Superfish module to handle the top menu, and Menu Blocks to place the menu in my footer region. I'm using D7 and am sub-themeing the Bootstrap theme. Ideally, I'm looking for a way to simply output the Main menu as a very simple unordered list of links, without any of the dropdown classes or scripting applied to it. Where would be the best place to do this? I tried overriding `theme_menu_link` but that didn't seem right (since I can't figure out how to get the region.)

# Answer
We use the menu\_block module for this - it lets you create unlimited menu blocks and control menu depth and other options.

> This module provides configurable blocks of menu links with advanced features not available in Drupal 8 core.
>
> Drupal 8 core allows you to display blocks of menu links starting with any desired level of a menu and limited to any desired depth.
>
> And this Menu Block module provides additional configuration so you can choose to expand all menu links with children or to root the menu tree to a specific menu item.
>
> The Drupal 7 version of this module provides all of these features since Drupal 7 core does not have any of this functionality.

So I just noticed you're already using menu\_block. You can add multiple\_menu blocks - you should simply be able to add a new menu\_block for the main-menu on your site and use that one in the footer.
> 1 votes

# Answer
This is the solution I ended up using. It works, but I'm not confident it's the "right" way to do it. The menu will never be more than 2 levels deep, so it's not a recursive solution by design. This is in my `page.tpl.php` right above `print render($page['footer']);`

```
$tree = menu_build_tree('main-menu');
$output = "<ul>";
foreach ($tree as $item) {
  $menu_link = $item['link'];
  $link = sprintf('<a href="%s" title="%s">%s</a>', $menu_link['link_path'], $menu_link['link_title'], $menu_link['link_title']);
  $element = "<li>".$link;
  if (isset($item['below']) && count($item['below'])) {
    $element .= "<ul>";
    foreach ($item['below'] as $sub_item) {
      $sub_menu_link = $sub_item['link'];
      $sub_link = sprintf('<a href="%s" title="%s">%s</a>', $sub_menu_link['link_path'], $sub_menu_link['link_title'], $sub_menu_link['link_title']);
      $sub_element = "<li>".$sub_link."</li>";
      $element .= $sub_element;
    }
    $element .= "</ul>";
  }
  $element .= "</li>";
  $output .= $element;
}
output .= "</ul>";
print $output;

```
> 0 votes

---
Tags: 7, routes, theming, navigation, blocks
---


# Question
Title: Is it possible to use public:// for inline images (in text) to protect against changes in config?
There's a similar question here, but it concerns D6 or D7. It seems to me the suggested solution won't work in Drupal 8 for two reasons:

1. It's very unadvisable to attack the database directly with SQL, you should be using Entity queries and the API
2. As of D8, inline images become managed files, and are referenced as being attached to the nodes in which they appear - another reason for using the API.

I'm in the middle of writing a Drush command whose purpose is to go through all the inline images migrated from an existing (D6) site, detect them, enter them into the system as managed files, and attach them to their nodes. Looking at the file\_managed table in the database, I see that the file URI is always `public://something.jpg` (for example), so that if you add an inline image via CKEditor then (with the default settings) it will be `public://inline-images/mypicture.jpg` (for example).

Well that seemed to me very cool, because it protects you from changes in the public files settings (for example, if you're building a site with shared code for multiple domains and the public files folders will change when it goes into production). So I started trying out using a URI in body text something like this: `<img src="public://cwg.jpg" />`

But this doesn't work: the image doesn't show up and if I try saving it, the "public" gets removed so that it looks like this: `<img src="//cwg.jpg" />`.

When I enter an inline image through CKEditor in the normal way, I get something like this:

```
<img alt="" data-entity-type="file" data-entity-uuid="f80852d8-af54-45f8-9c4e-7a2c2196fee5" src="/sites/d822.dd/files/inline-images/cwg.jpeg">

```

Is there any way of persuading the inline images to use "public://"? Or should I be looking at the Media Entity module (which I wanted to avoid, because it's overkill for my requirements)

# Answer
Your issue is (currently) covered in the Drupal issue queue here against Core-8.2.x. This was committed to 8.2.x 4 months ago and I would imagine is in core - reading the issue should let you know which parts have been resolved.

I haven't found any non-core workarounds for this issue at present, the basic concept (from D6/D7 is an input filter to translate public:// URIs into canonical URIs when the content is rendered).

Issue Link: https://www.drupal.org/node/2666382

**EDIT**

It appears that only part of this change has been finalised, there is another issue suggesting that final resolution for this problem will occur with 8.3.x

Issue Link: https://www.drupal.org/node/2755223

It's possible (based off your description) that things are working as intended i.e. public:// values should be replaced with their canonical counterpart during the rendering. If this isn't the case I'd suggest following up with the second issue link above.
> 3 votes

---
Tags: 8, media, wysiwyg
---


# Question
Title: Are there any working Form Modules in Drupal 8 yet?
Webform doesn't work yet. Eform won't send emails yet (because rules isn't ready yet). Drupal's built in Contact form sends an email but doesn't save the entries or let you redirect to a thank you page.

Basically I need form builder that saves the results and sends an email - like webform in D7

Is there anything I'm missing or do I just have to wait?

# Answer
It seem like the built in contact module is the best solution for the time-being. Couple that with the contact\_storage module and it's a good temp solution until webform is up and running.
> 1 votes

# Answer
As of 29 mar 2016, there is a dev version of webform, but they're not confident in it enough even to publish it as dev: https://www.drupal.org/node/7404/release?api\_version%5B%5D=7234

There's also eform, which is a D8 version of the entityform module: https://www.drupal.org/project/eform

When you're digging through dev versions, a good metric is looking at how many people are using that version-- check the per-version usage stats. Ideally you want thousands or tens of thousands of sites reporting, but we're not there yet.

For now, I'm hacking the d8's core contact module. I hope that a more complete solution will be available soon.

People who say you shouldn't use dev modules on production sites are living in the past. Drupal 7 would have been functionally unusable to a huge chunk of its user base for a long time if no one put dev modules into production. There are still dev modules that are integral to the function of thousands of substantial d7 sites. Drupal 8 is nothing but a toy without relying on dev modules-- the form question being an excellent illustration.
> 3 votes

# Answer
I have used Yaml form. This module helped me a lot and is a very good alternative for the webform. https://www.drupal.org/project/yamlform
> 1 votes

# Answer
Try this one: https://www.drupal.org/project/contact\_emails Module works perfect.

blueblot
> 0 votes

---
Tags: webforms, entities
---


title: Invoke function from module in form

text:
# Question
Title: Invoke function from module in form
I'm trying to port the OpenID module from Drupal 7 to Drupal 8.

I have a form OpenIdLoginForm.php with the following code.

```
<?php
...
namespace Drupal\openid\Form;
use Drupal\user\Form\UserLoginForm;
use Drupal\Core\Form\FormStateInterface
use Drupal\Core\Url;
use Drupal\user\UserStorageInterface
...
class OpenIdLoginForm extends UserLoginForm {
... // getFormId, buildForm methods work nicely

  public function validateForm(array &$form, FormStateInterface $form_state) {
    ... // some validations
    openid_begin($claimed_id, $return_to, $form_state);
  }

... // submitForm method
}

```

openid\_begin is defined in openid.module.

```
<?php

use Drupal\Core\Routing\RouteMatchInterface;

... // openid_help, working nicely

function openid_begin($claimed_id, $return_to = '', $form_state = null) {
  // some stuff
}

```

The folder structure is the following.

```
modules/
  openid/
    README.md
    openid.module
    ...
    src/
      Form/
        OpenIdLoginForm.php
        ...

```

Whenever I submit the form, and `validateForm()` is called, I get an error:

> PHP Fatal error: Call to undefined function Drupal\openid\Form\openid\_begin() in /modules/openid/src/Form/OpenIdLoginForm.php

What am I doing wrong? How would I invoke a module function from a form belonging to the same module?

Fun fact: invoking the function `user_login_finalize()` from `submitForm()` in OpenIdLoginForm.php works and I don't know why.

# Answer
> 1 votes
I was looking for a solution for hours. Right after posting the question, i found one:

calling

```
\Drupal::moduleHandler()->invoke('openid','begin',array($openid,$return_to,$form_state));

```

seems to do the trick.

Still, I wonder why I can call user\_login\_finalize directly.

---
Tags: forms, 8, hooks
---


title: Migration from SQL table with no ids

text:
# Question
Title: Migration from SQL table with no ids
I'm trying to migrate from a SQL table using migrate module. The fields in the table are a unique file hash (media), an url, a drupal internal path. In the class extending SqlBase I have this function:

```
  public function getIds() {
    // The row property that represent the unique id for the id map.
    $ids['media'] = array(
        'type' => 'integer',
        'alias' => 'm');
    return $ids;
  }

```

It seems that *migrate* only accepts integers and **requires** ids to fill its migration map. Is there a way to migrate with a string hash or without any id?

# Answer
You do have to have an ID - and you can use your hash here simply by defining it with 'type' =\> 'string'.
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: How do I setup the date picker popup for date fields in a view?
I setup a date field for my content type and also have an exposed date filter for my view, but I can't seem to figure out how to get the date picker popup to show up. Is there a setting that I have to set somewhere?

I've also installed Better Exposed Filters and I still don't see any option for my view. Also installed Date and the Calendar module. I know jQuery UI has a built in calendar popup and that's installed by default on Drupal 8 installs.

How do I turn this on?

# Answer
This is usually because the ui.datepicker wasn't added as a dependency in your theme as this isn't usually enabled by default in themes.

I use the seven theme for administration, so I had to add the line:

```
  - core/jquery.ui.datepicker

```

Looks like this in my seven.libraries.yml file:
> 0 votes

---
Tags: 8, datetime, views
---


# Question
Title: Drush site install without dropping/recreating database
I am from Ukraine, so sorry for my bad English... Please help me to fix a problem. I'm trying to install Drupal with Drush on shared hosting.

I use the command `drush site-install`. On localhost everything worked correctly, but on the hosting I get an error: `Access denied for user 'bigferwn_t'@'localhost' to database 'bigferwn_t'`.

Command string is 100% correct. The problem lies with permissions. When Drush runs the site-install command it DROPs the RECREATEs the db. So if the db user does not have that permission (like in many hosting provider) we get the error access denied.

So I created a db in hosting account manually and want to install drupal using the database that I just created. I don't want to drop and recreate this db. I simply want use the existing database.

There are issues discussing the same problem https://www.drupal.org/node/1105514.

In the site-install command there is no option to "NOT CREATE OR DROP DB" or if there is I can't find it.

I tried to use the patch from https://www.drupal.org/files/issues/drush-script-options.patch which was proposed in the issue above, but it is old and for a different version of drush.

# Answer
> 1 votes
Drush doesn't and likely isn't going to support this workflow based on developer comments in these pull requests:

https://github.com/drush-ops/drush/issues/134

https://github.com/drush-ops/drush/pull/353

Your remaining option is to install using the Drupal installer script.

# Answer
> 0 votes
It is not my case. In my case, user has not permission to drop and create db (because it's shared hostin). He only can use it.

So, I can create a new database only through the hosting control panel.

When I create new db, for example:

Db\_name - testdrupal db\_pass - testpass

and then in my drupal directory (where are all drupal files...) i run drush command:

drush si --db-url=mysql://testdrupal:testpass@localhost/testdrupal --account-name=admin --account-pass=1 -y

I get the error Access denied for user 'testdrupal'@'localhost' to database 'testdrupal'. could not drop and create database.

That's happened because when run site inctall command, drush trying to create db thas is aleady created, and user has no permission to do that.

Here is some patch https://www.drupal.org/node/1105514 to run site install command without crate db options.. But I can not modify it to drush 6.

---
Tags: drush
---


# Question
Title: How to Display a Single Image Gallery per Album in Content Teaser?
I have made a Hierarchical Photography site using Views, Panels and Organic Groups.

The Hierarchy is as follows:

* Top-Level: Category (e.g. - SCENIC, STREET SCENES, MODELS )
* Sub-Level1: ALBUMS | (e.g."BROOKLYN" and "Mid-Manhattan | July 2016" under STREET SCENES Category)
* Sub-Level2: IMAGE GALLERY (e.g. "Commercial and Residential" and "Midtown Streets" under MANHATTAN Album)

Using Views, I am able to display a preview using a **single image** from the Gallery, of each Image Gallery under its respective Album. See attached "album view" screenshot..

One the Category Level, I am trying to create a preview image of each Album using a **single image** from **one** of the image galleries in each Album to represent that Album on the Category page, but instead it displays ***all the image galleries*** from each album. See attached 'category view" screenshot....

In both views, I am using Panels on the pages to help structure them.

Here is my View for the Category Level:

and my ALBUM TEASER VIEW

and finally my Image Gallery View....

Any ideas on how to ensure only one Image Gallery per Album appears on the Category Level when using Content:Teaser? Thank You!

# Answer
Okay Drupalizer! You don't need any special coding or modules to fix this. I figured it out. So basically, I just needed to create a NEW view of the Album Image Gallery Teaser with the same settings except for the Pager which I made to be "Display a specified number of items | 1 item".

Then I use this view as the Content Teaser for the Category Level and the Content-type 'ALBUM" I set the teaser display to be this EVA view.

See attached screenshot ...
> 0 votes

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


# Question
Title: Is it possible to leverage browser caching?
I have ran a site through Google Page speed insights and one of its recommendations is to leverage browser caching for https://www.google-analytics.com/analytics.js.

Is this possible on a Drupal site?

# Answer
As per one of the comments below the question, this is possible only if you:

1. Get Google to change their cache expiry or
2. Serve a copy of the analytics yourself from your domain, and set appropriate headers. Probably not a good idea as you won't be keeping up with changes to Google's code.

Credits: Clive.
> 1 votes

# Answer
If you have a .htaccess file, you can add the following code at the top of it:

```
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

```
> 1 votes

---
Tags: caching, google-analytics
---


title: Page to show submenu items

text:
# Question
Title: Page to show submenu items
I have this kind of menu set up in my Drupal 8 project.

```
Level 1 item A1
    Level 2 item A2
    Level 2 item B2
    Level 2 item P2
    Level 2 item Q2
Level 1 item B1
    Level 2 item D2
    Level 2 item E2
Level 1 item C1
    Level 2 item Z2
    Level 2 item X2

```

Is there any way to create a page containing all the submenu links on a page. The desired result would be:

1. Click on "A1" menu link
2. Display a page containing A2, B2, P2 and Q2 in a list(the direct children of A1)

I've tried setting this up using views, the problem with that is i don't find a way to filter based on the parent menu item. Only the type of the node and therefor it shows all my content.

Is it possible to use views to achieve this, or is there a better way?

# Answer
> 0 votes
I'm trying to solve the same problem and one part of a possible solution would be to assign every linked page (A2, B2, etc.) to taxonomy terms based on the menu structure. This way you can get a list of all items linked under A1. The problem is to bring it in the same order as the menu links...

---
Tags: views, 8
---


# Question
Title: How to edit views twig template to process node information
I have created a views slider block in which have the following fields; image, title, text, and position. What I would like to do is look at the value of the position element and then add an css class to the title and text field to either display on the left or right side of the image.

In Drupal 7 I could do this very easily, but I can't figure out for the life of me how to do this in Drupal 8. I am overriding the views-view-fields.html.twig file.

Normally in Drupal 7 I would get the node ID, load it and then check the position value. In Drupal 8 using views-view-fields.html.twig file all I get is the rendered value (which contains html markup that I don't want).

Trying the preprocess route for the views-view-fields template file, I have the same problem in that value is already marked-up and no way to get the node that it came from.

If anyone has any suggestions how to go about accomplishing this, that would be fantastic.

# Answer
> 1 votes
In Drupal 8 using views-view-fields.html.twig file:

```
{{ row._entity.field_example.value }}

```

Trying the preprocess route for the views-view-fields template file:

```
$node = $vars['row']->_entity;
$field_value = $node->field_example->value;

```

---
Tags: theming, 8
---


title: Remove name attribute - Form API

text:
# Question
Title: Remove name attribute - Form API
For PCI compliance reasons, I need to remove the `name` attribute from a form field.

I have tried:

(1)

```
$form['field']= array(
    '#name'=>'',
)

```

(2)

```
$form['field']= array(
    '#name'=>false,
)

```

3)

```
$form['field']= array(
    '#attributes' => array('name' => ''),
)

```

(4)

```
$form['field']= array(
    '#attributes' => array('name' => false),
)

```

None of the above work (each of the above produce a field with the `name` attribute present, just empty. I need it removed altogether).

I haven't managed to achive it with the `hook_form_alter` hook either.

Any ideas?

Thanks

# Answer
Assuming it's a textfield, I think the simplest way would be via a preprocess on `theme_textfield`:

```
function MYMODULE_preprocess_textfield(&$vars) {
  // Identify the element and remove the name property (which will always be present)
  if ($vars['element']['#foo'] == 'bar') {
    unset($vars['element']['#name'];
  }
}

```

Bear in mind that Drupal won't be able to process the value for that field correctly if you submit the form, but I guess you're submitting this offsite anyway.

If it's not a textfield you should be able to use the same principle with the the theme function for whatever element type you're using.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: custom hash generated password and module wise added db password is different?
```
function custom_submit_method(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $cusers = $form_state->getValue(array('name'));
  $cpass = $form_state->getValue(array('pass'));

  $gh = new \Drupal\Core\Password\PhpassHashedPassword();
  $hash_password = $gh->hash($cpass);
  $check_pass = $gh->check($cpass, $hash_password);

  //  \Drupal::logger(' customusersubmit')->notice('customusersubmit submit ') ;

 //  login_finalize($cusers, $cpass);

   drupal_set_message($hash_password .'------------'. $check_pass);
 }

Output : $S$5JdG.BjCPSTzc03AJ7aYPwMMH6HR.63IDUzqG3h2kkjG0NEcXtIo------------1 for admin

 Admin Password: $S$EnLPNV41YaHAPKhzwTGHVIir.OlOyK9ngYyEzVKdsd//WMnlaegV

```

When on comparing to db admin password the hash generated salt value is different. It timely change for every runtime.

Kindly suggest me the Idea.

# Answer
Yes, that is correct: The password is always salted with a different string.

If you want to verify a password, don't hash it, just check it against the value that was stored, that *does* work.

You're probably asking the wrong question. Explain what you're actually trying to do.
> 2 votes

# Answer
As Berdir said, if you call `\Drupal\Core\Password\PhpassHashedPassword::hash()`, you will get a different result each time. That is normal: Saving the same password more than once should give a different result each time. This doesn't allow to notice if there are users using the same password, and this is better for security. In the case they get the password of one of the users, and they are able to read the database, they would not find out so easily every user using the same password.

The code you are showing is not the code you should use. To verify the given password for a user is correct, you should use the user.auth service. `UserAuth::authenticate()` gets the username and password, and it returns the user ID, if there is a user with that username and the password is correct, or `FALSE`.
`UserLoginForm::validateAuthentication()`, one of the validation methods used from the login form, uses that service.

Notice that the `\Drupal\Core\Password\PhpassHashedPassword` class is a class implementing a service. You should not create an object of that class directly, but invoke it as service or, rather better, invoke the *user.auth* service which uses it.
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: How to make taxonomy term checkbox display multicolumn?
I have about 20 items for checkbox. Drupal default checkbox is too long down. How to make it in to column like this?

\[ \] list1 \[ \] list4 \[ \] list7 \[ \] list10
\[ \] list2 \[ \] list5 \[ \] list8 \[ \] list11
\[ \] list3 \[ \] list6 \[ \] list9 \[ \] list12

# Answer
> 1 votes
You can accomplish this using CSS, specifically flexbox. The exact element you need to target with your CSS rules will depend on your theme. You will need to add the following CSS to the element that **contains** your checkbox items.

```
.container {
  display:flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:20vh; /* You will need to set a height on the container
                  to get the look you want, this is an example height */
}

```

In my example, I'm using Drupal 8 and the Seven administration theme. On an add/edit node page, I have a taxonomy field (the default tags) using checkboxes. You can see in the below image that each checkbox element is wrapped in a div and all of those divs are wrapped in a container div with the id `edit-field-tags`. So, if I apply the above CSS to that container, I get the results that match your goal:

You may want to play around with the alignment or spacing of the flex elements, for more information on that that I recommend checking out "A Complete Guide to Flexbox" on CSS Tricks.

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


# Question
Title: How to pass multiple IDs to a Views exposed filter?
Is there any way to pass multiple IDs to a Views exposed filter?

We need to pass an array of IDs to the filter.

**Notes**:

* There we can see operator "=" but it not taken 1,2 etc.
* We have tried regular expressions to, but it also not working.
* We are not using contextual filters.

# Answer
You can pass it using contextual filter,

Remember to choose multiple selection

if we have url http://example.com/test/20+10+12
> 1 votes

# Answer
You need to use Context Filter to achieve this ....

You can read values from URL , Multiple values can be separated using + or , operator...

* Your view path should be /some-path/%
* Add Contextual Filter should be content id or any other id
* Select Filter Value, Provide default value and select raw value from URL , Path component 2

* Select Multiple Value setting in More settings

* You can call your page with path something like http://example.com/some-path/24+25
* You can read your multiple values from a text box in a view and on submit simply redirect to url like above.
> 0 votes

# Answer
If your filter filter values is not much pass it in URL but if you have custom id and they are very items I render you views programmatically and passed your arguments to it

```
$array = array(1,2,3,4,66,5,54,33,22,111,222,333,);
$view = views_get_view('yourviewname');
$view->set_display("yourdisplayneme");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();
print $content;

```
> 0 votes

# Answer
Here is what I did to add a multiple select exposed filter of `nid` to a view, just make a example for you here.

* I would like to create a views listing movies('movie' content type).
* Movie has a cast field which lists actors('actor' content type).
* I want to have search movies by actors, which need to support multiple select.

In above example, actors are nodes. So I need a views exposed filter to pass multiple nids to views.

What I used to achieve that, is **'entity reference'** module. I created a entity reference field in movie content type called 'cast'. Which is referencing to 'actor' content type. Then in 'cast' field setting, remember to tick *'Render Views filters as select list'* as below:

**Then you will able to add a nids exposed filter in views!!**

In my movies views, add a new filter with `Content: Cast (field_cast)`. Then you will see the **select list and multiple options** as below:

After adding that filter, you will have a **multiple select filter** and it should look like this:

**NOTE**: You may get duplicated result in some case, just enable the views advance 'Use aggregation' setting.

That's it! :)

The last thing I would like to do is make the multi select looks better. What I like to use is a jQuery plugin Sumoselect which you can add if you like.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Best way to redirect a page after javascript tracking code has executed
I'm looking for the best way (and also simplest if different) to accomplish this in Drupal 7.

* Users arriving at *example.com/special-redirect* should be redirected quickly to *example.com/newpage*
* Nothing needs to be rendered, but before they are redirected to the new URL on our site, I need to make sure our JS tracking script is executed.
* the tracking script is currently loaded into the header from the theme.info file, and needs to run on every page of the site.

I assume that the URL redirect module won't accomplish this (ie. never loads the page).

I'm thinking I have to rely on the javascript method of putting this somewhere:

```
   <script type="text/javascript">
        window.location = "http://www.yoururl.com";
   </script>

```

But I'm not sure where I should put this (or a modified one) on the site. It's just for the one page, but would putting it in the html.tpl.php file with and if statement for the NodeID work? I'm also open to moving the tracking script if it makes sense to.

thanks for any advice

# Answer
> 2 votes
You can do something like below:

1. Create a *custom module*, If not already created (read more).
2. In your custom module, define a custom callback using hook\_menu, and add a `page callback`.
3. In `page callback` function simply '**echo "script file/code"**'. This will prevent Drupal from rendering various template files in your callback. **NOTE:\* If you use `return` instead of `echo`, Drupal will start rendering template files.**
4. In your ***.JS file/code***, do required tracking and re-direct user to another page.

Sample Code:

**MODULE\_NAME.module**

```
/**
 * Implements hook_menu().
 */
function [MODULE_NAME]_menu() {
  $items['custom_url'] = array(
    'title' => 'Test',
    'page callback' => '_[MODULE_NAME]_callback',
    // Check required access.
    'access callback' => TRUE,
  );

  return $items;
}

function _[MODULE_NAME]_callback() {
  $jquery = base_path() . 'misc/jquery.js';
  $script = drupal_get_path('module', 'MODULE_NAME') . '/[MODULE_NAME].js';
  echo '<script src="' . $jquery . '"></script>
    <script src="' . $script . '"></script>';
}

```

**MODULE\_NAME.js**

```
(function() {
  $(document).ready(function() {
    // Do your tracking here.
    console.log("Test");
    window.location.href = "http://example.com";
  });
}(jQuery));

```

---

## Edit :

No worries, if you've not created a module before, you can follow steps given in How to Make a Simple Module with a Form and Menu Link to try how it works. The documentation is regarding creating a module which will define a menu callback and form.

Here you can find a detailed guide regarding Creating custom modules.

The code snippet I've provided above includes all basic code as per your requirement, except the tracking code which you need to write inside ***MODULE\_NAME.js*** file. See the comment saying *`// Do your tracking here.`*

---
Tags: 7, javascript, redirection
---