# Question
Title: How do I implement a block suggesting other relevant content?
I want to put a block in the left column on my products page, to suggest similar products. Can I do this with a block based on the "search API" module? Does this module allow to propose products in a block, similar to the viewed page?

# Answer
> 0 votes
Try to use Similar Entries module for this.

> Similar Entries provides lists of links to site content related to the current node being viewed. Links can be displayed in standard blocks or as part of custom views.

---
Tags: views, taxonomy-terms, search
---


# Question
Title: How do I secure pages and related media files?
I would like to password protect Drupal pages (solved) and media files related to these pages (solved, but not optimally). Currently the Drupal pages are secured via Drupal and the media files via htaccess. The problem with this is the users then have to authenticate twice to get to the media content. I've been told that the way to solve this is to create a role and restrict access to both Drupal pages and media using Private files download permission module.

I'm quite new to Drupal and am wondering if this is the *normal* way that people solve this problem; or is another method better/more common/etc..

# Answer
> 1 votes
Try to use Secure Site for this.

> This module allows you to authenticate users with a browser-based password (HTTP Auth). You can restrict access to the site by role and choose to secure restricted pages or the entire site. This means the site will be inaccessible to search engines and other crawlers, but you can still allow access to certain users.

---
Tags: 7, security
---


# Question
Title: How to set ajax event to onkeypress event?
```
$form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#size' => '27',
        '#inline' => 'true',
        '#required' => TRUE,
        '#prefix' => '<div id="ajax-link">',
        '#suffix' => '</div><div id="ajax-display"></div>',
        '#ajax' => array(
          'effect' => 'fade',
          'callback' => 'ajax_textfield_callback',
          'wrapper' => 'ajax-display',
          'event' => 'onkeypress',   /////////////////Want to add event
        ),
    );

```

Here in example i have to add event (slashed location). By Default it takes **on change** event. I want to change that event to **onkeypress** event.

# Answer
See this link.

You can specify any valid jQuery event.

So, you need to change 'onkeypress' to 'keypress'.
> 2 votes

# Answer
By definition from MDN

> The onkeypress property sets and returns the onKeyPress event handler code for the current element.

**onkeypress** is not a event name but a element property for returning the event handler.

The event name should be `keypress`.

Theoretically, jQuery should be able to handle any JS event name.
> 0 votes

---
Tags: 7, ajax
---


title: How to create link to a view

text:
# Question
Title: How to create link to a view
I've a view with a page display on url `"progetti"`.

On my controller I'm trying to create a link to this url but I can't find the right way. I've added `\Drupal\Core\Url` namespace on top of the file.

I'm creating an items list:

```
$url = Url::fromRoute('progetti');
$variables['items'][]['value'] = array(
  '#type' => 'link',
  '#title' => array('#value' => 'sergio'),
  '#url' => $url,
);

```

It doesn't work, also if I use `"/progetti"` as argument.

Logs say:

```
PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "progetti" does not exist."

```

# Answer
As you want to create url object from a path instead of route, use the function fromUri() instead of `fromRoute()`.

```
$url  = Url::fromUri('internal:/progetti');
$variables['items'][]['value'] = array(
  '#type' => 'link',
  '#title' => array('#value' => 'sergio'),
  '#url' => $url,
);

```

In fromUri() function you need to pass the URI of the resource including the scheme. For user input that may correspond to a Drupal route, use internal: for the scheme.
> 2 votes

---
Tags: 8, navigation
---


title: Products not display in other languages

text:
# Question
Title: Products not display in other languages
I am using multi-language internationalize module for category and products translate. When product created assigning only English language category only but not assign other languages, How to assign to other languages.

There is any solution for this with module or else any other solution.

# Answer
check the (http://drupal.org/project/entity\_translation) module and also read this https://drupalcommerce.org/discussions/820/how-do-i-setup-multilingual-products

https://www.drupal.org/documentation/modules/translation
> 0 votes

---
Tags: taxonomy-terms, i18n-l10n, panels, multi-sites
---


# Question
Title: Resizing image from one field and save result in another field
As mentioned on the comments on this question, on my node-editing-form there are fields for WIDTH, HEIGHT, and an IMAGE. I would like to resize the given image by the dimesions WIDTH and HEIGHT and to save the result in another image field. I hope someone could outline (or even concretise) how to build that module.

# Answer
have you seen Imagefield Focus?

This would give your users a much nicer UI to edit and crop images, and more importantly choose the correct regions to crop.
> 0 votes

---
Tags: entities, media
---


title: How do I define checkboxes in a form?

text:
# Question
Title: How do I define checkboxes in a form?
I have a form where I need to add a checkboxes field. The purpose of this form is to display some values from the database. I would like to display *id* from my database table as checkbox' value (when `"active" = 1`) and *url* as checkbox' labels.

The database table's structure is the following.

```
id | uid | hash          | url          | active

1  | 1   | myhashstring1 | example_url  | 1
2  | 1   | myhashstring3 | example_url4 | 1
3  | 1   | myhashstring2 | example_url2 | 0

```

How can I achieve this?

# Answer
> 1 votes
1. Creating an '\_form' type entry in the mymodule.routing.yml
2. Form controller will first always do a database query `\Drupal::database()->select('mytable')`...
3. You will need the id, url, and active values.
4. You need to prepare the "options" array like this: array("id" =\> "url", ...)
5. And the default array should contain all the active=1 records.
6. Create the checkbox field item based on Form API description.
7. In form submission (`submitForm`) you save back the results (which elements newly activated / deactivated) to the database.

# Answer
> 2 votes
As per Drupal 8 form api you can define checkboxes like below:

```
$form['high_school']['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => array('SAT' => $this->t('SAT'), 'ACT' => $this->t('ACT')),
  '#title' => $this->t('What standardized tests did you take?'),
  ...
);

```

In your case you can update above code

```
$options = array();
$options[1] = 'example_url';
$options[2] = 'example_url4';
$options[3] = 'example_url2';

$form['items_selected'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#title' => $this->t('Title you want to give'),
  ...
);

```

---
Tags: forms, 8, database
---


# Question
Title: How to iterate over all field collection items in an eMail body using Rules?
I'm trying to write a rule (using Rules) that will send an email to users of a role. Within the body of the email, I'd like to display the contents of a nested field collection.

I've tried using what Rules gives me for data selectors, but I can't seem to put it together. Specifically, I have two field collections: `field-boat-lineup` and `field-equip-rowers.`field-equip-rowers`is actually nested within`field-boat-lineup`. The contents of`field-boat-lineup`are consistent. That is, their fields are fixed values except for`field-equip-rowers`.`field-equip-rowers\` is variable and can consist of up to 8 user names.

Any pointers in the direction of how to display the contents of the field collections in the body of an email? Do I need to write some PHP code to make this happen? If so, what's the critical piece I'm missing?

On a side note, I find the field collection syntax used when working with the Rules data selector somewhat confusing. Specifically, the use of what appears to be an index. For example,

```
[node:field-boat-lineup:0:field-equip-boat-name:title]

```

I see the usage of a '0','1', '2', and '3' in the above token. I'm never quite sure what to select: 0, 1, 2, or, 3. Can anyone shed some light on the purpose of the numbers?

**Update**:

While I understand the example shown in the existing answer, I can't seem to conceptualize how I would be able to write a Rules "loop" to display the field collections in an email. The email body of the Rules module does not seem to have the ability to "loop" over content.

# Answer
### Part 1: Processing field collections in a rule

Consider a configuration with a field collection like so:

* The machine name of the field collection is `field_treatment_details`, and the number of values for it is unlimited.
* This field collection has 2 fields:

+ a text field labeled "***Doelpubliek***" (Dutch for "Target audience") with machine name `field_doelpubliek`.
    + a boolean field labeled "***Betalend***" (Dutch for "Payable") with machine name `field_betalend`.
* Assume a node with "some number of" field collection items, with values that look like so (with some number = 2 in this case, but that could be any number as per the "unlimited" above):

+ Doelpubliek=Baby with Betalend=Nee
    + Doelpubliek=Moeder with Betalend=Ja

Let's assume you want to display these data via a Rule, using Rules Action "Set message", and using Rules Event "Content is viewed", so that such message looks like so:

> ```
> This is a demo of a node containing a field collection ...
>
> About this demo:
>
> The machine name of the field collection is field_treatment_details, and the number of values for it is unlimited.
> This field collection has 2 fields:
>
> - a text field labeled Doelpubliek with machine name field_doelpubliek.
> - a boolean field labeled Betalend with machine name field_betalend.
>
> Part 1: The field collection with machine name 'field_treatment_details' looks like so:
>
> Doelpubliek: Baby
> Betalend:    Nee
>
> Doelpubliek: Moeder
> Betalend:    Ja
>
> Part 2: The result of a Rules loop that iterates for each of the field collection items (using its unique ID) ...
>
> The unique ID of the field collection item: 2
> The host entity of this field collection item: 43
> Field "field_doelpubliek": Baby
> Field "field_betalend": Nee
>
> The unique ID of the field collection item: 3
> The host entity of this field collection item: 43
> Field "field_doelpubliek": Moeder
> Field "field_betalend": Ja
>
> ```

Here is the Rule (in Rules export format) that produced the above "message":

```
{ "rules_field_collection_demo" : {
    "LABEL" : "Field Collection Demo",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_treatment_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_treatment_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has 2 fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EDoelpubliek\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_doelpubliek\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EBetalend\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_betalend\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The field collection with machine name \u003Cstrong\u003E\u0027field_treatment_details\u0027\u003C\/strong\u003E looks like so:\r\n\u003Chr \/\u003E\r\n[node:field_treatment_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-treatment-details" ] },
          "ITEM" : { "treatment_details_item" : "Treatment details item" },
          "DO" : [
            { "drupal_message" : { "message" : "The unique ID of the field collection item: [treatment-details-item:item-id]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [treatment-details-item:host]\u003Cbr \/\u003E\r\nField \u0022field_doelpubliek\u0022: [treatment-details-item:field-doelpubliek]\u003Cbr \/\u003E\r\nField \u0022field_betalend\u0022: [treatment-details-item:field-betalend]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      }
    ]
  }
}

```

Admitted, this is a slightly simplified field collection configuration (no "nesting" involved). But apart from that it is similar to what you will need to specify in your Rules logic. Here are some more details to explain the above rule:

* You need (repeat: need) a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field.
* The 1st Rules Action (which produces the data below "Part 1" in the message) just displays the entire field collection, simply by referring to token `[node:field_treatment_details]`.
* The 2nd Rules Action (which produces the data below "Part 2" in the message) is simply a Rules "loop", which iterates over each of the field collection items (it uses a variable that I named `treatment_details_item` to actually display a message for each item). You will then be able to use any of the typical tokens (in the replacement patterns) related to that variable, such as how I used them to create my message I wanted to display, i.e.:

> ```
> The unique ID of the field collection item: [treatment-details-item:item-id]<br />
> The host entity of this field collection item: [treatment-details-item:host]<br />
> Field "field_doelpubliek": [treatment-details-item:field-doelpubliek]<br />
> Field "field_betalend": [treatment-details-item:field-betalend]<br />
>
> ```

Notice how, in the message I wanted my rule to display, I was able to refer to my "Doelpubliek" and "Betalend" fields (part of my field collection).

### Part 2: Performing a loop within

After posting **Part 1** of my answer, this "Update" got added to the end of the question (after it was first posted as a comment below this answer):

> While I understand the example shown in the existing answer, I can't seem to conceptualize how I would be able to write a Rules "loop" to display the field collections in an email. The email body of the rules module does not seem to have the ability to "loop" over content.

I think you're right about '***`The email body of the rules module does not seem to have the ability to "loop" over content`***', or at least I've never discovered anything to do so. However, if what you're looking for is not available, then just make it available ... **The trick to do so** is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

1. Populate some new Rules variable ***before the Rules Action to send an eMail***, say you name the variable `field_collection_var_for_email_body`. And the value of this variable should consist of a concatenation of the appropriate values of your nested field collection.
2. Within the Rules Action to send an eMail, you'll be able to select the token for `field_collection_var_for_email_body` to include anywhere in your eMail body.

Attention: even though it should technically possible to do all this in a single rule, such rule would possibly get pretty complicated to understand/maintain. That's why if it was up to me, I'd probably implement the Rules logic (as explained in this Part 2) in a separated Rules Component, which ***provides*** ... (cfr Rules Component terminology) `field_collection_var_for_email_body`!!!

### Voilà ...

Happying Rules-ing! ... Also with (unlimitted) field collections ... even inside the body of an eMail created with a Rules action to *Send an eMail*.

**PS**: No need to write some PHP code to make this happen ...

---

**PPS**: For the newbies out there, it should look something like this:

Note that the fields are different here, and not the same as the example/scenario provided above.

**Important:** Make sure you select True for the uniqueness option in Add an item to a list, other wise this will trigger a bug that causes your fields to become empty or get readed multiple times. Once you get this bug, the only fix is to restore to a DB backup as you are not able to remove these fields even after turning off the Rule. Some more details about the bug (to avoid):
> 2 votes

---
Tags: 7, rules, emails, entities
---


# Question
Title: Views Load More pagination causes duplication
I am encountering an issue with Views Load More with Waypoints module. My question is more focused on the next contents that are retrieved. Because there are new contents added to the top, the page 2, for example, now contains items from page 1, thereby showing duplicates. Please see explanation below. How can this be addressed?

# Answer
> -1 votes
I was able to achieve this by:

* Setting a JavaScript variable with the current timestamp (`drupal_add_js()` in `hook_preprocess_page()`)
* Appending this value to my pager anchor through JavaScript

# Answer
> 0 votes
Some suggestions:

1) Do not use the LOAD MORE option in views but use a self generated link with the help of global text in the footer. Then this link is going to a second page and then you have the view in a new fresh window. Hopes this helps.

2) You can try if the behavior of the view is the same without Ajax. Sometimes live is a miracle. if so you know that is a ajax issue and not a views issue.

# Answer
> 0 votes
You can solve this by using Views Random Seed module.

This may occurred due to any of your SORT CRITERIA which is likely the cause of duplicates. So add *Global: Random seed* also as one your sort criteria conditions to avoid duplicates.

# Answer
> -1 votes
In Drupal views we have an advanced section .In that Other options we ll find the Query edit that settings into distinct .This may avoid duplicates

---
Tags: ajax, paging, views
---


# Question
Title: Drupal 7 commons AJAX bulk operations active queue error
Drupal 7 commons site with private trusted contacts enabled. When the accept trusted contact or break contact button is clicked this error appears. An error has occurred. Please continue to the error page

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /en/batch?id=6305&op=do StatusText: Service unavailable (with message) ResponseText: ERROR PAGE - An error occurred while processing views\_bulk\_operations\_active\_queue\_process with arguments: views\_bulk\_operations\_active\_queue\_process I have tried searching and this error seems quite wide with no results. How do I resolve this?

# Answer
For me, this error was due to the PHP version being used (5.3). Using PHP 5.4+ resolved it. You may also want to look at https://www.drupal.org/node/1871702 if the PHP version isn't your issue.
> 1 votes

---
Tags: ajax, 7, views
---


title: How do I use the access arguments?

text:
# Question
Title: How do I use the access arguments?
Hel', I don't understand how to use "access argument" with Services Module.

Drupal is used like a server. When I follow specific link some informations about client, user and projects are added. That's work, but everybody can do it. So I want "limit access" : if you are not admin, the access is denied. So I've activated the authentication "Session authentication" and add some code in my custom module :

```
'create' => [
    'help' => 'Add',
    'callback' => 'custom_api_create_user',
    'access arguments' => array('administer create'),
    'access arguments append' => FALSE,
    'args' => [
        [
            'name' => 'data',
            'type' => 'struct',
            'description' => 'Something',
            'optional' => FALSE,
            'source' => 'data'
        ]
    ],
]

```

And when I add hook\_node\_access I get this message : "Access denied for user Lambda", and only the first letter of "access argument" is added to the content.

Someone can explain to me how I can add content and limit access with Services module ?

Do you understand what I want to do ?

(Yes you can see the same post here)

# Answer
> 0 votes
in this case, the first letter is "a" because the access argument is "administer create". If I remove administer the first letter will be "c" from &create". And all fields from user entity get this letter as content :

name : "a" tel : "a" mail : "a", etc.

Actually I just want to know how to say "if you are admin you can add content, if not, you can't". The best way is to use "Session authentication" or "Basic authentication" or "oAuth" ?? Don't know...

---
Tags: 7, services
---


# Question
Title: How to replace Views PHP field and sorting by custom Views handler?
In order to address some Views performance issues and respect best practices, I'd like to replace some Views PHP I configured some time ago by my own *custom handlers*.

For instance I've got a Views PHP field, *excluded from display*, with that setup :

**Value code :**

```
if( $row->sticky ==1 ) {
  return 100;
} else {

  if ( isset($row->product_id) && $row->product_id != ""  ){

    $query = "SELECT COUNT(statut.entity_id) FROM field_data_field_statut_depart statut"
    . " INNER JOIN  field_data_field_product product ON statut.entity_id= product.field_product_product_id"
    . " INNER JOIN  field_data_field_date_depart depart ON statut.entity_id = depart.entity_id"
    . " WHERE product.entity_id = ". $row->nid." AND field_statut_depart_value IN (2,3) AND field_date_depart_value > NOW(); ";

    $select = db_query($query);
    $count = $select->fetchField();

    return $count;
  }
  else {
    return -1;
  }
}

```

**Output code** :

```
<?php print $value ; ?>`

```

Then I use that field as first sort criteria (*ascending*), in a **Global PHP sort criteria:**

```
if ($row1->php> $row2->php) return -1; else return 1;

```

I'd be really thankful if you could put me on the right way: in which function(s) shall I build that same code to end up with PHP in database ?

## Summary :

After search and progress, plus @Renrahf help, most of the implementation seems ok, detailed below. But I'm **still fighting with one point** : I added a custom field handler to calculate a value, but how can I order by that handler ?

## Edits :

What I did so far :

**.info file**

```
files[] = views_handler_vts_products_sort.inc
files[] = includes/views_handler_vts_count_depconf_field.inc

```

**Module file**

```
/**
 * Implements hook_views_data().
 */
function vts_views_handler_views_data() {
  $data['custom']['table']['group'] = t('Custom');
  $data['custom']['table']['join'] = array(
    // #global is a special flag which let's a table appear all the time.
    '#global' => array(),
  );

  $data['custom']['custom_handler'] = array(
    'title' => t('Vts custom Sort Handler'),
    'help' => 'Sorts products by sticky first then by custom statut field',
    'sort' => array(
      'handler' => 'views_handler_vts_products_sort',
    ),
  );

  $data['custom']['count_depconf_field'] = array(
    'title' => t('Sum of products with status confirmed '),
    'help' => t('Calculate Sum of products with status confirmed, to order lists".'),
    'field' => array(
      'handler' => 'views_handler_vts_count_depconf_field',
      'click sortable'=> TRUE,
    ),
    /*'sort' => array(
      'handler' => 'views_handler_sort',
    ), */
  );
  return $data;
}

function vts_views_handler_views_api() {
    return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'vts_views_handler'),
  );
}

```

**`views_handler_vts_products_sort` file**

```
/**
 * Base sort handler that has no options and performs a simple sort.
 *
 * @ingroup views_sort_handlers
 */
class views_handler_vts_products_sort extends views_handler_sort {

  function query() {
    $this->ensure_my_table();
    // Add the field.
    $this->query->add_orderby('node', 'sticky', 'DESC');
  }
}

```

**`views_handler_vts_count_depconf_field` file**

```
/*
 * A simple field to calculate the value I wish to order by.
 */
class views_handler_vts_count_depconf_field extends views_handler_field {

  function query() {
    //do nothing
  }

  function render($values) {
    $count = 0;

    $product_id = isset($values-> commerce_product_field_data_field_product_product_id)? $values-> commerce_product_field_data_field_product_product_id: NULL;
    if(!is_null($product_id)){

      $query = "SELECT COUNT(statut.entity_id) FROM field_data_field_statut_depart statut"
      . " INNER JOIN  field_data_field_product product ON statut.entity_id= product.field_product_product_id"
      . " INNER JOIN  field_data_field_date_depart depart ON statut.entity_id = depart.entity_id"
      . " WHERE product.entity_id = " . $values->nid . " AND field_statut_depart_value IN (2,3) AND field_date_depart_value > NOW(); ";

      $select = db_query($query);
      $count = $select->fetchField();
    }
    return $count;
  }
}

```

**Remaining question :**

* how to order by the custom field handler ? I tried adding `'click sortable'=> TRUE,` OR `'sort' => array('handler' => 'views_handler_sort',),` OR `$this->query->add_orderby('custom', 'count_depconf_field', 'DESC');` into custom sort handler. None works but return Unknown column in 'order clause'
* ***DONE*** *: How can I get `$row->product_id` and `$row->nid` inside `query()` ? I need it to build the subquery.* : Added a views handler field and found the row values in render($values)...
* ***DONE*** *: Which part of the example handler do I have to edit ? The query function only ? Do I need to keep the whole example code or just the custom parts ?*

Thank you

# Answer
> 7 votes
You need to use a views sort handler : https://api.drupal.org/api/views/handlers!views\_handler\_sort.inc/group/views\_sort\_handlers/7.x-3.x

You can't use PHP for sorting your results for performance reasons. PHP can only be used to sort results if you fetch the entire table results, and that's not an option most of the time.

So, you need to create your own view sort handler, configure it in your view and then use the views API functions to make the proper joins, where, maybe even subqueries to reach the data you need for your sort. In your case, a number of entities having particular date and type conditions.

All this code has to reside in the "query()" method of your object. You need to achieve a query like this :

```
SELECT table_x.field_y, ...
FROM  ...
...
...
ORDER BY row.sticky, (SELECT COUNT(statut.entity_id)
FROM field_data_field_statut_depart statut
INNER JOIN field_data_field_product product
INNER JOIN field_data_field_date_depart depart
WHERE product.entity_id = table_x.field_y
AND field_statut_depart_value IN (2,3)
AND field_date_depart_value > NOW())

```

By using the function https://api.drupal.org/api/views/plugins%21views\_plugin\_query\_default.inc/function/views\_plugin\_query\_default%3A%3Aadd\_orderby/7.x-3.x and a subquery.

The subquery may be optimized in 3 or more joints and some where conditions maybe but I can't tell without the whole query.

**EDIT**

You extends from "views\_handler" object but you should directly extends from "views\_handler\_sort" to be able to use the maximum of core default code :

```
class views_handler_vts_products_sort 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($this->table_alias, $this->real_field, $this->options['order']);
  }
}

```

As you can see above, only the "query" method is needed in your case as you don't need any specific configurations in the UI etc.

To get the **product\_id** or **nid** inside your "query()" method, you have to use existing fields that were added to the query by views field handlers (and defined in your views UI).

This file is the perfect example of what you want to achieve (you can find it in the views documentation, it is an existing one but I'm not allowed to set the link as my reputation is too low) :

```
class views_handler_sort_node_version_count extends views_handler_sort {
  function query() {
    $this->ensure_my_table();

    $this->query->add_orderby(NULL, '(SELECT COUNT(vid) FROM {node_revision} WHERE nid = {' . $this->table_alias . '}.nid)', $this->options['order'], 'sort_node_version_count');
  }
}

```

See if you can adapt this code to your need and I'll be glad to see the end result :)

# Answer
> 4 votes
I share below the full implementation on how I did to **replace Views PHP sorting by a custom Views handler**.

**.info file**

```
files[] = includes/views_handler_my_custom_sort.inc

```

**Module file**

```
/**
 * Implements hook_views_data().
 */
function MODULE_NAME_views_data() {
  $data['custom']['table']['group'] = t('Custom');
  $data['custom']['table']['join'] = array(
    '#global' => array(),
  );

  $data['custom']['custom_handler'] = array(
    'title' => t('My custom Sort Handler'),
    'help' => 'Sorts products by sticky first then by custom statut field',
    'sort' => array(
      'handler' => 'views_handler_vts_products_sort',
    ),
  );

  return $data;
}

function MODULE_NAME_views_api() {
    return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MODULE_NAME'),
  );
}

```

**views\_handler\_my\_custom\_sort.inc file**

```
/**
 * Base sort handler that has no options and performs a simple sort.
 *
 * @ingroup views_sort_handlers
 */
class views_handler_my_custom_sort extends views_handler_sort {

  function query() {
    $this->ensure_my_table();

    $sub_query = "(SELECT COUNT(p.field_product_product_id) "
      . "FROM field_data_field_product p "
      . "LEFT JOIN field_data_field_statut_depart statut ON statut.entity_id = p.field_product_product_id "
      . "LEFT JOIN field_data_field_date_depart depart ON depart.entity_id = p.field_product_product_id  "
      . "LEFT JOIN node nod ON nod.nid = p.entity_id "
      . "WHERE nod.nid = node.nid "//This is a the obligatory condition mapping the subquery with the outer query
      . "AND field_statut_depart_value IN (2,3) "
      . "AND field_date_depart_value > NOW())";

    /* I'm timeless to write the query with the object syntax, here was a beginning
    $sub_query = db_select('field_data_field_product', 'p');
    $sub_query->addField('p', 'field_product_product_id');
    $sub_query->leftJoin('node', 'nod', 'nod.nid = p.entity_id');
    $sub_query->where("nod.nid = node.nid");
    $sub_query->countQuery(); */

    $this->query->add_orderby('node', 'sticky', 'DESC');
    $this->query->add_orderby(NULL, $sub_query, 'DESC', 'subquery');

  }
}

```

A bit of explanation : after understanding how to implement Views handlers, I got confused with the subquery :

* map it with the outer query to get a dynamic "row by" result : same table and column but different alias : `WHERE nod.nid = node.nid`
* set the alias in `add_orderby` : `$this->query->add_orderby(NULL, $sub_query, 'DESC', 'subquery');` works, but `$this->query->add_orderby(NULL, $sub_query, 'DESC');` doesn't

This last point was surprising because while `SELECT TITLE FROM node ORDER BY (SELECT COUNT(field_product_product_id) FROM field_data_field_product p LEFT JOIN node nod ON nod.nid = p.entity_id WHERE nod.nid = node.nid )` works in SQL direct input, it doesn't across current setup.

You need to specify the subquery alias and the final query will be something like `SELECT TITLE, (SELECT COUNT(field_product_product_id) FROM field_data_field_product p LEFT JOIN node nod ON nod.nid = p.entity_id WHERE nod.nid = node.nid ) as subquery FROM node ORDER BY subquery`

The tries to calculate the values to sort the result in a custom handler field, did not work because Views sorting is done on a DB basis and the custom field handler is kind of dummy field... at least this was my conclusion.

---
Tags: 7, views
---


# Question
Title: How to bypass CAPTCHA during Behat functional testing?
We have a site that uses the CAPTCHA and CAPTCHA After modules to protect forms from invalid submissions. We're doing some functional and BDD testing using Behat and the tests are sometimes triggering the CAPTCHA After thresholds, causing the CAPTCHA to be displayed. Is there an easy way to bypass the CAPTCHA, when performing tests?

I realize that we can probably override the CAPTCHA After threshold settings in the database, if the tests are running on the same machine. However, it would be nice to also be able to run the tests from a different machine than the web server hosting the site. I think that something like an IP whitelist might work, but I haven't found anything along those lines yet. Before we start coding something like that, anyone have a better idea?

Thanks!

# Answer
> 1 votes
Using the API Driver you can, as you say, modify CAPTCHA After threshold and restore it at the end of test, but you need to execute tests in the same machine.

If you want to do it form another machine you have to set up a way to alter that variable from outside. You can define a hook menu that alters that variable, in a dev module that will not be enabled in production site. You can also set up a drush remote command that modifies the threshold in th remote machine and restores and the end of the test. You can add this drush command in the script that lauchhes behat tests or even inside behat in a behat hook.

# Answer
> 1 votes
I realize this thread is almost two years old, but in the event someone finds this, you should be able to disable captcha in settings.php files. For example if you are running site locally, local.settings.php, or if CI, something like travis.settings.php (or whatever you use).

For each place captcha is used, you would have an entry for the config setting ie. for login form:

`$config['captcha.captcha_point.user_login_form']['status'] = FALSE;`

If you are unsure of the setting, on whatever page you want to remove CAPTCHA you should be able to inspect the global `$config[]` and find the relevant setting set to `TRUE`. Setting it back to false in the relevant settings.php should remove captcha entirely.

Be careful that you do not accidentally put it in a settings.php that is used by your live site, or you will disable CAPTCHA!

---
Tags: captcha, testing
---


# Question
Title: Some links are still visible after logging out in drupal8
The question is clear from the title itself , after logging out i can see some view links , one on the side navigation menu and two on the main navigation . I checked the view permission , but its same as the other view which are not visible . Any idea ??

# Answer
> 1 votes
I would suggest, you check the permission at two places

(1) Views permission, which you can find at views UI, under page setting, so from there you can apply the Role restriction.

(2) Permission of Entire that Navigation block under blocks layout, Which allows the display of entire block.

---
Tags: 8, users, navigation
---


# Question
Title: How to send a confirmation reservation email using the Reservations module?
I'm using the Reservations module to control certain resources. I'd like to send an email to the user who reserved the resource when it is confirmed. I also installed the Reservations email module to handle that. I could not find a token to use to refer to the user in the email body.

Currently, when a user requests a resource, an admin receives an email. When the admin confirms the resource I'd like to send the user an email confirmation.

Any suggestions about how this can be done with the existing module?

# Answer
> 1 votes
The Reservations: Email module is what allows you to send eMails. Some more details about it (from its project page):

> This module extends Reservations to send emails at different stages in the reservation process. Token based templates are included so the emails can be customized with any information from the Reservation node or User objects. Also included is a pseudo-token for a confirmation link that allows users to confirm reservations without the need to grant them the permission to confirm reservations.

However, looking at the module source, using tokens in the eMail body requires that the token module is enabled. So if you haven't enabled that module yet, it may explain why you "*could not find a token to use to refer to the user in the email body*" (as in your question).

**Update**:

About your extra comment like "***... I had to add a new field to the reservation type to save the name of the user requesting the resource. I later used that field in the email.***": that seems like a variation of what's written in the issue about "Sending emails to anonymous users". That issue contains a patch that you may want to look at also.

---
Tags: 7, emails
---


title: Change logo based on taxonomy term

text:
# Question
Title: Change logo based on taxonomy term
I'm trying to change the logo in my header based on the taxonomy term of a page. I have managed to get it working on the taxonomy landing page itself. However, I have content pages that have term references on them which don't pull through the term title.

This the code that allowing me to display the title on the taxonomy page:

```
$termid = arg(2);
      $term = taxonomy_term_load($termid);
      $title = $term->name;

      $title = str_replace(' ', '', $title);

      $field_organisation->field_organisation['und'][0]['tid'];

```

I am then stripping out the whitespace and printing the value inside an `img` tag.

I've tried doing this with views and creating a list of all nodes and adding a contextual filter. Yet this seems to only work the other way. So it only displays the image on the node page itself and NOT the taxonomy landing page.

Any help would be much appreciated.

Thanks.

# Answer
> 1 votes
You can make the code work in 2 situations.

```
$term = menu_get_object('taxonomy_term', 2);
if (empty($term)) {
  if ($node = menu_get_object('node', 1) ) {
    $wrapper = entity_metadata_wrapper('node', $node);
    $term = $wrapper->field_organisation->value();
  }
}

if ($term) {
  $title = $term->name;
  $title = str_replace(' ', '', $title);
}

```

`entity_metadata_wrapper()` is the function provided by module Entity

---
Tags: views, theming, taxonomy-terms
---


# Question
Title: How do I alter images being added via IMCE CKEditor plugin?
I just wanted to share my solution since I did not find any clue or different way of fixing the following problem:

Formerly, you could add a default class/ alter attributes of newly inserted images (or elements) in CKEditor. In Drupal 8, the `ckeditor.config.js` apparently was removed. Also, images added via IMCE CKEditor plugin are added via `insertHTML` and there seems not to be any way of manipulate the html string (despite listening to the `insertHtml` event) with the `htmlParser`.

How to alter the attributes of images added via imce in ckeditor?

# Answer
So, here is what I did, even if maybe its dirty.

Add a new module which attaches a custom library to forms:

```
function mymodule_form_alter(&$form, $form_state) {
  $form['#attached']['library'][] = 'mymodule/form';
}

```

In the `mymodule.libraries.yml`:

```
form:
  version: 1.x
  js:
    js/mymodule.js: {}
  dependencies:
    - core/ckeditor
    - ckeditor/drupal.ckeditor
    - imce/drupal.imce
    - imce/drupal.imce.ckeditor

```

And in the `mymodule.js` I pretty much just re-write the imce `sendto` function:

```
if (undefined !== CKEDITOR && CKEDITOR.imce.sendto) {
  CKEDITOR.imce.sendto = function (File, win) {
    var imce = win.imce;
    var editor = CKEDITOR.instances[imce.getQuery('ck_id')];
    if (editor) {
      var i;
      var text;
      var lines = [];
      var selection = imce.getSelection();
      var is_img = imce.getQuery('type') === 'image';
      for (i in selection) {
        if (!imce.owns(selection, i)) {
          continue;
        }
        File = selection[i];
        // Image
        if (is_img && File.width) {
          lines.push('<img class="img-responsive" src="' + File.getUrl() + '" />');
        }
        // Link
        else {
          // Use the selected text/image for the first link
          text = !lines.length && CKEDITOR.imce.getSelectedHtml(editor) || File.formatName();
          lines.push('<a href="' + File.getUrl() + '">' + text + '</a>');
        }
      }
      editor.insertHtml(lines.join('<br />'));
    }
    win.close();
  };
}

```

Hope this is helpful to somebody. And maybe there is another, better way of doing this - glad for any input!
> 1 votes

---
Tags: 8, wysiwyg, files
---


# Question
Title: Duplicate Meta description on shared node across multiple subdomains
I have a drupal site with multiple subdomains which share a single node. I installed Yoast SEO for Drupal and added title / description etc. for each node. Now the problem is that it shows same meta title and description for all sites (subdomain). Any idea on how to resolve this issue.

# Answer
I haven't used that module (looks cool!), but it does depend on metatag, which is probably what's providing the title & description fields. The metatag module saves its configuration in a database table `metatag_config`, which is probably shared across all of your subdomains.

It looks like you can have tokens in your config, so for example, we use `[node:title] [site:name]` for our page title config. And if you wanted an unique title for each subdomain, you could just specify a separate site name for each one.

We use subdomains (www, m, staging, dev, etc) and we're fine to share the node's title & description across all of them. The thing we do want unique is the canonical meta tag, so if a search engine comes across duplicated content on a subdomain, it won't take anything away from the original. So we'll specify the full domain in the canonical url like this:

https://www.example.com/\[current-page:url:path\]
> 0 votes

---
Tags: meta-tags
---


# Question
Title: How can I schedule adding a new field collection item for all users?
My users have a field collection, called 'Score', with two fields: 'Date' and 'Points'. I'd like to add a new field collection item for all users at the end of the day, with the current date in 'Date' and their current userpoints in 'Points'.

I thought about using a scheduled rule, but I don't know how I can select something like 'all users'. Is this possible with Rules or is there another way to achieve this?

---

This question is part of How to create a line graph of the total user points on a profile page?.

# Answer
Yes this is possible with Rules, if combined with Views Bulk Operations, as further detailed below ...

What you actually need to do is similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

> * You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
> * However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
> * You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displays with at least one VBO field will be selectable.
> * The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

In your case you want to start from a VBO list of all the users you want to get processed. And for each user in the list you want the rules action to be as in your "scheduled rule", whatever that rule is actually supposed to do (instead of "remove sticky").

You want to pass the userid as a parameter also, similar to what is shown around 7:30 in that video also.

The Rules component that you create as described above, should then become the action to be performed by a rule that is triggered daily, via the Rules Scheduler, similar to what is shown in the video, starting from 11:30.

Should you need any other rules "conditions" (eg: only for selected roles), you can add them to the rules component you created.

Easy, no? Happy VBO-ing with Rules ... ( or Rules-ing with VBO if you prefer)!
> 1 votes

# Answer
I'm not sure about rules but you could do that in a custom module with a little code:

```
$uids = db_query("SELECT uid FROM {users} WHERE status=1")->fetchCol();
$accounts = user_load_multiple($uids);
foreach($accounts as $account) {
    $edit['my_field'][LANGUAGE_NONE]['0']['value'] = 'my new value';
    user_save($account, $edit);
}

```
> 1 votes

---
Tags: 7, rules, userpoints, entities
---


# Question
Title: Why is my Rules Component not being scheduled accurately?
My aim is to send an email to new students at certain weeks after admission. E.g week 28, week 32, week 45.

I set up components with action to send email.

I configured a rule with event: after saving new content type(student).

The content type has a field - date of admission.

I scheduled component evaluation based on the offset of 'date of admission'.

So for example:

Date of admission: 02/03/13 (March 2nd 2013)

Offset: 224 days

However when the rule is triggered and I go to admin/config/workflow/rules/schedule, I noticed that the scheduled date is 16/10/13 rather than 12/10/13.

Please how can I resolve this?

# Answer
> 1 votes
When scheduling a Rules Component, you specify a value within **Scheduled evaluation date**. One of the options to do so, is to specify ***Relative dates*** like "+1 day", as mentioned within the Rules UI:

> ***... any other values in GMT known by the PHP strtotime() function (like "+1 day")***

As per your "offset = 224 days", I'm assuming you used a value like "+224 days".

However since you want to schedule the Rules Component a certain number of weeks after admission (like "week 28, week 32, week 45."), try to specify Relative dates like "+28 weeks", "+32 weeks", "+45 weeks". That might help for the Rules Scheduler to show a more accurate date.

---
Tags: rules
---


title: Enabling view programmatically

text:
# Question
Title: Enabling view programmatically
I want to know how to enable view programmatically in drupal 7? I need it to be exportable with features. I need a snippet code for that. Thanks!

# Answer
Based on your question I honestly think you are doing something wrong, but if you really do have a legit use case I think you can just do this:

```
$view = views_get_view('machine-name-of-view');
views_export_status($view, TRUE);
views_save_view($view);

```
> 0 votes

---
Tags: views
---


# Question
Title: Use selected NID from Entity Reference field to populate second Entity Reference field
I have three content types:

1. organization profile
2. internship posting
3. hours submission

The 'hours submission' content type has two entity reference fields:

1. Entity reference for 'organization profile' nodes
2. Entity reference for 'job posting' nodes

I'd like to pass the NID from the first entity reference such that the second entity reference is filtered (only shows nodes that are associated with that NID).

The 'job posting' content type is tied to an 'organization profile' via an entity reference field.

Any help or guidance would be appreciated.

# Answer
My solution is to:

1. Pre-populate and disable the first entity reference field with a node ID
2. Add an extra path component with the same nid and have the second field use an entity reference view with *default: Path Component 4*

So the URL looks like /node/add/hacky/123?field\_solution=123.

While hacky, it has uses, especially if you want to filter fields that don't have a connection. In that case the URL could be /node/add/hacky/123/456?field\_solution=789.
> 2 votes

# Answer
The Dynamic Dependent Fields (DDF) module does exactly what I described above.

The module introduces a new view mode: "Filter by an entity reference view with dynamic arguments". Then you can filter the entity reference view you set up with the value from a field in the entity.

In the Entity Reference View, use contextual filters to filter the results.

For example, I added the NID (provided by content ID) as a contextual filter.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Control content type availability based on day and time
I have a website that delivers products that are ordered during the day. I would like the order form to only be available during business hours. Outside of those hours, the form shouldn't be available for ordering.

I am using Webform but I can easily enough create my own content type if needed. I've looked into using Rules, but I am not sure how to write the rules to accomplish this.

I thought there would already be a quick and easy module for this, but I have not been able to find one. Any suggestions?

# Answer
This is quite straight forward with rules.

1. Create a page called "Order Form Unavailable" with your message about products only being available during the day.
2. Enable the PHP Filter module.
3. Create a rule with event "Content is viewed" of type "Order form Webform" (Or whatever)
4. Add condition "Execute custom PHP code".

Add the following into the PHP text area...

```
if( (date('H') < 9) && (date('H') > 17) ){
 // before 9AM and after 5PM
 return TRUE;
}

```
5. Add action "Page Redirect" to redirect the user to the "Order Form Unavailable" page.
> 0 votes

# Answer
using your excellent answer and a little of my own brain power (which I don't like doing.. ;) I came up with this. It works, but if anyone has more "elegant" code, please share it:

```

$hhmm = date('H') * 100 + date('i');
  // converts and joins hours and minutes
if( (date('w') == 0) && (($hhmm < 1100) || ($hhmm > 1645))) {
 // Sunday before 11AM and after 4:45PM
 return TRUE;
} elseif( ($hhmm < 0900) || ($hhmm > 2045) ) {
 // All other days 9AM and after 8:45PM
 return TRUE;
} else {
 return FALSE;
}

```
> 0 votes

---
Tags: forms, rules, webforms, datetime
---


title: EFQ - sort by reference entity label

text:
# Question
Title: EFQ - sort by reference entity label
I'm trying to add an `sort` condition to an EFQ on an reference entity table, I think a code example explains this better.

```
$query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
$ids = $query->condition('type', 'some_type')
  ->condition('some_more', 'conditions')
  ->sort('a_term_field', 'ASC')
  ->execute();

```

Now what happens is that the nodes will be sorted by the term id (since that is what is stored in the field table) but I would like to sort on the term label instead. Is something like that possible with EFQs?

# Answer
> 3 votes
Have you tried `->sort('a_term_field.entity.name', 'ASC')`, that should work.

Some limitations exists with multilingual fields, as it is not defined on which language it should be sorted.

---
Tags: 8, entities
---


# Question
Title: How to switch to other site's database in multisite enviroment?
The use case is the following:

I am in default site. I want to get the connection of the "preview" site instance database from the default site code. How is it possible?

I tried `Database::setActiveConnection('preview'))`, but it didn't help. setActiveConnection method seems to choose only from your site settings.php.

*** WORKAROUND ***

If you want to handle multiple database under one site instance then you should declare their connection array under your site's settings.php!

# Answer
> 1 votes
You can't.

Multi-site is *only* about sharing the code in the file system. Unless you actually add the database connections to the specific settings.php, Drupal doesn't even know that there are other sites.

Functionally, once the bootstrap and site selection happened, there is 0 difference between two different installations and a multi-site.

IMHO, there are more downsides than advantages with multi-sites these days, you can use git and e.g. different branches to share code between multiple sites at least as well, with way more flexibility and options for updating and customizing them.

---
Tags: 8, database
---


# Question
Title: What is causing the "username_link not found" error in the LDAP integration module?
After integration and configuration of the LDAP integration module, my site is unable to access the LDAP Server. During testing it throws below error:

> Notice: Undefined variable: username\_link in theme\_ldap\_authorization\_test\_results() (line 91 of /var/www/drupal/sites/all/modules/ldap/ldap\_authorization/ldap\_authorization.theme.inc).

I am using Drupal - v7.44, and LDAP v 7.x-2.0-beta8 and the same LDAP server is working on other sites.

Is this a configuration issue or a bug?

# Answer
> 0 votes
According to comment nr 2 in issue nr 2751219 this is not a bug, but it's just a configuration issue. Here is a quote from it:

> Incorrect admin password for LDAP server.

So double check the password is correct, and try again ...

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


# Question
Title: Default to 'this display' when editing views
I am working on a display of a view I have. I want to make changes that apply only to the display that I'm working on; however the various editing widgets (relationships, filters, fields, etc) keep defaulting to apply to all displays. For the most part I remember to change it to "this display", but sometimes I don't, and I end up changing all displays.

Is there a way to change the default application to "this display"? Or have views remember which I chose?

# Answer
Not that Im aware of, Im afraid this is the default behaviour. I often catch myself out by not selecting "This block override". :-(

But actually - Breaking the default behaviour for the very first display when you create a new view would mean that every new display you add would have its own settings for filters etc. You would just have to remember to do this everytime you add a view
> 2 votes

---
Tags: views
---


title: Get Exposed Filter Value

text:
# Question
Title: Get Exposed Filter Value
How does one get the actual value for an exposed filter?

I can get the 'id' for a filter value using the following code and pulling the data out of the array, but this just returns integer values of 1,2,3,etc.:

```
$view = views_get_current_view();
$view->exposed_input['filter_name'];

```

using `$view->get_exposed_input()` results in the exact same issue.

How do I get the actual text string that is applied for the filter?

Specifically I'm trying to do this with a Global PHP field.

# Answer
The simplest way to do this is by using a Taxonomy to define your filter. By default, the 'IDs' returned in the array will be TIDs, which you can link back to Term name.

This post provides some easy instructions on how to use a Taxonomy as your filter (you possibly need to add it as a relationship in your view)

Get your IDs (values) the same way previously:

```
$view = views_get_current_view();
$view->exposed_input['filter_name'];

```

Then simply step through the array to pick up and match the IDs to the term name:

```
$view = views_get_current_view();
foreach ($view->exposed_input['filter_name'] as $tid) {
  $term = taxonomy_term_load($tid);
  $name = $term->name;
  print $name;
}

```

Boom!
> 2 votes

# Answer
To get both filter name and its value, you can do something like that :

**Make a variable out of each filter**

```
function MODULE_preprocess_exposed_filter_data(&$vars) {

  $view = $vars['view'];

  // In case no view - get the current view
  if ($view == NULL) {
    $view = views_get_current_view();
  }

  if (isset($view->exposed_input)) {
    foreach ($view->exposed_input as $filter => $value) {
      $vars[$filter] = $value;
      if (is_array($value)) {
        $vars['exposed_filters'][$filter] = check_plain(implode(", ", $value));
      } else {
        $vars['exposed_filters'][$filter] = check_plain($value);
      }
    }
  }
}

```

**Declare your template**

```
function MODULE_theme() {
  return array(
    'exposed_filter_data' => array(
      'template' => 'exposed_filter_data',
      'variables' => array(
        'view' => NULL,
      ),
    ),
  );
}

```

**Call to template output**

```
function get_exposed_filter_output() {
  return theme('exposed_filter_data');
}

```

**In `exposed_filter_data.tpl.php` file**

```
<?php if (isset($exposed_filters)): ?>
  <div class="exposed_filter_data">
    <div class="title"><?php print t('Filtered by:'); ?></div>
    <div class="content">
      <?php foreach ($exposed_filters as $filter => $value):
      //Do stuff with your filters and values here ?>
        <?php if ($value): ?>

        //taxonomy terms for instance
        if ($filter == 'field_taxonomy_tid') :
          if($value != '' && $value != 'All' ){

            $term = taxonomy_term_load($tid);
            $vocab = taxonomy_vocabulary_load($term->vid);
            $vocab_name = $vocab->name; ?>

            <div class="filter">
              <div class="name">$vocab_name :</div>
              <div class="value">
                <?php $types = explode(',', $value);
                $t = taxonomy_term_load_multiple ($types);
                $exp_types = '';
                foreach ($t as $k=>$v) {

                  $exp_types .= $v-> name . ', ';

                }
                $exp_types = substr($exp_types, 0, -2);
                print $exp_types;
                ?>
              </div>
            </div>
            <?php }
          endif;
        <?php endif; ?>
      <?php endforeach; ?>
    </div>
  </div>
<?php endif; ?>

```

Finally print your exposed filter data : instead of using global PHP in your view, you'd better try something like that :

```
function MODULE_views_pre_render(&$view) {

  if ( $view->name == 'MYVIEWNAME' ){
    //display exposed filters in a custom text area
    if (isset($view->header['area_text_custom'])){
      $exp = get_exposed_filter_output();
      $view->header['area_text_custom']->options['content'] = $exp;
    }
  }
}

```

This is 80% inspired by this little handy module : Exposed Filter Data
> 0 votes

---
Tags: views
---


# Question
Title: Why doesn't loading a form in the view header work?
I've been checking for the past 2 days on how to do a drupal\_get\_form() for Drupal 8 and everyone seems to give me the following answers which don't seem to work. Let's just say I want to take the following **Basic Page** creation form and embed it into a Views header:

The ID of the form is: **node-page-form** or **node\_page\_form** if we were using drupal\_get\_form() from Drupal 7. But this time its the following:

**$form = \Drupal::formBuilder()-\>getForm(Drupal\user\Form\NodePageForm::class);**

**I'm assuming "NodePageForm" is the parameter I'm suppose to use. If not how can one find this out from viewing the source of that page?**

I then put the following PHP code in the Views header of my page like this:

I click save and update... my header is blank. What did I do wrong?

I'm trying to be as descriptive as I can explaining this problem. End result I just want to be able to take **ANY** form from any D8 page and be able to render it anywhere that takes PHP. That's my end goal. So no 3rd party modules as a solution.

# Answer
> 3 votes
sEntity forms should be built using the entity.form\_builder service. You'll need an entity to work with, for a node your code might change to something like this:

```
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create(['type' => 'page']);

$form = \Drupal::service('entity.form_builder')->getForm($node);

print \Drupal::service('renderer')->render($form);

```

As noted in the comments, this won't actually work in the context you're using it, regardless of how you render the form. The views\_php area handler renders the output of the custom PHP using `#markup`, which will strip out the `<input>` and other form tags. You'll need a custom or contributed module, or to alter the views\_php module directly, to make this work.

Here's a simple area handler that adds support for common form tags:

```
<?php

namespace Drupal\foo\Plugin\views\area;

use Drupal\Component\Utility\Xss;
use Drupal\views_php\Plugin\views\area\ViewsPhp;

/**
 * Views area PHP text handler with support for common form tags.
 *
 * @ingroup views_area_handlers
 *
 * @ViewsArea("foo")
 */
class ViewsPhpForm extends ViewsPhp {

  public function render($empty = FALSE) {
    if (!$empty || !empty($this->options['empty'])) {
      $content = $this->renderViewsPhp($this->options['content']);
      $form_tags = ['form', 'input', 'select', 'fieldset', 'option', 'button', 'textarea', 'optgroup'];
      $allowed_tags = array_merge(Xss::getAdminTagList(), $form_tags);

      return [
        '#type' => 'inline_template',
        '#template' => Xss::filter($content, $allowed_tags),
      ];
    }

    return [];
  }

}

```

This code should be in `src/Plugin/views/area/ViewsPhpForm.php` and will need updating for the name of your module.

You'll also need to make views aware of it with a hook either in your .module file, or foo.views.inc:

```
/**
 * Implements hook_views_data().
 */
function foo_views_data() {
  $data['views']['php_with_form'] = [
    'title' => t('PHP with form'),
    'help' => t('Use PHP code with support for form tags.'),
    'area' => [
      'id' => 'foo',
    ],
  ];

  return $data;
}

```

After a cache rebuild you'll be able to add a new area handler, *PHP with form*, and your form should be rendered.

# Answer
> 1 votes
See How to render form in drupal 8. Also has a link to the Change Record over on Drupal.org

---
Tags: forms, 8
---


# Question
Title: How to dynamically add options to <select> list in CKeditor dialog
I am building a CKEditor plugin for Drupal 8. Currently it adds a toolbar button which triggers a modal dialog containing a select list with a few options. I've hardcoded the options in `plugin.js`, and everything works as expected. But those options must actually be dynamically added with php.

This is my plugin dialog definition, as per http://docs.ckeditor.com/#!/api/CKEDITOR.dialog.definition.select with hardcoded options.

This goes in the `plugin.js` file loaded via `CKEditorPluginInterface::getFile()` in my plugin class:

```
CKEDITOR.dialog.add('pluginDialog', function(editor) {
  return {
    title: 'Available options',
    minWidth: 300,
    minHeight: 200,
    resizable: CKEDITOR.DIALOG_RESIZE_BOTH,
    setup: function(e) {},
    commit: function(e) {},

    contents: [{
      id: 'tab-options',
      elements: [{
        type: 'select',
        id: 'select-options',
        label: 'Select an option:',
        items: [
          ['Option 1', '<span>Option 1</span>'],
          ['Option 2', '<span>Option 2</span>'],
          ['Option 3', '<span>Option 3</span>'],
          ['Option 4', '<span>Option 4</span>']
        ]
      }]
    }]
  };
});

```

`CKEDITOR.dialog.definition.contents.elements.items[]` have to be built from PHP. Any help is appreciated.

# Answer
You can pass data to ckeditor via the `getConfig` method in your plugin, e.g.:

```
public function getConfig(Editor $editor) {
  return [
    'pluginName_options' => $this->buildOptions()
  ];
}

```

And in the JS:

```
items: editor.config.pluginName_options

```
> 3 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How to customize the webform field validation message?
there is a huge issue where when a Phone number field is validated on a webform, we get the following error message:

North American Phone numbers should only contain numbers and + and - and ( and ) and spaces and be like 999-999-9999. Please enter a valid ten-digit phone number with optional extension.

In reality we need an ability to customize this and we were looking into the hook\_form\_alter, but we hit a snag and cannot find ways to modify the error message. How would we be able to modify the validation messages?

# Answer
One solution here is the String Overrides module.

> Provides a quick and easy way to replace any text on the site.
>
> **Features**
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.

For your case, you can override the Phone module's default error message. By placing this string in this string:

> "%value" is not a valid North American phone number
> North American Phone numbers should only contain numbers and + and - and ( and ) and spaces and be like 999-999-9999. Please enter a valid ten-digit phone number with optional extension.

And substituting whatever you need it to display.
> 0 votes

---
Tags: 7, forms, webforms
---


title: How to customize the node edit form?

text:
# Question
Title: How to customize the node edit form?
I need to customize the access to details like 'Publishing options', 'menusettings', 'authoring information' etc while the user is editing the node.

These options should be shown only if the admin has allowed the users to view those. I Have searched for this, but unfortunately found no answers for Drupal 8.

# Answer
You can use Simplify

> Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.

Enable the module, then go to People \>\> Permissions and check mark **View hidden fields** for the user role you want to allow to see them.
> 4 votes

---
Tags: forms, 8
---


# Question
Title: How to set value to an unlimited field collection using Rules?
I want to copy the values of the field collections from *entityform* to node form, using the Rules module.

I tried to loop my field collection, then set value of the field collection from *entityform* to *entitycreated*, but this didn't work. I only get blank fields but the number of field collections are the same.

For example I have 5 *field collection items* per field collection and 5 *field collections* from *entityform*, after executing the rule I also have 5 empty field collections on the *entitycreated*.

Here's a sample of the rule:

```
{ "rules_after_submitting_entityform_custom_package" : {
"LABEL" : "After submitting entityform Custom package",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "entityform" ],
"ON" : { "entityform_update" : [] },
"IF" : [
  { "data_is" : { "data" : [ "entityform:type" ], "value" : "custom_package_entity_form" } }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "sample",
        "param_title" : "Your Event",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },

  { "LOOP" : {
      "USING" : { "list" : [ "entityform:field-option-criteria" ] },
      "ITEM" : { "list_entity_form_option_criteria" : "Current list item" },
      "DO" : [
        { "data_set" : {
            "data" : [ "entity-created:field-option-criteria" ],
            "value" : [ "entityform:field-option-criteria" ]
          }
        }
      ]
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-entityform-referenced" ],
      "value" : [ "entityform" ]
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } },
  { "redirect" : { "url" : "[entity-created:url]", "destination" : "1" } }
] }}

```

Any idea, how to set this the right way?

Also, after creating this rule, I get this error when trying to delete the node created:

> Fatal error: Call to a member function delete() on a non-object in /sites/all/modules/field\_collection/field\_collection.module on line 830

I also tried using the Entity reference autofill module but it's not auto-filling the fields if I try it with Rules.

Any suggestions?

# Answer
> 0 votes
I see 2 errors in your rule, which is about processing a **list** of field collection **items**. Each of these errors is further explained below (though I'm not sure if they are the only errors).

### Error 1: Rules Condition 'Entity has field' is missing

You should add a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field. Since your rule doesn't have such condition yet, it may also explain why you got those blank values so far.

For way more details about this, refer to "How to iterate over all field collection items in an eMail body using Rules?" (which also includes a rule in export format you may want to experiment with, if you only adapt some machine names of the used fields).

### Error 2: 'Set a data value' needs to be replaced by 'Add an item to a list'

The Rules Action **Set a data value** that your Rule uses, can only set 1 value, while you're trying to update something that is a list.

So try to replace that action (ie the first `data_set` within the loop) with an action "**Add an item to a list**". When doing so, you probably also want to set "ENFORCE UNIQUENESS" to `true`, so that you "*only add the item to the list if it is not yet contained*". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

For way more details about this, refer to "How to set multiple values to an unlimited Term Refence field with Rules". While reviewing this, also pay attention to the "Fetch entity by ID" (within the Rules loop): I'm about sure (99%), you'll also need to add a similar "Fetch entity by ID" (but from the variable names you used in your rule it's hard to tell).

---
Tags: 7, rules, entities
---


# Question
Title: How to link to live chat TawkTo module pop up window with Drupal 7?
I have Tawkto module installed, and I want to create link on my main menu for:

"Live Chat"

The link is:

```
  <a href="javascript:void(Tawk_API.toggle())"> Click to Chat </a>

```

Now this works fine on static HTML pages, but when I paste it in field for main menu, it doesn't work.

I've tried:

```
 /javascript:void(Tawk_API.toggle())

```

And:

```
 javascript:void(Tawk_API.toggle())

```

How can I do this?

The site with Livechat is:

www.vuxi.com

# Answer
> 0 votes
You can easily achieve this by using Void Menu module.

1. Download & Install Void Menu module.
2. Go to http://www.yoursite.com/admin/config/user-interface/void\_menu
3. Set **javascript:void(Tawk\_API.toggle())** as value for **HTML value for `<void2>`**
4. Then go to main menu configuration and set menu **Path** as **`<void2>`**

---
Tags: navigation
---


# Question
Title: How to hide particular field for specific role?
I have Article page content type with field title,description,ad\_article\_top,video etc. Also have one other role writer.writer can create article page content.

My issue is how to hide the ad\_article\_top field for writer role at the time he create content but if super admin create article page content the ad\_article\_top field not hidden

Give me some solution for solving this issue.

# Answer
> 1 votes
You can use Field Permissions module.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> Features
>
> * Enable field permissions on any entity, not just nodes.
>     + Role-based field permissions allowing different viewing patterned based on what access the user has.
>     + Author-level permissions allow viewing and editing of fields based on who the entity owner is.
>     + Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

---
Tags: entities
---


# Question
Title: Conditionally remove / blank out field values in View using Views PHP
I am trying to build a map (IPVGM) of locations which will be used as a block appended to all entities of type Person. Locations are stored in a taxonomy, with an extra field to hold the coordinates. There are multiple fields in a Person that reference the Locations taxonomy (Field:birthplace and Field:other\_locs), and I am trying to plot all of them on the same map. IPVGM can handle multiple locations per row, but the view I've been able to construct so far duplicates the birthplace in every row. This means that IPVGM constructs a map with (in this case) 4 birthplaces.

I'd like to use Views PHP to remove values for birthplace and birthplace coordinates in every row *but* the first one. I've had some luck trying to do this in the Output Code of Views PHP, but I think it needs to be handled in the Value Code area in order for IPVGM to pick up on the field values (or hopefully lack thereof). Any help? I looked at Views Distinct, and using a Global:PHP filter, but both of these would remove the entire row, when I only want to remove the birthplace & birthplace coordinates components.

# Answer
> 0 votes
Try to use Views Conditional.

Views Conditional is a simple module that allows you to define conditionals with fields in views.

Conditions include:

1. Equal To
2. Not Equal To
3. Greater Than
4. Less Than
5. Empty
6. Not Empty

Views conditional allows you to output text based on the result of the condition.

---
Tags: views
---


# Question
Title: Remove link to terms page when printing taxonomy term on node--content_type.tpl.php?
I have a node--content\_type.tpl.php template where I want to print the taxonomy term associated with the current content as plain text so that I can surround it with a div class to print a special label for content with the selected term.

So for example I have chosen "Sold" as a taxonomy term and want to display the word with no link to the taxonomy terms page. It currently outputs as "\<*a* datatype="" property="rdfs:label skos:prefLabel" typeof="skos:Concept" href="/taxonomy/term/6"\>Sold", so links to the taxonomy terms page.

I am currently using this code to print the term:

```
<?php

if(!empty($node->field_p_status['und'][0]['value'])) {
  $status = $node->field_p_status['und'][0]['value'];
}

?>

<?php if(isset($status)) { ?>

<?php print render(field_view_field('node', $node, 'field_p_status', array('label'=>'hidden'))); ?>

<?php } ?>

```

Any idea how to strip it down so it prints just "Sold"?

# Answer
> 1 votes
To print the raw value you can use this code:

```
<?php

if(!empty($node->field_p_status['und'][0]['value'])) {
  print $node->field_p_status['und'][0]['value'];
}
?>

```

# Answer
> 1 votes
I used a different solution which was better for me by printing the id of the taxonomy term (which I then wrapped in a div class). Obviously that didn't technically print the taxonomy term itself, but allowed me to have a class where I could style a background image unique to that class to show to the user (a Sold banner).

The code I used was:

```
                    <?php

                        if(!empty($node->field_p_status['und'][0]['value'])) {
                            $status = $node->field_p_status['und'][0]['value'];
                        }

                    ?>

                    <?php if(isset($status)) { ?>

                        <div class="status_<?php print $node->field_p_status[$node->language][0]['tid'] ?>"></div>

                    <?php } ?>

```

---
Tags: 7, theming, nodes, taxonomy-terms
---


# Question
Title: Views: Display number of nodes published by author on profile
Using Views, I can create a list of authors, and show the number of nodes that they have published. I've done this using aggregation. The part I can't figure out is how to filter the output based on the user profile that you're viewing. For example, if you're viewing user/1, I want you to see the number of nodes that user 1 has published.

I've tried using different `uid contextual filters`. In this example, I'm using `"User: Uid"` as the filter, and I'm trying to pull the uid from the URL by selecting `"'Provide default value' > 'Use ID from URL'"` in the filter's options. Since `aggregation settings are on`, you have to apply an aggregation type to the filter, and I'm not sure what that should be set on.

Any feedback would be appreciated. By the way, I'm using Display Suite to build the profile layout, so if there's an easier way to get want I need, I'm open for suggestions. Thanks in advance.

EDIT: For anyone attempting to do this, keep in mind that your output will not show up in the Views preview. I was forced to navigate to a user profile in order to test this. This issue seems to sprout from the combination of aggregation and contextual filters.

>

# Answer
In my opinion, You do not need Display suite to achieve this. You can do this in very Simple Drupal way .

**1.** Your views configuration if perfectly fine. I am just posting my one for reference purpose, Where I did two changes, (1) In the pager setting, I have set the `pager item to 1`. (2) I removed the `User: name` as it is not needed.

*Note: You do not need to anything with aggregation setting at filter level.*

>

**2.** From your views it is visible that you have created block.

**3.** Now, What you need to do is put that block in your user profile, so it looks like as a one of the field of user profile.

**4. How to do that:**

4.1 Place that Block under Main page content in Content region on as shown in following image.

>

4.2 Set the display rule for this block as shown in following image. So what happens, the block are visible only on the user profile page.

>

4.3 Set the `Role permission` for the `User Role`, so other user can see teh profile page of other's Or anonymous users also can see teh profile page of other's: I am sure you are aware of all this.

**5.** **Output Image:** As you can see, I have tried in my Bartik theme. I have just given block title, So it can distinguished in the image. Note: I have removed `User:name` field from the views, as it is not necessary. The views will automatically detect from the url.

>

\**Other example from other login \**

>

Hence, this way without using any other display help, you can add the new field in the User profile. So you do not have to much play with the User profile page.
> 1 votes

# Answer
Not the best approach, aggregation could get ugly if user creates 100 or 1000 nodes.

You're better off adding/creating a numeric field in User Manage Fields.

* Use Content Access module to hide the field from edit view, so only admins can see it in the user edit form (**Edit own content** only ☑ Administrator).
* With Rules when node is added/deleted, you +1/-1 the user numeric field.

Similarly to +1 user field after comment is made
> 0 votes

---
Tags: 7, views
---


title: The "php" plugin does not exist

text:
# Question
Title: The "php" plugin does not exist
I got this error after migrating from Drupal 6 to Drupal 8.1.3.

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "php" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 52 of core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php).

How can I fix this error?

# Answer
Do these actions in your database :

1. Locate php\_code in 'node\_revision\_body' table at 'body\_format' column, and change it from 'php\_code' to 'filtered\_html'.
2. There is also 'filter.format.php\_code' in my config table, i delete that.
3. `drush cr`.
4. Enable 'php' module from drush using the command 'drush pm-enable php'.
> -1 votes

# Answer
It's a guess, but the php module was removed from core in D8 and is now supplied by a contrib module: PHP

You will need to install it additionally.

---

**Edit 1:**

If you don't intend to use the module in the future, enable it only temporarily, find alternatives for the fields/text formates currently using it (if needed, the filter may be available but not actually used for php) then uninstall it again once you are done.
> 2 votes

---
Tags: 8
---


# Question
Title: Image style effect for removing empty space around image
There can be a lot of situations when e. g. set of logos in png format are not cropped regularly and some images can have different white spaces around the actual logo in the image.

Is there any module that adds an image style effect capable of cropping white space (transparent or white) around image?

# Answer
I don't think you can with a module. The only solution is use Photoshop or else. ImageCache Actions is the best module for custom style image, but I don't believe is going to...
> 1 votes

---
Tags: 7, media
---


# Question
Title: How do I create a custom template for view?
I have created a content type called "Hotels". I want to display to the view in different manner other than view options provided by Views module. For that I have to create custom template but don't know how to do it. What should be the naming conventions and where to store the template file. Please help me.

# Answer
> 9 votes
To create custom template for that view, create file and give name to that template as **views-view-fields--viewname--page/block.html.twig** and then create the HTML structure and then simply print the field accordingly and then save the file and don't forget to flush the cache.

To print the field...suppose you want to print the title and image field then do as below **{{ fields.title.content}}** **{{fields.machine\_name\_of\_image\_field.content}}** thats it.

**Note:** To get the machine name of the field, goto the content type and then manage fields, there you will find machine name of those fields. And remember if you have not add field in view in admin panel and adding it in your template file then it will not reflect.

# Answer
> 8 votes
Below give are the views template suggestion allowed in Drupal 8.

* views-view--foobar--page.html.twig
* views-view--page.html.twig
* views-view--foobar.html.twig
* views-view.html.twig
* views-view-unformatted--foobar--page.html.twig
* views-view-unformatted--page.html.twig
* views-view-unformatted--foobar.html.twig
* views-view-unformatted.html.twig
* views-view-fields--foobar--page.html.twig
* views-view-fields--page.html.twig
* views-view-fields--foobar.html.twig
* views-view-fields.html.twig

Refer Views template files for more information.

# Answer
> 6 votes
Create a services.yml file (an example file is under sites/default)

In that file, set debug: true (set to false in example file)

Save the file and clear you cache.

If you go to your view and inspect the code it will show you all of the theme suggestions you can use (similar to what theme info did in Views 3)

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


# Question
Title: Is it possible to declare a Javascript library dependency at Hook.info?
Below is my `module.info` file:

```
name = myid
description = Creates an ID template, Inputs ID form, Prints an ID and View System Statistics .
core = 7.x
package = CSU

;Jquery Library
dependencies[] = jquery_update (>=7.x-2.5)

;Needed to create text editors.
dependencies[] = imce (>=7.x-1.9)
dependencies[] = wysiwyg (>=7.x-2.2)
dependencies[] = imce_wysiwyg (>=7.x-1.0)

```

I know required module of my custom module can be declared in my `module.info` file to inform module users that it depends on it. How about `javascript` library like `TinyMCE`? Is it possible to declare it at hook.info? How will I inform that the user must also download `TinyMCE`.

I was thinking of including it using `drupal_add_js` but `Tinymce` is always stored at `drupal\sites\all\libraries\`. Please enlighten me in my problem. I'm a bit lost.

# Answer
> 1 votes
You can define library dependency using hook\_requirements(). Then if the library is missing, drupal will automatically shows the error message in status report(admin/reports/status).

Also it will show the error message, when trying to install module without having required library.

You need to define hook\_requirements() in your `youmodule.install` file like below:

```
/**
 * Implements hook_requirements().
 */
function yourmodule_requirements($phase) {
  $requirements = array();

  if ($phase == 'runtime') {
      $t = get_t();
      $library = libraries_detect('tinymce');
$error_message = isset($library['error message']) ? $library['error message'] : '';

if (empty($library['installed'])) {
  $requirements['tinymce'] = array(
    'title' => $t('TinyMCE Library'),
    'value' => $t('Not installed'),
    'severity' => REQUIREMENT_ERROR,
    'description' => $t('!error Please download !tinymce, and extract it into the %directory directory.', array(
        '!error' => $error_message,
        '!vimeo.ga.js' => l($t('TinyMCE'), $library['vendor url']),
        '%directory' => 'sites/all/libraries/tinymce',
      )
    ),
  );
}
else {
  $requirements['tinymce'] = array(
    'title' => $t('TinyMCE Library'),
    'severity' => REQUIREMENT_OK,
    'value' => $t('Installed'),
  );
}
  }

  return $requirements;
}

```

---
Tags: 7, hooks, .info, installation, wysiwyg
---


# Question
Title: How to create a custom markup for a views-block?
I'm trying to understand the templating system of Drupal 8, allready did some basic stuff. My next step is trying to create a template to mark up a list generated by a view.

Here's what I've done so far:

I created:

* A Content Type, with 3 fields: Title, Body, Link
* Some (5) content entries with this Content Type
* A View (Block) that lists all of the entries of this Content Type.

In Block layout I placed the View-block in a custom Region (werk\_items) (configured in the my-theme.info.yml file.)

Than I created a page template (page--node--23.html.twig) that includes this region, like so

{{ page.werk\_items }}

When I go to the corresponding URL all works well and all of the content is displayed.

Now my question is: How to extract the variables to create a custom markup for the view content?

# Answer
If you want to create custom markup/template for that particular view of content type then create file and name it as **views-view-fields--\[view-name\]--page/block.html.twig** and save it in template directory of your theme.

Now to get the variable just goto the content type -\> manage fields. There you will find the machine names of fields. those are the variable you need to place in html structure like this
**{{ fields.field-machine-name.content }}**
Hope this helps :)
> 1 votes

# Answer
If you want to see all the variables available in the Twig template you can just call dump Twig function without any parameters:

```
{{ dump() }}

```

In case you want to modify the markup inside the region or the blocks you should override corresponding templates instead of trying to modify the render array inside your page template.
> 0 votes

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


# Question
Title: Multivalue field with Twig and its length
I am playing around with Twig and D8. I created a content type called `community` and it contains a field called `field_banner_images` which is an image field with a max limit of 10 images.

I am trying to get the length of `field_banner_images` via Twig, but the number I am receiving is incorrect. My current node has 10 images on it. It also has alt text enabled if that makes a difference.

I created a file called `node--community.html.twig` and inside I have:

`{{ content.field_banner_images|length }}`

which outputs 26, which is wrong. I would expect it to output 10.

Furthermore, I add

```
{% for item in content.field_banner_images %}
  <span class="banner-img">{{ content.field_banner_images[loop.index0] }}</span>
{% endfor %}

```

and while it does output the 10 images wrapped in span elements, I also get 16 empty span elements since it is looping 26 times.

What am I doing wrong here?

# Answer
**How to count in page or node template**

`content` is the render array of the fields, that is build according to the view mode you have configured. The render array contains a lot of additional elements, that are not field items.

If you want to count the items in the field that are in the database, use the `node` object:

In php:

```
$node->field_banner_images->count();

```

In twig:

`count()` is not on the whitelist of allowed methods. Use .getvalue() instead, which gets the complete field array and count the array keys with the filter length:

```
{{ node.field_banner_images.getvalue|length }}

```

**Better solution with field template**

But you don't have to code the loop yourself in the node template, you can add the wrapper in the field twig.

Put the complete field in the node template:

```
{{ content.field_banner_images }}

```

And then put the wrapper in:

**field--field-banner-images.html.twig**

```
{% for item in items %}
    <span>{{ item.content }}</span>
{% endfor %}

```

You can remove the content of the field twig and replace it with the code above. You know the content of this field and you don't need the div containers, when you want span's.
> 4 votes

# Answer
FYI

This doesn't work.

```
{{ node.field_banner_images.count }}

```

Instead you can do something like that :

```
{{ node.field_banner_images|length }}

```
> 0 votes

---
Tags: theming, 8
---


title: How to list all url of contents?

text:
# Question
Title: How to list all url of contents?
I have so many content type like `article`, `contribution`, `event`, `c_program` etc.

For all content url alias is,

`[site_name]/[content type name]/title`

But we have some url alias that are like this,

`[site name]/title`

So, I want to list all url of,

`[site name]/title` format

How I can I list them out?

# Answer
> 1 votes
Use Drupal Pathauto

After enabling it go to `admin/config/search/path/patterns` and under **Default path pattern (applies to all content types with blank patterns below)** fieldset you'll get what you want.

Add your desired format there:

```
[site:name]/[node:title]

```

Once the configuration is done, click on `admin/config/search/path/update_bulk` and select **Content paths** from the given options.

# Answer
> 0 votes
You can use Views Excel Export. And export all URL's and filter them in Microsoft excel

> Simple module that allows to export Views data to Excel (xls).
>
> Uses php-excel class with UTF8 support.

---
Tags: views
---


# Question
Title: Event does not trigger each time I load a page
I'm using event dispatcher in a custom module to auto login users in a Drupal 8 website. I'm using the KernelEvents::REQUEST, with a onRequest fonction. I put an echo for testing that the function was call :

* When the user is already log in, the event work and my function was call on every request
* When the user **IS NOT** log in (anonymous), the function was call on the only first request of a page. Never call again if you reload the page. Only way to get my echo again is to empty drupal cache (I make a *drush cr*).

Don't know exactly how Drupal cache work... Is there any way to trigger my event on every request, anonymous or not ? Or another better way to do my auto login ? Thanks.

my module structure :

```
/mymodule
|-- /src
|---- /Controller
|------ MyModuleController.php
|---- /EventSubscriber
|------ MyModuleEventSubscriber.php
mymodule.info.yml
mymodule.routing.yml
mymodule.services.yml

```

MyModuleEventSubscriber.php

```
<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\ResettableStackedRouteMatchInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\externalauth\ExternalAuthInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;

class MyModuleEventSubscriber implements EventSubscriberInterface {

  protected $currentRouteMatch;
  protected $externalauth;
  protected $currentUser;

  /**
   * Constructs a MyModuleEventSubscriber object.
   */
  public function __construct(ResettableStackedRouteMatchInterface $currentRouteMatch, ExternalAuthInterface $externalauth, AccountProxyInterface $currentUser) {
    $this->currentRouteMatch = $currentRouteMatch;
    $this->externalauth = $externalauth;
    $this->currentUser = $currentUser;
  }

  /**
   * Implements EventSubscriberInterface::getSubscribedEvents().
   *
   * @return array
   *   An array of event listener definitions.
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('onRequest');
    return $events;
  }

  public function onRequest(GetResponseEvent $event) {
      // echo 'test' => do my echo here
      if ($this->currentUser->id() == '0') {
         auto_login(); // I simplified the code here, but you get the idea
      }
  }
}

```

mymodule.services.yml

```
services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MyModuleEventSubscriber
    arguments: ['@current_route_match', '@externalauth.externalauth', '@current_user']
    tags:
      - { name: event_subscriber }

```

# Answer
> 3 votes
This look like it is the module "Internal Page Cache", which caches pages for anonymous users. This cache runs before any event as middleware.

In your case there is no need for this module and you can uninstall it.

If there is other code that does interfere you should be able to control this with a priority you set on the event subscriber.

---
Tags: users, 8, caching, services, event-subscribers
---


# Question
Title: How to get values of selected options in Form api?
I am using Form api to build one form.In that I have used select type field and for that options are coming from an array. Below is the code

```
  $fnames = array();
  $dir_path = variable_get('file_public_path', conf_path(). '/files');
  $files1 = scandir($dir_path);
  $dirs = glob($dir_path . '/*' , GLOB_ONLYDIR);
    foreach($dirs as $directs){
     $names = explode('/', $directs);//
     $fnames[] = end($names);
    }

  $form['select_list'] = array(
    '#type' => 'select',
    '#title' => t('Folder Names'),
    '#options' => $fnames,
  );

```

While displaying on the select list it will display all names but when I will fetch the value in one of the submit function it will show only index value not the name.

```
function custom_submit_file_upload($form, &$form_state){
  $foldername = $form_state['values']['select_list'];
}

```

Here it shows,

```
$foldername = 0 or 1 or 2 whatever I select in the options,

```

but I need name of the selected element not the index values. Please suggest me to get the names.Thank you in advance..

# Answer
Since the form submission handler has access to the `$form` variable, you just use the following code.

```
$foldername = $form['select_list']['#options'][$form_state['values']['select_list']];

```

To make it clear with an example: `$form['select_list']['#options']` is an array like `array( 1 => 'first folder', 2 => 'second folder')`, and `$form_state['values']['select_list']` is a value between 1 and 2.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: drupal 7 add element after the username input text element on login form
I would like to add the domain name of my company in a simple element right after the username login text input element. Something like this:

I already tried the instructions defined in https://drupal.org/node/350634 and this only affects the text field label or anything around the login form, but not the input fields themselves (unless I'm misunderstanding the directions). This method doesn't seem to affect how I can add an html element after the username text field but before the password text field.

I'm not certain how I should attempt this? Any direction would be wonderful.

BTW - I tried LoginToboggan to simply allow my users to use either their username or their email address, but that solution only partially works. We have LDAP integration, so for the first time the user attempts to log into our Drupal site they must use just their username (without the @companydomain.com) to allow the LDAP authentication to go through. I did not see a way to configure LoginToboggan to force the username through to the LDAP authentication.

Thanks

# Answer
> 1 votes
You need to add suffix element to username field in login form. You can do it using hook\_form\_alter(&$form, &$form\_state, $form\_id)

Implement above hook in your custom module

```
function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['name']['#suffix'] = '@mycompany.com';
  }
}

```

# Answer
> 0 votes
While Anil Sagar's answer is perfectly correct, sometimes you'll want to use '#field\_suffix' instead of '#suffix' (when you add a title as well).

---
Tags: 7, users
---


# Question
Title: How to remove a page from a books and/or delete a book?
I placed a basic page into a book but now want it removed from every book. In the book outline settings I only see a way to move it to another book, I see no option to set it to none. I also don't see a way to delete a book in structure/books.

One option I've considered is uninstalling the book module and reenabling it but I'd rather not lose every book I have because of one page.

Is there a way to remove a page from a book, and/or delete a book without uninstalling the book module?

# Answer
There is a option to remove the any page from the Book outline. Suppose I have created a basic page and put in a Book outline. Now if I want to remove, click outline as shown in the follwoing image

>

Now, you can see `Remove from book outline` in red in as show in following option. That will remove that Basic page from the book.

>

**Update:**

You can not delete entire book at a once. Why, because Book is just a indexing tool, It is not a content type. Book page is a content type. Book page and Book are two different thing. And it should be that way. Hence, you can delete all nodes of one content type by deleting that content type itself. But, if you are putting some node under book outline, you are not creating a entire group/content type, You are just indexing your node in specific order.

Hence, If you delete any Parent item in book, It shows a message that the `child will be re-ordered automatically`. Hence, you can understand its just a ordering/indexing tool.

Hence, to provide this feature Book Delete module was created. But still it does not have Drupal 8 Version.
> 5 votes

---
Tags: nodes, 8
---